Search code examples
pythondiscord.py

How can I change parameters of slash command?


I am using discord.py. For example, if there is a command named "/food" If user use "/food asian" There is a new parameter. The new parameter includes "korean", "japanese", "chinese" And if user use "/food european" There is a new parameter that includes "german", "french", "english" How can I change parameters of slash command?


Solution

  • What you are trying to do is impossible. The way that slash commands are registered in discord do not allow for parameters to be changed on the go. However, we can do something a little different that allows us to do something very similar.

    What the following approach does is take the user's first input and return a select menu where they can select their second response. This means that you can tie a different view to a different response (However, in the example I used the same view twice, you can of course use a different view for each response so that you can give the user more options).

    Here's an example:

    # --- Imports ---
    import discord
    import os
    from discord import app_commands
    from discord.ui import Select
    
    intents = discord.Intents.default()
    bot = discord.Client(intents=intents)
    tree = app_commands.CommandTree(bot)
    
    # --- Sync Commands ---
    @bot.event
    async def on_ready():
        await tree.sync()
        print('tree synced')
    
    # --- View used later to select the food's country or something ---
    class View(discord.ui.View):
        @discord.ui.select(cls=Select, options=[discord.SelectOption(label=x, value=x) for x in ['France', 'other_country', 'other_other_country']])
        async def select_country(self, interaction: discord.Interaction, select):
            return await interaction.response.send_message(f'You selected {select.values[0]}')
    
    # --- Command to select food ---
    @tree.command()
    @app_commands.choices(food=[
        app_commands.Choice(name="Choice_one", value="1"),
        app_commands.Choice(name="Choice_two", value="2")
    ])
    async def testing_options(ctx, food: app_commands.Choice[str]):
        # Return view
        if food == "1":  # If the food selected is the first choice
            await ctx.response.send_message('Hello', view=View())
        else:  # If the food is the second choice
            await ctx.response.send_message('Hello2', view=View())  # I used the same view twice, but if you want a different select menu, use another view
    

    This is what the output is:

    When running the command:

    Choices

    When inputting something not there:

    Inputting something invalid doesn't work (which is good)

    When you input something valid:

    Input returns message with view

    When you select something in the view's select menu:

    Seleting returns the select's text which means it worked

    Documentation used