【问题标题】:discord.py - delete guild from json after bot leaves serverdiscord.py - 在 bot 离开服务器后从 json 中删除公会
【发布时间】:2021-04-29 00:43:23
【问题描述】:

我正在尝试公开我的机器人,因此我需要在 json 中存储多个 ID。

如果机器人加入公会,它将在json中创建一个条目:

{
    "token": "MY_TOKEN",
    "guilds": {
        "TiLiKas": {
            "rules_message": {
                "rules_id": 780729484931366912
            },
            "ticket_message": {
                "ticket_id": 778567282321391638
            }
        },
        "Darkness": {
            "rules_message": {
                "rules_id": 765132820049428481
            },
            "ticket_message": {
                "ticket_id": 798839023031549962
            }
        },
        "Bot-Test-Server": {
            "rules_message": {},
            "ticket_message": {}
        }
    }
}

我如何创建公会信息:

@commands.Cog.listener()
async def on_guild_join(self, ctx):

    default_prefix = "?"

    for guild in self.client.guilds:

        guildName = guild

    with open("data.json", "r") as f:
        data = json.load(f)

        tmpDict = {
            "rules_message": { },
            "ticket_message": { }
        }

        data["guilds"][str(guildName)] = tmpDict

        with open("data.json", "w") as f:
            json.dump(data, f, indent=4)

问题是,如果 bot 被服务器踢出,该条目仍保留在 json 中。

如果机器人离开公会,我如何从 json 中删除服务器?

感谢您的帮助!

【问题讨论】:

  • 想想,有on_guild_join事件,所以有on_guild_remove事件

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


【解决方案1】:

正如我在cmets中所说,有一个on_guild_remove事件,你可以从那里的json文件中删除公会

@commands.Cog.listener()
async def on_guild_remove(self, guild):
    with open("data.json", "r") as f:
        data = json.load(f)

    del data["guild"][str(guild)]
 
    with open("data.json", "w") as f:
        json.dump(data, f, indent=2)

参考:

【讨论】:

  • 好吧,我只是想得太复杂了。我试图将self.client.guilds 与data["guilds"] 中的条目进行比较。但现在一切正常,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2022-01-15
  • 2018-07-24
  • 2021-09-03
  • 2021-10-14
相关资源
最近更新 更多