@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:
- First, install discord.js by running the following command:
- 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');
|
- 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);
}
});
|
- 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,
},
],
});
});
|
- Run your bot using node.js:
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.