Discord机器人交互扩展触发Error404及Ping值异常问题排查
问题排查与解决:Discord机器人/ping命令异常
异常现象
- 正常响应时,返回的3位延迟数值频繁重复(可达3-5次)
- 异常触发时抛出
discord.app_commands.errors.CommandInvokeError错误,附带NotFound: 404 Not Found (error code: 10062): Unknown interaction提示,同时返回长实数延迟
相关代码
bot.py
import discord from discord.ext import commands import logging import os import asyncio from config import settings discord.utils.setup_logging(level=logging.INFO,root=True) bot = commands.Bot(command_prefix = settings['prefix'],intents=discord.Intents.all()) # 由于我们在settings中指定了前缀,因此通过字典的prefix键调用 @bot.event async def on_ready(): synced = await bot.tree.sync(guild=discord.Object(id=1283589491298402314)) print(f'已同步 {len(synced)} 条命令!') print(bot.guilds) async def load(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): if filename != '__init__.py': await bot.load_extension(f"cogs.{filename[:-3]}") async def main(): await load() await bot.start(settings['token']) asyncio.run(main())
Utils.py
import discord from discord.ext import commands from discord import app_commands class UtilsCommand(commands.Cog): def __init__(self,bot:discord.Client): self.bot=bot @app_commands.command(name='ping',description='Check ping') async def ping(self,interaction:discord.Interaction): await interaction.response.defer() await interaction.followup.send(content=f"Pong! ({str(self.bot.latency)[2:5]})") async def setup(bot): await bot.add_cog(UtilsCommand(bot),guild=discord.Object(id=1283589491298402314))
报错回溯
[2024-09-15 00:43:13] [ERROR ] discord.app_commands.tree: Ignoring exception in command 'ping' Traceback (most recent call last): File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\app_commands\commands.py", line 857, in _do_call return await self._callback(self.binding, interaction, **params) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\PyProject\Jack\cogs\Utils.py", line 13, in ping await interaction.response.send_message(content=f"Pong! ({latency})",ephemeral=True) File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\interactions.py", line 855, in send_message await adapter.create_interaction_response( File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\webhook\async_.py", line 221, in request raise NotFound(response, data) discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\app_commands\tree.py", line 1310, in _call await command._invoke_with_namespace(interaction, namespace) File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\PyProject\Jack\.venv\Lib\site-packages\discord\app_commands\commands.py", line 876, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
成因分析与解决方法
问题1:延迟数值频繁重复
成因
- 延迟截取方式有缺陷:
str(self.bot.latency)[2:5]通过字符串截取获取三位数字,若机器人延迟波动极小(比如稳定在0.123-0.125之间),截取结果会频繁重复;同时将秒级延迟直接截取,用户感知不直观。 - 命令重复注册:
on_ready事件每次机器人重启都会同步命令,多次重启会导致同一个/ping命令被注册多次,触发时多次执行响应逻辑,返回重复内容。
解决方法
- 优化延迟显示逻辑,将秒转毫秒并格式化保留三位小数:
@app_commands.command(name='ping',description='Check ping') async def ping(self,interaction:discord.Interaction): latency_ms = round(self.bot.latency * 1000, 3) await interaction.response.send_message(content=f"Pong! ({latency_ms}ms)") - 限制命令仅同步一次,避免重复注册:
修改bot.py中的on_ready事件:bot._synced = False # 新增标记变量 @bot.event async def on_ready(): global bot if not bot._synced: synced = await bot.tree.sync(guild=discord.Object(id=1283589491298402314)) print(f'已同步 {len(synced)} 条命令!') bot._synced = True print(bot.guilds)
问题2:404 Unknown interaction错误
成因
- 交互逻辑不一致:报错回溯显示代码调用了
interaction.response.send_message,但你提供的Utils.py代码用的是defer()+followup.send,说明存在旧代码残留或命令重复注册后,旧逻辑仍在执行,导致同一交互被多次响应。 - 交互超时:即使机器人延迟低,网络波动或Discord API端的延迟可能导致交互在响应前就过期。
解决方法
- 统一交互响应逻辑:若命令逻辑简单(无需异步耗时操作),直接使用
send_message回复,无需defer():@app_commands.command(name='ping',description='Check ping') async def ping(self,interaction:discord.Interaction): latency_ms = round(self.bot.latency * 1000, 3) await interaction.response.send_message(content=f"Pong! ({latency_ms}ms)") - 清理重复命令:进入Discord服务器设置→整合→应用程序,找到你的机器人,删除重复的/ping命令,再重新启动机器人同步。
- 捕获超时异常:添加try-except块处理NotFound错误,避免程序报错:
@app_commands.command(name='ping',description='Check ping') async def ping(self,interaction:discord.Interaction): try: latency_ms = round(self.bot.latency * 1000, 3) await interaction.response.send_message(content=f"Pong! ({latency_ms}ms)") except discord.errors.NotFound: pass
内容的提问来源于stack exchange,提问作者enot_poloskun
相关产品推荐
相关产品推荐

