You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py自定义前缀触发KeyError '905126423902167041'如何解决?

问题排查

错误原因

你遇到的KeyError是以下几个原因导致的:

  • 你的机器人在开发自定义前缀功能之前就已经加入了ID为905126423902167041的服务器,你代码里仅设置了on_guild_join(机器人新加入服务器时)才会写入默认前缀,现有服务器没有对应的前缀记录
  • 未兼容私信触发指令的场景:私信场景下message.guild为None,调用message.guild.id会直接报错
  • (潜在问题)如果你的prefixes.json文件初始为空,加载json时也会抛出解析错误

修复方案

1. 修复get_prefix函数逻辑,兼容缺失记录和私信场景

把原来的get_prefix函数替换为以下代码:

def get_prefix(client, message):
    # 私信场景默认用/作为前缀
    if not message.guild:
        return "/"
    with open("prefixes.json", "r") as f:
        prefix = json.load(f)
    guild_id = str(message.guild.id)
    # 如果当前服务器没有前缀记录,自动写入默认前缀
    if guild_id not in prefix:
        prefix[guild_id] = "/"
        with open("prefixes.json", "w") as f:
            json.dump(prefix, f, indent=4)
    return prefix[guild_id]

2. 修复on_guild_remove异常

如果机器人离开的服务器没有前缀记录,直接调用pop会抛出KeyError,修改为:

@client.event
async def on_guild_remove(guild):
    with open("prefixes.json", "r") as f:
        prefix = json.load(f)
    # 加第二个参数None,不存在也不会报错
    prefix.pop(str(guild.id), None)
    with open("prefixes.json", "w") as f:
        json.dump(prefix, f, indent=4)

3. 初始化检查(可选,优化启动速度)

如果你的机器人加入了大量服务器,每次调用指令都检查前缀会降低性能,可以加on_ready事件启动时批量补全所有服务器的前缀记录:

@client.event
async def on_ready():
    with open("prefixes.json", "r") as f:
        prefix = json.load(f)
    # 遍历所有已加入的服务器
    for guild in client.guilds:
        guild_id = str(guild.id)
        if guild_id not in prefix:
            prefix[guild_id] = "/"
    with open("prefixes.json", "w") as f:
        json.dump(prefix, f, indent=4)
    print(f"已登录为 {client.user}")

4. 初始文件检查

确保你的项目根目录下存在prefixes.json文件,且文件内容至少为{},不要留空。

内容的提问来源于stack exchange,提问作者Mixu lol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:36:08