Tutorial

How To Build a Discord Bot with Node.js

Updated on January 18, 2022
English
How To Build a Discord Bot with Node.js

The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

Introduction

Discord is a chat application that allows millions of users across the globe to message and voice chat online in communities called guilds or servers. Discord also provides an extensive API that developers can use to build powerful Discord bots. Bots can perform various actions such as sending messages to servers, DM-ing users, moderating servers, and playing audio in voice chats. This allows developers to craft powerful bots that include advanced, complex features like moderation tools or even games. For example, the utility bot Dyno serves millions of guilds and contains useful features such as spam protection, a music player, and other utility functions. Learning how to create Discord bots allows you to implement many possibilities, which thousands of people could interact with every day.

In this tutorial, you will build a Discord bot from scratch, using Node.js and the Discord.js library, which allows users to directly interact with the Discord API. You’ll set up a profile for a Discord bot, get authentication tokens for the bot, and program the bot with the ability to process commands with arguments from users.

Prerequisites

Before you get started, you will need the following:

Step 1 — Setting Up a Discord Bot

In this step, you’ll use the Discord developers graphical user interface (GUI) to set up a Discord bot and get the bot’s token, which you will pass into your program.

In order to register a bot on the Discord platform, use the Discord application dashboard. Here developers can create Discord applications including Discord bots.

Image of the Discord application dashboard after first visiting https://discord.com/developers/applications

To get started, click New Application. Discord will ask you to enter a name for your new application. Then click Create to create the application.

Image of the prompt to create an application, with "Test Node.js Bot" entered as the name of the application

Note: The name for your application is independent from the name of the bot, and the bot doesn’t have to have the same name as the application.

Now open up your application dashboard. To add a bot to the application, navigate to the Bot tab on the navigation bar to the left.

Image of the bot tab of the application dashboard

Click the Add Bot button to add a bot to the application. Click the Yes, do it! button when it prompts you for confirmation. You will then be on a dashboard containing details of your bot’s name, authentication token, and profile picture.

Dashboard containing details of your bot

You can modify your bot’s name or profile picture here on the dashboard. You also need to copy the bot’s authentication token by clicking Click to Reveal Token and copying the token that appears.

Warning: Never share or upload your bot token as it allows anyone to log in to your bot.

Now you need to create an invite to add the bot to a Discord guild where you can test it. First, navigate to the URL Generator page under the OAuth2 tab of the application dashboard. To create an invite, scroll down and select bot under scopes. You must also set permissions to control what actions your bot can perform in guilds. For the purposes of this tutorial, select Administrator, which will give your bot permission to perform nearly all actions in guilds. Copy the link with the Copy button.

OAuth2 tab, with scope set to "bot" and permissions set to "administator"

Next, add the bot to a server. Follow the invite link you just created. You can add the bot to any server you own, or have administrator permissions in, from the drop-down menu.

Page from following the invite link, allowing users to add the bot to servers

Now click Continue. Ensure you have the tickbox next to Administrator ticked—this will grant the bot administrator permissions. Then click Authorize. Discord will ask you to solve a CAPTCHA before the bot joins the server. You’ll now have the Discord bot on the members list in the server you added the bot to under offline.

Members list of a Discord server with the newly created bot under the "offline" section of the members list

You’ve successfully created a Discord bot and added it to a server. Next, you will write a program to log in to the bot.

Step 2 — Creating Your Project

In this step, you’ll set up the basic coding environment where you will build your bot and log in to the bot programmatically.

First, you need to set up a project folder and necessary project files for the bot.

Create your project folder:

  1. mkdir discord-bot

Move into the project folder you just created:

  1. cd discord-bot

Next, use your text editor to create a file named config.json to store your bot’s authentication token:

  1. nano config.json

Then add the following code to the config file, replacing the highlighted text with your bot’s authentication token:

discord-bot/config.json
{
    "BOT_TOKEN": "YOUR BOT TOKEN"
}

Save and exit the file.

Next you’ll create a package.json file, which will store details of your project and information about the dependencies you’ll use for the project. You’ll create a package.json file by running the following npm command:

  1. npm init

npm will ask you for various details about your project. If you would like guidance on completing these prompts, you can read about them in How To Use Node.js Modules with npm and package.json.

You’ll now install the discord.js package that you will use to interact with the Discord API. You can install discord.js through npm with the following command:

  1. npm install discord.js

Now that you’ve set up the configuration file and installed the necessary dependency, you’re ready to begin building your bot. In a real-world application, a large bot would be split across many files, but for the purposes of this tutorial, the code for your bot will be in one file.

First, create a file named index.js in the discord-bot folder for the code:

  1. nano index.js

Begin coding the bot by requiring the discord.js dependency and the config file with the bot’s token:

discord-bot/index.js
const Discord = require("discord.js");
const config = require("./config.json");

Following this, add the next two lines of code:

discord-bot/index.js
...
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});

client.login(config.BOT_TOKEN);

Save and exit your file.

The first line of code creates a new Discord.Client and assigns it to the constant client. This client is partly how you will interact with the Discord API and how Discord will notify you of events such as new messages. The client, in effect, represents the Discord bot. The object passed into the Client constructor specifies the gateway intents of your bot. This defines which WebSocket events your bot will listen to. Here you have specified GUILDS and GUILD_MESSAGES to enable the bot to receive message events in guilds.

The second line of code uses the login method on the client to log in to the Discord bot you created, using the token in the config.json file as a password. The token lets the Discord API know which bot the program is for and that you’re authenticated to use the bot.

Now, execute the index.js file using Node:

  1. node index.js

Your bot’s status will change to online in the Discord server you added it to.

Image of the bot online

You’ve successfully set up a coding environment and created the basic code for logging in to a Discord bot. In the next step you’ll handle user commands and get your bot to perform actions, such as sending messages.

Step 3 — Handling Your First User Command

In this step, you will create a bot that can handle user commands. You will implement your first command ping, which will respond with "pong" and the time taken to respond to the command.

First, you need to detect and receive any messages users send so you can process any commands. Using the on method on the Discord client, Discord will send you a notification about new events. The on method takes two arguments: the name of an event to wait for and a function to run every time that event occurs. With this method you can wait for the event message—this will occur every time a message is sent to a guild where the bot has permission to view messages. Therefore you will create a function that runs every time a message is sent to process commands.

First open your file:

  1. nano index.js

Add the following code to your file:

discord-bot/index.js
...
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});


client.on("messageCreate", function(message) { 
                                         
});                                      

client.login(config.BOT_TOKEN);

This function, which runs on the messageCreate event, takes message as a parameter. message will have the value of a Discord.js message instance, which contains information about the sent message and methods to help the bot respond.

Now add the following line of code to your command-handling function:

discord-bot/index.js
...
client.on("messageCreate", function(message) {
  if (message.author.bot) return;
});
...

This line checks if the author of the message is a bot, and if so, stops processing the command. This is important as generally you don’t want to process, or respond to, bots’ messages. Bots usually don’t need to use information from other bots, so ignoring their messages saves processing power and helps prevent accidental replies.

Now you’ll write a command handler. To accomplish this, it’s good to understand the usual format of a Discord command. Typically, the structure of a Discord command contains three parts in the following order: a prefix, a command name, and (sometimes) command arguments.

An image of a typical Discord command reading "!add 1 2"

  • Prefix: the prefix can be anything, but is typically a piece of punctuation or abstract phrase that wouldn’t normally be at the start of a message. This means that when you include the prefix at the start of the message, the bot will know that the intention for this command is for a bot to process it.

  • Command name: The name of the command the user wants to use. This means the bot can support multiple commands with different functionality and allow users to choose between them by supplying a different command name.

  • Arguments: Sometimes if the command requires or uses extra information from the user, the user can supply arguments after the command name, with each argument separated by a space.

Note: There is no enforced command structure and bots can process commands how they like, but the structure presented here is an efficient structure that the vast majority of bots use.

To begin creating a command parser that handles this format, add the following lines of code to the message handling function:

discord-bot/index.js
...
const prefix = "!";

client.on("messageCreate", function(message) {
  if (message.author.bot) return;
  if (!message.content.startsWith(prefix)) return;
});
...

You add the first line of code to assign the value "!" to the constant prefix, which you will use as the bot’s prefix.

The second line of code you add checks if the content of the message the bot is processing begins with the prefix you set, and if it doesn’t, stops the message from continuing to process.

Now you must convert the rest of the message into a command name and any arguments that may exist in the message. Add the following highlighted lines:

discord-bot/index.js
...
client.on("messageCreate", function(message) {
  if (message.author.bot) return;
  if (!message.content.startsWith(prefix)) return;

  const commandBody = message.content.slice(prefix.length);
  const args = commandBody.split(' ');
  const command = args.shift().toLowerCase();
});
...

You use the first line here to remove the prefix from the message content and assign the result to the constant commandBody. This is necessary as you don’t want to include the prefix in the parsed command name.

The second line takes the message with the removed prefix and uses the split method on it, with a space as the separator. This splits it into an array of sub-strings, making a split wherever there is a space. This results in an array containing the command name, then, if included in the message, any arguments. You assign this array to the constant args.

The third line removes the first element from the args array (which will be the command name provided), converts it to lowercase, and then assigns it to the constant command. This allows you to isolate the command name and leave only arguments in the array. You also use the method toLowerCase as commands are typically case insensitive in Discord bots.

You’ve completed building a command parser, implementing a required prefix, and getting the command name and any arguments from messages. You will now implement and create the code for the specific commands.

Add the following code to start implementing the ping command:

discord-bot/index.js
...
  const args = commandBody.split(' ');
  const command = args.shift().toLowerCase();

  if (command === "ping") {
                           
  }                        
});
...

This if statement checks if the command name you parsed (assigned to the constant command) matches "ping". If it does, that indicates the user wants to use the "ping" command. You will nest the code for the specific command inside the if statement block. You will repeat this pattern for other commands you want to implement.

Now, you can implement the code for the "ping" command:

discord-bot/index.js
...
  if (command === "ping") {
    const timeTaken = Date.now() - message.createdTimestamp;
    message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
  }
...

Save and exit your file.

You add the "ping" command block that calculates the difference between the current time—found using the now method on the Date object—and the timestamp when the message was created in milliseconds. This calculates how long the message took to process and the "ping" of the bot.

The second line responds to user’s command using the reply method on the message constant. The reply method pings (which notifies the user and highlights the message for the specified user) the user who invoked the command, followed by the content provided as the first argument to the method. You provide a template literal containing a message and the calculated ping as the response that the reply method will use.

This concludes implementing the "ping" command.

Run your bot using the following command (in the same folder as index.js):

  1. node index.js

You can now use the command "!ping" in any channel the bot can view and message in, resulting in a response.

Image of bot replying in Discord to "!ping" with "@T0M, Pong! This message had a latency of 1128ms."

You have successfully created a bot that can handle user commands and you have implemented your first command. In the next step, you will continue developing your bot by implementing a sum command.

Step 4 — Implementing the Sum Command

Now you will extend your program by implementing the "!sum" command. The command will take any number of arguments and add them together, before returning the sum of all the arguments to the user.

If your Discord bot is still running, you can stop its process with CTRL + C.

Open your index.js file again:

  1. nano index.js

To begin implementing the "!sum" command you will use an else-if block. After checking for the ping command name, it will check if the command name is equal to "sum". You will use an else-if block since only one command will process at a time, so if the program matches the command name "ping", it doesn’t have to check for the "sum" command. Add the following highlighted lines to your file:

discord-bot/index.js
...
  if (command === "ping") {
    const timeTaken = Date.now() - message.createdTimestamp;
    message.reply(`Ping! This message had a latency of ${timeTaken}ms.`);
  }

  else if (command === "sum") {
                               
  }                            
});
...

You can begin implementing the code for the "sum" command. The code for the "sum" command will go inside the else-if block you just created. Now, add the following code:

discord-bot/index.js
...
  else if (command === "sum") {
    const numArgs = args.map(x => parseFloat(x));
    const sum = numArgs.reduce((counter, x) => counter += x);
    message.reply(`The sum of all the arguments you provided is ${sum}!`);
  }
...

You use the map method on the arguments list to create a new list by using the parseFloat function on each item in the args array. This creates a new array (assigned to the constant numArgs) in which all of the items are numbers instead of strings. This means later you can successfully find the sum of the numbers by adding them together.

The second line uses the reduce method on the constant numArgs providing a function that totals all the elements in the list. You assign the sum of all the elements in numArgs to the constant sum.

You then use the reply method on the message object to reply to the user’s command with a template literal, which contains the sum of all the arguments the user sends to the bot.

This concludes implementing the "sum" command. Now run the bot using the following command (in the same folder as index.js):

  1. node index.js

You can now use the "!sum" command in any channel the bot can view and message in.

Image of bot replying "The sum of all the arguments you provided is 6!" to "!sum 1 2 3", then replying "The sum of all the arguments you provided is 13! to "!sum 1.5 1.5 10"

The following is a completed version of the index.js bot script:

discord-bot/index.js
const Discord = require("discord.js");
const config = require("./config.json");

const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});

const prefix = "!";

client.on("messageCreate", function(message) {
  if (message.author.bot) return;
  if (!message.content.startsWith(prefix)) return;

  const commandBody = message.content.slice(prefix.length);
  const args = commandBody.split(' ');
  const command = args.shift().toLowerCase();

  if (command === "ping") {
    const timeTaken = Date.now() - message.createdTimestamp;
    message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
  }

  else if (command === "sum") {
    const numArgs = args.map(x => parseFloat(x));
    const sum = numArgs.reduce((counter, x) => counter += x);
    message.reply(`The sum of all the arguments you provided is ${sum}!`);
  }
});

client.login(config.BOT_TOKEN);

In this step, you have further developed your Discord bot by implementing the sum command.

Conclusion

You have successfully implemented a Discord bot that can handle multiple, different user commands and command arguments. If you want to expand on your bot, you could possibly implement more commands or try out more parts of the Discord API to craft a powerful Discord bot. You can review the Discord.js documentation or the Discord API documentation to expand your knowledge of the Discord API. In particular, you could convert your bot commands to slash commands, which is a best practice for Discord.js v13.

While creating Discord bots, you must always keep in mind the Discord API terms of service, which outlines how developers must use the Discord API. If you would like to learn more about Node.js, check out our How To Code in Node.js series.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
5 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

If you want to node script to run forever in the background, checkout the forever npm package: https://www.npmjs.com/package/forever

If you want forever to watch your file for changes and automatically reload, run it with the -w flag:

forever -w index.js

This comment has been deleted

    Additional Settings

    If you aren’t able to make the bot an administrator, then at least give it as many options possible under the “text permissions” column. When you follow the link to add the bot to the channel, make sure there is a green checkmark next to each of the items you selected. If you notice any denied permissions then your bot will not be able to do those activities. You may have to adjust your permissions on the server you are attempting to add the bot.

    There are also new setting for a bot you may want to adjust in the https://discord.com/developers/applications/

    • You may want to uncheck Public Bot if you want to control what servers the bot goes to
    • Check the items under the privileged gateway intents (Presence intent, server members intent, message content intent)

    Updated Script for discord.js v14

    Here is a new code snippt using discord.js v14

    // Require the necessary discord.js classes
    const { Client, Events, GatewayIntentBits } = require('discord.js');
    const { token } = require('./config.json');
    
    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
      ]
    });
    
    client.on("messageCreate", (message) => {
    
      if (message.author.bot) return;
      if (!message.content.startsWith(prefix)) return;
    
      const commandBody = message.content.slice(prefix.length);
      const args = commandBody.split(' ');
      const command = args.shift().toLowerCase();
    
      if (command === "ping") {
        const timeTaken = Date.now() - message.createdTimestamp;
        message.reply("Pong! This message had a latency of " + timeTaken.ms + ".");
      }
    
      else if (command === "sum") {
        const numArgs = args.map(x => parseFloat(x));
        const sum = numArgs.reduce((counter, x) => counter += x);
        message.reply("The sum of all the arguments you provided is " + sum + "!");
      }
    });
    

    Run script in background forever

    If you want your script to always stay running on your server in the background, look into the forever npm package: https://www.npmjs.com/package/forever

    Once you install it you can run your script: forever index.js

    If you want to see what scripts are running you can use forever list

    If you want forever to watch your file for changes and automatically reload it, you can run it with the -w hook:

    forever -w index.js

    Not recommended.

    No command handler (all commands in the main file). No informations about intents (very important when the bot hit 100+ servers). Nothing about slash commands. So it’s not “How To Build a Discord Bot with Node.js” but “how to build a very useless basic discord bot with node.js”.

    Don’t waste your time and take a look on YouTube.

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel