Node.js for Discord Bot

Using Node.js To Create a Discord Bot

Josh Green Development Technologies, JavaScript, Node.js, Programming, Tutorial Leave a Comment

Attention: The following article was published over 3 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

After being nearly two years deep into a global pandemic, it’s no surprise to find that many aspects of our everyday lives are shifting to virtual spaces. From visiting family and friends to meeting with your manager at work, odds are you may be staring into a computer screen with a webcam pointing at you, with your extremely clean and tidy office on display in the background.

From Zoom to Skype to Microsoft Teams, there is an endless number of platforms to help keep you connected. One such platform is Discord – a service primarily intended for gaming that allows you to voice chat, video chat, or screen share with a community you have developed on your own hosted “server.”

One of Discord’s best features is a developer portal with an open API that allows you to add bots and apps to your server, as well as write your own. The most popular bots on my server include a music bot that streams to a voice channel for all to hear and HaikuBot, which detects when someone has accidentally posted a message in a 5-7-5 syllable format and reposts the message with proper formatting as a congratulation for such an achievement.

The true beauty is the ability to create your own custom solutions to fill your needs. So in this brief tutorial, I’ll show you how to get up and running writing your own Bots and Apps for Discord with Node.js.

Part 1: Project Setup

Because this is a Node.js tutorial at its core, I’m going to assume that if you’re reading, you have a baseline understanding of JavaScript. If not, feel free to check out some of the other awesome Keyhole Technical Blogs! Filter by ‘JavaScript’. It’s also worth mentioning this tutorial is written using macOS, but all steps are nearly equivalent for Windows users.

I’ll be using Visual Studio Code for this tutorial.

To begin, let’s create a directory for our project. Use the terminal or finder to create a new directory. I’m going to name mine Keyhole Discord App.

This application will eventually be deployed, so let’s make sure we create a package.json file with all of our dependencies.

npm init -y

Head on over to the Discord.js website. From there, you can install discord.js. If you’re on macOS like me, change the directory into your tutorial-bot folder and install discord.js.

Keep in mind this is a 3rd party library that is not part of the core Node.js library, which is why we’re installing it separately.

 npm i discord.js

You’ll notice that discord.js has been added to the dependency list in our package.json file if this was done properly.

Let’s create a folder for our code. Let’s create a .env file as well.

After you make this file and directory, the project structure should look like this:

Discord Bot with NodeJS code

Head over to the developer portal for Discord. You will need a Discord account to access this page. Click the blue-button near the top right titled “New Application” and give your app a name. I named mine “Keyhole Tutorial Bot.”

Next, click on “Bot” on the right. Then, select “Add Bot.” Now, under “Token,” click copy.

In your .env file, enter the following and paste your token after the equals sign. Be sure to keep your bot token private.

TOKEN= 

Next, go back to your developer dashboard and copy your Client ID. This will be under the OAuth2 tab on the menu to the left of the screen.

Next, navigate to the following web address. Be sure to substitute the Client ID you copied from the last step and paste it over YOUR_CLIENT_ID in the URL.

https://discord.com/api/oauth2/authorize?client_id=YOUR_CLIENT_ID&scope=bot

From here, you will be able to choose a server to add your application to. I created a new server called “Test Server” as a playground environment. I highly recommend doing this if you have a primary server that you share with others. You can also only add bots to servers where you have the Manage Server permission for yourself.

This should be it for project setup, and if you’ve made it this far, I congratulate you!

To recap, we…

  1. Created a new project
  2. Installed Discord.js
  3. Created a new Application in the Discord development portal
  4. Setup our Application’s token in our project
  5. Created a new server and added our Application to the server

Pat yourself on the back! Once you get over these annoying setup steps, we can start to code and see our application come to life.

Part 2: Bringing The Application Online

It’s important to note that Discord.js uses Object Oriented Programming patterns and terminology.

Here is the basic layout of your app.

require('dotenv').config();
const {Client, Intents} = require('discord.js');
 
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});
 
client.once('ready', () => {
 console.log('Keyhole Discord App online');
})
// Bring the bot online on your server
client.login(process.env.DISCORD_TOKEN);

This is the bare minimum you need to bring a Discord Application online. On line 13 I’ve provided a variable name for my token instead of hard coding it into the application. This helps make your app secure and prevents outsiders from fiddling with your bot.

In the terminal, type in the following command, and go look at your Discord server. Your application should now show up as an online user. Fun, right?

node .

As you can see, our bot should appear on the right-hand side of the Discord server with a green status icon, indicating that it is online.

NodeJS for Discord Bot

Part 3: Communicating With Your Bot

So you’ve set up your new Discord application, added it to your server, and brought it online. Now what? Let’s work on talking to our bot and making it talk back to us directly in our Discord server.

We’re going to give our Bot’s chat commands a prefix to keep its functionality separate from any other bots we may have on the server. For example, a music bot may respond to…

@play Never Gonna Give You Up

But we don’t really want our new application to pick up on that command. For this tutorial, let’s use an exclamation point as our command prefix.

Now, anytime we add a ! before a command, the server will know we’re trying to communicate with our specific application.

Add the following code to your main class to send a message and have your bot reply.

require('dotenv').config();
 
const {Client, Intents} = require('discord.js');
 
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});
 
 
client.once('ready', () => {
 console.log('Keyhole Discord App online');
})
 
// Our bots chat command prefix
const prefix = '!';
 
client.on('message', message => {
 /* If the message does not start with our prefix
 or if the author is the bot, do not continue */
 if(!message.content.startsWith(prefix) || message.author.bot) return;
 
 //parse the command provided on the Discord server
 const args = message.content.slice(prefix.length).split(/ +/);
 const command = args.shift().toLowerCase();
 
 // define your commands here
 if(command === 'greet') {
   message.channel.send('Hello world');
 }
})
 
// Bring the bot online on your server
client.login(process.env.DISCORD_TOKEN);

Now, heading over to the Discord server…

You type the !greet command, and the bot replies to you. Congratulations! This is basically the entry point to any Discord Application. From here, you can get creative as you want.

Wrapping Up

In a post-COVID world, online communication has become the primary method. This neat little trick allows you to have more command over the tools you use to stay connected socially and at work. There’s value in being able to customize and tweak a platform like Discord to fit your needs!

You could write a bot that allows your users to keep a running game journal everyone can contribute to, remember user’s birthdays, or simply repost funny cat pictures when someone gives the !cat command.

I hope you enjoyed this tutorial! Please let me know if you have any questions or feedback in the comments below.

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments