【问题标题】:Getting guild id [Discord.py] [json]获取公会 ID [Discord.py] [json]
【发布时间】:2021-03-11 07:34:09
【问题描述】:

所以,当我的机器人离线并且有人在他们的服务器中添加它时,我在机器人再次启动后遇到了一个关键错误,因为在 json 文件中找不到 ID,所以我需要以某种方式解决这个问题,当机器人再次上线获取公会ID并放入json中时。有人告诉我做try except 的事情,但我不明白如何在机器人上线后获取公会 ID 并放入 json 这是代码,我觉得做起来很简单,但现在我真的不明白

    with open('prefixes.json' , 'r') as f:
        prefixes = json.load(f)

 
        return prefixes[str(message.guild.id)]

 
client = commands.Bot(command_prefix=get_prefix)



@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = 's!'

    with open('prefixes.json' , 'w') as f:
        json.dump(prefixes, f, indent = 4 )

@client.event
async def on_guild_remove(guild) :
    with open('prefixes.json' , 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes.json' , 'w') as f:
        json.dump(prefixes, f, indent = 4 )```

【问题讨论】:

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


    【解决方案1】:
    try:
       # get prefix, and then return it
       with open('prefixes.json' , 'r') as f:
            prefixes = json.load(f)
    
     
            return prefixes[str(message.guild.id)]
    
    except KeyError: # if the code above failed and raise KeyError code below will executed
       #insert the data to json, and the return the default prefix
       with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)
    
        prefixes[str(message.guild.id)] = 's!'
    
        with open('prefixes.json' , 'w') as f:
            json.dump(prefixes, f, indent = 4 )
        return "s!" # or you can repeat the process of getting the prefix
    

    【讨论】:

    • 我试过了,然后给了我另一个错误,`第 28 行,在 get_prefix prefixes[str(guild.id)] = 's!' AttributeError: 'Bot' object has no attribute 'id'` and : line 21, in get_prefix return prefixes[str(message.guild.id)] KeyError: ' - '
    • @Ares 已编辑,我错过了一些东西。对此感到抱歉。仍然有任何错误?
    • 现在一切正常,谢谢,我真的很难修复它
    猜你喜欢
    • 2020-12-09
    • 2021-12-17
    • 2021-10-19
    • 2021-02-03
    • 2021-02-02
    • 1970-01-01
    • 2019-12-29
    • 2020-09-25
    • 2021-04-30
    相关资源
    最近更新 更多