Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

python - discord.py - delete guild from json after bot leaves server

I am trying to make my bot public and therefore I need to store several IDs in a json.

If the bot joins a guild, it will create an entry in 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": {}
        }
    }
}

How I create the guild information:

@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)

The problem is, if the bot gets kicked from the server, the entry remains in the json.

How can I delete the server from json if the bot leaves the guild?

Thanks for the help!

question from:https://stackoverflow.com/questions/65880901/discord-py-delete-guild-from-json-after-bot-leaves-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I said in the comments, there is an on_guild_remove event, you can delete the guild from the json file there

@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)

Reference:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...