discord.py - 在机器人离开服务器后从 json 中删除公会

时间:2021-01-25 07:59:30

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

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

如果bot加入公会,它会在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)

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

正如我在评论中所说的,有一个 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)

参考: