You need to enable JavaScript to run this app. Discord.py Asyncio 实现反应分页消息超时功能时报任务异常未检索错误
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py Asyncio 实现反应分页消息超时功能时报任务异常未检索错误

问题根源

报错核心不是except asyncio.TimeoutError捕获逻辑写错,是对asyncio.wait的任务生命周期管理有疏漏:

  • 你同时创建了两个带独立7秒超时的wait_for任务,分别监听反应添加、反应移除事件。
  • 7秒无操作时,第一个触发超时的任务抛出的TimeoutError被你的异常捕获逻辑接住,直接return退出了交互循环;但第二个仍在后台运行的任务,过极短时间后同样会触发超时抛异常,此时已经没有任何逻辑承接这个异常,Python才会打印「Task exception was never retrieved」的提示。
  • 你之前尝试的asyncio.gather写法完全用错:gather需要接收任务对象,不是事件名字符串,自然起不到异常捕获的作用。

修正方案

  • 不要给每个wait_for单独设置超时,把7秒超时逻辑统一放在asyncio.wait的参数里,避免单个任务独立抛异常的情况。
  • 不管任务是正常完成还是触发超时,必须在退出循环前把所有pending状态的任务手动取消,再用带return_exceptions=True的gather接住所有取消流程里抛出的异常,彻底消除未捕获提示。
  • 顺便修复原代码里的几处笔误:循环添加反应时误写的未定义变量r、未初始化的total_pages变量、漏加的消息ID/机器人身份校验(否则其他用户在同频道其他消息上的反应,也可能触发你的分页逻辑)。

修正后可正常运行的代码

embed = await self.get_member_list(ctx, member, page)
msg = await ctx.send(embed=embed)
reactions = ["⬅️", "➡️", "🗑️"]
# 修正原代码笔误:循环遍历预设的反应列表,替换原来的未定义变量r
for emoji in reactions:
    await msg.add_reaction(emoji)
    await asyncio.sleep(0.35)

def check(payload):
    # 补充必要校验:确保反应作用于当前分页消息、且不是机器人自身的操作
    return (
        payload.message_id == msg.id
        and str(payload.emoji) in reactions
        and not payload.member.bot
    )

page = 1
total_pages = # 此处补上你原本计算总页数的逻辑
while True:
    # 创建两个独立的事件监听任务,不单独设置超时
    tasks = [
        asyncio.create_task(self.bot.wait_for('raw_reaction_add', check=check)),
        asyncio.create_task(self.bot.wait_for('raw_reaction_remove', check=check))
    ]
    try:
        # 统一设置7秒超时,首个任务完成即返回
        done, pending = await asyncio.wait(
            tasks,
            timeout=7.0,
            return_when=asyncio.FIRST_COMPLETED
        )
        # 超时触发时done集合为空,直接跳出循环
        if not done:
            break
        # 取出完成的任务拿到反应payload
        payload = done.pop().result()
        user = await commands.MemberConverter().convert(ctx, str(payload.user_id))
    finally:
        # 无论正常完成还是超时,把所有未跑完的任务全部取消
        for task in pending:
            task.cancel()
        # 静默收集所有任务的异常,避免抛出未捕获提示
        await asyncio.gather(*pending, return_exceptions=True)

    # 原有分页交互逻辑保持不变
    if user == ctx.author:
        emoji_str = str(payload.emoji)
        if emoji_str == "🗑️":
            await msg.delete()
            return
        if emoji_str == "⬅️":
            page = total_pages if page == 1 else page - 1
        if emoji_str == "➡️":
            page = 1 if page == total_pages else page + 1
        await msg.edit(embed=await self.get_member_list(ctx, member, page))

方案生效原理

原逻辑的异常漏接问题会被彻底解决:

  • 超时判定由asyncio.wait统一触发,不会有单个任务独立抛TimeoutError漏接的情况。
  • 无论流程是正常完成交互、还是触发超时退出,都会在finally块里把剩余后台任务全部取消,并用gather接住所有取消流程抛出的异常,从根源上消除「Task exception was never retrieved」的提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 02:36:03