【发布时间】: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