slash commands not working with openai with discod bot

Question:

I have this command on my personnal bot that generates a image based on a discord users prompt but when i make it into a slash command, there is an error, i have done tests and the image is fine but it never sends the image back

working code

@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)

non working code

@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)  

Console

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

example of command

Example of working slash command in code

@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)

image of working code

i tried running both commands and everthing work on both exept for the returning of the slash command’s image

full code

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'))
Asked By: Hoadi605

||

Answers:

Try below:

@slash.slash(name="gen")
async def gen(ctx: SlashContext, *, 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)
Answered By: nub_discordDev

You have to respond to an interaction within 3 seconds, or the command will fail. If it takes longer to respond because you’re doing something slow/intensive – like you generating images using AI, or API calls – you can defer. Deferring tells Discord "I’ve received the interaction, but I’ll respond later".

Note: this codeblock is for discord.py, not discord_slash as I’ve never used it. However, the idea is the exact same & you’ll just have to look the function names up in the docs.

# Deferring should be the FIRST thing you do
await interaction.response.defer()

here_be_slow_thing()

# Respond when your computation is complete
await interaction.followup.send_message("...")

PS. there’s no need to use discord_slash or any of that stuff, interactions and slash commands are built-in to discord.py and you’ll find a lot more docs/examples/help for the official solution.

Answered By: stijndcl
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.