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

discord.py中on_reaction_add函数获取用户反应消息及表情包机器人私信推送功能实现求助

解决discord.py中获取反应目标消息与表情包私信机器人的问题

我来帮你搞定这两个需求!下面分步骤给你讲清楚怎么实现:

一、获取用户反应的目标消息

其实在on_reaction_add(或者更推荐的on_raw_reaction_add)事件里,直接就能拿到目标消息:

  • 如果用on_reaction_add,reaction.message就是用户触发反应的那条消息,但它依赖机器人的消息缓存,重启前的历史消息可能无法直接获取,这时候可以用await reaction.message.channel.fetch_message(reaction.message.id)主动拉取。
  • 更推荐用on_raw_reaction_add,它不依赖缓存,能处理所有反应事件(包括历史消息的反应),通过payload.channel_id和payload.message_id就能精准获取目标消息。

二、实现表情包私信机器人

结合你的需求,我整理了完整的示例代码,包含核心逻辑和避坑要点:

1. 先配置好Intents(关键!)

discord.py v2.x版本必须开启对应Intents才能监听消息和反应事件,否则事件不会触发:

import discord

# 配置Intents
intents = discord.Intents.default()
intents.message_content = True  # 允许读取消息内容
intents.reactions = True        # 允许监听反应事件

client = discord.Client(intents=intents)

2. 实现反应触发私信逻辑

这里用on_raw_reaction_add兼容历史消息,代码如下:

@client.event
async def on_raw_reaction_add(payload):
    # 排除机器人自己的反应,避免死循环
    if payload.user_id == client.user.id:
        return
    
    # 判断触发的表情是➡️
    if str(payload.emoji) == "➡️":
        try:
            # 获取目标消息所在频道
            channel = client.get_channel(payload.channel_id)
            # 获取目标消息(自动从API拉取,不依赖缓存)
            target_message = await channel.fetch_message(payload.message_id)
            
            # 提取消息里的表情包(假设是图片附件)
            if target_message.attachments:
                meme_attachment = target_message.attachments[0]
                # 获取触发反应的用户
                user = await client.fetch_user(payload.user_id)
                
                # 发送表情包到私信
                await user.send(file=await meme_attachment.to_file())
                await user.send("表情包已发送到你的私信啦!")
            else:
                # 消息无附件时的提示
                await channel.send("这条消息里没有表情包哦!", delete_after=5)
        except discord.Forbidden:
            # 处理用户关闭私信的情况
            await channel.send("无法给你发送私信,请检查是否开启了私信权限!", delete_after=5)
        except Exception as e:
            print(f"运行出错:{e}")

# 启动机器人
client.run("你的机器人Token")

3. 自动给表情包消息添加反应按钮

如果想让机器人自动给表情包消息加上➡️反应,可以再加一个on_message事件:

@client.event
async def on_message(message):
    # 排除机器人自身的消息
    if message.author == client.user:
        return
    
    # 判断消息是否包含图片类表情包
    if message.attachments and any(att.content_type.startswith("image/") for att in message.attachments):
        await message.add_reaction("➡️")

关键注意事项

  • 确保机器人拥有发送消息和添加反应的频道权限。
  • 如果表情包是嵌入链接形式(不是附件),需要修改提取逻辑,比如从target_message.embeds[0].url获取图片链接。
  • on_raw_reaction_add的payload对象包含了反应的所有关键信息,比on_reaction_add更灵活,适合处理全场景的反应事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:14:06