DEV Community

Cover image for Build and Deploy a Discord Bot with Node and Discord.js in 5 minutes
Gabe Romualdo
Gabe Romualdo

Posted on • Edited on • Originally published at xtrp.io

Build and Deploy a Discord Bot with Node and Discord.js in 5 minutes

Title assumes 265 words per minute reading time, as used by Medium and others.

Discord bots can be useful in doing a variety of things like playing music in a voice chat, or sending automated announcements when a Youtuber releases a new video.

I'm active on several Discord servers myself and have always wanted to build my own Discord bot. After building, deploying, and using my own bot for over a month now, I've written this article as a starting point in building a basic bot and moving from there.

We'll be building a bot that does something pretty simple: solves math equations. Users will be able to send a message on any channel that looks like !solve [math equation] and receive a response with the calculated result. For example:

Bot Functionality Graphic

Before Reading, You Should:

  • Know basic JavaScript and Node.js (with Node and NPM installed)
  • Have a Discord account (create one here)

1. Create a Discord API Application and Bot

Go to discord.com/developers/applications and click 'New Application' on the top right. Let's call the app 'Solver Bot'.

New Application Button Screenshot

By creating an app, you'll be able to get a unique API key to connect to the Discord API, create a bot, and do things like send and receive messages with that bot.

Now click on the 'Bot' tab on the right sidebar and click 'Add Bot'.

Bot Tab and Add Bot Screenshot

Add a profile picture to the bot by importing a file from your local machine.

I'll be using an icon which you can download here (this icon is CC0 Licensed, and you can use it without attribution).

Bot Icon and Name Screenshot

2. Add Your Bot to a Server!

Now that we've created a Discord API App with a bot account, we can add the bot to a server. I recommend making your own server to test your bots.

To add a bot to a server, all we need is an Discord OAuth2 URL. Upon opening this URL, any Discord user can add your bot to a server they own, and grant it permissions.

To generate the URL, open up the OAuth2 tab.

You'll see a grid of checkboxes, and here, select the 'bot' option. Another grid should appear, and here is where you'll select bot permissions. For this basic bot, we'll just need to manage and read messages.

App and Bot Scopes and Permissions Screenshot

Given these selected options, Discord automatically generates an OAuth2 URL, which you can see in the input box under the first grid. The URL should look something like https://discord.com/oauth2/....

Try copying and opening the URL! You should be able to add the bot to any servers you own.

Discord OAuth2 URL

3. Create the Functionality of Your Bot With Node and Discord.js

Let's start building the functionality of the bot in Node.

Make a new folder (or Git repository if that's what you prefer) on your machine called discord-solver-bot.

On your Terminal or Command Line, navigate to the folder and run npm init, adding any the necessary details when you see fit.

Now, let's add our dependencies. We'll be using Discord.js, a package which simplifies connecting and using the Discord API. For solving math equations, we'll use the useful Equations module.

Run npm install discord.js equations --save to install these packages.

Okay, now we can create an index.js file in the folder and start writing some code.

Command Line Example of Creating a Node Project and Adding Packages

We can start by importing any necessary packages.

const Discord = require('discord.js');
const Equation = require('equations').default; // .default to fix a problem I encountered while importing without it
Enter fullscreen mode Exit fullscreen mode

Connect to Your Bot With Your Bot Token and Login to Discord

To connect to your bot with Discord.js, we initialize Discord.js Client object to connect to the Discord API.

To login with our bot with the client, we need the bot token. Copy the token by going to your app in the developer portal > bot > token > copy.

Now we can login to our bot by calling the Client login function and passing the copied token.

const client = new Discord.Client();
client.login("[your bot token here]");
Enter fullscreen mode Exit fullscreen mode

Don't share your bot token with anyone else. It can be used to take complete control over your bot.

Check if Your Bot is Logged In

To check if your bot is logged in and ready to do things on Discord, use the Client ready event:

client.on('ready', async () => {
  console.log(`Logged in successfully as bot!`);
});
Enter fullscreen mode Exit fullscreen mode

Try running the bot by running node index.js. You should see that your bot is logged in. In Discord, you should also be able to see that the bot is marked as online.

Bot Logged In Screenshot

Listen for a Message and Respond

Use the client message event to listen any time a user sends a message anywhere on any server the bot is on. The event comes with a message object which contains the content (text content of the message) property among others.

The object also has a .reply method, for your bot to reply to the message directly to the user that sent it.

Typically a message we're looking for looks like !solve [equation here].

So, all we have to do is check if the message starts with '!solve ', and then solve the equation written afterwards. We can do this with the JavaScript string .startsWith and .slice functions respectively.

For solving the equation the equations package has a .solve function to solve any given equation. .solve throws an error if the equation is not valid, and we can catch that error to reply saying the equation could not be solved.

Here's what this code looks like:

client.on('message', (msg) => {
    msg.content = msg.content.trim(); // remove extra whitespace
    const flag = '!solve ';
    if (msg.content.startsWith(flag)) {
        const toSolve = msg.content.slice(flag.length, msg.content.length);
        try {
            const solved = Equation.solve(toSolve);

            msg.reply(`${toSolve} = ${solved}`); // backticks (TLs) are used to embed variables in strings like `${var}`
        } catch (err) {
            msg.reply(`Could not solve the equation '${toSolve}'.`);
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

4. We're Done! Let's Test the Bot

After running node index, go to a server with the bot (in my case my bot testing server), and try sending a message like !solve 2 + 2. You should see a response like 2 + 2 = 4. You can additionally try more complex equations, and test the error checking with a malformed equation.

Bot Functionality Screenshot

5. Deploying Your Bot and Next Steps

Deploying your bot is pretty simple. All you have to do is keep the index file (in this case node index) running whenever you want your bot to be online, typically 24/7. You can choose to run it on an old computer or Raspberry Pi, your own server, or you can choose to deploy on a platform like Heroku.

In terms of next steps in building a more complex bot, the Discord.js documentation can be really useful in using the Discord API to perform functions on text and voice channels, multiple servers, direct messages, and more.

In sharing your bot, there are many websites dedicated to listing Discord bots, including bots.ondiscord.xyz, discord.bots.gg, and top.gg. Building a website for your bot can be useful in showcasing its features and linking the URL to add the bot to a server. Sharing the bot among servers you own are know the owner of can also be useful.

Thanks for Reading

View the source code and assets here, at my tutorials repo.

I hope you enjoyed this post and found it useful in creating your own Discord bots with Node and Discord.js.

Thanks for scrolling.

— Gabriel Romualdo

Top comments (0)