DEV Community

Cover image for Build Your Own Discord Bot: A Node.js Journey from Scratch
Akram Sakib
Akram Sakib

Posted on

Build Your Own Discord Bot: A Node.js Journey from Scratch

1 - Discord configuration

First, you go to the developers page of the Discord website. From there create a Discord application.

Image description

After creating the application click on the application and edit the profile with the application name, description, etc. Then click on the bot tab from the sidebar and from there click on the presence intent and server intent toggle button.

Image description

Now click on the OAuth2 tab and go to that page from there click the bot from Scopes and the administrator checkbox from BOT PERMISSIONS, then copy the link from the generated URL and open it in a new tab.

Image description
Image description

After opening the link you will be redirected to a webpage and from there you can select the server for which you want to install the bot on your Discord and continue, thus completing the next steps.

Image description

Now you will open your Discord app. Open the settings and go to the advanced tab and from there turn on the developer mode

Image description
Image description

2 - Developing bot with Node

Please ensure that Node is installed on your computer system.

1: Create a project folder

Time to breathe some life into our bot creature. Let's start with creating a folder and initializing Node:

mkdir welcomeBot
cd welcomeBot
npm init -y
Enter fullscreen mode Exit fullscreen mode

2: Install packages

Our little fellow requires a couple of packages to function:

  • discord.js – a Node.js module that allows interactions with the Discord API
  • dotenv– allows loading environment variables from a process.env file in Node apps Run the following command to install the packages:
npm install discord.js dotenv
Enter fullscreen mode Exit fullscreen mode

3: Configure main.js

Now we need a main.js file to host the functions of our bot. Also, create a .env file, have an env variable called BOT_TOKEN, and put the token in there.

In the project directory, run:

touch main.js
touch .env
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

3 - Adding bot commands

Before working on main.js, the ID of the server on which we want to use the bot. Copy the channel ID on which the bot will give the welcome message and the channel on which the leave message will be given. And later I will set them in variables of main.js.

Image description
Image description
Image description

Now write the following codes in main.js

require("dotenv").config();

const token = process.env.BOT_TOKEN
const { Client, EmbedBuilder, GatewayIntentBits } = require("discord.js");
const serverID = "977250450799726662"

const bot = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});

bot.on("ready", () => {
  console.log("Ready Up");
});

bot.on("guildMemberAdd", (member) => {
  const channelID = "1272858378862985278";
  if (member.guild.id !== serverID) return;

  const embed = new EmbedBuilder()
    .setTitle("Member Joined!!")
    .setDescription(`${member.user.displayName} has joined this server`)
    .setColor("Orange")
    .setTimestamp();

  const channel = bot.channels.cache.get(channelID);
  if (channel) {
    channel.send({ embeds: [embed] }).catch(console.error);
  } else {
    console.error("Channel not found");
  }
});

bot.on("guildMemberRemove", (member) => {
  const channelID = "1272858477294915715";
  if (member.guild.id !== serverID) return;

  const embed = new EmbedBuilder()
    .setTitle("Member Left!!")
    .setDescription(`${member.user.displayName} has left from the server`)
    .setColor("Orange")
    .setTimestamp();

  const channel = bot.channels.cache.get(channelID);
  if (channel) {
    channel.send({ embeds: [embed] }).catch(console.error);
  } else {
    console.error("Channel not found");
  }
});

bot.login(token);

Enter fullscreen mode Exit fullscreen mode

This code is for a Discord bot that sends a custom message whenever a user joins or leaves a specific server. The bot is built using the discord.js library, which is a popular JavaScript library for interacting with the Discord API.

4 - Code Breakdown:

Loading Environment Variables:

require("dotenv").config();
Enter fullscreen mode Exit fullscreen mode

This line imports the dotenv package and loads environment variables from a .env file into process.env. This is commonly used to keep sensitive information like API tokens secure.
Declaring Variables:

const token = process.env.BOT_TOKEN;
const { Client, EmbedBuilder, GatewayIntentBits } = require("discord.js");
const serverID = "977250450799726662";
Enter fullscreen mode Exit fullscreen mode

token: Retrieves the bot token from the environment variables. The bot token is required to authenticate the bot with Discord.
Client, EmbedBuilder, and GatewayIntentBits: These are classes and constants imported from the discord.js library.
serverID: This is the ID of the Discord server (guild) the bot is targeting.
Creating the Bot Client:

const bot = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
Enter fullscreen mode Exit fullscreen mode

Client: Creates a new instance of the Discord client, which represents the bot.
intents: These are used to specify which events the bot should listen to. In this case, the bot listens for events related to guilds and guild members.
Bot Ready Event:

bot.on("ready", () => {
  console.log("Ready Up");
});
Enter fullscreen mode Exit fullscreen mode

This event triggers when the bot successfully logs in and is ready to start working. The bot logs "Ready Up" to the console.
Member Join Event:

bot.on("guildMemberAdd", (member) => {
  const channelID = "1272858378862985278";
  if (member.guild.id !== serverID) return;

  const embed = new EmbedBuilder()
    .setTitle("Member Joined!!")
    .setDescription(`${member.user.displayName} has joined this server`)
    .setColor("Orange")
    .setTimestamp();

  const channel = bot.channels.cache.get(channelID);
  if (channel) {
    channel.send({ embeds: [embed] }).catch(console.error);
  } else {
    console.error("Channel not found");
  }
});
Enter fullscreen mode Exit fullscreen mode

This event triggers whenever a new member joins the server.
It checks if the member joined the specified server (serverID).
It creates an embedded message using EmbedBuilder, announcing the new member.

The bot retrieves the channel by its ID (channelID), and if found, sends the embed message. If the channel is not found, it logs an error.
Member Leave Event:

bot.on("guildMemberRemove", (member) => {
  const channelID = "1272858477294915715";
  if (member.guild.id !== serverID) return;

  const embed = new EmbedBuilder()
    .setTitle("Member Left!!")
    .setDescription(`${member.user.displayName} has left from the server`)
    .setColor("Orange")
    .setTimestamp();

  const channel = bot.channels.cache.get(channelID);
  if (channel) {
    channel.send({ embeds: [embed] }).catch(console.error);
  } else {
    console.error("Channel not found");
  }
});
Enter fullscreen mode Exit fullscreen mode

This event triggers whenever a member leaves the server.
Similar to the guildMemberAddevent, it checks if the member left the specified server.
An embed message is created to announce the member's departure.
The bot then tries to send this message in the specified channel, logging an error if the channel is not found.
Logging the Bot In:

bot.login(token);
Enter fullscreen mode Exit fullscreen mode

This line logs the bot into Discord using the token retrieved from the environment variables.

5 - Run Your Bot

Finally, our application is ready to run. Now go to Terminal and run:

node main.js
Enter fullscreen mode Exit fullscreen mode

After the application is run, open the Discord server, you can see on the right side that your bot is now active.

Image description

Now login to another account and enter that server. Then you can see a message from your bot on your #welcome channel. And if someone leaves the channel, the member can see a message left.

Image description
Image description

Summary:
This code sets up a simple Discord bot that automatically sends a welcome message when a new member joins a specific server and a farewell message when a member leaves. It uses discord.js to handle these events and sends nicely formatted embed messages to specific channels.

Source Code: https://github.com/Akram-Sakib/discord-welcome-bot

Top comments (6)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello good post abou how to create a welcome Discord bot! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
akramsakib profile image
Akram Sakib

Thanks for the guide. I am new to writing in the dev community. I hope my future writings will be better

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Oh no problem! 🚀

Collapse
 
hamzarahman profile image
Hamza Rahman

awesome article, makes me want to create a bot.
btw what to use for hosting the bot.

Collapse
 
akramsakib profile image
Akram Sakib

Discord Bots that require a server to be constantly listening and reacting to events will not work on Vercel, Render since Serverless Functions have execution limits. Maybe you should get their Pro plan. As far as I know, Bots can be hosted on Digital Ocean, AWS hosting, etc... Or there may be some free platform where bot can be hosted I have no idea.

Collapse
 
jeromfdolk profile image
Jerom Fernando

Great Article