KlangDocs

    Open Klang

    Bots

    View as Markdown

    Slash commands

    Register a bot’s commands with discord.js, discord.py or JDA, globally or for one server, for the message box and for the menu of a person or a message. Options and choices, translations, who sees each command, and the limits.

    Three kinds of command

    A bot registers its commands once, and Klang shows them to people where they belong:

    Kind type Where people find it in Klang
    Slash 1 Typing / at the start of the message box: a list of the commands they can use there.
    User 2 Right click on a person, then Apps. The command gets the person as its target.
    Message 3 Right click on a message, then Apps. The command gets the message as its target.

    Slash commands can take options: text, numbers, yes or no, a person, a channel or a role. Klang checks every value against what the bot registered before the bot sees it, so a number outside its range or a text that’s too long never reaches your code.

    When someone uses a command, your bot gets an interaction and has 3 seconds to answer. That part is in Responding to interactions.

    Register your commands

    Libraries register commands with one request that sends the whole list. Do it when the bot starts, or from a small script you run when the commands change: the list replaces whatever was there, and commands that didn’t change keep their ID.

    This registers /tide, a slash command with three options, and Wave at, a user command:

    import {
      ApplicationCommandType,
      Client,
      ContextMenuCommandBuilder,
      Events,
      GatewayIntentBits,
      InteractionContextType,
      SlashCommandBuilder,
    } from 'discord.js';
    
    const tide = new SlashCommandBuilder()
      .setName('tide')
      .setNameLocalizations({ 'es-ES': 'marea' })
      .setDescription('Show the tide table for a harbor')
      .setDescriptionLocalizations({ 'es-ES': 'Muestra la tabla de mareas de un puerto' })
      .setContexts(InteractionContextType.Guild, InteractionContextType.BotDM)
      .addStringOption((option) =>
        option.setName('harbor').setDescription('Which harbor').setRequired(true).setAutocomplete(true),
      )
      .addIntegerOption((option) =>
        option.setName('days').setDescription('How many days ahead').setMinValue(1).setMaxValue(7),
      )
      .addStringOption((option) =>
        option
          .setName('units')
          .setDescription('Heights in meters or feet')
          .addChoices(
            { name: 'Meters', name_localizations: { 'es-ES': 'Metros' }, value: 'm' },
            { name: 'Feet', name_localizations: { 'es-ES': 'Pies' }, value: 'ft' },
          ),
      );
    
    const waveAt = new ContextMenuCommandBuilder()
      .setName('Wave at')
      .setType(ApplicationCommandType.User);
    
    const client = new Client({
      intents: [GatewayIntentBits.Guilds],
      rest: { api: 'https://api.klang.gg/api' },
    });
    
    client.once(Events.ClientReady, async () => {
      // Global commands: every server the bot is in, and its direct messages.
      await client.application.commands.set([tide.toJSON(), waveAt.toJSON()]);
    });
    
    client.login(process.env.KLANG_BOT_TOKEN);
    import os
    
    import discord
    import yarl
    from discord import app_commands
    
    discord.http.Route.BASE = "https://api.klang.gg/api/v10"
    discord.gateway.DiscordWebSocket.DEFAULT_GATEWAY = yarl.URL("wss://bot-gateway.klang.gg/")
    
    
    class Lighthouse(discord.Client):
        def __init__(self):
            super().__init__(intents=discord.Intents.default())
            self.tree = app_commands.CommandTree(self)
    
        async def setup_hook(self):
            # Global commands: every server the bot is in, and its direct messages.
            await self.tree.sync()
    
    
    client = Lighthouse()
    
    
    @client.tree.command(description="Show the tide table for a harbor")
    @app_commands.describe(
        harbor="Which harbor",
        days="How many days ahead",
        units="Heights in meters or feet",
    )
    @app_commands.choices(
        units=[
            app_commands.Choice(name="Meters", value="m"),
            app_commands.Choice(name="Feet", value="ft"),
        ]
    )
    async def tide(
        interaction: discord.Interaction,
        harbor: str,
        days: app_commands.Range[int, 1, 7] = 1,
        units: app_commands.Choice[str] | None = None,
    ):
        await interaction.response.send_message(f"Tides for {harbor}, {days} day(s) ahead.")
    
    
    @client.tree.context_menu(name="Wave at")
    async def wave_at(interaction: discord.Interaction, member: discord.Member):
        await interaction.response.send_message(f"👋 {member.mention}")
    
    
    client.run(os.environ["KLANG_BOT_TOKEN"])
    // After building the JDA instance as in "Connect your library":
    jda.updateCommands().addCommands(
        Commands.slash("tide", "Show the tide table for a harbor")
            .setNameLocalization(DiscordLocale.SPANISH, "marea")
            .setDescriptionLocalization(DiscordLocale.SPANISH, "Muestra la tabla de mareas de un puerto")
            .setContexts(InteractionContextType.GUILD, InteractionContextType.BOT_DM)
            .addOptions(
                new OptionData(OptionType.STRING, "harbor", "Which harbor", true, true),
                new OptionData(OptionType.INTEGER, "days", "How many days ahead")
                    .setRequiredRange(1, 7),
                new OptionData(OptionType.STRING, "units", "Heights in meters or feet")
                    .addChoice("Meters", "m")
                    .addChoice("Feet", "ft")),
        Commands.user("Wave at")
    ).queue();

    The addresses are the ones in Connect your library: commands need nothing else. We ran the discord.js and discord.py examples against Klang. JDA registers through the same routes, but we haven’t run it against Klang yet.

    Without a library, it’s one PUT with the list:

    Shell
    curl -X PUT "https://api.klang.gg/api/v10/applications/$KLANG_APP_ID/commands" \
      -H "Authorization: Bot $KLANG_BOT_TOKEN" \
      -H "Content-Type: application/json" \
      -d '[{"name": "tide", "description": "Show the tide table for a harbor", "options": [{"type": 3, "name": "harbor", "description": "Which harbor", "required": true}]}]'

    Every route, with its body and answers, is in the commands reference.

    Global or for one server

    Scope Route Where it shows
    Global /applications/{app.id}/commands Every server the bot is in, and its direct messages if contexts allows it.
    One server /applications/{app.id}/guilds/{guild.id}/commands Only that server, never in direct messages.

    Both kinds show up at once: people see a new or changed command the next time they open the list, without restarting anything. A server’s commands need the bot to be in that server; otherwise the route answers 403 with 50001.

    Use server commands while you develop, in a test server of your own, and global commands for what every server gets. If a global and a server command have the same name, people see both.

    The bulk PUT is the safest way to keep the list in step with your code:

    • a command in the list with the same name and type as one already registered keeps its ID;
    • one that isn’t in the list any more is deleted, with its permissions;
    • if nothing changed, nothing is written, and the command keeps its version.

    To change just one command, POST it (a command with the same name and type is updated, not duplicated), PATCH it by ID or DELETE it.

    Options and choices

    A slash command has up to 25 options. Each has a type, a name and a description:

    type Option What people enter in Klang
    1 Subcommand Picks a branch of the command: /lamp on, /lamp off.
    2 Subcommand group Groups subcommands: /config alerts add.
    3 Text Up to 6,000 characters, or min_length to max_length.
    4 Integer A whole number between min_value and max_value.
    5 Boolean Yes or no.
    6 User A member of the server, or the other person in a direct message.
    7 Channel A channel they can see, of the types in channel_types.
    8 Role A role of the server.
    9 Mentionable A person or a role.
    10 Number A number with decimals, between min_value and max_value.
    11 Attachment Can be registered, but people can’t attach files to commands yet.

    The rules are Discord’s, so a list that registers there registers here:

    • Names of slash commands and options are 1 to 32 characters: lowercase letters of any alphabet, numbers, - and _. User and message commands take any name of 1 to 32 characters, with capitals and spaces, such as Wave at.
    • Descriptions are 1 to 100 characters. User and message commands have none.
    • Required options go first. A subcommand or a group can’t be required, and they can’t be mixed with other options at the same level.
    • choices: up to 25 for a text or number option, each with a name people read and a value your bot gets. An option with choices only takes one of them.
    • autocomplete: true asks your bot for suggestions as people type. It can’t go with choices. See Autocomplete.
    • Numbers stay between −2⁵³ and 2⁵³, as in JavaScript.
    • Channel types: Klang has text channels (0), voice channels (2), categories (4) and threads (11). An option limited to other types matches no channel in Klang.
    • Size: all of a command’s names, descriptions and choices, in all their languages, add up to 8,000 characters at most.

    Breaking a rule answers 400 with 50035 and the field that’s wrong. See Field errors.

    Values that name something (a user, a channel, a role or a mentionable) reach your bot as IDs, with the full object in resolved. A channel or a person someone can’t see can’t be picked.

    Attachment options are the exception for now. A command can have them, but Klang doesn’t let people attach a file to a command yet: an optional one is left out, and a command with a required one can’t be used until files arrive.

    Translations

    name_localizations and description_localizations give a command, an option or a choice a name and a description in other languages. They take Discord’s locale codes as keys, and Klang accepts all 32 of them, so your list registers unchanged and reads back as you wrote it.

    Klang’s interface is in ten languages. Each person sees the translation for theirs, or the default text if there’s none:

    Klang language Locales it reads, in order
    English en-US, en-GB
    Spanish es-ES, es-419
    Portuguese (Brazil) pt-BR
    French fr
    German de
    Italian it
    Russian ru
    Japanese ja
    Turkish tr
    Polish pl

    Other locales, such as ko or nl, are kept for your bot and never shown. The interaction’s locale is the first locale of the person’s language (es-ES for Spanish), so your bot can answer in it. The suggestions of an autocomplete are translated the same way.

    People search the list both by the translated name and by the default one, and your bot always gets the default name in data.name.

    Who sees a command

    A command shows to someone in a channel only if all of these let them:

    1. The channel. They need Use application commands there. Bots read it as USE_APPLICATION_COMMANDS (1 << 31). It’s on for everyone by default, and server managers can turn it off per channel or per role, apart from Send messages. People who are timed out lose it.
    2. default_member_permissions: the permissions someone needs to see the command, as a string of Discord’s bits. null is everyone; "0" is administrators only; "32" is people with Manage server. Klang translates the bits to its own permissions (see Permissions). A bit for something Klang doesn’t have can’t be met, so the command becomes administrators only.
    3. The server’s own rules. People with Manage server can choose who uses each command, by role and by channel, in Server settings › Integrations, on the bot’s page. Their choice wins over default_member_permissions, both ways. Your bot can read these rules (see Command permissions) but not change them: the change routes answer 403 with 20001, as Discord’s do for bot tokens.
    4. contexts: 0 is servers, 1 is the bot’s direct messages. Without contexts, a global command shows in both. 2 (group and other private chats) is kept, but bots aren’t in those chats in Klang.
    5. nsfw: true shows the command only in age-restricted channels, and never in direct messages.

    Administrators and the server’s owner can use every command, whatever default_member_permissions and the server’s rules say. The bot also has to be able to see the channel: a command of a bot that can’t see a channel doesn’t show there. In a direct message with the bot, only global commands with 1 in contexts show, and neither default_member_permissions nor the server’s rules apply.

    Klang checks the same rules again when someone uses a command, so your bot only gets interactions from people allowed to use it.

    Limits

    What Limit
    Slash commands, per scope 100
    User commands, per scope 15
    Message commands, per scope 15
    New commands per server and day (UTC), per app 200
    Options per command, subcommand or group 25
    Choices per option 25
    Registering, editing and deleting, per app 20 requests every 20 seconds
    Reading commands and their permissions, per bot 20 requests every 10 seconds

    A scope is the global list, or one server’s. Creating a command over a scope’s limit answers 400 with 30032; a bulk PUT with too many answers 50035. The daily limit only counts commands created in a server, not updates and not global commands; going over it answers 400 with 30034, not a 429: libraries wait and retry a 429, and this wait would last until midnight UTC.

    More on how the rate limits work in Limits and rate limits.