Build a Discord Bot with Node.js
Discord has evolved far beyond a simple voice and text chat platform for gamers. Today, it is the premier community hub for developer communities, open-source projects, gaming guilds, and enterprise teams. Bots are the lifeblood of Discord servers—automating moderation, delivering live notifications, managing role permissions, and integrating interactive mini-games.
Node.js is one of the most popular platforms for building Discord bots due to its asynchronous event-driven architecture and `discord.js`, the most robust wrapper library for the Discord API. This comprehensive tutorial walks through setting up a bot application in the Discord Developer Portal, initializing a Node.js project, registering slash commands, and handling real-time guild events.
1. Creating the Bot Application in Discord Developer Portal
Before writing any code, you must register your bot application with Discord:
- Navigate to the Discord Developer Portal and log in with your Discord account.
- Click **New Application**, give it a name (e.g., CodeCrownBot), and accept terms.
- Go to the **Bot** tab on the left sidebar and click **Add Bot**.
- Under Privileged Gateway Intents, enable **Message Content Intent** so your bot can read user messages.
- Copy your bot's **Token** and keep it secure (never commit tokens to public version control).
# Terminal setup and installation commands
mkdir discord-bot-node
cd discord-bot-node
npm init -y
npm install discord.js dotenv
npm install --save-dev nodemon
2. Writing the Bot Script with `discord.js`
Create an `index.js` file to initialize the Discord client, handle ready events, and respond to incoming slash commands or messages.
// index.js
const { Client, GatewayIntentBits, REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
// Create Discord client instance with required intents
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
client.once('ready', () => {
console.log(`🤖 Logged in successfully as ${client.user.tag}!`);
});
// Handle slash command interactions
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong! Latency is good 🚀');
} else if (commandName === 'hello') {
await interaction.reply(`Hello ${interaction.user.username}! Welcome to the server.`);
}
});
const TOKEN = process.env.DISCORD_BOT_TOKEN;
client.login(TOKEN);
3. Registering Slash Commands with Discord API
Create a `deploy-commands.js` script to register global or guild-specific slash commands (`/ping`, `/hello`) with Discord's REST API.
// deploy-commands.js
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with Pong and latency!'),
new SlashCommandBuilder().setName('hello').setDescription('Greets the user warmly!'),
].map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
// Register globally (takes up to 1 hour) or for a specific test guild
await rest.put(
Routes.applicationCommands(process.env.CLIENT_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
Conclusion
Building a Discord bot with Node.js and `discord.js` is both powerful and rewarding. By registering slash commands, configuring gateway intents, and handling event listeners, you can scale simple scripts into advanced moderation bots, music players, and developer tool integrations.