python - 保持消息计数离线 discord.py
问题描述
我有一个机器人可以在说出 nword 时计数,但是当机器人离线时计数会重置
这是我的代码(正在审查 nword)
bot.softn = 0
bot.hardn = 0
@bot.event
async def on_message(message):
user = message.author
if message.content == "nibba":
embed=discord.Embed(title="racist", description=f"{user} said the N-word! \n racist!", color=0xb1f1c0)
await message.channel.send(embed=embed)
bot.softn += 1
elif message.content == "nibberr":
embed=discord.Embed(title="racist", description=f"{user} said the N-word! \n racist!", color=0xb1f1c0)
await message.channel.send(embed=embed)
bot.softn += 1
bot.hardn += 1
await bot.process_commands(message)
@bot.command()
async def racist(ctx):
embed=discord.Embed(title="Rascist Counter", description=f"N-word has been said {ctx.bot.softn} times!\n\nand of which the hard-R has been said {ctx.bot.hardn} times", color=0xefe0b4)
embed.add_field(name="Conclusion", value="The n-word is overrated. Get a better vocabulary", inline=True)
await ctx.send(embed=embed)
我怎样才能让计数器不被重置?
解决方案
我在这里根据不同的贡献找到了一个很好的解决方案,所以下次你应该仔细看看。您必须将计数器保存在文件中,否则无论您做什么,它都会丢失。
你主要需要2个功能:
def load_counters():
with open('counter.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('counter.json', 'w') as f:
json.dump(counters, f)
counter
我们使用在这种情况下调用的 JSON 文件。这里我们load
和save
JSON 作为一个文件。
dump
意味着我们更新计数器本身。
如果您现在想收听所有消息并将您的话保存在此文件中,您可以使用以下on_message
事件:
@bot.event()
async def on_message(message):
if "YourWord" in message.content:
counters = load_counters() # First load the file
counters["YourWord"] += 1 # Count up
save_counters(counters) # Save the count
我们现在如何从文件中获取计数?
要读出文件,我们首先要读取open
它,然后在命令中使用它:
with open('counter.json', 'r') as f:
counters1 = json.load(f) # Open and load the file
现在我们可以使用counter1
以下方式显示计数器:
f"{counters1['YourWord']}"
我建议再次阅读文档并查看如何在 Python 中使用 JSON 文件
推荐阅读
- rust - 如何在 Rust 中访问系统定时器中断
- java - 为什么我的 ImageButtons 不能为我的滑动益智游戏随机播放?
- excel - 我们如何在没有 MSCOMCT2.OCX 文件的情况下使用 datepicker?
- c++ - Cmake找不到提升窗口
- javascript - 在 *ngfor(Angular) 中插入具有特定样式属性的动态元素
- google-maps - ionic 4 地图在浏览器中工作但在 Andriod 设备中不工作
- javascript - 用户可以在加载页面之前使用开发人员工具控制台取消绑定页面加载事件处理程序吗?
- python-3.x - 一次访问 RDD 中的 200 个文件 pyspark
- operators - 数学等价于双右移和 AND 运算符?
- python - 如何修复 TypeError:不支持的操作数类型?