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

discord.py机器人如何为Embed消息加反应并响应用户交互

Discord机器人自动添加表情+反应触发逻辑实现

核心修改点

  • 发送Embed后接收返回的消息对象,主动调用接口添加预设表情
  • 新增反应监听事件,过滤无效触发后匹配表情执行对应业务逻辑
  • 提前开启必要的权限意图,否则反应事件无法正常捕获

完整修改后代码

首先初始化客户端时必须开启对应intents,否则无法接收反应相关事件:

import discord

# 配置网关意图,缺少配置会导致反应事件不触发
intents = discord.Intents.default()
intents.reactions = True
intents.messages = True
client = discord.Client(intents=intents)

# 存储所有生效中的召唤Embed消息ID,用于过滤无关消息的反应
active_summon_msg_ids = set()

@client.event 
async def on_message(message):
    # 跳过机器人自身发送的消息避免循环
    if message.author == client.user:
        return
    if message.content.startswith('.summon'):
        embed = discord.Embed(
            title=":crossed_swords:I have been summoned:crossed_swords:", 
            description="to proceed select lvl of your enemy", 
            color=0x00ff00
        )
        embed.add_field(name="Difficulty level :one:", value="suitable for quick xp, or single take down", inline=False)
        embed.add_field(name="Difficulty level :two:", value="higher level enemy, with lots of hp and sweet reward", inline=False)
        embed.add_field(name="Difficulty level :three:", value="almost if not impossible enemy, strongest of them all, suitable only for raids", inline=False)
        # 接收发送完成的消息对象
        summon_msg = await message.channel.send(embed=embed)
        # 将消息ID加入生效集合
        active_summon_msg_ids.add(summon_msg.id)
        # 按顺序添加三个难度对应的表情
        await summon_msg.add_reaction('1️⃣')
        await summon_msg.add_reaction('2️⃣')
        await summon_msg.add_reaction('3️⃣')

@client.event
async def on_reaction_add(reaction, user):
    # 跳过机器人自己添加的反应,防止自触发逻辑
    if user == client.user:
        return
    # 非召唤Embed的反应直接忽略
    if reaction.message.id not in active_summon_msg_ids:
        return
    
    # 匹配表情执行对应难度逻辑
    if str(reaction.emoji) == '1️⃣':
        # 此处填写难度1的业务逻辑,比如生成普通怪物、发放经验等
        await reaction.message.channel.send(f"{user.mention} 选择了难度1,即将生成普通敌人")
    elif str(reaction.emoji) == '2️⃣':
        # 此处填写难度2的业务逻辑
        await reaction.message.channel.send(f"{user.mention} 选择了难度2,即将生成精英敌人")
    elif str(reaction.emoji) == '3️⃣':
        # 此处填写难度3的业务逻辑
        await reaction.message.channel.send(f"{user.mention} 选择了难度3,即将生成团本BOSS")

注意事项

  • 需要到Discord开发者后台的机器人配置页,在「Privileged Gateway Intents」板块打开消息、反应相关的意图开关,否则本地配置intents也无法接收事件
  • 如果不需要某条召唤消息继续响应反应,直接把对应ID从active_summon_msg_ids集合中移除即可
  • 匹配表情时需要将reaction.emoji转为字符串,使用自定义表情时可以直接匹配表情ID或表情对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:30:39