Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Darkilen/0e9d0623603fe1cdf802d0af7e5f9319 to your computer and use it in GitHub Desktop.
Save Darkilen/0e9d0623603fe1cdf802d0af7e5f9319 to your computer and use it in GitHub Desktop.
Slash Commands in Discord.js

Slash Commands in Discord.js

These are some simple examples for using Slash Commands in discord.js.
discord.js doesn't have full support for slash commands yet (there's a pr) but you can still use the underlying api and websocket to use them.
Note that discord.js doesn't officially support using client.api, this is basically just a workaround until they fully release support.

Please read Discord's Slash Command docs since they have actual docs and details for slash commands; the code examples below are just how you can implement it using discord.js.

Note that slash commands won't show in a server unless that server has authorized it with the applications.commands oauth2 scope (not just the bot scope).

This does not require a discord.js update! It should work as long as you're using a modern version (anything v12 would probably work, obviously v12.5.1/latest is recommended)

Alternatively, you can manage commands and handle interactions with slash-create.

Registering a Command:

You only need to register each command one time. You might wanna use an eval command for this.

Alternatively, instead of using discord.js to create the command, you might want to use a UI tool such as Postman, or create them in your code with discord-slash-commands

Send a Command object

For help creating the command object json, try https://rauf.wtf/slash

if your application id and bot id are different, change client.user.id to the application id

Global Commands

global commands show in all authorized servers, but take up to an hour to deploy.

client.api.applications(client.user.id).commands.post({data: {
    name: 'ping',
    description: 'ping pong!'
}})

Guild-specific commands

guild commands deploy immediately - use these for testing

client.api.applications(client.user.id).guilds('guild id').commands.post({data: {
    name: 'ping',
    description: 'ping pong!'
}})

Receiving the Event

interaction is an Interaction object

client.ws.on('INTERACTION_CREATE', async interaction => {
  // do stuff and respond here
})

Responding To An Interaction:

this goes inside the "receiving the event" block.
send an Interaction Response object

client.api.interactions(interaction.id, interaction.token).callback.post({data: {
  type: 4,
  data: {
    content: 'hello world!'
  }
}})

Sending a Followup Message

this also goes inside the "receiving the event" block.
see Webhook#send docs

new Discord.WebhookClient(client.user.id, interaction.token).send('hello world')

shortlink: s.advaith.io/slashdjs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment