JavaScript

Creating a Simple Discord Bot with Node.js

Discord has become the application of choice for many internet users specifically for its VOIP features. During the pandemic, a lot of work was shifted to online (“work from home”) and thus increased the popularity of Discord and Discord servers. With increasing popularity came the increasing numbers of Discord bots. Bots in general are nothing but automation of various tasks. Anyone familiar with Discord is familiar with what a Discord bot is.

Maybe the most well-known Discord bots are the music playing bot (music bot, rhythm, groovy, etc.) These bots allow you to play music by pinging it with a song name and then they search for that specific song, join the channel from where it was pinged, and start playing that song.

The purpose of this post is going to be creating your first Discord bot, using the well known Discord.js library.

Let’s get into building our first Discord bot.

Prerequisites

Almost every task that we do online requires some sort of prerequisite. The prerequisites for creating a Discord bot are as follows:

  • Node.js v10 or higher (latest version >16.0 is preferred)
  • Discord account and a Discord server
  • Some basic knowledge of the terminal (not compulsory)

Step 1: Creating a bot application on Discord.com

We start by creating\registering our bot on discord.com. If we wish to control the bot using our code, we need to first register the bot under our Discord account.

Go to Discord.com and then Applications. After logging in to your Discord account, you’ll be taken to your Discord dashboard. Click on “NEW APPLICATION”  from the top right side of the browser window.

Next, you’ll see a screen where the name of the application would be demanded from you. For this post, we’ll call out the bot “my-greeter-bot”. Next, hit on the button that says “Create”. This will create the Discord API application.

This will create the bot as an application under the name given by you. In our tutorial, it is called “my-greeter-bot”. Now you’ll be able to notice client ID and other information about the bot application. Like the image below.

What we want is to give this bot permission and invite it to our server and get the TOKEN. For that, click on the “Bot” tab from the left sidebar.

Now click on add Bot on the right side and our bot will be created.

Once the process has finished creating and setting up the bot on the Discord server, you’ll be able to see its information.

Click on the COPY TOKEN option on the screen, this will copy the authorization token code, now save this code somewhere in a text file or write it down.

We will require this code later on in the tutorial to connect our VS Code (or any editor of your choice) to the bot:

Step 2: Defining Bot permission and adding the bot to our server

The next step is to define the permission we are going to ask from the server to which our bot will be added. Explore the OAuth2 segment as shown in the image below. Here we can characterize the degree for our bot. Check the “bot” option from the list.

From the permission, listen beneath it, select Send messages, and Read Message History as well. We’ll have our bot go through messages in the text channel and reply to those messages which meet the criteria determined by us.

Copy the link and open it. There you’ll see a pop-up box that will ask you about which server to ask the bot into.

Select your desired server and voila, you have added your custom bot to your desired server.

Step 3: Setting up Visual Studio Code

Visual studio code isn’t a necessity, it’s up to you to choose which code editor you want to use. For this post, we’ll be utilizing visual studio code:

This project depends on two major dependencies.

  • Dotenv
  • Discord.js

So, let’s create a node project and install these dependencies:

Create a folder and using the terminal start the node project by using “npm init”.Install dependencies by typing “npm install dotenv” and “npm install Discord.js

To complete the installation of the dotenv dependency, create a file in the root of the project with a “.env” extension. To do this, right-click in the explorer in visual studio code and create a new file.

And name it as “.env” just like it is shown in the image below.

Once the file is created what you are going to do now is to add one environment variable called TOKEN to the file like:

TOKEN=my-unique-bot-token

Make sure to replace “my-unique-bot-token” with your bot token.

Step 4: Index.js (exploring Discord.js)

We are going to create another file just the how we created the “.env” file. and we are going to name this file “index.js” just like this:

After this file has been created we can start working on coding our bot now.

Start by requiring “dotenv”, by doing that we are going to be able to use various environment variables, but in our case, it is only going to be the TOKEN variable. In order to access this variable, the one we have created in the .env, we use the line: const TOKEN = process.env.token ;

And lastly, to link our code to the discord bot which we have just added to our discord server, we use the command

bot.log(TOKEN), the block of code is as:

require('dotenv').config();
const Discord = require('Discord.js');
const bot = new Discord.Client();
const TOKEN = process.env.TOKEN;
bot.login(TOKEN);

The next step is to set up a listener, which only listens for the “ready” Event:

Knowing node.js, we can listen for events. The ready event automatically launches once we have connected to the bot.

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

To test if the bot you are getting connected to or not. Type the following command in the terminal of the root directory of the project “node index.js”. You should see something like this.

Step 5: Listen for “message” events

We now know that our code is connecting to the bot. All we need to do now is to code a simple message listening event and reply to that message.

This would mean that the bot can go through messages in the text channel and reply to those messages. These messages would generally contain requests by the users.

This message listening event would make our bot able to go through the text messages in the message channels, and will even allow the bot to respond to those messages as a “reply”, to do that append the following code in the index.js file.

bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
msg.channel.send('pong');
}
});

The code above is a listener on any message in a text channel. What the bot does every time a message is sent in a channel is that it reads that message and searches it for the string “ping”. If the channel has a message that just has the word ping in it, the bot replies with pong.

After that, we need to reply in a channel, and to do exactly that we use the command: msg.channel.send(‘pong’).

The above code can be broken down into:

  • msg.reply: tags the initial user who has sent the message
  • msg.channel.send: sends a message to the channel without tagging anyone

I guess we now know the general concepts of the commands above. Fire up the code using the node index.js command (just like we did before) and send a message ping to the general text channel.

That’s it. You have created your first ever Discord bot, which reads and replies to messages.

Conclusion

Discord bot seems nothing less than a work of magic at first. But, once you know how a Discord bot is created, it won’t seem like the work of a magician. True, at first it all seems very overwhelming, but thanks to the Discord.js Api, it all becomes easy. There are a ton of different permissions to be uncovered and implemented.

Hoping this tutorial was useful to you, as it was only a first step towards creating your own ultimate bot. To explore Discord.js API  and its package then you can head over to the Discordjs.guide website.

All the best on building your very first Discord bot, and taking more steps towards greatness.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.