How to Create a Simple Bot Using Discord.js

In this tutorial, you’ll learn how to set up, create, and deploy a Discord bot using Discord.js.

Nithil Krishnaraj
TechTalkers
13 min readDec 24, 2020

--

Video version of this tutorial can be found here

Ever wanted to create your own Discord bot? Well, I have. I’ve always worried about privacy on my Discord server about bots tracking my messages. To stop my worrying, I decided to learn how to make my own Discord bots, so I know for sure my server is 100% secure. In this tutorial, I will be showing you how you set up, create, and deploy a simple Discord bot using JavaScript. Since this is the first part, I’ll only cover how to set up the bot.

Prerequisites

Step 1: Registering the Bot

The first step of creating a Discord bot is to register the bot with Discord. To do that, go here.

Once you’re there, click on “New Application” on the top right. Give your bot a name.

On this page, you can modify your bot’s name, description, and logo. The logo will essentially be the profile picture of your bot. I usually use this website to generate logos for my projects quickly.

Now that we’ve created a project on Discord, we want to assign a bot to it. To do that, go to the “Bot” tab.

Select “Add Bot.”

Select “Yes, do it!” to confirm.

Awesome! We have successfully set up the bot. Now, we’ll learn how to download dependencies and code the bot.

Step 2: Install Required Dependencies

First, open your terminal.

Create a folder specifically for your bot. I’m going to call my bot “My First Bot.”

Now, we’re going to create a package.json file. This file allows us to add custom scripts to development and is going to keep a record of your app’s version and dependencies installed. To do that, run npm init -y.

Now, let’s install our dependencies. Dependencies are packages that we can install that allow us to do more with our code, often reducing the amount of code we need to write. For our bot, we’re going to be installing three dependencies:

  • Discord.js — The Discord library used to create our Discord bot.
  • dotenv — This is going to allow us to hide certain variables, such as our bot’s client ID.
  • Nodemon — This is going to allow us to develop without having to restart the development server every time we make a change to our code, as it will automatically do it for us.

To install our dependencies, run npm i {package name} for each dependency like so (see below images).

Now that our packages are installed, let’s start coding the bot.

Step 3: Set Up the Environment

To start coding your bot, open your preferred code editor.

Now, create a file called index.js. We will be writing our JavaScript code here.

Also, create a .gitignore and a .env file. In our .gitignore, we’ll be hiding our .envand node_modules from our GitHub repository.

In your .gitignore file, type in .envand node_modules to hide those files. Make sure you put them on separate lines.

In your .env file, create an environment variable called BOT_TOKEN. Our client token will be stored here, allowing us to connect to Discord.

To get your client token, go to your Discord Developer Portal and get to your project.

Go to the Bot tab.

In the token section, press the “Copy” button to copy the ID to your clipboard. Then, simply paste the token with your BOT_TOKEN variable.

Also, don’t show your ID to people you don’t trust, because if they obtain it, they can misuse it. I’m going to delete my project later, so my client ID will be invalid.

Lastly, let’s configure the package.json file for development. Open package.json.

Copy and paste the code below into the "scripts" section. While you’re at it, remove the "test" script because we won’t need it.

"start": "node index.js",
"devStart": "nodemon index.js"

After doing this, your "scripts" section should look like the one shown in the below image.

Now that we’ve set up everything, let’s get into development.

Step 4: Coding the Bot

Open your index.js file.

Let’s start by importing our packages into our index.js file. This will allow us to use them in our project. Add the below code to your index.js file to import the needed dependencies using require.

require('dotenv').config()const Discord = require('discord.js')
const client = new Discord.Client();

The first line imports dotenv, the package we’re going to use for handling .env files. We’re also importing the discord.js library and creating a reference to our bot using the client variable.

Now, let’s add our bot to a Discord server. I suggest you create a dedicated server for bot testing. Once, you’ve created a server, go back to your Developer Portal.

Go to the OAuth2 tab.

Scroll down to the “Scopes” section and select “bot”, because that’s what we’re creating.

In the “Bot Permissions” section, select “Manage Roles” and “Send Messages”. When the user is adding the bot, these are the permissions it will ask the user when they’re adding the bot to their server. You can share this link with anyone, and it will allow them to add the bot to their server.

Copy the link at the bottom of the “Scopes” section and go to that link to add your bot to a server. You can share this link with anyone, and it will allow them to add the bot to their server as well.

If you did the steps correctly, the bot should have been added to the server.

Let’s connect the client ID to our bot with the code below.

client.login(process.env.BOT_TOKEN)

The client is referring to our bot and the login is connecting it to our token, sort of like a password. The process.env is the file path to our .env file.

Let’s start up our bot. To do that, open the terminal, go to your project folder directory, and run npm run devStart.

You should see this message. If you don’t, check your package.json for any syntax errors.

As you can see, our bot is now online.

Now, let’s make our bot log a message in the console so we know it’s running successfully. Let’s create a function that runs when the bot is ready.

client.on("ready", () => {// Code goes here})

Once again, the client refers to the bot. The .on() will trigger the function on an event, in our case "ready". Inside the function, let’s do a console.log() that logs “Bot is ready” to the terminal.

client.on("ready", () => {console.log("Bot is ready")})

This will display a message in the console. Save the file and check the terminal.

Awesome, our bot has started up successfully! Let’s create some commands.

We’re going to create another client.on() function with an event of "message". This will listen for any messages. In the function, add the parameter of msg.

client.on("message", msg => {// Code goes here})

Okay, so let’s create a command.

client.on("message", msg => {if (msg.content === "hey") {msg.reply("hi there")}})

As you can see, we’ve made an if statement. The msg.content looks for a message matching its value, in our case “hey”. The msg.reply will reply to the user, by mentioning their username. Let’s test out the command on Discord.

As you can see, our bot is working! It replied to our message by mentioning our username. We can also create a command that answers the message without pinging the user. Let’s create a new command called “u good bro”.

client.on("message", msg => {if (msg.content === "hey") {msg.reply("hi there")} else if (msg.content === "u good bro") {// code here}})

Instead of using .reply(), we’re going to send the message in the text channel of which the user typed their command. To do that, we’ll use msg.channel.send().

if (msg.content === "hey") {msg.reply("hi there")} else if (msg.content === "u good bro") {msg.channel.send("nah")}})

The msg means a message, thechannel specifies the channel in which the user typed in the command, and the send() is the function that sends the message.

Awesome! At this point, we’ve created a simple Discord bot with simple commands. Now, let’s learn how we can let our bot do some more complex tasks.

If you have done everything correctly, your code should look like this:

This is good, but let’s create some more complex commands. If you’re making a moderation bot, the commands we make will be quite useful.

Let’s say someone on your server keeps deleting their messages. You can create a command on your bot that will alert that user to stop deleting their messages. Let’s create a .on() function that listens for any messages being deleted. It’s going to listen for "messageDelete" and will accept the parameter of msg so we can send messages in the channel.

client.on("messageDelete", msg => {// Code goes here})

Alright, now that we set up our function, we can make it send a message when the user deletes a message. For this, I am going to be using .reply() because I want the bot to specifically ping the user that’s deleting the messages.

msg.reply("stop deleting messages!!");

Once you add that, your code should look like this:

Let’s go on Discord and test out our function.

As you can see, it works! There is one problem though. The bot will send the warning message only for messages that have been sent after the bot’s initialization. This means that the bot can only read the messages after it. We want our bot to send a message for any message being deleted. To do that, we need to grant access to all the messages for our bot. In your client variable, add a property called partials.

const client = new Discord.Client({
partials:
});

Inside partials, add ['MESSAGE'] so that the bot will know to read all messages. Your code should look like this:

const client = new Discord.Client({
partials: ['MESSAGE']
});

Great! We’ve successfully allowed our bot to read all messages.

You can also make your bot react to a message. Let’s create a command called rtn is epic. We want this command to react to our message with a ❤️.

client.on("message", msg => {if (msg.content === "hey") {msg.reply("hi there")} else if (msg.content === "u good bro") {msg.channel.send("nah")} else if (msg.content === "rtn is epic") {// Code goes here}})

Reacting to a message is super simple, just use the .react() function.

client.on("message", msg => {if (msg.content === "hey") {msg.reply("hi there")} else if (msg.content === "u good bro") {msg.channel.send("nah")} else if (msg.content === "rtn is epic") {msg.react("❤️")}})

Let’s test out our function in Discord.

Awesome! It works!

Let’s create one last command. This command will grant a role.

First, create a new command called gimme mod. This will grant the user the moderator role.

Let’s first create a moderator role. To do that, go to your Discord server and go to the settings menu.

Select “Server Settings”.

Select “Roles”.

.

You can click on the + to create a role, but as you can see, I have already created a moderator role. Also, every time you add a bot to your server, it gets assigned a role. The role will handle all the permissions. As you can see, our bot “my first bot” has its own role. Make sure the role you want to grant is below the role of your bot, like so:

On Discord, each role has a unique ID. It makes the roles unique. To grant a role with our Discord bot, we need the ID of our role. To get the ID of the role, right-click on the role and select “Copy ID”.

Now, let’s create a new command.

client.on("message", msg => {if (msg.content === "hey") {msg.reply("hi there")} else if (msg.content === "u good bro") {msg.channel.send("nah")} else if (msg.content === "rtn is epic") {msg.react("❤️")} else if (msg.content === "gimme mod") {// code goes here}})

To grant roles, we need to use member.roles.add(). This will grant the role to whoever typed in the command.

msg.reply("hi there")} else if (msg.content === "u good bro") {msg.channel.send("nah")} else if (msg.content === "rtn is epic") {msg.react("❤️")} else if (msg.content === "gimme mod") {msg.member.roles.add("783390808028086272");}})

As you can see, I have also included the ID of my role here. Let’s test out our command on Discord.

Awesome! It worked! For some reason, if it didn’t work, make sure the ID is correct.

Great job! We have successfully learned the basics of a Discord bot. There’s one last thing to do, which is to host our bot. Right now, we’re using our computer to host the bot, but we need our bot running 24/7. We can’t use our main computer to have it run 24/7, so we’re going to use a hosting service called Heroku. It’s completely free.

Step 5: Hosting the Bot

In your bot’s folder, create a file called Procfile (with no file extension). This is a file that will talk to Heroku. In your Procfile, add the following lines:

worker: node index.js

Once you have completed that, push your code to a Git repository. I’m using GitHub (if you don’t know how to do this, follow this tutorial).

Now, go to Heroku.com and sign in to your account.

Select “New” > “Create new app”.

Give your app a name.

Click the “Create app” button.

Select GitHub.

Search for the GitHub repository containing your bot.

Select “Enable Automatic Deploys”.
This will restart the bot every time a change has been made.

Scroll back up and select “Settings” in the app menu (pictured above).

In the “Config Vars” section, we need to add our bot token. Create a new key-value pair by filling the “KEY” input with “BOT_TOKEN” and the “VALUE” input with the token from your .env file.

Awesome! Now, go back to the app menu and navigate to the Deploy page.

Select “Deploy Branch”.

Go to the Resources page.

Uncheck npm start and check node index.js. This will tell Heroku to run our bot 24/7.

You just learned how to set up, create, and deploy a Discord bot. In my opinion, creating these bots are very simple. I was surprised by how easy it was to create a Discord bot. These are only basic commands, though. If you’d like to learn more, I recommend using the Discord.js Guide and the official Discord.js website.

You can find the code for the bot here: https://github.com/realtechnerd/my-first-bot-tutorial.

--

--

Nithil Krishnaraj
TechTalkers

Co-founder and Writer of TechTalkers. Learning about technology and photography are my passions!