Skip to main content

Creating a basic slash command

caution

This section covers the absolute minimum for setting up a slash command. We have an entire "Application Commands" section on how to effectively set up slash commands, and if you are doing anything serious we highly recommend you start there with What are application commands?

To create a slash command (known as a Chat Input Command in Sapphire), you will need to implement the registerApplicationCommands method in the Command class. Let's create a ping command and register a corresponding slash command with Discord:

import { Command } from '@sapphire/framework';export class PingCommand extends Command {  public constructor(context: Command.Context, options: Command.Options) {    super(context, { ...options });  }  public override registerApplicationCommands(registry: ChatInputCommand.Registry) {    registry.registerChatInputCommand((builder) =>      builder.setName('ping').setDescription('Ping bot to see if it is alive')    );  }}

The example above will register a slash command with Discord called ping with the description 'Ping bot to see if it is alive'. This is the information users will see in Discord when interacting with your bot through the slash command.

In order for your bot to respond to the slash command when it is invoked by a user, you must implement the chatInputRun method for the Command class.

import { isMessageInstance } from '@sapphire/discord.js-utilities';import { Command } from '@sapphire/framework';export class PingCommand extends Command {  public constructor(context: Command.Context, options: Command.Options) {    super(context, { ...options });  }  public override registerApplicationCommands(registry: ChatInputCommand.Registry) {    registry.registerChatInputCommand((builder) =>      builder.setName('ping').setDescription('Ping bot to see if it is alive')    );  }  public async chatInputRun(interaction: Command.ChatInputInteraction) {    const msg = await interaction.reply({ content: `Ping?`, ephemeral: true, fetchReply: true });    if (isMessageInstance(msg)) {      const diff = msg.createdTimestamp - interaction.createdTimestamp;      const ping = Math.round(this.container.client.ws.ping);      return interaction.editReply(`Pong 🏓! (Round trip took: ${diff}ms. Heartbeat: ${ping}ms.)`);    }    return interaction.editReply('Failed to retrieve ping :(');  }}

Creating a slash command with subcommands

note

For handling subcommands, please refer to the Sapphire Plugin Subcommands documentation.