Square CloudSquare Cloud

How to create slash commands for your Discord bot

To create a slash command, register its definition with the Discord API and handle the interaction in your bot, replying within 3 seconds. Register per guild for testing and globally in production.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Define commands with options, choices, autocomplete and default permissions
  • Register per guild and globally without duplicate commands or hitting limits
  • Reply within the 3-second window with reply, defer and response edits
On this page

A slash command is a command Discord knows about before your bot receives anything. You describe its name, its options and who may use it, send that definition to the API, and Discord takes over: it lists the command in the / menu, validates what the user types and hands your bot a structured interaction, with no text parsing on your side.

This guide starts from a bot that already logs in and answers a /ping, like the one in how to create your first Discord bot, and goes further: validated options, registration without duplicates, autocomplete, the reply deadline and permissions. The examples use discord.js v14 and discord.py 2.x.

How does a slash command work under the hood?#

A slash command is an application command of type CHAT_INPUT: a definition Discord stores and turns into an interaction sent to your app whenever someone uses it. The cycle has four steps:

  1. Registration. Your code sends the command list to the HTTP API. A PUT replaces the whole list for that scope, and any command left out is deleted.
  2. Use. The Discord client shows the command, validates types and limits and, when autocomplete is on, asks your bot for suggestions as the user types.
  3. Interaction. Discord delivers the command name and option values over the Gateway (the default) or over HTTP, if the app has an Interactions Endpoint URL. Both paths are compared in Discord HTTP interactions vs the Gateway.
  4. Response. The bot has 3 seconds for the initial response and, after it, 15 minutes to edit the response or send extra messages with the interaction token.

To receive slash commands over the Gateway, the Guilds intent is enough. The privileged Message Content intent is only needed if the bot also reads regular messages.

How do you define options, choices and permissions?#

Every option has a type: STRING, INTEGER, NUMBER, BOOLEAN, USER, CHANNEL, ROLE, MENTIONABLE or ATTACHMENT, plus SUB_COMMAND and SUB_COMMAND_GROUP for grouping. Discord validates the type in the client, so an INTEGER field never arrives with text in it.

The rules that most often break registration:

  • Command and option names are 1 to 32 characters, lowercase, no spaces (hyphens and underscores are fine).
  • Descriptions are 1 to 100 characters.
  • A command takes up to 25 options, and each option up to 25 choices.
  • Required options must come before optional ones.

In discord.js, a commands.js file holds the definitions. It creates two commands: /announce, which posts an embed to a channel and only shows up for members who can manage messages, and /time, with autocomplete:

js
import {
  ChannelType,
  InteractionContextType,
  PermissionFlagsBits,
  SlashCommandBuilder,
} from "discord.js";

export const commands = [
  new SlashCommandBuilder()
    .setName("announce")
    .setDescription("Posts a highlighted announcement to a channel")
    .addStringOption((o) =>
      o.setName("message").setDescription("Announcement text").setRequired(true).setMaxLength(2000),
    )
    .addChannelOption((o) =>
      o
        .setName("channel")
        .setDescription("Where to post (default: this channel)")
        .addChannelTypes(ChannelType.GuildText),
    )
    .addStringOption((o) =>
      o
        .setName("color")
        .setDescription("Side bar color")
        .addChoices(
          { name: "Blue", value: "blue" },
          { name: "Green", value: "green" },
          { name: "Red", value: "red" },
        ),
    )
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
    .setContexts(InteractionContextType.Guild),

  new SlashCommandBuilder()
    .setName("time")
    .setDescription("Shows the current time in a time zone")
    .addStringOption((o) =>
      o
        .setName("zone")
        .setDescription("e.g. Europe/London")
        .setRequired(true)
        .setAutocomplete(true),
    ),
];

Who can use the command?#

setDefaultMemberPermissions sets the default_member_permissions field: members without the permission (Manage Messages here) don't even see the command in the menu. The value "0" hides it from everyone except administrators and whoever the server allows under Integrations. setContexts(InteractionContextType.Guild) removes the command from DMs; without it, a global command also shows up in private conversations with the bot. The old dm_permission field is deprecated in favor of contexts.

This permission is a default, not a lock. Admins can allow or deny the command per role, member or channel under Server Settings, Integrations, and anyone with Administrator can use every command. If the action requires a real permission, like banning or deleting messages, also check it in code with interaction.memberPermissions.has(...). And remember the user's permissions are not the bot's: to post the embed, the bot itself needs Send Messages and Embed Links in the channel.

Global or guild registration: which one to use?#

Per guild Global
Where it shows up Only in the given server Every server that added the app and, without contexts, DMs with the bot
Updates Immediate No fixed time; Discord reloads the command if someone uses an old version
Slash command limit 100 per guild 100
Typical use Development and single-server commands Production

The two scopes add up. If the same command is registered in your test server and globally, it shows up twice there. When you promote commands to global, clear the guild scope by sending an empty list (body: []) to the same route.

Discord also allows only 200 command creates per day per guild. That is why registration lives in a separate script you run when the definition changes, not in the bot's startup event:

js
// deploy-commands.js
import { REST, Routes } from "discord.js";
import { commands } from "./commands.js";

const isGlobal = process.argv.includes("--global");
const route = isGlobal
  ? Routes.applicationCommands(process.env.CLIENT_ID)
  : Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID);

const rest = new REST().setToken(process.env.DISCORD_TOKEN);
const data = await rest.put(route, { body: commands.map((c) => c.toJSON()) });
console.log(`${data.length} command(s) registered ${isGlobal ? "globally" : "in the test server"}.`);
bash
node --env-file=.env deploy-commands.js           # test server
node --env-file=.env deploy-commands.js --global  # production

In the invite, the bot scope already includes applications.commands, which lets the app create commands in the server; checking both only makes the URL explicit. The walkthrough is in how to add a bot to your Discord server.

How do you handle the command and autocomplete?#

The same InteractionCreate event carries two kinds of interaction: autocomplete, sent while the user types, and the command itself, sent when they press Enter. Autocomplete answers with at most 25 suggestions, within 3 seconds, and cannot be deferred. So the suggestion source must be fast: an in-memory list or a cache, never a slow API call on every keystroke.

The index.js below uses JavaScript's own time zone list (Intl.supportedValuesOf) as the source:

js
import { Client, EmbedBuilder, Events, GatewayIntentBits, MessageFlags } from "discord.js";

const ZONES = Intl.supportedValuesOf("timeZone");
const COLORS = { blue: 0x3b82f6, green: 0x22c55e, red: 0xef4444 };

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

async function handle(interaction) {
  if (interaction.isAutocomplete() && interaction.commandName === "time") {
    const typed = interaction.options.getFocused().toLowerCase();
    const suggestions = ZONES.filter((z) => z.toLowerCase().includes(typed)).slice(0, 25);
    await interaction.respond(suggestions.map((z) => ({ name: z, value: z })));
    return;
  }

  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === "time") {
    const zone = interaction.options.getString("zone", true);
    if (!ZONES.includes(zone)) {
      // suggestions are not enforced: the user can type any text
      await interaction.reply({ content: "Unknown time zone. Pick one from the list.", flags: MessageFlags.Ephemeral });
      return;
    }
    const now = new Date().toLocaleString("en-US", { timeZone: zone });
    await interaction.reply(`Current time in ${zone}: ${now}`);
  }

  if (interaction.commandName === "announce") {
    const channel = interaction.options.getChannel("channel") ?? interaction.channel;
    const embed = new EmbedBuilder()
      .setDescription(interaction.options.getString("message", true))
      .setColor(COLORS[interaction.options.getString("color") ?? "blue"]);
    try {
      await channel.send({ embeds: [embed] });
    } catch {
      await interaction.reply({ content: "I can't post in that channel.", flags: MessageFlags.Ephemeral });
      return;
    }
    await interaction.reply({ content: `Announcement posted in ${channel}.`, flags: MessageFlags.Ephemeral });
  }
}

client.on(Events.InteractionCreate, async (interaction) => {
  try {
    await handle(interaction);
  } catch (err) {
    console.error(err);
  }
});

client.once(Events.ClientReady, (c) => console.log(`Online as ${c.user.tag}`));
client.login(process.env.DISCORD_TOKEN);

Three details apply to any library. Autocomplete can't be combined with choices on the same option. Suggestions validate nothing, so the command handler checks the value. And the try/catch around everything keeps an unhandled rejection from crashing the bot process.

How do you reply when the work takes longer than 3 seconds?#

If the command queries a database, calls an external API or renders an image, answer first with a defer: Discord shows "thinking..." and your deadline becomes the token's 15-minute lifetime. Then edit the original response. In discord.js that is deferReply() followed by editReply(); in discord.py, interaction.response.defer(thinking=True) followed by edit_original_response().

Decide at defer time whether the reply is ephemeral (visible only to the user who ran the command) by passing the Ephemeral flag right there: a sent message can't change visibility later. For extra messages, use followUp, which creates new messages with the same token.

The full discord.js defer example, including handling for 10062 Unknown interaction and 40060 Interaction has already been acknowledged, is in Discord bot not responding. If your bot receives interactions over HTTP, the defer is a type 5 response in the HTTP response body.

What does the same bot look like in discord.py?#

In discord.py, commands live in a CommandTree, and registration is called syncing (tree.sync). The bot.py below only syncs when SYNC_COMMANDS=1 is set, to the test server if GUILD_ID exists and globally if it doesn't (pip install discord.py tzdata; tzdata guarantees the time zone list on any system):

python
import asyncio
import os
import zoneinfo
from datetime import datetime
from typing import List, Optional

import discord
from discord import app_commands

ZONES = sorted(zoneinfo.available_timezones())
COLORS = {"blue": 0x3B82F6, "green": 0x22C55E, "red": 0xEF4444}


class Bot(discord.Client):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self) -> None:
        if os.environ.get("SYNC_COMMANDS") != "1":
            return
        guild_id = os.environ.get("GUILD_ID")
        if guild_id:  # test server: updates immediately
            guild = discord.Object(id=int(guild_id))
            self.tree.copy_global_to(guild=guild)
            synced = await self.tree.sync(guild=guild)
        else:  # global: every server
            synced = await self.tree.sync()
        print(f"{len(synced)} command(s) synced")


bot = Bot()


@bot.tree.command(description="Posts a highlighted announcement to a channel")
@app_commands.describe(message="Announcement text", channel="Where to post", color="Side bar color")
@app_commands.choices(color=[
    app_commands.Choice(name="Blue", value="blue"),
    app_commands.Choice(name="Green", value="green"),
    app_commands.Choice(name="Red", value="red"),
])
@app_commands.default_permissions(manage_messages=True)
@app_commands.guild_only()
async def announce(
    interaction: discord.Interaction,
    message: app_commands.Range[str, 1, 2000],
    channel: Optional[discord.TextChannel] = None,
    color: Optional[app_commands.Choice[str]] = None,
) -> None:
    target = channel or interaction.channel
    embed = discord.Embed(description=message, color=COLORS[color.value if color else "blue"])
    try:
        await target.send(embed=embed)
    except discord.Forbidden:
        await interaction.response.send_message("I can't post in that channel.", ephemeral=True)
        return
    await interaction.response.send_message(f"Announcement posted in {target.mention}.", ephemeral=True)


@bot.tree.command(description="Shows the current time in a time zone")
@app_commands.describe(zone="e.g. Europe/London")
async def time(interaction: discord.Interaction, zone: str) -> None:
    if zone not in ZONES:  # suggestions are not enforced: validate
        await interaction.response.send_message("Unknown time zone. Pick one from the list.", ephemeral=True)
        return
    now = datetime.now(zoneinfo.ZoneInfo(zone)).strftime("%Y-%m-%d %H:%M")
    await interaction.response.send_message(f"Current time in {zone}: {now}")


@time.autocomplete("zone")
async def time_autocomplete(interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
    typed = current.lower()
    return [app_commands.Choice(name=z, value=z) for z in ZONES if typed in z.lower()][:25]


@bot.tree.command(description="Builds a report (takes a few seconds)")
async def report(interaction: discord.Interaction) -> None:
    await interaction.response.defer(thinking=True, ephemeral=True)  # acknowledges in under 3 s
    await asyncio.sleep(5)  # slow work: database, API, image
    await interaction.edit_original_response(content="Report ready.")


@bot.event
async def on_ready() -> None:
    print(f"Online as {bot.user}")


bot.run(os.environ["DISCORD_TOKEN"])

The decorators play the builder's role: describe sets descriptions, choices fixes the values, Range caps the text length, default_permissions sets the default permission and guild_only removes the command from DMs. To enforce the permission in code, as in discord.js, add @app_commands.checks.has_permissions(manage_messages=True). If you're still choosing a Python library, see which Python library to use: Pycord and Nextcord sync commands on their own when they connect.

Which errors show up with slash commands?#

Symptom Likely cause Fix
The command doesn't show up under / Registration didn't run, GUILD_ID points to another server, or the invite lacks the bot scope (and applications.commands) Run registration and re-invite with bot
The command shows up twice Registered in the guild and globally Send body: [] to the guild scope
"The application did not respond" Reply after 3 seconds, or an exception before replying Defer before slow work and try/catch in the handler
10062 Unknown interaction The initial response went out after 3 seconds Reply or defer right at the start
40060 Interaction has already been acknowledged Two initial replies to the same interaction Turn the second into editReply or followUp
Autocomplete shows no suggestions Slow handler, an error, or more than 25 items Filter in memory and cut at 25
50013 Missing Permissions when posting The bot can't send in that channel Fix the bot's role or the channel override

If the bot is online but reacts to nothing, the full diagnosis, from intents to permissions, is in Discord bot not responding. If it drops and comes back, that is a different problem: see why a Discord bot goes offline.

How to do this on Square Cloud#

A bot that receives its commands over the Gateway runs as a background application, with no subdomain, since it receives no inbound traffic. On Square Cloud, it lives in an isolated, always-on container, with automatic restart (on by default for dashboard deploys) when the process exits with an error. The platform supports discord.js, discord.py or any Gateway library.

  1. Upload the project as a ZIP in the dashboard, or use the CLI, GitHub or the VS Code extension, without node_modules or .env. At start, the platform runs npm install (Node.js) or pip install -r requirements.txt (Python). The squarecloud.app file is optional: the dashboard generates it at deploy, and writing it at the project root is the alternative.
  2. Set DISCORD_TOKEN in the application's environment variables. With discord.py, add SYNC_COMMANDS=1 when commands change and remove it after the restart. Changes apply on the next restart, with no rebuild.
  3. With discord.js, run deploy-commands.js from your machine when the definition changes, and follow the real-time logs until you see Online as ....

Each bot uses at least 256 MB from the plan's RAM pool, and Hobby costs R$12.49 per month with 1 GB of RAM. See Discord bot hosting.

Bot hosting

Keep your bot online 24/7 with automatic restarts

Discord bot hosting

FAQs

How long does a global slash command take to show up?

Guild commands show up immediately. Discord's documentation sets no fixed time for global ones: if someone uses an outdated version, Discord rejects it and reloads the command. For testing, register in a guild.

Can I register commands every time the bot starts?

It works, but it isn't recommended. Discord allows 200 command creates per day per guild, and registration only needs to run when the definition changes. Keep it in a separate script.

How do I hide a command from non-moderators?

Set default_member_permissions to the required permission, such as Manage Messages. Members without it don't see the command. Server admins can change this under Server Settings, Integrations.

What is the difference between choices and autocomplete?

Choices are up to 25 fixed values, and Discord only accepts one of them. Autocomplete suggests values from your code as the user types, but free text is still accepted, so validate what you receive.

How many slash commands can a bot have?

Up to 100 global slash commands and up to 100 per guild, each with at most 25 options. Subcommands help group related actions without using up top-level commands.

Next articleWhat is a Discord bot and how does it work?A Discord bot is a program that uses a bot account to receive events and act in servers. See how the Gateway, the API, intents and commands fit together.