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

如何实现Discord Bot检测用户表情反应并发送对应赛事消息?

解决Discord Bot反应检测问题

以下是修正后的代码,实现了检测用户对指定表情的反应并发送对应消息的功能:

import asyncio
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command()
async def tournament(ctx, arg):
    async def tournament_host(ctx):  
        # 发送提示消息并添加自定义表情反应
        message = await ctx.channel.send("React to this message to host either an FFA or 2V2 tournament")
        ffa_emoji = "<:ffa:1197727051898163331>"
        two_v_two_emoji = "<:2v2:1197727046080679996>"
        await message.add_reaction(ffa_emoji)
        await message.add_reaction(two_v_two_emoji)
        
        # 定义反应检查逻辑:仅响应发起命令的用户,且是指定的两个表情之一
        def check(reaction, user):
            return user == ctx.author and str(reaction.emoji) in [ffa_emoji, two_v_two_emoji]
        
        try:
            # 等待用户添加反应,超时时间设置为60秒(可根据需求调整)
            reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
            
            # 根据用户选择的表情发送对应消息
            if str(reaction.emoji) == ffa_emoji:
                await ctx.channel.send("You are hosting an FFA tournament")
            else:
                await ctx.channel.send("You are hosting a 2v2 tournament")
                
        except asyncio.TimeoutError:
            # 超时后发送提示(可选,可根据需求删除或修改)
            await ctx.channel.send("Tournament hosting timed out. Please run the command again.")
    
    if arg.lower() == "host":
        await tournament_host(ctx)

# 替换为你的Bot令牌
bot.run("YOUR_BOT_TOKEN")

关键修改说明:

  • 移除了原代码中冗余的ctx.channel.send(message)语句(消息已通过await ctx.channel.send(...)发送)。
  • 添加了check函数,确保仅处理发起命令的用户对指定表情的反应,避免无关操作触发响应。
  • 使用bot.wait_for('reaction_add')监听用户的反应事件,并设置超时时间防止Bot无限等待。
  • 通过try-except块处理超时场景,提升用户体验。
  • 明确区分不同表情对应的响应消息,实现需求功能。

注意事项:

  • 确保已导入asyncio模块,否则会出现TimeoutError未定义的错误。
  • 确保Bot的Intents已开启message_content和reactions权限,否则无法接收消息和反应事件。
  • 替换代码中的YOUR_BOT_TOKEN为你自己的Discord Bot令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:42:52