discord.py v2.0帮助反应菜单响应所有未超时消息bug求解
discord.py 帮助菜单多消息反应串扰bug修复方案
问题根因
- 你的反应事件校验逻辑只限制了触发用户和表情类型,没有绑定当前命令生成的帮助消息ID
- discord.py的
wait_for("reaction_add")会监听全局的反应添加事件,所有未超时的监听实例都会收到事件推送,只要满足校验规则就会执行后续逻辑,导致不同命令生成的帮助消息的反应互相触发。
修复方法
- 修改校验函数
check,新增反应所属消息的ID校验,确保只有当前帮助消息的反应会被处理 - 删除冗余的
if messageid == ctx.message.id判断(该判断永远为真,无实际作用) - 优化异常捕获逻辑,仅捕获超时异常,避免吞掉其他运行错误
- 超时后可清空帮助消息的反应,避免用户继续点击无响应的按钮
关键修改代码
# 此处删除冗余的 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
相关产品推荐
相关产品推荐

