This content originally appeared on DEV Community and was authored by Akram Sakib
1 - Discord configuration
First, you go to the developers page of the Discord website. From there create a Discord application.
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.
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.
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.
Now you will open your Discord app. Open the settings and go to the advanced tab and from there turn on the developer mode
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
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
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
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.
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);
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();
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";
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],
});
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");
});
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");
}
});
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");
}
});
This event triggers whenever a member leaves the server.
Similar to the guildMemberAdd
event, 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);
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
After the application is run, open the Discord server, you can see on the right side that your bot is now active.
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.
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
This content originally appeared on DEV Community and was authored by Akram Sakib
Akram Sakib | Sciencx (2024-08-18T16:58:49+00:00) Build Your Own Discord Bot: A Node.js Journey from Scratch. Retrieved from https://www.scien.cx/2024/08/18/build-your-own-discord-bot-a-node-js-journey-from-scratch/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.