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

Discord.py如何检测自身发送消息的用户反应并返回对应emoji

Discord.py 监听机器人自身消息反应的代码调整方案

原有代码核心问题

  • 未定义channel变量,运行时会直接抛出变量不存在的报错
  • 没有过滤机器人自身的反应操作,机器人自己给消息加反应也会触发逻辑,容易造成死循环
  • 没有判断反应所属消息的发送者,服务器内所有被用户添加反应的消息都会触发提示,不符合需求
  • 默认的on_reaction_add事件仅处理机器人运行时缓存内的消息,机器人重启前发送的消息无法触发对应逻辑

修正后实现代码

基础版本(仅处理机器人启动后发送的消息,性能开销更低)

import discord
from discord.ext import commands

# 开启必要意图,同时需要在Discord开发者后台对应机器人页面开启对应权限
intents = discord.Intents.default()
intents.members = True
intents.message_content = True

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

@bot.command()
async def react(ctx):
    await ctx.send("React to me!")

@bot.event
async def on_reaction_add(reaction, user):
    # 过滤机器人自身的反应
    if user.bot:
        return
    # 仅处理机器人自己发送的消息的反应
    if reaction.message.author == bot.user:
        channel = reaction.message.channel
        await channel.send(f"{user.mention}, you reacted with {reaction.emoji}")

bot.run("你的机器人Token")

兼容历史消息版本(支持机器人重启前发送的所有消息,无需依赖本地缓存)

如果需要处理机器人重启前发的消息的反应,把on_reaction_add替换为on_raw_reaction_add即可:

@bot.event
async def on_raw_reaction_add(payload):
    # 过滤机器人自身的反应
    user = await bot.fetch_user(payload.user_id)
    if user.bot:
        return
    # 获取对应频道和消息对象
    channel = await bot.fetch_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    # 仅处理机器人自己发送的消息的反应
    if message.author == bot.user:
        await channel.send(f"{user.mention}, you reacted with {payload.emoji}")

注意事项

  • 必须在Discord开发者后台的机器人设置页面开启Server Members Intent和Message Content Intent权限,否则事件无法正常触发
  • 如果使用Python 3.6以下版本不支持f-string,把格式化部分替换为你原本的format写法即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:18:03