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

如何解决discord.py中on_member_join事件的KeyError问题

解决discord.py on_member_join事件中的KeyError问题

错误原因

你遇到的KeyError: 'Youtube tutorial bot test',是因为当前warns字典中不存在对应服务器名称的键,直接尝试访问该键下的成员ID会触发键不存在的错误。

修复代码

修改on_member_join事件处理函数,先检查服务器是否已在警告字典中,不存在则先创建对应空字典,再设置成员警告数:

import json

@client.event
async def on_member_join(member):
    guild_name = str(member.guild.name)
    member_id = str(member.id)
    
    # 读取现有警告数据
    with open('warns.json', 'r') as f:
        warns = json.load(f)
    
    # 检查服务器条目是否存在,不存在则初始化
    if guild_name not in warns:
        warns[guild_name] = {}
    
    # 设置该成员的警告数为0
    warns[guild_name][member_id] = 0
    
    # 保存修改后的数据
    with open('warns.json', 'w') as f:
        json.dump(warns, f, indent=4)

优化建议

优先使用服务器ID而非名称:服务器名称可能被管理员修改,导致后续读取警告数据时出现匹配错误。建议改用member.guild.id作为字典键,代码调整如下:

import json

@client.event
async def on_member_join(member):
    guild_id = str(member.guild.id)
    member_id = str(member.id)
    
    with open('warns.json', 'r') as f:
        warns = json.load(f)
    
    if guild_id not in warns:
        warns[guild_id] = {}
    
    warns[guild_id][member_id] = 0
    
    with open('warns.json', 'w') as f:
        json.dump(warns, f, indent=4)

这样即使服务器名称变更,也不会影响警告数据的存储和读取。

内容的提问来源于stack exchange,提问作者Ivan Parvanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:35:36