Discord机器人实现分服务器自定义前缀时KeyError报错如何解决
报错原因
这个KeyError: '882434407212925000'是因为你触发命令的服务器ID没有提前存入prefixes.json的字典中,直接查询不存在的key就会抛出该错误。另外你代码里写的读取文件名为prefixes.js,如果实际存储的是JSON结构,建议先把文件后缀修改为prefixes.json避免混淆。
修复方案
1. 改造get_prefix函数,增加默认前缀回退逻辑
找不到对应服务器配置时自动写入默认前缀,同时兼容私聊场景:
import json def get_prefix(client, message): # 私聊场景直接返回默认前缀 if not message.guild: return "!" # 读取前缀配置文件 with open("prefixes.json", "r") as f: prefixes = json.load(f) guild_id = str(message.guild.id) # 该服务器无配置时写入默认前缀 if guild_id not in prefixes: prefixes[guild_id] = "!" with open("prefixes.json", "w") as f: json.dump(prefixes, f, indent=4, ensure_ascii=False) return prefixes[guild_id]
2. 初始化配置文件
如果你的prefixes.json文件不存在或者内容为空,先写入初始空对象:
{}
3. 添加自定义前缀修改命令
给服务器管理员提供修改前缀的入口:
@client.command() @commands.has_permissions(administrator=True) async def set_prefix(ctx, new_prefix: str): with open("prefixes.json", "r") as f: prefixes = json.load(f) prefixes[str(ctx.guild.id)] = new_prefix with open("prefixes.json", "w") as f: json.dump(prefixes, f, indent=4, ensure_ascii=False) await ctx.send(f"本服务器命令前缀已更新为 `{new_prefix}`")
额外优化
可以监听机器人加入新服务器事件,提前写入默认前缀,避免首次调用命令才写入的延迟:
@client.event async def on_guild_join(guild): with open("prefixes.json", "r") as f: prefixes = json.load(f) prefixes[str(guild.id)] = "!" with open("prefixes.json", "w") as f: json.dump(prefixes, f, indent=4)
内容的提问来源于stack exchange,提问作者Derek
相关产品推荐
相关产品推荐

