Discord机器人GPT斜杠命令报错:NotFound 404(10062) Unknown interaction
Discord机器人GPT斜杠命令出现Unknown interaction错误的解决方法
问题场景
我编写了一段Discord机器人的GPT斜杠命令代码,具体实现如下:
@bot.tree.command(description="create a txt with chat-gpt") async def gpt(interaction: discord.Interaction, *, prompt:str): async with aiohttp.ClientSession() as session: payload = { "model":"text-davinci-003", "prompt":prompt, "temperature": 0.5, "max_tokens": 50, "presence_penalty": 0, "frequency_penalty": 0, "best_of": 1, } headers = {"Authorization": f"Bearer {API_KEY}"} async with session.post("https://api.openai.com/v1/completions", json=payload, headers=headers) as resp: response = await resp.json() em = discord.Embed(title="Chat gpt’s responce:", description=response) await interaction.response.defer() await asyncio.sleep(delay=0) await interaction.followup.send(embed=em)
执行该命令时触发如下错误:
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/haoroux/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call await command._invoke_with_namespace(interaction, namespace) File "/home/haoroux/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) File "/home/haoroux/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'gpt' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
我尝试过调整延迟、将embed参数放入response.defer()、覆盖embed等方法,但问题仍未解决。
问题原因与修复方案
核心原因
Discord要求斜杠命令必须在3秒内给出初始响应(包括defer操作),否则会判定交互超时,后续的followup.send就会触发Unknown interaction错误。你的代码是先调用OpenAI API获取结果,再执行defer,这时候大概率已经超过了3秒的时间窗口。
修复步骤
- 优先执行defer操作:函数开头就调用
await interaction.response.defer(),先告诉Discord“正在处理,稍后返回结果”,抢占3秒时间窗口。 - 修复响应内容格式化:原代码把字典格式的
response直接塞到Embed的description里会显示异常,需要提取choices[0].text字段并做格式处理。 - 删除无用sleep:
await asyncio.sleep(delay=0)完全没必要,直接删掉即可。
修复后的代码:
@bot.tree.command(description="create a txt with chat-gpt") async def gpt(interaction: discord.Interaction, *, prompt: str): # 第一步:立即延迟响应,避免超时 await interaction.response.defer() async with aiohttp.ClientSession() as session: payload = { "model": "text-davinci-003", "prompt": prompt, "temperature": 0.5, "max_tokens": 50, "presence_penalty": 0, "frequency_penalty": 0, "best_of": 1, } headers = {"Authorization": f"Bearer {API_KEY}"} async with session.post("https://api.openai.com/v1/completions", json=payload, headers=headers) as resp: response = await resp.json() # 提取并格式化OpenAI的响应内容 if "choices" in response and len(response["choices"]) > 0: gpt_response = response["choices"][0]["text"].strip() else: gpt_response = "请求失败,请检查API密钥或网络连接。" # 创建Embed并发送后续响应 em = discord.Embed(title="Chat GPT的响应:", description=gpt_response) await interaction.followup.send(embed=em)
额外注意事项
- 确保OpenAI API密钥有效且有足够调用额度。
- 如果OpenAI API调用耗时较长,可以在
defer时添加ephemeral=True,让后续响应仅对命令发起者可见,避免其他用户等待。
内容的提问来源于stack exchange,提问作者Pandaroux 1400
相关产品推荐
相关产品推荐

