You need to enable JavaScript to run this app. discord.py check_vouches命令调用member.id报NoneType属性错误
优惠活动
大模型
产品
解决方案
定价
更多

discord.py check_vouches命令调用member.id报NoneType属性错误

报错根因
  • 缩进错位:原代码中if member is not None 块未缩进在命令函数内部,完全脱离函数作用域
  • 执行顺序错误:vouches_gotten = users[str(member.id)]["vouches_gotten"] 这行代码在判断member is not None之前执行,当用户未传入member参数时,member值为None,直接调用.id属性就会触发'NoneType' object has no attribute 'id'报错
  • 参数类型适配错误:后续需要给服务器内用户添加角色,参数类型应使用discord.Member而非discord.User(discord.User是全局账号对象,不包含服务器内的角色相关属性)
  • 格式化错误:发送的提示消息"you now have the {role} role"未加f前缀,无法正常替换变量内容
  • 缺少边界判断:直接通过下标取字典值,当传入的member id不在users存储的数据集里时,会额外触发KeyError报错
  • 之前修改的*, id参数属于冗余错误写法:*后跟的是强制关键字参数,会和原有member参数逻辑冲突,不需要额外传id,discord.py的参数转换器会自动把用户输入的@提及/数字ID转换成对应的member对象
修复后可运行代码
@client.command()
async def check_vouches(ctx, member: discord.Member = None):
    # 未指定查询目标时,默认查询当前调用命令的用户
    if member is None:
        member = ctx.author
    users = await get_vouch_data()
    role = discord.utils.get(ctx.guild.roles, name="10 vouches")
    # 提前校验角色是否存在,避免后续操作报错
    if not role:
        return await ctx.reply("服务器未配置「10 vouches」角色,请联系管理员处理")
    # 用get取值避免KeyError,无对应数据时默认vouch数为0
    user_vouch_data = users.get(str(member.id), {})
    vouches_gotten = user_vouch_data.get("vouches_gotten", 0)

    if vouches_gotten == 10:
        # 按原代码逻辑,给命令调用者加角色;如果要给被查询的目标加,把ctx.author换成member即可
        if role not in ctx.author.roles:
            await ctx.author.add_roles(role)
            await ctx.send(f"你已达到10 vouch要求,获得 {role.name} 角色")
        else:
            await ctx.send("你已经拥有该角色,无需重复获取")
    else:
        await ctx.reply(f"当前你仅有 {vouches_gotten} 个vouch,需要攒够10个才能获取对应角色")
调用说明

执行命令时不需要手动传id,直接@目标用户或者输入用户数字ID即可,discord.py会自动将输入内容转换为对应的member对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 07:27:08