Random Posts

Discord Prompts for 2 Channel Auth at Login Updated FREE

Discord Prompts for 2 Channel Auth at Login

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

Introduction

Discord is a chat awarding that allows millions of users across the globe to bulletin 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 diverse 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 fifty-fifty games. For case, 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 lot will build a Discord bot from scratch, using Node.js and the Discord.js library, which allows users to straight interact with the Discord API. Yous'll ready a profile for a Discord bot, become authentication tokens for the bot, and programme the bot with the ability to process commands with arguments from users.

Prerequisites

Before you go started, you volition demand the following:

  • Node.js installed on your development machine. To install this on macOS or Ubuntu 20.04, follow the steps in How to Install Node.js and Create a Local Development Surround on macOS or the Installing Node.js with Apt Using a NodeSource PPA section of How To Install Node.js on Ubuntu 20.04.

  • Any text editor of your choice, such as Visual Studio Code, Atom, Sublime, or nano.

  • A free Discord business relationship with a verified email account and a complimentary Discord server you volition use to test your Discord bot.

Step one — Setting Upwards a Discord Bot

In this pace, you'll use the Discord developers graphical user interface (GUI) to ready a Discord bot and get the bot's token, which yous will pass into your program.

In gild to register a bot on the Discord platform, utilize 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 contained from the name of the bot, and the bot doesn't accept to have the same name as the application.

Now open up 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 yous for confirmation. Y'all volition then exist on a dashboard containing details of your bot's name, hallmark token, and profile moving-picture show.

Dashboard containing details of your bot

You tin modify your bot's name or profile picture show here on the dashboard. Yous also need to copy the bot's hallmark token by clicking Click to Reveal Token and copying the token that appears.

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

Now yous demand to create an invite to add the bot to a Discord guild where you tin test it. First, navigate to the URL Generator page nether the OAuth2 tab of the awarding dashboard. To create an invite, scroll downwards and select bot nether scopes. Yous must as well set permissions to control what actions your bot can perform in guilds. For the purposes of this tutorial, select Ambassador, which will give your bot permission to perform well-nigh 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 yous only created. You tin add together the bot to any server you ain, or have administrator permissions in, from the drop-downwards bill of fare.

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

Now click Go along. Ensure y'all have the tickbox next to Administrator ticked—this will grant the bot administrator permissions. Then click Authorize. Discord will ask yous to solve a CAPTCHA before the bot joins the server. You'll now have the Discord bot on the members list in the server y'all 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 plan to log in to the bot.

Stride ii — Creating Your Project

In this stride, y'all'll set the basic coding environment where you volition build your bot and log in to the bot programmatically.

Outset, you demand to fix upwards a project folder and necessary project files for the bot.

Create your project folder:

                      
  1. mkdir discord-bot

Move into the projection binder 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

So add the following code to the config file, replacing the highlighted text with your bot'southward 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 volition shop details of your projection and information near the dependencies you'll apply for the project. You lot'll create a package.json file past running the post-obit npm control:

                      
  1. npm init

npm will ask yous for diverse details about your projection. If you would similar guidance on completing these prompts, you can read almost them in How To Use Node.js Modules with npm and packet.json.

Y'all'll at present install the discord.js packet that you will utilize to collaborate with the Discord API. You can install discord.js through npm with the post-obit command:

                      
  1. npm install discord.js

Now that you've ready up the configuration file and installed the necessary dependency, you're ready to begin building your bot. In a existent-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 alphabetize.js in the discord-bot folder for the code:

                      
  1. nano index.js

Brainstorm coding the bot by requiring the discord.js dependency and the config file with the bot'due south token:

discord-bot/alphabetize.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"            ]            }            )            ;            customer.            login            (config.            BOT_TOKEN            )            ;                  

Save and exit your file.

The offset line of code creates a new Discord.Client and assigns information technology to the constant client. This client is partly how you lot will interact with the Discord API and how Discord will notify you of events such as new letters. The client, in outcome, 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 heed to. Here you have specified GUILDS and GUILD_MESSAGES to enable the bot to receive bulletin events in guilds.

The second line of code uses the login method on the customer 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 plan is for and that you're authenticated to use the bot.

Now, execute the index.js file using Node:

                      
  1. node alphabetize.js

Your bot'south status will change to online in the Discord server you added information technology to.

Image of the bot online

You've successfully gear up a coding environs and created the bones lawmaking for logging in to a Discord bot. In the side by side step you'll handle user commands and go your bot to perform actions, such as sending messages.

Step 3 — Treatment Your First User Command

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

First, you need to observe and receive any messages users ship so you lot can process any commands. Using the on method on the Discord customer, Discord will send you a notification about new events. The on method takes two arguments: the proper noun of an outcome to wait for and a function to run every time that effect occurs. With this method you can look for the event bulletin—this will occur every fourth dimension a message is sent to a guild where the bot has permission to view messages. Therefore y'all will create a function that runs every time a bulletin is sent to process commands.

Starting time open your file:

                      
  1. nano index.js

Add the post-obit lawmaking 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 part, which runs on the messageCreate event, takes bulletin every bit a parameter. message volition have the value of a Discord.js message instance, which contains information about the sent message and methods to aid the bot answer.

At present add the following line of code to your command-treatment part:

discord-bot/alphabetize.js

                      ...            customer.            on            (            "messageCreate"            ,            function            (            message            )            {                          if              (bulletin.author.bot)              render              ;                        }            )            ;            ...                  

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

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

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

  • Prefix: the prefix can exist anything, but is typically a piece of punctuation or abstract phrase that wouldn't unremarkably be at the first of a message. This ways that when you include the prefix at the showtime of the bulletin, the bot will know that the intention for this control is for a bot to process it.

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

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

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

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

discord-bot/index.js

                      ...                          const              prefix              =              "!"              ;                        client.            on            (            "messageCreate"            ,            role            (            message            )            {            if            (message.author.bot)            render            ;                          if              (              !bulletin.content.              startsWith              (prefix)              )              return              ;                        }            )            ;            ...                  

You add the showtime line of lawmaking to assign the value "!" to the constant prefix, which y'all volition use as the bot'south prefix.

The second line of code you add together checks if the content of the bulletin the bot is processing begins with the prefix y'all prepare, and if it doesn't, stops the message from continuing to process.

At present you must catechumen the rest of the message into a control name and any arguments that may exist in the bulletin. Add together the following highlighted lines:

discord-bot/index.js

                      ...            client.            on            (            "messageCreate"            ,            function            (            message            )            {            if            (message.author.bot)            render            ;            if            (            !bulletin.content.            startsWith            (prefix)            )            render            ;                          const              commandBody              =              message.content.              slice              (prefix.length)              ;                                      const              args              =              commandBody.              carve up              (              ' '              )              ;                                      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 divide method on information technology, with a space as the separator. This splits it into an assortment of sub-strings, making a split wherever there is a infinite. This results in an assortment containing the command name, and so, if included in the bulletin, any arguments. You assign this array to the constant args.

The third line removes the first chemical element from the args assortment (which will be the command proper noun provided), converts information technology to lowercase, and then assigns information technology to the constant command. This allows you to isolate the command proper noun and exit only arguments in the array. You also utilize the method toLowerCase as commands are typically case insensitive in Discord bots.

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

Add the following code to start implementing the ping control:

discord-bot/index.js

                      ...            const            args            =            commandBody.            split            (            ' '            )            ;            const            command            =            args.            shift            (            )            .            toLowerCase            (            )            ;                          if              (command              ===              "ping"              )              {                                                              }                        }            )            ;            ...                  

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

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

discord-bot/index.js

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

Save and go out your file.

You add together the "ping" control block that calculates the difference betwixt the current time—institute 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 control using the reply method on the message abiding. The answer method pings (which notifies the user and highlights the bulletin for the specified user) the user who invoked the command, followed past the content provided equally the first argument to the method. You provide a template literal containing a message and the calculated ping as the response that the respond method will use.

This concludes implementing the "ping" command.

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

                      
  1. node index.js

You can now utilise 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 take successfully created a bot that tin handle user commands and y'all have implemented your first command. In the next footstep, yous will go along developing your bot by implementing a sum command.

Step 4 — Implementing the Sum Command

Now you volition extend your plan past implementing the "!sum" command. The control will accept 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 lot can terminate its process with CTRL + C.

Open your index.js file again:

                      
  1. nano index.js

To begin implementing the "!sum" control you lot volition utilise an else-if block. After checking for the ping command proper name, it volition bank check if the control name is equal to "sum". You lot will use an else-if cake since only i command will procedure at a time, so if the program matches the command name "ping", it doesn't have to check for the "sum" command. Add the post-obit highlighted lines to your file:

discord-bot/index.js

                      ...            if            (control            ===            "ping"            )            {            const            timeTaken            =            Date.            now            (            )            -            message.createdTimestamp;            message.            answer            (                          `              Ping! This bulletin had a latency of                                            ${timeTaken}                            ms.              `                        )            ;            }                          else              if              (command              ===              "sum"              )              {                                                              }                        }            )            ;            ...                  

You can begin implementing the lawmaking for the "sum" command. The code for the "sum" command will go within the else-if block you lot but created. Now, add the post-obit lawmaking:

discord-bot/index.js

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

You lot 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 subsequently y'all 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 listing. You assign the sum of all the elements in numArgs to the constant sum.

You lot so use the reply method on the message object to respond to the user'southward control 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 control (in the aforementioned folder as index.js):

                      
  1. node index.js

You can now use the "!sum" command in any channel the bot tin 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            customer            =            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            =            bulletin.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 bulletin 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}                            !              `                        )            ;            }            }            )            ;            customer.            login            (config.            BOT_TOKEN            )            ;                  

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

Conclusion

You lot accept successfully implemented a Discord bot that can handle multiple, different user commands and control arguments. If you lot want to aggrandize on your bot, yous could possibly implement more commands or try out more parts of the Discord API to craft a powerful Discord bot. Y'all can review the Discord.js documentation or the Discord API documentation to expand your knowledge of the Discord API. In particular, yous could convert your bot commands to slash commands, which is a all-time practice for Discord.js v13.

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

Discord Prompts for 2 Channel Auth at Login

DOWNLOAD HERE

Source: https://www.digitalocean.com/community/tutorials/how-to-build-a-discord-bot-with-node-js

Posted by: manningwitiong.blogspot.com

Related Posts

There is no other posts in this category.
Subscribe Our Newsletter