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

如何实现Discord机器人仅监听指定消息的表情反应来分配角色

实现方案

核心逻辑

你猜测的通过消息ID比对的方案是可行的,reaction对象本身携带message属性,可直接获取关联消息的ID,只需在校验规则中增加ID匹配的判断即可。

两种实现方式

方式1:更适合多用户场景的事件监听写法(推荐)

原来的wait_for只会触发一次,仅能给第一个添加反应的用户分配角色,无法适配多用户使用,推荐拆分逻辑到独立的反应监听事件:

# 全局变量存储目标规则消息的ID
target_rule_msg_id = None

@client.event
async def on_ready():
    global target_rule_msg_id
    cid = client.get_guild(#################) # 替换为你的服务器ID
    channel = client.get_channel(#################) # 替换为规则通知频道ID

    # 发送规则消息并记录ID
    rule_msg = await channel.send("React if you agree, and gain access to the server")
    target_rule_msg_id = rule_msg.id
    await rule_msg.add_reaction('☑️')

@client.event
async def on_reaction_add(reaction, user):
    # 跳过机器人自身的反应
    if user.bot:
        return
    # 同时校验表情符号、关联消息ID两个条件
    if reaction.emoji == '☑️' and reaction.message.id == target_rule_msg_id:
        role = discord.utils.get(reaction.message.guild.roles, name="member")
        await user.add_roles(role)

方式2:修改原有wait_for的校验逻辑

如果你不需要支持多用户触发,只需调整原有wait_for的check参数即可:

# 仅需在原来的check逻辑中增加消息ID比对即可
reaction, user = await client.wait_for(
    'reaction_add', 
    check=lambda reaction, user: reaction.emoji == '☑️' and reaction.message.id == message.id
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:45:03