How to add slash commands using discord.js?

by darrion.kuhn , in category: Javascript , 2 months ago

How to add slash commands using discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 2 months ago

@darrion.kuhn 

To add slash commands using discord.js, you can use the interactionCreate event handler to listen for interactions of type SlashCommand, and then handle the command based on the received data. Here's how you can add slash commands using discord.js:

  1. First, install discord.js by running the following command:
1
npm install discord.js


  1. Next, create a new instance of Discord.js client and log in to the application:
1
2
3
4
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.login('YOUR_BOT_TOKEN');


  1. Add an event handler for the interactionCreate event, and listen for interactions of type SlashCommand:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'ping') {
    await interaction.reply('Pong!');
  } else if (commandName === 'say') {
    const message = interaction.options.getString('message');
    await interaction.reply(message);
  }
});


  1. Finally, register your slash commands by creating a new command object and setting the command name and options:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
client.on('ready', async () => {
  await client.application.commands.create({
    name: 'ping',
    description: 'Ping command',
  });

  await client.application.commands.create({
    name: 'say',
    description: 'Say command',
    options: [
      {
        name: 'message',
        description: 'Message to say',
        type: 'STRING',
        required: true,
      },
    ],
  });
});


  1. Run your bot using node.js:
1
node <your bot file>


Your bot should now be able to listen for slash commands and respond accordingly. Make sure to replace <your bot file> with the path to your bot script.