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
相关产品推荐
相关产品推荐

