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

Discord机器人Slash命令调用OpenAI生成图片后无法发送问题排查

Discord Slash命令调用OpenAI生成图片后无法发送,报错Unknown interaction

开发的Discord机器人中,前缀命令能正常调用OpenAI生成并发送图片,但转为Slash命令后,虽然控制台能打印有效图片URL,却无法发送到频道,报错discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction。


正常运行的前缀命令代码

@client.command(aliases=['gen'])
async def genimage(ctx, *, ideel):
    print("reg: " + ideel)
    response = openai.Image.create(
    prompt=ideel,
    n=1,
    size="1024x1024")
    image_url = response['data'][0]['url']
    print(image_url)
    print(" ")
    await ctx.send(image_url)

异常的Slash命令代码

@slash.slash(name="gen")
async def gen(ctx, *, ideasl):
    print("slash: " + ideasl)
    response = openai.Image.create(
    prompt=ideasl,
    n=1,
    size="1024x1024")
    image_urll = response['data'][0]['url']
    print(image_urll)
    print(" ")
    await ctx.send(image_urll)  

控制台输出

reg: dog cat
https://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-6mmEETlF8a5bA7B4hUI46nSE.png?st=2022-11-12T14%3A22%3A00Z&se=2022-11-12T16%3A22%3A00Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-11-11T23%3A38%3A17Z&ske=2022-11-12T23%3A38%3A17Z&sks=b&skv=2021-08-06&sig=6MuyNRj6MDOalZLJOD9/1TwX2KbJAJJSCsMvRqgaC5c%3D
 
slash: dog cat
https://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-bUNRJwcIjhFcYf3xywxE96Aw.png?st=2022-11-12T14%3A22%3A31Z&se=2022-11-12T16%3A22%3A31Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-11-12T03%3A02%3A46Z&ske=2022-11-13T03%3A02%3A46Z&sks=b&skv=2021-08-06&sig=cAOqhtWoe5VIq0ITY0%2BPhBRUZb%2BsLj%2BVy%2BarZe9OHsk%3D
 
An exception has occurred while executing command `gen`:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/client.py", line 1352, in invoke_command
    await func.invoke(ctx, **args)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/model.py", line 210, in invoke
    return await self.func(*args, **kwargs)
  File "main.py", line 42, in gen
    await ctx.send(image_urll)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py", line 256, in send
    await self._http.post_initial_response(json_data, self.interaction_id, self._token)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 243, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

可用Slash命令示例

@slash.slash(name="modapp")
async def enbed(ctx: SlashContext):
    embed = Embed(title="Mod Applications.", url="https://www.youtube.com/watch?v=QB7ACr7pUuE", description="Click above to apply for mod.")
    await ctx.send(embed=embed)

完整项目代码

import discord
import random
import os
import openai
import json
import math
from discord.ext import commands, tasks
from itertools import cycle
from random import choice
from math import pi
from keep_alive import keep_alive
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext
openai.api_key = os.getenv("teken")
openai.Model.list()

client = commands.Bot(command_prefix = '+',intents=Intents.default())
status = cycle(['with life','with death'])
slash = SlashCommand(client, sync_commands=True)

#slash commands
@slash.slash(name="modapp")
async def enbed(ctx: SlashContext):
    embed = Embed(title="Mod Applications.", url="https://www.youtube.com/watch?v=QB7ACr7pUuE", description="Click above to apply for mod.")
    await ctx.send(embed=embed)

@slash.slash(name="sus")
async def simp(ctx: SlashContext):
    image="index.jpg"
    await ctx.send(file=discord.File(image))   

@slash.slash(name="gen")
async def gen(ctx, *, ideasl):
    print("slash: " + ideasl)
    response = openai.Image.create(
    prompt=ideasl,
    n=1,
    size="1024x1024")
    image_urll = response['data'][0]['url']
    print(image_urll)
    print(" ")
    await ctx.send(image_urll)  

#events
@client.event
async def on_ready():
    change_status.start()
    print('We have logged in as {0.user}'.format(client))
    print(" ")

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please Put In The Required Argument!')
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send("Don't cheat the System Please!")

#tasks
@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))

#commands
@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(client.latency * 1000)}ms')

@client.command()
async def hello(ctx):
    await ctx.send('Hi!')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ['Definitely', 'Maybe', 'Absolutely Not']
    await ctx.send(f'Question: {question}\nAwnswer: {random.choice(responses)}')
    print (f'Question: {question}')
    print(" ")

@client.command(aliases=['gen'])
async def genimage(ctx, *, ideel):
    print("reg: " + ideel)
    response = openai.Image.create(
    prompt=ideel,
    n=1,
    size="1024x1024")
    image_url = response['data'][0]['url']
    print(image_url)
    print(" ")
    await ctx.send(image_url)


@client.command()
async def roll(ctx, *, dicesize):
    await ctx.send(f'You rolled a d{dicesize}\nYou got a {random.randint(1,int(dicesize))}')

@client.command()
async def calculator(ctx):
    await ctx.send('https://replit.com/@Hoadi605/Calculator#main.py')

@client.command()
async def testss(ctx):
    await ctx.send('this was a rickroll')

@client.command()
async def idea(ctx, *,idean):
    ideeees = open('ideaas.txt', 'a+')
    ideeees.write(f'{idean}\n')
    ideeees.close

@client.command()
async def ideas(ctx):
    ideeees = open('ideaas.txt', 'r')
    cheeese = ideeees.read()
    await ctx.send(cheeese)
    ideeees.close

@client.command()
async def pylearn(ctx):
    await ctx.send('https://www.youtube.com/watch?v=rfscVS0vtbw&t=615s')

#MOVE
@client.command()
async def start_move(ctx):
    move_them.start()

@client.command()
async def stop_move(ctx):
    move_them.stop()

@tasks.loop(seconds=10)
async def move_them():
    await client.move_member(next('336185999824650242', '801605503250595844'))

keep_alive()
client.run(os.getenv('TOKEN'))

问题原因与解决方法

原因

Discord的Slash命令要求在3秒内返回初始响应,而调用OpenAI生成图片的过程耗时通常超过3秒,导致交互超时失效,触发Unknown interaction错误。前缀命令没有这个时间限制,所以可以正常运行。

解决方法

先发送初始响应保持交互活跃,生成图片后再编辑初始响应替换为图片URL:

修改后的Slash命令代码:

@slash.slash(name="gen")
async def gen(ctx: SlashContext, *, ideasl):
    print("slash: " + ideasl)
    # 发送初始响应,延长交互有效期
    initial_msg = await ctx.send("正在生成图片,请稍候...")
    
    response = openai.Image.create(
        prompt=ideasl,
        n=1,
        size="1024x1024"
    )
    image_urll = response['data'][0]['url']
    print(image_urll)
    print(" ")
    
    # 编辑初始响应,替换为图片URL
    await initial_msg.edit(content=image_urll)

同时注意给Slash命令的ctx指定SlashContext类型,和其他可用命令保持一致,避免潜在类型问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:20:32