如何用discord.py编写Reaction Bot,检测对勾表情后向用户发送DM
Python实现Discord反应触发私信机器人方案
前置准备
- 安装依赖库:执行命令
pip install discord.py - 前往Discord开发者后台的机器人设置页,开启Privileged Gateway Intents下的
Server Members Intent、Message Content Intent、Guild Reactions Intent三个权限开关
完整可运行代码
import discord from discord.ext import commands # 配置机器人网关意图,必须开启反应相关的意图 intents = discord.Intents.default() intents.members = True intents.message_content = True intents.reactions = True # 初始化机器人,命令前缀可自定义,这里用!为例 bot = commands.Bot(command_prefix="!", intents=intents) # 机器人启动完成的提示 @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 监听用户添加表情反应的事件,用raw版本可支持未缓存的历史消息 @bot.event async def on_raw_reaction_add(payload): # 排除机器人自己添加的反应 if payload.user_id == bot.user.id: return # 判断添加的反应是否为✅对勾表情 if str(payload.emoji) == "✅": # 获取触发反应的用户对象 user = await bot.fetch_user(payload.user_id) try: # 向用户发送私信 await user.send("Nice to know you checked the message thanks") except discord.Forbidden: # 处理用户关闭了陌生人私信的情况,可根据需要添加服务器内提醒逻辑 print(f"无法向用户 {user.name} 发送私信,对方未开启陌生人私信权限") # 填入你自己的机器人Token运行 bot.run("你的机器人Token")
功能说明
你提到的示例场景逻辑已在上述代码中实现:
机器人发送的任意消息,只要用户添加✅反应,就会自动触发私信发送,效果如下:
如果你需要限制仅对机器人发送的消息触发反应,可以在判断表情的代码前添加如下逻辑:
# 获取反应对应的消息对象 channel = await bot.fetch_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) # 仅当消息是机器人发送的才继续执行 if message.author.id != bot.user.id: return
内容的提问来源于stack exchange,提问作者Secretcode
相关产品推荐
相关产品推荐

