Your Bot Token Is Incorrect Read the Guide Again

This tutorial will show you how to use JavaScript and Node.js to build your own Discord bot completely in the deject.

You practise not need to install anything on your computer, and y'all do non demand to pay annihilation to host your bot.

We are going to utilize a number of tools, including the Discord API, Node.js libraries, and a cloud calculating platform chosen Repl.it.

If you'd rather lawmaking your discord bot using Python instead of JavaScript, read this tutorial instead.

There is as well a video version of this written tutorial. The video is embedded below and the written version is after the video.

How to Create a Discord Bot Account

In society to work with the Node.js library and the Discord API, we must first create a Discord Bot account.

Here are the step to creating a Discord Bot account.

1. Make certain you lot're logged on to the Discord website.

2. Navigate to the awarding page.

3. Click on the "New Application" button.

image-117

iv. Give the application a name and click "Create".

image-118

5. Go to the "Bot" tab and and so click "Add Bot". You lot will have to ostend by clicking "Yeah, practise it!"

image-119

Go on the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked).

Your bot has been created. The next step is to copy the token.

image-122

This token is your bot's password then don't share information technology with anybody. It could allow someone to log in to your bot and practice all sorts of bad things.

You can regenerate the token if it accidentally gets shared.

How to Invite Your Bot to Bring together a Server

Now you have to go your Bot User into a server. To do this, you should create an invite URL for it.

Go to the "OAuth2" tab. And so select "bot" under the "scopes" department.

image-123

Now choose the permissions you want for the bot. Our bot is going to mainly utilise text messages so we don't need a lot of the permissions. Yous may need more depending on what y'all want your bot to exercise. Be careful with the "Administrator" permission.

image-124

After selecting the advisable permissions, click the 're-create' push in a higher place the permissions. That will copy a URL which tin can be used to add the bot to a server.

Paste the URL into your browser, cull a server to invite the bot to, and click "Authorize".

To add the bot, your account needs "Manage Server" permissions.

Now that y'all've created the bot user, we'll start writing the Python code for the bot.

How to Code a Basic Discord Bot with the discord.js Library

We'll be using the discord.js Node library to write the code for the bot. discord.js is an API wrapper for Discord that makes information technology easier to create a Discord bot in Node.js / JavaScript.

How to Create a Repl and Install discord.js

You can develop the bot on your local figurer with any code editor. Yet, in this tutorial, we'll be using Repl.it because information technology volition make it simpler for anyone to follow along. Repl.information technology is an online IDE that you can use in your web browser.

Get-go by going to Repl.it. Create a new Repl and choose "Node.js" as the linguistic communication. This means the programming language will be JavaScript.

To use the discord.js library, just add together const Discord = require("discord.js"); at the top of main.js. Repl.it will automatically install this dependency when you press the "run" button.

How to Set Upwards Discord Events for Your Bot

discord.js revolves effectually the concept of events. An event is something you listen to and then respond to. For example, when a message happens, yous will receive an issue about information technology that you lot tin respond to.

Permit's make a bot that replies to a specific message. This uncomplicated bot code is taken direct from the discord.js documentation. Nosotros volition be adding more features to the bot later.

Add this code to main.js. I'll explain what all this code does shortly.

          const Discord = crave("discord.js") const client = new Discord.Customer()  customer.on("ready", () => {   console.log(`Logged in as ${client.user.tag}!`) })  client.on("message", msg => {   if (msg.content === "ping") {     msg.reply("pong");   } })  client.login(process.env.TOKEN)        

When yous created your bot user on Discord, you copied a token. Now nosotros are going to create a .env file to store the token.

.env files are used for declaring surroundings variables. On Repl.it, most files you create are visible to anyone just .env files are simply visible to y'all.  Other people viewing a public repl volition not exist able to see the contents of the .env file.

And so if you are developing on Repl.information technology, only include private information similar tokens or keys in a .env file.

Click the "Add file" button and create a file named .env.

Inside the file add together the post-obit line, including your bodily token y'all copied previously:

          TOKEN=[paste token hither]        

Now allow's go over what each line of code is doing in your Discord bot code.

The showtime line imports the discord.js library.  Adjacent, nosotros create an case of a Customer. This is the connection to Discord.

The client.on() is used to cheque for events.  It accepts an event name, and then a callback function to be called when the event takes place. In this code, the ready event is called when the bot is set up to offset being used. Then, when the Discord server has a new bulletin, the message consequence is called.

The code checks if the msg.content equals 'ping'. If and so, then the bot replies with 'pong' to the channel.

At present that the bot is set upward, the final line runs the bot with the login token. It gets the token from out .env file.

Nosotros have the code for the bot and so at present we just have to run it.

How to Run the Bot

Now click run button on the meridian to run your bot in repl.it.

At present go to your Discord room and type "ping". Your bot should return "pong".

image

How to Improve the Bot

Now that we have a basic bot working, we'll better it. It is called "Encourage Bot" for a reason.

This bot will reply with a message of encouragement whenever someone sends a message containing a distressing or depressing give-and-take.

Anyone will be able to add encouraging letters for the bot to use and the user-submitted messages will be stored in the Repl.it database.

The bot volition also return a random inspirational quote from an API when someone types the message "$inspire" into the chat.

We'll start with adding the "$inspire" feature.

How to Add Inspirational Quotes to the Bot

Nosotros will go inspirational quotes from an API called zenquotes.io. Nosotros need to import the node-fetch module, add a getQuote() function, and update our bot code to call the function.

Here is the updated code. Later on the code, I'll explain the new parts.

          const Discord = require("discord.js") const fetch = require("node-fetch") const client = new Discord.Client()  function getQuote() {   return fetch("https://zenquotes.io/api/random")     .then(res => {       return res.json()       })     .then(data => {       render information[0]["q"] + " -" + data[0]["a"]     }) }  client.on("ready", () => {   console.log(`Logged in equally ${client.user.tag}!`) })  client.on("message", msg => {   if (msg.writer.bot) return        if (msg.content === "$inspire") {     getQuote().then(quote => msg.channel.send(quote))   } })  client.login(procedure.env.TOKEN)        

We now have to import the node-fetch module. This module allows our code to make an HTTP request to get information from the API.

The getQuote() function is pretty straightforward. First, it uses the node-fetch module to asking information from the API URL. The API returns a random inspirational quote. This function could hands be rewritten to become quotes from a unlike API, if the electric current one stops working.

Then the function converts the response from the API to JSON and creates a cord to return. Through trial and error I figured out how to get the quote from the JSON into the string format I wanted. The quote is returned from the part equally a string.

The last office updated in the lawmaking is toward the end. Previously it looked for the message "ping". Now it looks for "$inspire". Instead of returning "pong", it gets the quote with getQuote() and returns the quote. Nosotros use msg.channel.send() to send the message to the aqueduct. Besides, the lawmaking checks if the message comes from the bot itself and if information technology does, it leaves the function so it does not do anything.

At this betoken you tin can run your lawmaking and try it out.

How to Add Encouraging Messages to the Bot

At present nosotros volition implement the feature where the bot responds with encouraging messages when a user posts a message with a sad word.

How to Add Sad Words to the Bot

Start we need to create an array that contains the sad words that the bot will respond to.

Add the following line later on the client variable is created:

sadWords = ["sad", "depressed", "unhappy", "angry", "miserable"]

Feel free to add more words to the list.

How to Add Encouraging Messages to the Bot

At present we'll add an assortment of encouraging messages that the bot will answer with.

Add the following array subsequently the sadWords list yous created:

          encouragements = [   "Cheer upward!",   "Hang in there.",   "You are a neat person / bot!" ]        

Like before, feel gratuitous to add more phrases of your choice to the assortment . I'1000 just using three items for now because later nosotros'll add the ability for users to add more encouraging phrases for the bot to use.

How to Respond to Letters

Now nosotros need to update our bot to use the ii lists nosotros created.

Now nosotros volition update the message function to check all messages to see if they contain a word from the sadWords listing. If a lamentable word is found, the bot will transport a random message of encouragement.

Here is the updated code:

          client.on("message", msg => {   if (msg.content === "$inspire") {     getQuote().so(quote => msg.channel.send(quote))   }    if (sadWords.some(word => msg.content.includes(word))) {     const encouragement = encouragements[Math.floor(Math.random() * encouragements.length)]     msg.reply(encouragement)   }  })        

This is a skilful time to test the bot. You know enough now to create your own bot. Simply next y'all'll larn how to implement more than advanced features and shop data using the Repl.it database.

How to Enable User-submitted Messages

The bot is completely functional, but now allow's brand information technology possible to update the bot right from Discord. A user should be able to add together more encouraging messages for the bot to employ when it detects a sad word.

We are going to use Repl.it's built-in database to store user-submitted messages. This database is a key-value store that's congenital into every repl.

At the top of the code, under the other import statements, add:

          const Database = require("@replit/database") const db = new Database()        

This will let us to use the Repl.information technology database. When you run the code, Repl.it should install the database module automatically. If for some reason information technology doesn't, you may have to go into the Crush tab (non the Console) and type "npm install @replit/database".

Afterward where the encouragements array is created, insert the following code to add the encouragements to the database if needed:

          db.become("encouragements").then(encouragements => {   if (!encouragements || encouragements.length < 1) {     db.ready("encouragements", starterEncouragements)   }   })        

Also, rename the encouragements array toward the elevation to starterEncouragements.

Users will be able to add together custom encouraging letters for the bot to use directly from the Discord chat. Before we add new commands for the bot, let'southward create 2 helper functions that volition add together custom messages to the database and delete them.

Add the post-obit code afterwards the getQuote() function:

          function updateEncouragements(encouragingMessage) {   db.get("encouragements").and then(encouragements => {     encouragements.push([encouragingMessage])     db.set("encouragements", encouragements)   }) }  function deleteEncouragment(alphabetize) {   db.get("encouragements").and then(encouragements => {     if (encouragements.length > index) {       encouragements.splice(index, ane)       db.ready("encouragements", encouragements)     }   }) }        

The updateEncouragements() part accepts an encouraging message as an argument.

Outset information technology gets the "encouragements" from the database. So, it adds the new encouragement to the assortment, and stores the updated array dorsum in the database under the "encouragements" key.

The deleteEncouragement() function accepts an alphabetize as an argument.

It gets the list of encouragements from the database stored under the "encouragements" key. If the length is more than the alphabetize, then the list item at that index is deleted. Finally, the updated list is stored back in the database under the "encouragements" key.

Here is the updated code for the message function. Afterwards the code, I'll explain the new sections.

          client.on("message", msg => {   if (msg.content === "$inspire") {     getQuote().then(quote => msg.channel.send(quote))   }       if (sadWords.some(word => msg.content.includes(word))) {     db.get("encouragements").then(encouragements => {       const encouragement = encouragements[Math.floor(Math.random() * encouragements.length)]       msg.answer(encouragement)     })   }    if (msg.content.startsWith("$new")) {     encouragingMessage = msg.content.split("$new ")[1]     updateEncouragements(encouragingMessage)     msg.channel.send("New encouraging message added.")   }    if (msg.content.startsWith("$del")) {     index = parseInt(msg.content.split("$del ")[1])     deleteEncouragment(alphabetize)     msg.aqueduct.send("Encouraging bulletin deleted.")   } })        

The sad words department has been updated to use the encouraging messages from the database and then user submitted messages tin can be used.

The side by side new section of code is used to add a new user-submitted message to the database. If a Discord message starts with "$new", then the text later on "$new" will be used as a new encouraging message.

The code msg.content.split('$new ')[1] splits off the message from the "$new" control and stores the bulletin in a variable. In that line of code, take note of the space in '$new '. Nosotros want everything later on the space.

Nosotros telephone call the updateEncouragements helper function with the new message, and then the bot sends a bulletin to the discord chat confirming that the message was added.

The third new department (at the end of the lawmaking above) checks if a new Discord message starts with "$del". This is the command to delete an item from the "encouragements" list in the database.

The index is separate off from the Discord message starting with "$del". So, the deleteEncouragement() role is called passing in the alphabetize to delete. The updated list of encouragements is loaded into the encouragements variable, and then the bot sends a message to Discord with the current listing.

Final Bot Features

The bot should work so this is a skilful time to examination it. Nosotros will now add a few final features.

We will add together the power to get a list of user-submitted letters correct from Discord and nosotros will add together the power to turn off and on whether the bot responds to lamentable words.

I will give y'all the full final code of the program, and then I'll discuss the updates below the code.

          const Discord = require("discord.js") const fetch = require("node-fetch") const Database = require("@replit/database")  const db = new Database() const client = new Discord.Customer()  const sadWords = ["lamentable", "depressed", "unhappy", "aroused", "miserable"]  const starterEncouragements = [   "Cheer up!",   "Hang in there.",   "You are a great person / bot!" ]  db.get("encouragements").and then(encouragements => {   console.log(encouragements)   if (!encouragements || encouragements.length < 1) {     db.set up("encouragements", starterEncouragements)   }   })  db.go("responding").then(value => {   if (value == null) {     db.set("responding", true)   }   })  role getQuote() {   return fetch("https://zenquotes.io/api/random")     .so(res => {       render res.json()       })     .then(information => {       return data[0]["q"] + " -" + data[0]["a"]     }) }  function updateEncouragements(encouragingMessage) {   db.become("encouragements").then(encouragements => {     encouragements.push([encouragingMessage])     db.set("encouragements", encouragements)   }) }  function deleteEncouragment(index) {   db.get("encouragements").and so(encouragements => {     if (encouragements.length > index) {       encouragements.splice(index, 1)       db.set("encouragements", encouragements)     }   }) }  client.on("set", () => {   panel.log(`Logged in as ${client.user.tag}!`) })  client.on("message", msg => {   if (msg.content === "$inspire") {     getQuote().then(quote => msg.channel.send(quote))   }    db.get("responding").then(responding => {     if (responding && sadWords.some(word => msg.content.includes(word))) {       db.become("encouragements").then(encouragements => {         const encouragement = encouragements[Math.flooring(Math.random() * encouragements.length)]         msg.reply(encouragement)       })     }   })    if (msg.content.startsWith("$new")) {     encouragingMessage = msg.content.split("$new ")[ane]     updateEncouragements(encouragingMessage)     msg.channel.transport("New encouraging message added.")   }    if (msg.content.startsWith("$del")) {     alphabetize = parseInt(msg.content.split("$del ")[1])     deleteEncouragment(alphabetize)     msg.channel.transport("Encouraging message deleted.")   }    if (msg.content.startsWith("$list")) {     db.go("encouragements").then(encouragements => {       msg.channel.send(encouragements)     })   }        if (msg.content.startsWith("$responding")) {     value = msg.content.carve up("$responding ")[one]      if (value.toLowerCase() == "truthful") {       db.set("responding", true)       msg.channel.ship("Responding is on.")     } else {       db.prepare("responding", false)       msg.channel.send("Responding is off.")     }   } })  client.login(procedure.env.TOKEN)        

The get-go section added to the lawmaking is correct under the starterEncouragements list:

          db.become("responding").then(value => {   if (value == null) {     db.set("responding", true)   }   })        

We create a new primal in the database called "responding" and gear up it to "true". Nosotros'll employ this to make up one's mind if the bot should answer to pitiful words or not. Since the database is saved even after the program stops running, we simply create the new fundamental if it doesn't already exist.

The side by side new part of the lawmaking is in the section that responds to sad words is now within this if argument. The bot volition only answer to sad words if db.get("responding") = true. The ability to update this value comes after this next section.

Next, afterwards the code to make the bot answer to the "$del" command, there is new code to reply to the "$list" control when sent as a Discord bulletin.

The bot sends the listing of encouragements as a Discord message.

The final new section comes next. This code makes the bot respond to the "$responding" control. This command takes an argument of either "true" or "false". Here is a usage example: "$responding truthful".

The code first pulls off the argument with value = msg.content.split up("$responding ")[1] (like earlier, note the space in "$responding "). Then in that location is an if/else statement that appropriately sets the "responding" key in the database and sends a notification message back to Discord. If the argument is anything just "true", the code assumes "false".

The code for the bot is consummate! You tin now run the bot and endeavor it out. But there is one more of import step that nosotros will talk over adjacent.

How to Set up the Bot to Run Continuously

If you run your bot in repl.information technology and and so close the tab it is running in, your bot will stop running.

But in that location are two means you can continue your bot running continuously, even later on y'all shut your web bowser.

The get-go fashion and simplest way is to sign up for paid plan in Repl.it. Their cheapest paid plan is chosen the Hacker Plan and it includes v e'er-on Repls.

You tin get three months free using this link (limited to offset 1000 people):  https://repl.information technology/claim?lawmaking=tryalwayson2103

Once you accept signed upwards for that plan, open your Repl and click the name at the height. Then select the "Always On" option.

image-36

There is another mode to go on your lawmaking running even on the complimentary tier but it is a piddling more complicated. Repl.it will continue running a web server even after the tab is closed. But fifty-fifty a web server will but run for up to an 60 minutes without any utilize.

Here is what the repl.it docs say:

Once deployed, the server volition go along to run in the background, even afterwards you close the browser tab. The server will stay awake and active until an hour after its terminal request, afterwards which it will enter a sleeping stage. Sleeping repls will exist woken up as soon as it receives another request; in that location is no demand to re-run the repl. However, if you make changes to your server, you will need to restart the repl in order to meet those changes reflected in the live version.

To keep the bot running continuously, nosotros'll use another free service called Uptime Robot at https://uptimerobot.com/.

Uptime Robot can be set upward to ping the bot's web server on repl.it every five minutes. With abiding pings, the bot volition never enter the sleeping phase and volition but go along running.

So we have to do 2 more things to become our bot to run continuously:

  1. create a web server in repl.information technology and
  2. set up up Uptime Robot to continuously ping the web server.

How to Create a Web Server in repl.information technology

Creating a web server is simpler than you lot may retrieve.

To do it, create a new file in your project called server.js.

Then add together the following code:

          const limited = require("express")  const server = express()  server.all("/", (req, res) => {   res.send("Bot is running!") })  office keepAlive() {   server.heed(3000, () => {     console.log("Server is set up.")   }) }  module.exports = keepAlive        

In this code, we use limited to start a web server. The server returns "Bot is running!" to anyone who visits it. The server will run on a carve up thread from our bot. We won't discuss everything here since the rest is not actually relevant to our bot.

Now we just need the bot to run this web server.

Add the following line toward the top of index.js to import the server.

          const keepAlive = crave("./server")        

To kickoff the web server when alphabetize.js is run, add the following line equally the second-to-last line, right before the bot runs.

keepAlive()

When you run the bot on repl.it after adding this code, a new web server window will open up. There is a URL shown for the web server. Copy the URL then yous can utilise it in the next department.

image-1

How to Set up Uptime Robot

At present we need to set up up Uptime Robot to ping the web server every five minutes. This volition cause the bot to run continuously.

Create a free business relationship on https://uptimerobot.com/.

In one case you are logged in to your account, click "Add together New Monitor".

image-21

For the new monitor, select "HTTP(s)" as the Monitor Type and name information technology whatever you like. Then, paste in the URL of your web server from repl.it. Finally, click "Create Monitor".

image-22

We're done! Now the bot will run continuously so people can ever collaborate with information technology on Repl.it.

Conclusion

Yous now know how to create a Discord bot with JavaScript, and run it continuously in the cloud.

There are a lot of other things that the discord.js library can do. Then if you want to give a Discord bot even more than features, your side by side step is to bank check out the docs for discord.js.

Learn to code for free. freeCodeCamp'south open source curriculum has helped more than 40,000 people go jobs equally developers. Get started

carrfratagen43.blogspot.com

Source: https://www.freecodecamp.org/news/create-a-discord-bot-with-javascript-nodejs/

0 Response to "Your Bot Token Is Incorrect Read the Guide Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel