after installing the required packages we move onto coding, something that is exciting for many. (Please note that this is just a guide, we won't include full code!)
Create a file called index.ts
import { Client, GatewayIntentBits, Routes, Interaction } from 'discord.js';
import { REST } from '@discordjs/rest';
import { SlashCommandBuilder } from '@discordjs/builders';
import 'dotenv/config';
// Create a new client instance
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});
// Define your slash commands
const commands = [
new SlashCommandBuilder().setName('first').setDescription('Replies with a funny message!'),
].map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
// Register the commands
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
// When the bot is ready
client.once('ready', () => {
console.log('Bot is online and ready with slash commands!');
});
// Responding to slash commands
client.on('interactionCreate', async (interaction: Interaction) => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'first') {
await interaction.reply('Congrats on your first command!');
}
});
// Login to Discord with your app's token
client.login(process.env.DISCORD_TOKEN);
Oh yes! to access the variable process.env.DISCORD_TOKEN, we have to create a .env file and add this line inside of it. The token is the one you have gotten from developer page by resetting the token!
DISCORD_TOKEN=Token here
And for the end, we run the file we have just created,
ts-node index.ts or npm start if you have defined start script in package.json