Search code examples
pythondiscordpycord

How do I make an optional parameter in a slash command (Pycord)


I have a slash command in my Pycord bot. Here is the code:

@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name):
    await ctx.send('Hello ' + name + '!')

How would I make "name" an optional parameter? I tried setting name=None, but it doesn't work.


Solution

  • There are a couple of ways to do this. The first way is the easiest and laziest way which is just setting the parameter to a default value as such:

    @bot.slash_command(name='greet', description='Greet someone!')
    async def greet(ctx, name=''):
        await ctx.respond(f'Hello {name}!')
    

    The second way that I know of is from the example code in the Pycord repository:

    from discord.commands import Option
    
    @bot.slash_command(name='greet', description='Greet someone!')
    async def greet(ctx, name: Option(str, "Enter your friend's name", required = False, default = '')):
        await ctx.respond(f'Hello {name}!')
    

    EDIT:

    await ctx.send(f'Hello {name}!') was changed to await ctx.respond(f'Hello {name}!') because discord requires a response from a slash command otherwise discord will show an ugly error message saying that there was no response.

    UPDATE:

    As of June 2022, you can write your slash commands with the default parameter value expressed in the decorator:

    @bot.slash_command(name='greet', description='Greet someone!')
    @option(
        "name", 
        description="Enter your friend's name",
        required=False,
        default=''
    )
    async def greet(
        ctx: discord.ApplicationContext,
        name: str
    ):
        await ctx.respond(f"Hello {name}!")