ProjectsDiscordNode.jsBotCommunity

Build a Discord Bot with Node.js and discord.js

3.775 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

We used telegraf for Telegram. Now let's use discord.js v14 for Discord.

Advertisement

Setup

  1. Go to the Discord Developer Portal.
  2. Create an Application -> Add Bot.
  3. Critical Step: Enable Message Content Intent (Privileged Gateway Intent). Without this, your bot cannot read messages!
  4. Copy the Token.

The Code

npm install discord.js dotenv
require('dotenv').config();
const { Client, GatewayIntentBits, REST, Routes } = require('discord.js');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
});

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', msg => {
    if (msg.author.bot) return; // Don't talk to yourself
    
    if (msg.content.toLowerCase() === 'ping') {
        msg.reply('Pong!');
    }
});

client.login(process.env.DISCORD_TOKEN);

Slash Commands (Interaction API)

Modern Discord bots utilize /commands. This requires registering the command structure with Discord's API separately.

const commands = [
  {
    name: 'ping',
    description: 'Replies with Pong!',
  },
];

// Run this ONCE to register commands
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });

Advertisement

Quiz

Quick Quiz

Why is 'Message Content Intent' a privileged intent in Discord?

Conclusion

Bots are a great way to "gamify" a server. Try creating an economy bot (fake money system) or a moderation bot that deletes bad words automatically.

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like