【问题标题】:Need help storing data for different servers with discord.py需要帮助使用 discord.py 为不同服务器存储数据
【发布时间】:2019-09-03 17:34:10
【问题描述】:

我想问我将如何存储不同服务器的变量,因为我在消息命令上有一个“F”,它将 F 存储在 json 中,以便我可以跟踪它在不同服务器上被调用的次数。我还想知道当机器人关闭时如何将其转储到 json 中,因为现在唯一的转储方法是运行命令 aut.disconnect。

filename = "respectspaid.json"
respects = 0
with open(filename) as f_obj:
    respects = json.load(f_obj)

@bot.event
async def on_message(message):
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
    cajo_guild = bot.get_guild(ID)

    if message.author == client.user:
        return

    if message.author.bot:
        return

    if "aut.membercount" == message.content.lower():
        await message.channel.send(f"```py\n{cajo_guild.member_count}```")

    elif "F" == message.content:
        global respects
        respects += 1
        await message.channel.send(f"```Respects paid: {respects}```")

    elif "aut.disconnect" == message.content.lower():
        with open(filename, 'w') as f_obj:
            json.dump(respects, f_obj)
        print("Dumping and closing client...")
        await bot.close()
        sys.exit()

    await bot.process_commands(message)

我在断开机器人(当我关闭我的电脑时)时转储更新的 F 计数并在我运行程序时加载它并在每次发送“F”时更新它但我不知道如何执行此操作在多台服务器上很好。这个机器人将主要用于我朋友的服务器,我让机器人做一些他们想要的笑话,所以我不希望机器人做一些更重的事情。

【问题讨论】:

    标签: python python-3.x bots discord.py


    【解决方案1】:

    如果您想要每个服务器的不同计数,您需要将统计信息保存在 dict json 文件中

    所以不要使用respects += 1,而是使用respects[str(guild.id)] += 1。这具有不需要全局语句的额外好处,因为 dicts 是不可变的。将公会 ID 字符串化的原因是因为 python dict 键可以是整数,而 json 对象键只能是字符串。

    要回答您的其他问题,您有几个选择。最简单的是每次调用后保存:

    def save_respect():
        with open(fp, "w") as fh:
            json.dump(respects, fp, indent=4)
    ...
    if message.content.lower() == "f":
        respects[str(message.guild.id)] += 1
        save_respects()
    

    替代方法是有一个断开处理程序

    try:
        bot.run()
    except BaseException:  # Catches keyboard interrupt
        pass
    finally:
        save_respects()
    

    虽然这不会处理代码没有干净退出的情况(例如系统关闭)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      相关资源
      最近更新 更多