首页 > 解决方案 > 保持消息计数离线 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)   

我怎样才能让计数器不被重置?

标签: pythondiscorddiscord.py

解决方案


我在这里根据不同的贡献找到了一个很好的解决方案,所以下次你应该仔细看看。您必须将计数器保存在文件中,否则无论您做什么,它都会丢失。

你主要需要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 文件。这里我们loadsaveJSON 作为一个文件。 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 文件


推荐阅读