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

Discord.py中如何检测对消息作出表情反应的用户?

Discord机器人监听首个消息反应报错解决方案

常见报错原因

  • wait_for的事件参数没有加引号:discord.py要求事件名以字符串形式传入,直接写reaction_add会触发变量未定义错误,正确写法为'reaction_add'
  • 未开启必要的Intents权限:v2.0及以上版本的discord.py默认关闭反应监听相关的Intents,需要手动在代码和Discord开发者后台开启
  • 检查函数逻辑错误:没有限定反应对应的消息ID,或者没有排除机器人自身的反应,会触发逻辑异常或者监听不到符合要求的反应
  • 机器人缺少频道权限:没有读取消息历史、查看频道权限时,无法监听到对应消息的反应事件

正确实现示例

1. 基础配置

import discord
from discord.ext import commands

# 开启反应监听所需的Intents
intents = discord.Intents.default()
intents.reactions = True
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

2. 发送消息后监听首个反应的实现

@bot.command()
async def get_first_reactor(ctx):
    # 发送需要监听反应的目标消息
    target_msg = await ctx.send("请对本条消息添加任意表情反应")

    # 定义校验规则:仅匹配目标消息的反应,且反应者不是机器人本身
    def check(reaction, user):
        return reaction.message.id == target_msg.id and user != bot.user

    try:
        # 等待30秒内第一个符合校验规则的反应,超时时间可自行调整
        reaction, first_react_user = await bot.wait_for("reaction_add", timeout=30.0, check=check)
        # first_react_user 即为首个添加反应的用户,可直接存入变量使用
        await ctx.send(f"首个添加反应的用户为:{first_react_user.name}")
    except TimeoutError:
        await ctx.send("超时,未收到任何用户反应")

报错排查步骤

  • 如果触发NameError:确认wait_for的第一个参数为带引号的字符串"reaction_add"
  • 如果触发权限相关报错:进入Discord开发者后台的Bot管理页,开启Privileged Gateway Intents分类下的Message Content Intent和Server Members Intent
  • 如果监听不到反应:确认机器人在对应服务器拥有读取消息历史权限,且check函数的逻辑匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:24:03