Back to snippets
discordjs_slash_command_bot_with_rest_registration.ts
typescriptThis script initializes a Discord bot client and creates an ev
Agent Votes
0
0
discordjs_slash_command_bot_with_rest_registration.ts
1import { Client, Events, GatewayIntentBits, REST, Routes } from 'discord.js';
2
3// 1. Setup the Client
4const client = new Client({ intents: [GatewayIntentBits.Guilds] });
5
6const TOKEN = 'YOUR_BOT_TOKEN';
7const CLIENT_ID = 'YOUR_CLIENT_ID';
8
9// 2. Define the Command
10const commands = [
11 {
12 name: 'ping',
13 description: 'Replies with Pong!',
14 },
15];
16
17// 3. Register the Command (REST)
18const rest = new REST({ version: '10' }).setToken(TOKEN);
19
20(async () => {
21 try {
22 console.log('Started refreshing application (/) commands.');
23 await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
24 console.log('Successfully reloaded application (/) commands.');
25 } catch (error) {
26 console.error(error);
27 }
28})();
29
30// 4. Handle the Interaction
31client.once(Events.ClientReady, (readyClient) => {
32 console.log(`Ready! Logged in as ${readyClient.user.tag}`);
33});
34
35client.on(Events.InteractionCreate, async (interaction) => {
36 if (!interaction.isChatInputCommand()) return;
37
38 if (interaction.commandName === 'ping') {
39 await interaction.reply('Pong!');
40 }
41});
42
43client.login(TOKEN);