How to Use a Discord.js Bot
In this professional guide, you’ll learn how to develop a Discord bot from scratch using Discord.js. We’ll cover Node.js installation, bot creation, token management, and adding a simple command with a clean and sustainable approach.
1. Installing Node.js
Download and install the LTS version of Node.js for your operating system.
2. Creating a Bot in the Discord Developer Portal
- Log in to the Discord Developer Portal.
- Click the New Application button, give it a name, and create it.
- Go to the Bot tab in the left menu and add your bot with Add Bot.
3. Getting Your Bot Token
In the Bot tab, generate a new token with Reset Token and copy it. Never share this token with anyone!
4. Project Folder and npm init
Click to copymkdir discord-bot
cd discord-bot
npm init -y
5. Installing Discord.js
Click to copynpm install discord.js
6. A Simple Ping Command
Click to copy// index.js
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]});
client.once('ready', () => {
console.log(`Bot logged in: ${client.user.tag}`);
});
client.on('messageCreate', message => {
if (message.content === '!ping') {
message.reply('Pong!');
}
});
client.login('BOT_TOKEN'); // Replace BOT_TOKEN with your actual token
7. Running the Bot
Click to copynode index.js
If you see Bot logged in: BotName#0000 in the terminal, your bot is running successfully.
Extra Tips
- Store your token in a
.env
file and load it with thedotenv
package. - Keep your project organized by splitting commands into separate files.
- Check the official documentation: discord.js.org