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

Discord机器人加表情分配角色报'Nonetype' has no attribute 'id'如何解决

报错原因与解决方案

你遇到的'NoneType' has no attribute 'id'错误,核心原因是discord.utils.get(user.guild.roles, name='Test_Bot')执行后返回了None,程序后续尝试读取这个空值的id属性时触发报错。

具体排查与修复步骤

  • 第一步先确认你的Discord服务器内存在名称完全匹配的Test_Bot角色,角色名的大小写、空格、特殊符号都要完全一致,不能有拼写误差。
  • 第二步检查机器人权限配置:
    • 机器人自身的角色在服务器角色列表中的排序,必须高于你要分配的Test_Bot角色
    • 机器人账号需要被授予「管理角色」权限
  • 第三步替换旧的反应监听事件:你当前使用的on_reaction_add仅对机器人启动后缓存在本地的消息生效,对历史消息添加反应时容易出现数据读取失败,建议替换为不依赖本地缓存的on_raw_reaction_add事件,同时添加空值判断避免报错。

修复后可直接运行的代码

import discord
from discord.ext import commands

# 显式声明必要的网关意图,discord.py v2.x 版本强制要求
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.reactions = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('ready')

@client.event
async def on_raw_reaction_add(payload):
    # 过滤机器人自身触发的反应
    if payload.user_id == client.user.id:
        return
    # 获取服务器对象,为空直接终止执行
    guild = client.get_guild(payload.guild_id)
    if not guild:
        return
    # 获取触发反应的用户对象,为空直接终止执行
    user = guild.get_member(payload.user_id)
    if not user:
        return
    # 获取目标角色,找不到直接终止执行避免报错
    role = discord.utils.get(guild.roles, name='Test_Bot')
    if not role:
        print("未找到匹配名称的角色,请检查服务器角色配置")
        return
    # 执行分配角色操作
    await user.add_roles(role, reason='用户添加指定表情反应')

client.run('替换为你的机器人TOKEN')

额外注意事项

如果你使用的是discord.py 2.0及以上版本,需要先进入Discord开发者平台的机器人管理页面,开启「Server Members Intent」「Guilds Intent」「Message Content Intent」三个权限开关,否则机器人无法正常读取服务器成员、角色等相关数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:57:04