Creating a Discord Bot with Discord.js 🤖
16/03/2025 Development 2 mins read
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
- Navigate to the Discord Developer Portal
- Click “New Application” and name your application
- Go to the “Bot” section, click “Add Bot”
- Under the “TOKEN” section, click “Reset Token” and copy the token (keep it secure!)
- Enable necessary “Privileged Gateway Intents” (Message Content, Server Members, Presence)
Project setup
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
# .envDISCORD_TOKEN=your_token_hereBasic bot code
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 tokenclient.login(process.env.DISCORD_TOKEN);Adding the Bot to a Server
- Go back to the Discord Developer Portal
- Navigate to the “OAuth2” section, then “URL Generator”
- Select the scopes:
botandapplications.commands - Select bot permissions:
Send Messages,Read Messages/View Channels, etc. - Copy the generated URL and open it in your browser
- Select the server to add your bot to and confirm