How to add options to an argument of a slash command in discord.py?

Question:

import discord
from discord import app_commands

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild=discord.Object(id=748244591387607111))
            self.synced = True
        print('---------------------Bot is ready---------------------')

client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(name='test')
async def test(interaction: discord.Interaction, option: str):
    pass

client.run('MYTOKEN')

That’s my code. I want to add an option where I can select between several categories, for example test1 and test2. I don’t want to use an external library like pycord or nextcord, I want to do it in the native discord.py. Not asking for any code, just an example of how I’d go about doing it. Everything I found online was either outdated or used nextcord, so I decided to ask here. Hope someone can help : )

Answers:

Here’s an example of how to specify options for a command parameter:

@tree.command(name='test')
@app_commands.describe(option="This is a description of what the option means")
@app_commands.choices(option=[
        app_commands.Choice(name="Option 1", value="1"),
        app_commands.Choice(name="Option 2", value="2")
    ])
async def test(interaction: discord.Interaction, option: app_commands.Choice[str]):
    pass

To make the option optional, you’d have to import typing and change the type to:

async def test(interaction: discord.Interaction, option: typing.Optional[app_commands.Choice[str]]):
    pass
Answered By: Kelo
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.