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

Pycord报错Unknown Interaction(404错误10062)求助

问题排查与修复

核心错误原因

你遇到的Unknown interaction(404)主要是Discord交互响应超时导致的:Discord要求所有斜杠命令必须在3秒内给出初始响应(比如defer),但你的代码先执行耗时的imageio.mimsave生成视频,再去调用defer,这时候已经超过3秒,Discord会把该交互标记为失效,后续的followup请求自然会返回404。

另外代码里还有几个明显问题:

  • 用了asyncio.sleep(10)而非await asyncio.sleep(10),这会造成同步阻塞,拖慢机器人响应速度,进一步加剧超时问题。
  • ani_frames和plt未定义或导入,运行时会先触发NameError中断流程。
  • 生成的视频文件没有清理,会残留占用磁盘空间。

修复后的代码

import discord
from discord.ext import commands, tasks
import imageio
import os
import numpy as np
import asyncio
# 补充导入matplotlib模块(假设你用它生成动画帧)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

@stocks.command(name="graph", description="Generate and display a stock price history graph")
async def graph(self, interaction: discord.Interaction, symbol: str):
    # 第一步:立即发送defer响应,确保在3秒内通知Discord我们需要处理时间
    await interaction.response.defer(ephemeral=False)  # ephemeral设为True则仅请求用户可见
    
    try:
        # 这里替换为你的实际股票数据获取与帧生成逻辑
        # 示例:生成模拟的股票价格动画帧
        fig, ax = plt.subplots()
        x = np.linspace(0, 30, 300)
        y = np.random.randn(300).cumsum()  # 模拟股价波动
        ani_frames = []
        
        for i in range(30):
            ax.clear()
            ax.plot(x[:i*10], y[:i*10], color='#2ecc71')
            ax.set_title(f"{symbol.upper()} 价格走势")
            ax.set_xlabel("时间")
            ax.set_ylabel("价格")
            # 将当前绘图帧转为数组
            fig.canvas.draw()
            frame = np.array(fig.canvas.renderer.buffer_rgba())
            ani_frames.append(frame)
        
        video_path = "temp_stock_graph.mp4"
        # 生成视频文件
        imageio.mimsave(video_path, ani_frames, fps=8)
        
        # 短暂等待确保文件写入完成(可选,视生成速度调整)
        await asyncio.sleep(1)
        
        # 发送生成的视频
        await interaction.followup.send(file=discord.File(video_path))
        
    except Exception as e:
        # 出错时给用户反馈
        await interaction.followup.send(f"图表生成失败:{str(e)}")
    finally:
        # 强制关闭所有绘图窗口,释放资源
        plt.close('all')
        # 删除临时视频文件
        if os.path.exists(video_path):
            os.remove(video_path)

关键修复点

  • 提前触发defer:把await interaction.response.defer()放在所有耗时操作之前,确保在3秒内给Discord初始响应。
  • 正确使用异步sleep:替换asyncio.sleep为await asyncio.sleep,避免同步阻塞机器人的事件循环。
  • 补充依赖与变量定义:导入matplotlib相关模块,补充动画帧的生成逻辑(你需要替换为实际的股票数据处理代码)。
  • 资源清理与异常处理:用finally块清理临时文件和绘图资源,捕获异常并通知用户,避免机器人崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:34:50