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

discord.py v2.0帮助反应菜单响应所有未超时消息bug求解

discord.py 帮助菜单多消息反应串扰bug修复方案

问题根因

  • 你的反应事件校验逻辑只限制了触发用户和表情类型,没有绑定当前命令生成的帮助消息ID
  • discord.py的wait_for("reaction_add")会监听全局的反应添加事件,所有未超时的监听实例都会收到事件推送,只要满足校验规则就会执行后续逻辑,导致不同命令生成的帮助消息的反应互相触发。

修复方法

  1. 修改校验函数check,新增反应所属消息的ID校验,确保只有当前帮助消息的反应会被处理
  2. 删除冗余的if messageid == ctx.message.id判断(该判断永远为真,无实际作用)
  3. 优化异常捕获逻辑,仅捕获超时异常,避免吞掉其他运行错误
  4. 超时后可清空帮助消息的反应,避免用户继续点击无响应的按钮

关键修改代码

# 此处删除冗余的 if messageid == ctx.message.id 判断
def check(reaction, user):
    # 新增 reaction.message.id == message.id 规则,绑定当前命令生成的帮助消息
    return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message.id == message.id

while True:
    try:
        reaction, user = await self.bot.wait_for("reaction_add", timeout=60, check=check)
        if str(reaction.emoji) == "▶️" and cur_page != pages:
            cur_page += 1
            await message.edit(embed = contents[cur_page-1])
            await message.remove_reaction(reaction, user)
        elif str(reaction.emoji) == "◀️" and cur_page > 1:
            cur_page -= 1
            await message.edit(embed = contents[cur_page-1])
            await message.remove_reaction(reaction, user)
        else:
            await message.remove_reaction(reaction, user)
    # 仅捕获超时异常,不要使用裸except吞掉所有运行错误
    except asyncio.TimeoutError:
        # 超时后清空反应、更新页脚提示过期(可选优化)
        await message.clear_reactions()
        timeout_embed = contents[cur_page-1]
        timeout_embed.set_footer(text=f'Page {cur_page}/5 · 帮助菜单已过期')
        await message.edit(embed=timeout_embed)
        # 退出循环结束当前消息的监听
        break

注:如果代码未导入asyncio模块,需要在文件头部添加import asyncio。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:06:03