One place for hosting & domains

      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 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

      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 that allows you to add the bot Discord guilds where you can test the bot. First, navigate to 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

      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

      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:

      Move into the project folder you just created:

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

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

      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:

      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:

      Now 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:

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

      index.js

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

      Following this, add the next two lines of code:

      index.js

      ...
      const client = new Discord.Client();
      
      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 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:

      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 let’s create a function, which runs every time a message is sent, to process commands.

      First open your file:

      Add the following code to your file:

      index.js

      ...
      const client = new Discord.Client();
      
      
      client.on("message", function(message) { 
                                               
      });                                      
      
      client.login(config.BOT_TOKEN);
      

      This function, which runs on the message 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:

      index.js

      ...
      client.on("message", 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, or want to, be using our bot, 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

      • 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:

      index.js

      ...
      const prefix = "!";
      
      client.on("message", 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:

      index.js

      ...
      client.on("message", 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:

      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:

      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):

      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

      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:

      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". We 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:

      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:

      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):

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

      Image of bot replying

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

      index.js

      const Discord = require("discord.js");
      const config = require("./config.json");
      
      const client = new Discord.Client();
      
      const prefix = "!";
      
      client.on("message", 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.

      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. You could also read this set of guidelines on how to best implement a Discord bot and provides tips on how to design Discord bots. If you would like learn more about Node.js check out our How To Code in Node.js series.



      Source link