Add a slash command

The commands that appear when you type / in Discord: first they are registered with Discord, then your bot answers them.

Documentation / Learn to write a bot / Add a slash command

  1. Define the command

    Write its name, description and options with SlashCommandBuilder.

  2. Register it with Discord

    Run deploy-commands.js once.

    node deploy-commands.js
  3. Reply

    Answer in the InteractionCreate event based on the command name.

Slash commands have two parts: introducing the command to Discord (registration) and the bot's answer when the command is used. Registration is done once; the answer code always lives inside the running bot.

Register the commands

Create a separate file called deploy-commands.js. You run this file once each time you add or change commands. Commands registered to a test server show up right away.

deploy-commands.jsjavascript
require("dotenv").config();
const { REST, Routes, SlashCommandBuilder } = require("discord.js");

const commands = [
  new SlashCommandBuilder().setName("ping").setDescription("Checks whether the bot answers"),
  new SlashCommandBuilder()
    .setName("hello")
    .setDescription("Greets someone")
    .addStringOption((o) => o.setName("name").setDescription("Who should I greet?").setRequired(true)),
].map((c) => c.toJSON());

const rest = new REST().setToken(process.env.TOKEN);

(async () => {
  await rest.put(
    Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
    { body: commands },
  );
  console.log("Commands registered.");
})();

Command names must be lowercase and must not contain spaces.

Reply to the command

Add the InteractionCreate event to index.js. Discord expects the bot to answer within 3 seconds.

index.jsjavascript
client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === "ping") {
    await interaction.reply("Pong!");
  }
});
  • If the work takes longer than 3 seconds, first write await interaction.deferReply(), then send the answer with await interaction.editReply("...") when the work is done.

A command with options

You read the value the user typed with interaction.options. Depending on the option type there are functions like getString, getInteger and getUser.

index.jsjavascript
if (interaction.commandName === "hello") {
  const name = interaction.options.getString("name");
  await interaction.reply(`Hello, ${name}!`);
}

A reply only the user can see

Sometimes you want only the person who used the command to see the answer (error messages, settings). Use the Ephemeral flag for that.

index.jsjavascript
const { MessageFlags } = require("discord.js");

await interaction.reply({
  content: "Only you can see this.",
  flags: MessageFlags.Ephemeral,
});