Search code examples
discorddiscord.pybots

How do I create an optional list of choices in a discord slash command?


I am creating a game using a discord bot and am in the process of switching to slash commands. I am trying to create a command to inspect an item (as in an in-game item e.g. "iron ore") and I want the player to be able to choose from a list of all items in the game while using the inspect command. I'd imagine it would look like this: /inspect iron_ore, where the iron_ore is an item select from a list. I have successfully implemented selecting from a list of members in a command, but I do not know how to get a selectable list from other sources.

In the snippet below, I have a database query that gets all of the items in the game and returns them in a list. Additionally, how can I make this optional? I would like the /inspect command to work even if the player doesn't input an item.

db_query = get_all_items_in_db()

@tree.command(name = "inspect", description = "Examine an item in more detail")
@app_commands.describe(item = "Select an item to inspect")
async def self(interaction: discord.Interaction, item: str):
await interaction.response.send_message(f"You inspect {item}!")

I've tried passing the database query into @app_commands.choices, but it does not accept lists as a datatype.


Solution

  • To make an argument optional, you can type annotate it as - very unsurprisingly - Optional. Alternatively, giving it a default value will work as well.

    To dynamically populate the suggestions shown to a user (I think this is what you want) you can use an autocomplete. There's an example in the docs: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=autocomplete#discord.app_commands.autocomplete

    Note that when using an autocomplete the user can only select one item, and they aren't forced to choose anything. These are only suggestions, and they can type in whatever they want.

    If you don't want that, then there's also an official example for how to create select menus ("dropdowns"): https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py