Discord Bot in Node.js
Here's a simple Discord bot using Node.js and the Discord.js library. This example includes basic setup and a few common features.
Step 1: Setup
First, create a new directory for your project, initialize npm, and install the required packages:
bash
mkdir discord-bot
cd discord-bot
npm init -y
npm install discord.js dotenv
Step 2: Create the Bot Files
Create a .env file for your bot token:
code
TOKEN=your_discord_bot_token_here
Create an index.js file:
javascript
// Import required packages
const { Client, GatewayIntentBits, Collection, Events } = require('discord.js');
require('dotenv').config();
// Create a new client instance
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});
// Command collection
client.commands = new Collection();
// Bot ready event
client.once(Events.ClientReady, () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity('with Discord.js');
});
// Message event handler
client.on(Events.MessageCreate, async message => {
// Ignore messages from bots
if (message.author.bot) return;
// Simple command handler with prefix "!"
const prefix = '!';
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
// Simple ping command
if (commandName === 'ping') {
const reply = await message.reply('Pinging...');
const pingTime = reply.createdTimestamp - message.createdTimestamp;
reply.edit(`Pong! Bot latency: ${pingTime}ms, API Latency: ${client.ws.ping}ms`);
}
// Simple hello command
if (commandName === 'hello') {
message.reply(`Hello, ${message.author.username}!`);
}
// Simple server info command
if (commandName === 'serverinfo') {
const serverInfo = {
name: message.guild.name,
memberCount: message.guild.memberCount,
createdAt: message.guild.createdAt.toDateString(),
owner: (await message.guild.fetchOwner()).user.tag
};
message.reply(`
**Server Information**
Name: ${serverInfo.name}
Members: ${serverInfo.memberCount}
Created: ${serverInfo.createdAt}
Owner: ${serverInfo.owner}
`);
}
});
// Login to Discord with your client's token
client.login(process.env.TOKEN);
Step 3: Getting a Bot Token
- Go to the Discord Developer Portal
- Click "New Application" and give it a name
- Go to the "Bot" tab and click "Add Bot"
- Under the bot's username, click "Reset Token" and copy the token
- Paste this token in your
.env file
Step 4: Inviting Your Bot to a Server
- In the Developer Portal, go to the "OAuth2" tab
- In the "URL Generator" section, select "bot" under scopes
- Select the permissions your bot needs (e.g., "Send Messages", "Read Message History")
- Copy the generated URL and open it in your browser
- Select a server to add your bot to and authorize it
Step 5: Running Your Bot
bash
node index.js
Features Included
!ping - Check the bot's response time
!hello - Get a greeting from the bot
!serverinfo - Get information about the current server
Next Steps
You can expand this bot by:
- Adding more commands
- Implementing slash commands
- Adding event handlers
- Creating a command handler system for better organization
- Adding database integration for persistent data
This is a basic starting point. Discord.js has extensive documentation that can help you build more complex features.