Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Commands and Events

Discord Slash Commands

Learn Discord application commands - defining names, options and subcommands, registering them over REST, handling interaction payloads, and replying with immediate or deferred responses - with runnable Node.js code.

Slash commands are Discord's built-in command system. Instead of reading chat text and guessing what a user meant, you register a list of commands with Discord. Users type / and see your commands with descriptions, typed options and autocomplete. When they submit one, Discord validates it and sends your bot a structured interaction. There is no parsing, no message content intent and no prefix collision with other bots.

This lesson covers the three steps: define commands, register them, and answer interactions.

Stand-in. Registration and replies go to a fake Discord endpoint on 127.0.0.1 that checks the real documented rules. The library equivalents (discord.js SlashCommandBuilder) are shown read-only.

Step 1: define a command

A command is a JSON object. The important fields are name, description and options.

JSON
{
  "name": "roll",
  "description": "Roll some dice",
  "type": 1,
  "options": [
    { "type": 4, "name": "sides", "description": "Number of sides", "min_value": 2, "max_value": 100 },
    { "type": 3, "name": "style", "description": "How to show it", "choices": [
        { "name": "Plain", "value": "plain" },
        { "name": "Verbose", "value": "verbose" } ] }
  ]
}

Rules from the documentation: a name is 1 to 32 characters, lowercase, made of letters, digits, - and _; a description is 1 to 100 characters; a command has up to 25 options; a choice list has up to 25 entries; required options must come before optional ones. Command type is 1 (chat input, the slash command), 2 (user context menu) or 3 (message context menu).

Option type values:

Value Type You receive
1 Subcommand nested options
2 Subcommand group nested subcommands
3 String string (optional min_length, max_length)
4 Integer integer (optional min_value, max_value)
5 Boolean true or false
6 User user id (string)
7 Channel channel id
8 Role role id
9 Mentionable user or role id
10 Number floating-point number
11 Attachment attachment id

Writing JSON by hand is error-prone, so wrap it in a tiny builder that checks the rules before you call the API.

Node.js A command builder that validates the rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(The same checks exist in the library you will actually use. The goal here is to know the rules so error messages from Discord make sense.)

Step 2: register the commands

Registration is a single PUT that replaces the whole command list:

  • PUT /applications/{application.id}/commands: global commands. They can take a while to propagate, and users in every server and in DMs can see them.
  • PUT /applications/{application.id}/guilds/{guild.id}/commands: commands for one server. They update immediately, which makes them ideal during development.

Run registration as a deploy-time script, not every time the bot starts: registering has its own rate limits, and a bot that restarts in a crash loop would burn them. Both discord.js and plain fetch use the same endpoint. In discord.js the builder looks like this (read-only, needs npm):

JavaScript
import { SlashCommandBuilder } from 'discord.js';

export const data = new SlashCommandBuilder()
  .setName('roll')
  .setDescription('Roll some dice')
  .addIntegerOption((o) => o.setName('sides').setDescription('Number of sides').setMinValue(2).setMaxValue(100).setRequired(true));

Step 3: handle interactions

When a user runs /roll sides:20, Discord sends your bot an interaction (over the gateway as INTERACTION_CREATE, or by HTTP POST if you configured an interactions endpoint). Its important fields:

  • id and token: you need both to reply. The token is valid for 15 minutes.
  • type: 1 ping, 2 application command, 3 message component (button, select), 4 autocomplete, 5 modal submit.
  • data: { id, name, type, options: [{ name, type, value }] }. For subcommands the options are nested.
  • member (in servers) or user (in DMs): who ran it. guild_id, channel_id, locale.

You must respond within 3 seconds, with a callback of one of these types:

Response type Value Meaning
CHANNEL_MESSAGE_WITH_SOURCE 4 Reply immediately
DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE 5 "Bot is thinking...": reply later (within 15 min)
DEFERRED_UPDATE_MESSAGE 6 For components: acknowledge without changing
UPDATE_MESSAGE 7 For components: edit the original message
APPLICATION_COMMAND_AUTOCOMPLETE_RESULT 8 Suggestions while typing
MODAL 9 Open a form popup

Flags in the response data matter too: flags: 64 makes a reply ephemeral (only the user sees it), which is perfect for errors and personal info.

Node.js A router for application command interactions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice readOptions: Discord nests subcommand options inside the subcommand, so a recursive reader keeps handlers simple. Subcommands let you group related actions (/settings language, /settings notifications) under one top-level name, which matters because a bot may register at most 100 chat-input commands.

Deferring slow work

If your command needs more than three seconds (a database query, an outside API call, rendering an image), send a deferred response (type 5) first. Discord shows "Bot is thinking..." and gives you 15 minutes to follow up by editing the original response: PATCH /webhooks/{application.id}/{interaction.token}/messages/@original. Further messages use POST /webhooks/{application.id}/{interaction.token}. These endpoints do not need your bot token because the interaction token authenticates them.

Node.js Defer, work, then follow up (stand-in endpoints)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The order is the whole trick: acknowledge first, work second, edit third. If you do the slow work before acknowledging, the user sees "The application did not respond" even though your code eventually succeeds.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How long does your bot have to acknowledge an interaction?

    The first response must arrive within 3 seconds. After a deferred response the interaction token lasts 15 minutes for follow-ups.
  2. 2. Which is the best place to register commands during development?

    Guild commands update instantly. Global commands can take time to propagate.
  3. 3. What does flags: 64 do in a response?

    The ephemeral flag (64) hides the response from everyone but the invoking user.
  4. 4. Where do the options of a subcommand appear in the interaction?

    Subcommands and groups nest their options, so handlers usually flatten them with a recursive reader.

Summary

  • Slash commands are registered with Discord (PUT .../commands), validated by Discord, and delivered as structured interactions.
  • Names are 1-32 lowercase characters; up to 25 options with typed values, min/max and choices; subcommands group related actions.
  • Respond within 3 seconds with a callback (type 4), or defer (type 5) and follow up for up to 15 minutes.
  • Use ephemeral replies (flag 64) for errors and private information.
  • Register commands in a deploy script, not at every startup.

Next: Telegram Handlers and Routing