Skip to main content

Creating a basic slash command

warning

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:

const { Command } = require('@sapphire/framework');

class PingCommand extends Command {
constructor(context, options) {
super(context, { ...options });
}

registerApplicationCommands(registry) {
registry.registerChatInputCommand((builder) =>
builder.setName('ping').setDescription('Ping bot to see if it is alive')
);
}
}
module.exports = {
PingCommand
};

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.

const { isMessageInstance } = require('@sapphire/discord.js-utilities');
const { Command } = require('@sapphire/framework');

class PingCommand extends Command {
constructor(context, options) {
super(context, { ...options });
}

registerApplicationCommands(registry) {
registry.registerChatInputCommand((builder) =>
builder.setName('ping').setDescription('Ping bot to see if it is alive')
);
}

async chatInputRun(interaction) {
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 :(');
}
}
module.exports = {
PingCommand
};

Creating a slash command with subcommands

note

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