discorddiscord.pydiscord-interactions

How to make a discord.py slash command option be optional and not required?


I've been working on my discord bot for quite some time, I've been working on a economy system. And need to make a 'user' option, but need to make this optional so the user can just do '/balance' instead of entering there username.

I've searched about every single possible thing I can, stack overflow, google, etc.

@client.tree.command(name="balance", description="Check the balance of yourself or another user")
@app_commands.describe(user="Who's balance do you want to check?")
async def balance(interaction: discord.Interaction, user: discord.Member):
    if user == None:
        user = interaction.user
    await interaction.response.send_message(user.display_name)

is my code.


Solution

  • Discord.py optional interaction parameter

    You can achieve this using Optional from the typing lib.

    from typing import Optional
    
    ...
    
    @client.tree.command(name="balance", description="...")
    @app_commands.describe(user="Who's balance do you want to check?")
    async def balance(interaction: discord.Interaction, user: Optional[discord.Member]): # Use Optional on your discord.Member
        if user == None:
            user = interaction.user
        await interaction.response.send_message(user.display_name)
    
    ...