Command

In Flask-Discord-Interactions, commands are created with a declarative syntax that should be familiar to users of Discord.py.

Slash Commands

Commands are created using the DiscordInteractions.command() decorator.

Here is a basic command:

@discord.command()
def ping(ctx):
    "Respond with a friendly 'pong'!"
    return "Pong!"

The ctx parameter is a Context object. For more information about it, see Context.

Options can be provided as parameters to this command. See Options for details.

The function must return either a string or a Message object. For more information about what kind of responses are valid, see Message Models.

User Commands

User Commands are created using the DiscordInteractions.command() decorator. The type needs to be specified using the ApplicationCommandType.USER.

Here is a basic command:

@discord.command(type=ApplicationCommandType.USER)
def userCmd(ctx):
    return "something"

Options and Description cannot be provided.

Message Commands

User Commands are created using the DiscordInteractions.command() decorator. The type needs to be specified using the ApplicationCommandType.MESSAGE.

Here is a basic command:

@discord.command(type=ApplicationCommandType.MESSAGE)
def msgCmd(ctx):
    return "something"

Options and Description cannot be provided.

Advanced Usage

If you use the options parameter of the DiscordInteractions.command() decorator to specify options manually, then it will override the options inferred from the function arguments and type annotation. You can use this to, for instance, route multiple subcommands with different options to the same function. This isn’t the recommended approach, but it is supported by the API.

@discord.command(options=[
    {
        "name": "google",
        "description": "Search with Google",
        "type": CommandOptionType.SUB_COMMAND,
        "options": [{
            "name": "query",
            "description": "Search query",
            "type": CommandOptionType.STRING,
            "required": True
        }]
    },
    {
        "name": "bing",
        "description": "Search with Bing",
        "type": CommandOptionType.SUB_COMMAND,
        "options": [{
            "name": "query",
            "description": "Search query",
            "type": CommandOptionType.STRING,
            "required": True
        }]
    },
    {
        "name": "yahoo",
        "description": "Search with Yahoo",
        "type": CommandOptionType.SUB_COMMAND,
        "options": [{
            "name": "query",
            "description": "Search query",
            "type": CommandOptionType.STRING,
            "required": True
        }]
    }
])
def search(ctx, subcommand, *, query):
    "Search the Internet!"
    quoted = urllib.parse.quote_plus(query)
    if subcommand == "google":
        return f"https://google.com/search?q={quoted}"
    if subcommand == "bing":
        return f"https://bing.com/search?q={quoted}"
    if subcommand == "yahoo":
        return f"https://yahoo.com/search?q={quoted}"

As you can see, this approach is extremely verbose, so it isn’t recommended.

The arguments passed to the function are:

  • First positional argument: The Context object.

  • Additional positional arguments: Subcommand group (if present), followed by subcommand (if present).

  • Keyword arguments: The options passed to the command.

Full API

class flask_discord_interactions.Command(command: Callable, name: str, description: str, *, options: List[Option], annotations: Dict[str, str], type: int = 1, default_member_permissions: int = None, dm_permission: bool = None, name_localizations: Dict[str, str] = None, description_localizations: Dict[str, str] = None, discord: DiscordInteractions = None)

Represents an Application Command.

command

Function to call when the command is invoked.

Type:

Callable

name

Name for this command (appears in the Discord client). If omitted, infers the name based on the name of the function.

Type:

str

name_localizations

Localization dictionary for name field.

Type:

Dict[str, str]

description

Description for this command (appears in the Discord client). If omitted, infers the description based on the docstring of the function, or sets the description to “No description”, if ApplicationCommandType is CHAT_INPUT, else set description to None.

Type:

str

description_localizations

Localization dictionary for description field.

Type:

Dict[str, str]

options

Array of options that can be passed to this command. If omitted, infers the options based on the function parameters and type annotations.

Type:

List[Option]

annotations

Dictionary of descriptions for each option provided. Use this only if you want the options to be inferred from the parameters and type annotations. Do not use with options. If omitted, and if options is not provided, option descriptions default to “No description”.

Type:

Dict[str, str]

type

Type for this command (depend on the action in the Discord client). The value is in ApplicationCommandType. If omitted, set the default value to ApplicationCommandType.CHAT_INPUT.

Type:

int

default_member_permissions

A permission integer defining the required permissions a user must have to run the command

Type:

int

dm_permission

Indicates whether the command can be used in DMs

Type:

bool

discord

DiscordInteractionsBlueprint instance which this Command is associated with.

Type:

DiscordInteractions

autocomplete()

Register an autocomplete handler function for this command.

Use as a decorator, e.g.

@app.command("test")
def test(ctx, value: str):
    return f"{value}!"

@test.autocomplete()
def autocomplete(ctx, value = None):
    return ["hello", "world"]
dump()

Returns this command as a dict for registration with the Discord API.

make_context_and_run(*, discord: DiscordInteractions, app: Flask, data: dict)

Creates the Context object for an invocation of this command, then invokes itself.

Parameters:
  • discord (DiscordInteractions) – The DiscordInteractions object used to receive this interaction.

  • app (Flask) – The Flask app used to receive this interaction.

  • data (dict) – The incoming interaction data.

Returns:

The response by the command, converted to a Message object.

Return type:

Message

run(context: Context, *args, **kwargs)

Invokes the function defining this command.

Parameters:
  • context (Context) – The Context object representing the current state.

  • *args – Any subcommands of the current command being called.

  • **kwargs – Any other options in the current invocation.

Slash Command Groups

The Discord API treats subcommands as options given to the main command. However, this library provides an alternative way of declaring commands as belonging to a SlashCommandGroup or a SlashCommandSubgroup.

To create a SlashCommandGroup, use the DiscordInteractions.command_group() method:

comic = discord.command_group("comic")


@comic.command()
def xkcd(ctx, number: int):
    return f"https://xkcd.com/{number}/"


@comic.command()
def homestuck(ctx, number: int):
    return f"https://homestuck.com/story/{number}"

You can then use the SlashCommandGroup.command() decorator to register subcommands.

Full API

class flask_discord_interactions.SlashCommandGroup(name, description, *, is_async=False, default_member_permissions=None, dm_permission=None, name_localizations=None, description_localizations=None)

Bases: SlashCommandSubgroup

Represents a Subgroup of slash commands.

name

The name of this subgroup, shown in the Discord client.

Type:

str

name_localizations

A dict of localized names for this subgroup.

Type:

Dict[str, str]

description

The description of this subgroup, shown in the Discord client.

Type:

str

description_localizations

A dict of localized descriptions for this subgroup.

Type:

Dict[str, str]

is_async

Whether the subgroup should be considered async (if subcommands get an AsyncContext instead of a Context.)

Type:

bool

default_member_permissions

Permission integer setting permission defaults for a command

Type:

int

dm_permission

Indicates whether the command can be used in DMs

Type:

int

autocomplete()

Register an autocomplete handler function for this command.

Use as a decorator, e.g.

@app.command("test")
def test(ctx, value: str):
    return f"{value}!"

@test.autocomplete()
def autocomplete(ctx, value = None):
    return ["hello", "world"]
command(name: Optional[str] = None, description: Optional[str] = None, *, name_localizations: Optional[Dict[str, str]] = None, description_localizations: Optional[Dict[str, str]] = None, options: Optional[List[Option]] = None, annotations: Optional[Dict[str, str]] = None)

Decorator to create a new Subcommand of this Subgroup.

Parameters:
  • name (str) – The name of the command, as displayed in the Discord client.

  • name_localizations (Dict[str, str]) – A dict of localized names for the command.

  • description (str) – The description of the command.

  • description_localizations (Dict[str, str]) – A dict of localized descriptions for the command.

  • options (List[Option]) – A list of options for the command, overriding the function’s keyword arguments.

  • annotations (Dict[str, str]) – If options is not provided, descriptions for each of the options defined in the function’s keyword arguments.

dump()

Returns this command as a dict for registration with the Discord API.

make_context_and_run(*, discord: DiscordInteractions, app: Flask, data: dict)

Creates the Context object for an invocation of this command, then invokes itself.

Parameters:
  • discord (DiscordInteractions) – The DiscordInteractions object used to receive this interaction.

  • app (Flask) – The Flask app used to receive this interaction.

  • data (dict) – The incoming interaction data.

Returns:

The response by the command, converted to a Message object.

Return type:

Message

property options

Returns an array of options that can be passed to this command. Computed based on the options of each subcommand or subcommand group.

Returns:

The options for this command.

Return type:

List[Option]

run(context, *subcommands, **kwargs)

Invokes the relevant subcommand for the given Context.

Parameters:
  • context (Context) – The Context object representing the current state.

  • *args – List of subcommands of the current command group being invoked.

  • **kwargs – Any other options in the current invocation.

subgroup(name: str, description: str = 'No description', *, name_localizations: Optional[Dict[str, str]] = None, description_localizations: Optional[Dict[str, str]] = None, is_async: bool = False)

Create a new SlashCommandSubroup (which can contain multiple subcommands)

Parameters:
  • name (str) – The name of the subgroup, as displayed in the Discord client.

  • name_localizations (Dict[str, str]) – A dict of localized names for the subgroup.

  • description (str) – The description of the subgroup. Defaults to “No description”.

  • description_localizations (Dict[str, str]) – A dict of localized descriptions for the subgroup.

  • is_async (bool) – Whether the subgroup should be considered async (if subcommands get an AsyncContext instead of a Context.)

Slash Command Subgroups

You can also create subgroups that sit “in between” a SlashCommandGroup and a SlashCommand using the SlashCommandGroup.subgroup() decorator.

base = discord.command_group("base", "Convert a number between bases")

base_to = base.subgroup("to", "Convert a number into a certain base")
base_from = base.subgroup("from", "Convert a number out of a certain base")


@base_to.command(name="bin")
def base_to_bin(ctx, number: int):
    "Convert a number into binary"
    return Message(bin(number), ephemeral=True)


@base_to.command(name="hex")
def base_to_hex(ctx, number: int):
    "Convert a number into hexadecimal"
    return Message(hex(number), ephemeral=True)


@base_from.command(name="bin")
def base_from_bin(ctx, number: str):
    "Convert a number out of binary"
    return Message(int(number, base=2), ephemeral=True)


@base_from.command(name="hex")
def base_from_hex(ctx, number: str):
    "Convert a number out of hexadecimal"
    return Message(int(number, base=16), ephemeral=True)

Full API

class flask_discord_interactions.SlashCommandSubgroup(name: str, description: str, *, name_localizations: Optional[Dict[str, str]] = None, description_localizations: Optional[Dict[str, str]] = None, is_async: bool = False)

Bases: Command

Represents a Subgroup of slash commands.

name

The name of this subgroup, shown in the Discord client.

Type:

str

name_localizations

A dict of localized names for this subgroup.

Type:

Dict[str, str]

description

The description of this subgroup, shown in the Discord client.

Type:

str

description_localizations

A dict of localized descriptions for this subgroup.

Type:

Dict[str, str]

is_async

Whether the subgroup should be considered async (if subcommands get an AsyncContext instead of a Context.)

Type:

bool

autocomplete()

Register an autocomplete handler function for this command.

Use as a decorator, e.g.

@app.command("test")
def test(ctx, value: str):
    return f"{value}!"

@test.autocomplete()
def autocomplete(ctx, value = None):
    return ["hello", "world"]
command(name: Optional[str] = None, description: Optional[str] = None, *, name_localizations: Optional[Dict[str, str]] = None, description_localizations: Optional[Dict[str, str]] = None, options: Optional[List[Option]] = None, annotations: Optional[Dict[str, str]] = None)

Decorator to create a new Subcommand of this Subgroup.

Parameters:
  • name (str) – The name of the command, as displayed in the Discord client.

  • name_localizations (Dict[str, str]) – A dict of localized names for the command.

  • description (str) – The description of the command.

  • description_localizations (Dict[str, str]) – A dict of localized descriptions for the command.

  • options (List[Option]) – A list of options for the command, overriding the function’s keyword arguments.

  • annotations (Dict[str, str]) – If options is not provided, descriptions for each of the options defined in the function’s keyword arguments.

dump()

Returns this command as a dict for registration with the Discord API.

make_context_and_run(*, discord: DiscordInteractions, app: Flask, data: dict)

Creates the Context object for an invocation of this command, then invokes itself.

Parameters:
  • discord (DiscordInteractions) – The DiscordInteractions object used to receive this interaction.

  • app (Flask) – The Flask app used to receive this interaction.

  • data (dict) – The incoming interaction data.

Returns:

The response by the command, converted to a Message object.

Return type:

Message

property options

Returns an array of options that can be passed to this command. Computed based on the options of each subcommand or subcommand group.

Returns:

The options for this command.

Return type:

List[Option]

run(context, *subcommands, **kwargs)

Invokes the relevant subcommand for the given Context.

Parameters:
  • context (Context) – The Context object representing the current state.

  • *args – List of subcommands of the current command group being invoked.

  • **kwargs – Any other options in the current invocation.