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

discord.py指定频道用户提及次数统计及超时报错排查

解决Discord.py统计用户提及次数超时的问题

问题分析

你碰到的discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction错误,本质是Discord要求交互类命令必须在2-3秒内返回响应,而你的代码遍历频道全部历史消息(limit=None)耗时过长,导致交互超时被Discord服务器判定为无效。

修复方案

核心思路是先发送一个即时响应满足Discord的超时要求,再在后台异步统计数据,完成后编辑原消息更新结果。

修改后的代码示例

async def testcommand(self, context: Context, user: discord.Member, channel: discord.TextChannel) -> None:
    # 先发送加载提示,快速响应交互
    loading_embed = discord.Embed(
        title="**统计中...**",
        description="正在计算用户被提及次数,请稍候",
        color=0x9C84EF
    )
    msg = await context.send(embed=loading_embed)

    # 后台执行统计逻辑
    mention_count = 0
    async for message in channel.history(limit=None):
        if user in message.mentions:
            mention_count += 1

    # 统计完成后更新消息内容
    result_embed = discord.Embed(
        title="**统计结果:**",
        description=f"{user.mention} 在 {channel.mention} 中共被提及 {mention_count} 次",
        color=0x9C84EF
    )
    await msg.edit(embed=result_embed)

额外优化方向

  • 添加进度反馈:如果频道消息量极大,可以每遍历固定数量的消息就更新一次加载提示,让用户感知任务进度
  • 缓存统计结果:将统计结果存入数据库或本地文件,避免重复遍历历史消息,提升后续查询效率
  • 支持时间范围筛选:允许用户指定统计的时间区间(比如近7天),减少需要遍历的消息量,缩短统计耗时

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:20:31