Creating a Discord Bot with Discord.js 🤖

16/03/2025 Development 2 mins read
Table Of Contents

Prerequisites

  • Node.js (v16.9.0 or higher)
  • Discord Developer Portal - To create the application and get the token
  • Code editor - such as Visual Studio Code, Sublime Text, etc.

Initial Setup

Create application in Discord Developer Portal

  1. Navigate to the Discord Developer Portal
  2. Click “New Application” and name your application
  3. Go to the “Bot” section, click “Add Bot”
  4. Under the “TOKEN” section, click “Reset Token” and copy the token (keep it secure!)
  5. Enable necessary “Privileged Gateway Intents” (Message Content, Server Members, Presence)

Project setup

Terminal window
mkdir my-discord-bot
cd my-discord-bot
npm init -y
npm install discord.js dotenv
Terminal window
mkdir my-discord-bot
cd my-discord-bot
yarn init -y
yarn add discord.js dotenv

Basic file structure

Create the following files in your project:

my-discord-bot/
├── .env # File for environment variables
├── index.js # Main entry point
├── config.json # Bot configuration
└── package.json # npm/yarn configuration

.env file

# .env
DISCORD_TOKEN=your_token_here

Basic bot code

index.js
require('dotenv').config();
const { Client, GatewayIntentBits, Events } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
});
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
client.on(Events.MessageCreate, async (message) => {
// Ignore messages from bots
if (message.author.bot) return;
// Simple command handling
if (message.content === '!ping') {
await message.reply('Pong!');
}
});
// Login with your token
client.login(process.env.DISCORD_TOKEN);

Adding the Bot to a Server

  1. Go back to the Discord Developer Portal
  2. Navigate to the “OAuth2” section, then “URL Generator”
  3. Select the scopes: bot and applications.commands
  4. Select bot permissions: Send Messages, Read Messages/View Channels, etc.
  5. Copy the generated URL and open it in your browser
  6. Select the server to add your bot to and confirm