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

discord.py实现DM私聊监听反应表情无响应无报错问题求助

故障原因

  • 网关意图(Intents)配置缺失:discord.py v2.0及以上版本默认不启用私聊消息、私聊反应相关的意图,需要在代码和Discord开发者后台同时开启对应权限才能监听到DM场景的反应事件。
  • 原有逻辑存在串行阻塞问题:代码会先等待第一个玩家做出反应后才会给第二个玩家发消息加反应,如果测试时先操作了第二个玩家的消息,会出现无响应的情况。
  • check函数判断逻辑不全:没有绑定消息ID,同一个用户有多条带反应的消息时会出现逻辑混乱。

解决步骤

  1. 先进入Discord开发者后台的机器人设置页,开启Privileged Gateway Intents下的Message Content Intent、Guild Reactions Intent、Direct Messages Reactions Intent权限。
  2. 初始化bot时显式声明需要的意图,示例如下:
import discord
from discord.ext import commands

# 开启必要意图
intents = discord.Intents.default()
intents.message_content = True # 允许读取消息内容
intents.reactions = True # 允许监听反应事件
intents.dm_messages = True # 允许监听私聊消息
intents.dm_reactions = True # 允许监听私聊反应事件

bot = commands.Bot(command_prefix="!", intents=intents)
  1. 修正指令逻辑,改成异步并行处理两个玩家的响应,修正后的完整代码如下:
import asyncio

@bot.command()
async def ping(ctx, user: discord.User):
    if user is None or user == ctx.author:
        return
    players = [ctx.author, user]

    # 封装单玩家处理逻辑,支持并行执行
    async def handle_player(player):
        message = await player.send("test")
        await message.add_reaction('👍')
        await message.add_reaction('👎')

        def check(reaction, reactor):
            return reactor == player and str(reaction.emoji) in ['👍', '👎'] and reaction.message.id == message.id

        try:
            # 加超时防止任务永久挂起,超时时间可自行调整
            reaction, _ = await bot.wait_for("reaction_add", check=check, timeout=300)
            await player.send(str(reaction.emoji))
        except asyncio.TimeoutError:
            await player.send("响应超时,已取消")

    # 同时启动两个玩家的处理任务
    await asyncio.gather(*[handle_player(p) for p in players])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:45:03