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

discord.py如何给消息反应者分配身份组及'int'无'id'属性报错解决

问题解决方法

错误原因

报错的核心是add_roles方法的传参逻辑错误:
discord.Member类的add_roles方法不需要传入服务器ID、用户ID这类参数,你额外传入的user.guild.id、user.id都是整数类型,方法内部会尝试读取传入参数的id属性,整数类型自然没有这个属性,就触发了'int' object has no attribute 'id'的报错。

修复步骤

  1. 修正add_roles调用语句
    只需要把原有调用行改成仅传入角色对象和reason参数即可:
await user.add_roles(role, reason='reason')
  1. 补充缺失的Intents配置
    discord.py v2.x版本默认关闭了成员、消息反应相关的权限,你需要在代码里启用对应意图,同时要在Discord开发者后台的机器人面板里开启「服务器成员意图」「消息内容意图」权限。
    代码初始化部分修改为:
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.reactions = True

client = discord.Client(intents=intents)
  1. 可选优化:改用on_raw_reaction_add事件
    on_reaction_add仅对机器人启动后缓存的消息生效,如果需要对机器人启动前发送的消息的反应也能触发逻辑,可以替换为on_raw_reaction_add事件,示例写法:
@client.event
async def on_raw_reaction_add(payload):
    guild = client.get_guild(payload.guild_id)
    if guild is None:
        return
    user = guild.get_member(payload.user_id)
    if user.bot: # 过滤机器人自身的反应
        return
    role = discord.utils.get(guild.roles, name='Test_Bot')
    if role:
        await user.add_roles(role, reason='用户添加反应自动分配身份组')

完整可运行代码示例

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.reactions = True

client = discord.Client(intents=intents)

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

@client.event
async def on_reaction_add(reaction, user):
    if user.bot: # 避免响应机器人自己的反应
        return
    channel = reaction.message.channel
    await channel.send(f'{user.name} 已使用 {reaction.emoji} 表情回应,对应消息内容为:{reaction.message.content}')
    role = discord.utils.get(user.guild.roles, name='Test_Bot')
    if role: # 先判断角色是否存在,避免不存在时报错
        await user.add_roles(role, reason='用户添加反应自动分配身份组')

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

内容的提问来源于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:48:02