Building a Discord Bot with Node — discord.js & Setup

KJ Richmond
8 min readSep 1, 2023

--

A meme about the glory of making discord bots

Welcome to Day 1 of your journey of building your own bot in Discord and becoming a Nodejs superhero! I will show you the ropes so that one day you too can get yourself a shiny Active Developer badge on your Discord profile and so you can level up your Nodejs skills!

Disclaimer: I want to make you great so I will intentionally leave some steps somewhat vague so you can problem-solve like a professional developer! But if you have questions or need clarification do not hesistate to leave a comment!

What is Discord.js?

Well, discord.js is a powerful Node.js module that allows you to interact with the Discord API very easily. It takes a much more object-oriented approach than most other JS Discord libraries, making your bot’s code significantly tidier and easier to comprehend.

Usability, consistency, and performance are key focuses of discord.js, and it also has nearly 100% coverage of the Discord API. It receives new Discord features shortly after they arrive in the API.

Getting Started

Before we get to using discord.js we have to install Node (which includes npm). Once you have npm downloaded run the following commands in your command prompt or terminal.

mkdir kirby #Name it whatever you want
cd kirby
npm init

Moving forward I will be referring to the bot as Kirby but feel free to name yours whatever you'd like!

After running these commands npm will ask you to fill out a form. Your form should look like this:

package name: (kirby) 
version: (1.0.0)
description:
entry point: (index.js) src/index.js
test command:
git repository:
keywords:
author:
license: (ISC)

Note the change to the entry point!

Installing discord.js & Other Dependencies

Before we can start using discord.js, we need to install it. You can install discord.js using npm. Run the following command in your terminal.

So first in your project folder run the following commands in your terminal:

npm install discord.js doenv

dotenv: Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. To put it simply, it allows us to use the aforementioned secrets we place inside of our .env file.

Creating Your Bot

Now that you’ve installed Node, discord.js, and hopefully a linter, you’re almost ready to start coding! The next step you need to take is setting up an actual Discord bot application via Discord’s website.

It’s effortless to create one. The steps you need to take are as follows:

  1. Open the Discord developer portal in a new window and log into your account.
  2. Click on the New Application button.
  3. Enter a name and confirm the pop-up window by clicking the Create button.

Afterwards, you should see a page like this:

Discord developer application general tab
Edit your application’s name, description, and avatar here.

Saved any of your changes, then move on by selecting the Bot tab in the left panel.

Discord developer application bot tab
The bot tab

If you are Bot tab does not look the same. Click the Add Bot button on the right and confirm the pop-up window by clicking Yes, do it!.

Note: You should be an admin or the owner of a server to add your bot.

Generating & Storing Bot Token

  1. Click the Reset Token button.
  2. Copy the entire token given
  3. In your project folder create a .env file. This will be where we store our secrets 🥸! Learn more about environment variables here.
  4. In the .env file add the following (replace with your bot info):
    BOT_TOKEN=YOUR-BOT-TOKEN-HERE
  5. Save and close the .env in your editor.

Do not share your token! I recommend saving it in a TXT file on your personal computer. Do NOT let it be visible on a public repository. If your bot token has been compromised click the “Reset Token” and the old token will become invalid.

Create a Bot Invite Link

  1. In the Discord Developer portal click the 0Auth2 button followed by the URL Generator
  2. Under SCOPES check bot and applications.commands
Discord developer application 0auth2 and url generator tab
0Auth Tab w/ checked scopes

3. Copy and open the URL generated at the bottom

4. Select the server you would like to add your bot

And your bot is now a member on your server! But it is offline.

Organizing Workspace

Before we get our bot online and start using discord.js, we need to add to create the main file. This file will be the “heart” of our bot.

  • In the root directory create a folder called src
  • Within the src folder create a file named index.js

The /src folder is used to store the file with the primary purpose of reading (and/or editing) the code. Which in this instance is the index.js file. The /src folder will also be where we add all subsequent commands & functions to our bot.

Your workspace should look like this:

kirby/
├── node_modules/
│ ├── (node.js modules and dependencies)

├── src/
│ ├── index.js

├── .env
├── package.json
└── package-lock.json

The workspace is simple now but throughout this series, I hope to show you how to make a scalable, maintainable, and functional node application. Note, later tutorials will build off of this.

Getting Your Bot Ready to be Online

Let’s start with the basics of getting our bot online using discord.js. Our first taste of success will be from the bot appearing online on the server we added it. We can do this starting with the src/index.js file using the following code:

// Require the necessary discord.js classes
const { Client, GatewayIntentBits } = require('discord.js');
// Initialize dotenv thus allowing the use of process.env
const dotenv = require('dotenv');
dotenv.config();

// Get the token from the .env file
const token = process.env.BOT_TOKEN;

// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

/**
* @description When the client is ready (logged in), this code will run
* @param {Client} cli The client
*/
client.on("ready", cli => {
console.log(`${cli.user.displayName} is online!`);
});

// Login to Discord with your bot's token
client.login(token);

And just like that you've created a client instance of your Discord bot and logged it into Discord. The GatewayIntentBits.Guilds intents option — is like the engine that keeps your discord.js client running. It ensures all the caches for guilds, channels, and roles info is prepped and ready behind the scenes.

Intents aren’t just your everyday notifications, they’re like the VIP pass to deciding which Discord events your bot gets to attend. And this is the minimum so feel free to explore the docs and enable more than just the basics. You can read more about the other intents here.

Before running your bot I would like to draw your attention to the following lines:

  • client.on(“ready”, cli => { — is used to set up a callback function that will be executed when the ready event occurs. The ready event is emitted when the bot successfully logs in to Discord. This “cli” is an instance of the Client class
  • console.log(`${cli.user.displayName} is online!`); — the callback function simply logs a message indicating that the bot has logged in (online) and displays its display name. cli.user.displayName the user is a property in the Client class and displayName is a property in the ClientUser class.
  • client.login(token); — the login method is called at the end with the bot's token as its argument. The bot token is a unique identifier that allows the bot to authenticate itself with the Discord servers. Once the bot is authenticated and successfully logged in, the 'ready' event will be triggered, and the provided callback function will be executed.

I know that was a lot but trust me the more you continue to work with Node and discord.js it will all make sense. I recommend familiarizing yourself with the docs or contacting me for any guidance.

It’s ALIVE!!!

To run your bot application in your terminal run: node .

The output in your terminal should read: Kirby is online! or WhateverYourBotsName is online!

Note: In the context of running a script with Node.js using the command node ., the dot (.) represents the current directory. When you run node ., you're telling the Node.js interpreter to execute the JavaScript file located in the current directory.

Usually, when you run node ., Node.js will look for a JavaScript file named index.js or another file specified in the package.json file's "main" field, and it will execute that file. But when we initialized npm we made it so the "main" field points to src/index.js.

Also to “kill the terminal” use control + c on Mac and ctrl + c on windows. Killing the Terminal means to close or terminate the running instance of a terminal window or command prompt that is executing a program.

Conclusion

And just like that you are already you are both a Node Developer and a Discord Bot Creator! Hooray!

Now to be great you must continue to learn and practice. Though this was a lot just to have a bot that just takes up space in your server, you should be proud because you took the first step!

  • In the next part of the series, I will show you how to create your very own Chat Commands. It will also cover user permissions & more!
  • Join my Discord to connect with me and be a part of a growing community of amazing & talented people!
  • Clap for the story, Comment, Follow & all that Jazz!

Finally, I just want you to know you are a gift to this world! And I hope you are taking care of yourself because if you don’t who will?!

BONUS! Setting Bot Status

Just because your bot is going to sit on your server not doing anything cool yet doesn’t mean it can’t have an online status for the public to see. So I will show you how to set your bot’s status while online!

Within the src/index.js file edit the client.on function:

client.on("ready", cli => {
console.log(`${cli.user.displayName} is online!`);
// Sets bot's status to "Watching you, watching me"
client.user.setPresence({ activities: [{ type: 3, name: `you, watching me `}]})
});
Before Presence
Kirby Discord status set to watching you, watching me
After Presence
  • Try and figure out how I did this. I added a little hint in the “Sources” section.
  • Challenge! Try and make it so that each activity has a type specific to it. In the next part of the series, I will show you the answer!

Sources:

--

--