banner



How To Register Ally Code For Discord

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

Y'all exercise not need to install anything on your reckoner, and you do not need to pay anything to host your bot.

Nosotros are going to use a number of tools, including the Discord API, Node.js libraries, and a cloud calculating platform chosen Repl.information technology.

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

In that location is also a video version of this written tutorial. The video is embedded below and the written version is afterward the video.

How to Create a Discord Bot Account

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

Here are the pace to creating a Discord Bot account.

one. Make sure you're logged on to the Discord website.

2. Navigate to the application page.

3. Click on the "New Application" button.

image-117

4. Give the application a proper noun and click "Create".

image-118

5. Go to the "Bot" tab and then click "Add together Bot". You will have to ostend past clicking "Yes, do it!"

image-119

Proceed 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'south password and so don't share information technology with anybody. Information technology could allow someone to log in to your bot and do all sorts of bad things.

You tin regenerate the token if information technology accidentally gets shared.

How to Invite Your Bot to Join a Server

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

Go to the "OAuth2" tab. So select "bot" nether the "scopes" section.

image-123

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

image-124

Later selecting the appropriate permissions, click the 'copy' button to a higher place the permissions. That volition copy a URL which can be used to add the bot to a server.

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

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

Now that you've created the bot user, we'll commencement 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 it easier to create a Discord bot in Node.js / JavaScript.

How to Create a Repl and Install discord.js

You tin can develop the bot on your local reckoner with any code editor. However, in this tutorial, nosotros'll be using Repl.information technology considering information technology volition go far simpler for anyone to follow forth. Repl.it is an online IDE that you lot can use in your web browser.

Start past going to Repl.it. Create a new Repl and choose "Node.js" equally the linguistic communication. This means the programming language will be JavaScript.

To utilise the discord.js library, just add const Discord = crave("discord.js"); at the height of main.js. Repl.it will automatically install this dependency when you press the "run" push button.

How to Gear up Upwards Discord Events for Your Bot

discord.js revolves around the concept of events. An event is something you heed to and so respond to. For example, when a message happens, you lot will receive an effect about information technology that yous can answer to.

Let's brand a bot that replies to a specific message. This uncomplicated bot code is taken straight from the discord.js documentation. We will exist adding more features to the bot later.

Add together this code to main.js. I'll explain what all this lawmaking does presently.

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

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

.env files are used for declaring environment variables. On Repl.it, well-nigh files you create are visible to anyone but .env files are but visible to you.  Other people viewing a public repl volition not exist able to run into the contents of the .env file.

So if y'all are developing on Repl.information technology, only include private information like tokens or keys in a .env file.

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

Inside the file add the following line, including your actual token you copied previously:

          TOKEN=[paste token here]        

Now let'southward get over what each line of lawmaking is doing in your Discord bot code.

The first line imports the discord.js library.  Side by side, nosotros create an instance of a Customer. This is the connectedness to Discord.

The client.on() is used to check for events.  It accepts an effect proper name, and and so a callback function to exist called when the event takes place. In this code, the fix outcome is chosen when the bot is ready to start beingness used. Then, when the Discord server has a new message, the message event is called.

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

At present that the bot is prepare, the final line runs the bot with the login token. Information technology gets the token from out .env file.

We have the code for the bot and then now we just have to run it.

How to Run the Bot

Now click run button on the top to run your bot in repl.information technology.

At present get 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 improve it. It is called "Encourage Bot" for a reason.

This bot will respond with a message of encouragement whenever someone sends a message containing a sad or depressing word.

Anyone will exist 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 will also return a random inspirational quote from an API when someone types the bulletin "$inspire" into the chat.

Nosotros'll start with calculation the "$inspire" feature.

How to Add Inspirational Quotes to the Bot

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

Here is the updated lawmaking. After the code, I'll explicate the new parts.

          const Discord = require("discord.js") const fetch = crave("node-fetch") const customer = new Discord.Customer()  office getQuote() {   render fetch("https://zenquotes.io/api/random")     .then(res => {       return res.json()       })     .then(information => {       return data[0]["q"] + " -" + data[0]["a"]     }) }  client.on("ready", () => {   panel.log(`Logged in as ${client.user.tag}!`) })  client.on("bulletin", msg => {   if (msg.author.bot) return        if (msg.content === "$inspire") {     getQuote().and then(quote => msg.channel.send(quote))   } })  client.login(process.env.TOKEN)        

We at present accept to import the node-fetch module. This module allows our code to make an HTTP request to get data from the API.

The getQuote() role is pretty straightforward. First, it uses the node-fetch module to request information from the API URL. The API returns a random inspirational quote. This function could easily be rewritten to get quotes from a different API, if the current ane stops working.

Then the role converts the response from the API to JSON and creates a string to return. Through trial and error I figured out how to go the quote from the JSON into the string format I wanted. The quote is returned from the office as a string.

The final part updated in the code is toward the end. Previously information technology looked for the message "ping". Now it looks for "$inspire". Instead of returning "pong", it gets the quote with getQuote() and returns the quote. We employ msg.channel.send() to send the message to the channel. Too, the code checks if the message comes from the bot itself and if it does, information technology leaves the office so it does not do anything.

At this signal y'all can run your code and endeavor it out.

How to Add Encouraging Messages to the Bot

Now nosotros will implement the feature where the bot responds with encouraging messages when a user posts a message with a sad word.

How to Add together Sad Words to the Bot

First we demand to create an assortment that contains the sorry words that the bot volition respond to.

Add the post-obit line after the client variable is created:

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

Experience free to add more than words to the list.

How to Add Encouraging Messages to the Bot

Now we'll add an array of encouraging messages that the bot will answer with.

Add together the following assortment after the sadWords list yous created:

          encouragements = [   "Cheer up!",   "Hang in at that place.",   "Yous are a cracking person / bot!" ]        

Like before, experience free to add more phrases of your choice to the array . I'm just using three items for now because later we'll add together the power for users to add more than encouraging phrases for the bot to employ.

How to Respond to Messages

Now nosotros need to update our bot to employ the two lists nosotros created.

At present nosotros will update the message function to bank check all letters to encounter if they contain a word from the sadWords list. If a sad word is found, the bot will ship a random message of encouragement.

Here is the updated code:

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

This is a good fourth dimension to test the bot. Y'all know enough now to create your ain bot. Merely next you lot'll learn how to implement more avant-garde features and shop information using the Repl.it database.

How to Enable User-submitted Messages

The bot is completely functional, but now let's make information technology possible to update the bot correct from Discord. A user should exist able to add more than encouraging messages for the bot to use when it detects a lamentable word.

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

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

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

This will allow us to utilize the Repl.it database. When you lot run the code, Repl.it should install the database module automatically. If for some reason it doesn't, yous may have to get into the Shell tab (non the Console) and type "npm install @replit/database".

After where the encouragements assortment is created, insert the following code to add together the encouragements to the database if needed:

          db.get("encouragements").and then(encouragements => {   if (!encouragements || encouragements.length < 1) {     db.set("encouragements", starterEncouragements)   }   })        

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

Users volition exist able to add custom encouraging letters for the bot to utilise directly from the Discord chat. Before we add new commands for the bot, let's create ii helper functions that will add custom messages to the database and delete them.

Add the following code later on the getQuote() part:

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

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

Beginning it gets the "encouragements" from the database. Then, it adds the new encouragement to the array, and stores the updated assortment back in the database under the "encouragements" key.

The deleteEncouragement() function accepts an index as an statement.

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

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

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

The pitiful words section has been updated to employ the encouraging messages from the database so user submitted letters can be used.

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

The code msg.content.split('$new ')[one] splits off the bulletin from the "$new" command and stores the message in a variable. In that line of lawmaking, take annotation of the space in '$new '. We want everything subsequently the space.

We call the updateEncouragements helper part with the new message, and and so the bot sends a message to the discord chat confirming that the message was added.

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

The index is split off from the Discord message starting with "$del". Then, the deleteEncouragement() role is called passing in the index 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 list.

Final Bot Features

The bot should piece of work so this is a good fourth dimension to test it. We volition now add a few final features.

We will add together the ability to get a list of user-submitted letters right from Discord and we volition add the ability to plow off and on whether the bot responds to distressing words.

I volition give you the total last lawmaking of the program, and then I'll discuss the updates beneath the code.

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

The first department added to the lawmaking is right under the starterEncouragements listing:

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

We create a new fundamental in the database called "responding" and fix it to "true". We'll use this to determine if the bot should respond to sad words or not. Since the database is saved even subsequently the program stops running, we but create the new key if it doesn't already exist.

The adjacent new function of the code is in the section that responds to sad words is now inside this if statement. The bot will only reply to sad words if db.get("responding") = truthful. The power to update this value comes after this next section.

Adjacent, later on the code to make the bot answer to the "$del" command, in that location is new code to respond to the "$list" control when sent equally a Discord message.

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

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

The lawmaking first pulls off the statement with value = msg.content.split("$responding ")[ane] (like earlier, note the space in "$responding "). So at that place is an if/else argument that accordingly sets the "responding" primal in the database and sends a notification message back to Discord. If the argument is anything but "true", the lawmaking assumes "imitation".

The code for the bot is complete! Yous can at present run the bot and endeavour information technology out. But there is ane more important step that we will talk over next.

How to Fix Upwardly the Bot to Run Continuously

If you run your bot in repl.it and then shut the tab information technology is running in, your bot volition stop running.

But there are 2 ways you can keep your bot running continuously, even later you close your web bowser.

The get-go mode and simplest way is to sign upward for paid plan in Repl.it. Their cheapest paid plan is called the Hacker Plan and it includes five ever-on Repls.

Yous can become three months free using this link (limited to starting time 1000 people):  https://repl.it/merits?lawmaking=tryalwayson2103

Once you accept signed up for that program, open up your Repl and click the proper noun at the top. Then select the "Ever On" option.

image-36

In that location is some other way to continue your code running even on the free tier but it is a footling more complicated. Repl.it will continue running a web server even after the tab is closed. But even a web server will only run for up to an hour without any use.

Here is what the repl.it docs say:

Once deployed, the server volition continue to run in the groundwork, fifty-fifty afterward you close the browser tab. The server volition stay awake and agile until an hour after its last request, after which information technology will enter a sleeping stage. Sleeping repls volition be woken upward equally presently as information technology receives another request; there is no need to re-run the repl. Yet, if you make changes to your server, you will need to restart the repl in order to run into those changes reflected in the live version.

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

Uptime Robot can exist set up to ping the bot's web server on repl.it every five minutes. With constant pings, the bot will never enter the sleeping stage and volition just go on running.

So we have to do two more things to get our bot to run continuously:

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

How to Create a Web Server in repl.it

Creating a web server is simpler than you may think.

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

So add the following code:

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

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

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

Add together the post-obit line toward the height of alphabetize.js to import the server.

          const keepAlive = require("./server")        

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

keepAlive()

When you run the bot on repl.it after calculation this code, a new spider web server window will open up. There is a URL shown for the web server. Copy the URL so yous can use it in the next section.

image-1

How to Set Uptime Robot

Now we need to set upwards Uptime Robot to ping the spider web server every v minutes. This volition cause the bot to run continuously.

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

Once you are logged in to your business relationship, click "Add together New Monitor".

image-21

For the new monitor, select "HTTP(s)" every bit the Monitor Blazon and name it whatever yous similar. Then, paste in the URL of your web server from repl.information technology. Finally, click "Create Monitor".

image-22

Nosotros're done! Now the bot will run continuously so people can always interact with information technology on Repl.information technology.

Determination

Y'all at present know how to create a Discord bot with JavaScript, and run it continuously in the deject.

In that location are a lot of other things that the discord.js library can do. And then if you want to give a Discord bot fifty-fifty more features, your adjacent stride is to check out the docs for discord.js.

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

How To Register Ally Code For Discord,

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

Posted by: deweyallonand.blogspot.com

0 Response to "How To Register Ally Code For Discord"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel