Search code examples
pythondiscordpycord

How to generate images in discord bot through slash commands in pycord?


I am facing problem in copying the prompt from the slash command

@bot.slash_command(name = 'generate', description='Generate any image')
async def generate(message, imageprompt: Option(str, description="The prompt to generate", required = True)):
    await message.channel.trigger_typing() #shows that the bot is typing 
    prompt = message.summary(imageprompt)
    image_url = await generate_image(prompt)
    try:
        await message.respond(image_url) #responds to the slash command (bot must respond within 3 seconds)
    except:
        await message.send(image_url) #sends as a regular message, if it cannot send as a slash command 

here in the 4th line how do i make the bot capable of copying the text from imageprompt and generate the image according to that? I have the generate image coded previously but i cant figure it out in case of slash commands of how to generate the image according to the user provided context

I tried using other syntax like message.content,message.summary none of them work i tried googling but found no answer


Solution

  • The first argument given to the slash command is a discord.ApplicationContext object. This is context so thats why its commonly named ctx.

    The line await ctx.defer() makes the bot do the "bot is thinking" loading so you can still respond if the image took a while to generate.

    prompt is the value given by the users and is asked for when you run the slash command"

    And finally to respond to the message i use ctx.respond

    @bot.slash_command(name="generate", description="Generate any image")
    async def generate(
        ctx: discord.ApplicationContext,
        prompt: Option(str, description="The prompt to generate", required=True),
    ):
        await ctx.defer()
        image_url = await generate_image(prompt)
        await ctx.respond(image_url)
    

    This code should work provided that the generate_image function you made works.