How to add slash commands using discord.js?

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

How to add slash commands using discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 6 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.

Related Threads:

How to create a list of options for slash commands in discord.js?
How to create a slash command in discord using discord.js?
How to change files in discord.js by using commands?
How to delete a slash command from discord.js client?
How to unregister/delete a slash command in discord.js?
How to add slash between seo friendly url in opencart?