How to Build a Discord Bot - Full JavaScript Chatbot Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello this is nano danau at dev dungeon comm and we're going to walk through the process of creating a discord bot in JavaScript with nodejs there's a written tutorial on dev dungeon if you prefer the blogpost format check the description for a link we're gonna start at the very beginning with how to register with discord and create your own server all the way through creating custom commands adding emoji reactions to messages and more also check out some of the other tutorials for discord that are available including how to write discord bots in python if you aren't already familiar with discord it is a great text and voice chat platform that's free to use they have a web mobile and a desktop app it has a lot of nice features for gamers in particular dev dungeon has a discord server you can join to chat about programming and security related topics here's a link and you can also find it in the video description and from the dev dungeon home page the first thing you'll need to do is register and then log in to discord go to https colon slash slash discord app comm slash channels slash at me once you're logged in the next step is to create a server for you to test with look on the left side for the server list and click the plus sign then click create a server you will need to fill out a name at a minimum you can also provide an image and change the region if desired I recommend picking the region closest to you for faster server responses after your server is created it should show up in the left side in your server list click on the server you should see a general channel and on the member list to the right you should see your user now that you have your very own server to mess around with you will need to register an app with discord go to the discord developer portal at discord app comm slash developers and then click on create an application fill out the name of your application by default it's named my application but you should give it a custom name then click on the bot section in the left and choose add bot change the bots name if you want to then under the token section of the bot page click on click to reveal and save this token this is essentially your BOTS username and password combined into one string so it's important to keep this a secret and don't share it with anybody you don't want to control your bot I'm showing mine for this tutorial only but I will be deleting it afterwards so nobody can use it later you will use this token in the source code so save it now that you have a server an app and a bot user there's one more step we have to do with this cord your bot can be invited to many servers but right now it doesn't belong to any server so we'll need to invite the bot to your server click on the to section on the left side of the page and then scroll down slightly to the scopes section check the box scope and it will generate a URL copy that URL and paste it into your web browser once on the page you'll be asked which server you want to invite the bot to choose the server that you created and click authorize once you see the authorized success screen your bot has successfully joined your server you should now see the bots in the member list as an offline user the same URL that you used to authorize the bot can be shared with others if you want them to invite your bot to their server they'll be able to interact with your bot but not control your bot now we're done with all the prep work needed on the discord side fortunately you only have to do all of this one time once the bot is created and invited to the server it will stay there you won't have to do this again now we can move on to writing the JavaScript code before we can do that though you need to make sure you have no js' installed on your system open your system terminal and run node - - version if you get a response and it says 8.0 or higher you're already good to go but if you get a message like unrecognized program or some kind of error you most likely need to go download and install node J s get it from nodejs org after you have installed nodejs you should be able to run node - - version in your terminal and it should look something like this next I'm going to open visual studio code a free editor that works well with JavaScript you can use any editor you want though but this is the one I'm going to use for the tutorial and I recommend you use it to follow along as well unless you already have a preferred editor go to file open folder I recommend creating a new directory to store your project I'm going to create a new directory on my desktop called my bot then I'm going to choose to open that folder once the folder is open you can hover your mouse over the folder name in the left sidebar and click on the new file icon give the file name like my bot J s the next thing we need to do is install the disk or das module using NPM go to view terminal and a terminal opened up in the bottom portion of your editor window it should automatically put you in the directory that you opened and you're working in in the terminal run NPM install disk or j/s you might see some warnings and that's okay there shouldn't be any errors though at the time of this video version 11 is the latest disk or j/s version future versions may change and break some of these examples so if that happens check out the video description and the comments to see if there's any updates ok now we finally have all the setup work out of the way we can actually start coding congratulations if you made it this far you've got most of the legwork out of the way let's go back to our file that we created let's write a very simple bot program just to make sure everything is installed properly and the bot user is working correctly we will load the discord module and then connect that's all it's going to do when the bot successfully connects we will have it print out a message to the console indicating that it did connect in the file write Const discord equals require discord KS and on the next line write Const client equals new discord dot client then let's add some code that will get triggered after the bot has successfully connected right the following code client dot on ready parentheses arrow console.log connected as plus client user dot tag then finally one more line where we call client login pass your bots secret token has the parameter to login if you need to get your bots token again go to discord app comm slash developers click on your application and then go to the bot section and click to reveal the token pass the token as a string to the client login function let's test this now by executing the program in the terminal using node Maybach Jas we should see a message printed out to our console to indicate success and if we look at our server the bot user should appear online if you see the message in your console and the bot appears online then congrats everything is installed correctly and your bot is configured properly the hardest parts are all out of the way now now we're gonna focus on making your bot do fun things if you happen to get an error message read the message carefully and see if you can figure out why it failed if you get stuck join the dev dungeon discord server or leave a comment here also check the comments to see if your question is already answered to terminate the program press control-c this will end the program and return you to the command prompt after you terminate the program your bot will appear online for a few minutes before it goes back offline that's normal let's modify the code so after the bot connects we have it updated status to say that it's playing a game near the bottom of the on ready event write client user dot set activity and pass it a string that says with JavaScript this will change the bot status to say playing with JavaScript let's run it and verify it works it looks like the bots status did update good you can change the verb from playing to streaming listening or watching let's change it to say watching YouTube instead of playing with JavaScript let's remove the line we currently have and replace it with client user dot set activity YouTube and as the second parameter we're going to pass it type watching let's run it again and make sure it works as expected perfect now let's extend the bot a little further to print out the list of all the servers that it's connected to right now it's probably only connected to your one server but it's possible that the bot belongs to many servers at once inside the ready event let's add a few lines of code write client Guild's dot for each guild arrow console.log guild dot name let's run it and verify it works we should see our test server listed at a minimum let's take it a little further and for each server let's have it print out all of the available channels inside that for each loop that we already created right guild channels dot for each channel arrow console.log channel name channel type channel ID let's run it again and view the output we should see a list of channels for each server listed notice that there are multiple types of channels including text voice and category let's look for a text channel there's one called general take note of the ID we're going to need this for later in the next steps you can add it as a comment to the existing code so you don't lose it each channel and channel ID is unique per server so you cannot use this exact ID that I'm using in my example you'll have to use the ID that you got from your own program on your server why don't we have the bot send a message to the general channel that we just identified in the previous step whenever it connects we'll make it say hello world at the bottom of the on ready event block right let general channel equals client channels get and pass it the ID of your channel as a string on the next line write general channel dot send hello world let's run the program again and make sure it works verify it sends a hello world message after it connects next let's demonstrate how to attach a file or an image to a message you send it's very similar to sending a message except instead of passing a string we're going to pass an attachment object we can create an attachment by writing const attachment equals new discord attachment we need to pass either a file name or a web URL to a file this works the same for files and images you can pass it a local file path to something on your hard disk or an internet address I'm going to provide a URL to the dev dungeon logo you can use the same URL since it is publicly accessible now on the line where we call general channel dot send let's replace the string of hello world with the attachment object we just created let's run the code and see what happens as expected it posted the image to the channel okay so now we have seen how to get a list of servers get a list of channels send a message send an image update the bot status but what if we want to respond to an incoming message from someone else so far we've been triggering all of our code based off of the ready event which is triggered after the bot connects and is ready to perform actions we're going to start using a different event now one that is triggered every time a message is sent that is the message event below the entire client ready event let's write client dot on message received message arrow open and close bracket right now we'll leave it empty so let's fill out the logic that we want to happen whenever a message is received the message event is triggered on every single message that means even messages that the bot sends out will trigger this event this could potentially send the bot into an infinite loop where it continues responding to its own messages forever to avoid this let's add a check to see if the message author is the bot itself if it is we will just ignore it and return and as get the function so it doesn't do anything do this by writing if received message dot author equals equals client dot user then return if the message was sent by someone else other than the bot the code will continue past these lines so after this if statement let's have the bot reply right received message channel dot send message received plus received message content this will have the bot respond in the same channel and echo back the message that it got as acknowledgment this could be a public channel or a private message it'll work correctly for both why don't we make the response a little more personalized let's have the bot tag the user who sent the message to do this we just need to reference the received message dauther and convert it to a string update the sent message to include received message to string like this let's run it again and make sure that it works good it looks like it tags the user who sent the message while we're at it why don't we have the bots at an emoji reaction to the users message inside the on message event let's have the bot add a reaction some servers have custom emojis that you can use while others only have the default set believe it or not there is actually an international standard for emojis you can check out all of the Unicode emojis at this link it's also in the video description to add a reaction we will write received message dot react and pass it the emoji string you can actually copy and paste the emoji itself into the source code a Unicode emoji is recognized as a character just like a P or a Q however this Court does not support every single Unicode emoji so you'll have to try it out and make sure the one that you want works for this example we'll use the thumbs up which is known to work you can also use custom images on your server to add custom emojis to a server go to server settings emoji upload emoji I will upload a sample one now to demonstrate to use a custom emoji as a reaction you will need to know the unique ID of the custom emoji we don't know what that ID is yet as I just uploaded it so why don't we just get every custom emoji from the server print out its ID and react with it so at the code received message guild emojis dot for each custom emoji arrow console dot log custom emoji name custom emoji ID and then on the next line received message react custom emoji this will go through each custom emoji available on the server and react with it as well as print out the ID let's run it once to see how it works notice how it reacted with our custom emoji in the server and in the console it printed out the ID now that we know the ID we can just react with that one specific emoji instead of loading all of them let's get rid of the four each and replace it with let custom emoji equals received message guild emojis dot get and then D ID on the next line ad received message react custom emoji let's run it and send a message again just to make sure it works at this point you should feel a little more comfortable with your bot and have enough building blocks to build a more complicated bot I want to cover one last topic though which is how to create a command a command in this sense is just a regular message that starts with a special character like an exclamation point that triggers inaction by the bot there are many ways you can implement this you could check the entire message to see if it contains the full command or you could make the command take a variable number of parameters I'm gonna walk through one way to create it that demonstrates making two commands help command and a multiply command with these examples you should have a good template for extending and creating more of your own custom commands first let's start inside the on message event block since the command will be a message let's inspect the first character of the message and see if it equals the exclamation mark if it does let's pass the logic off to a function called process command and let's pass it the received message as the argument next we'll need to create the process command function it takes the received message as a parameter we already know it starts with an exclamation point so let's remove that character from the beginning of the string with let full command equals received message content substr one this will remove the first character next let's take the remaining string and split it into pieces based off of each space character let split command equals full command dot split and passage of space this will return an array containing each word we want to treat the first word provided as the name of the command we'll call that the primary command so right let primary command equals split command bracket 0 if there are any remaining words in the array we want to store them as the arguments let arguments equal split command dot slice one this will exclude the first element and keep all of the rest of them if there are any so now we have one variable containing the primary command and another variable containing the array of all the arguments if there are any now we can inspect the primary command variable to see what command was triggered since we want to make a help command let's check and see if the primary command equals the string help please an if statement if it does equal help let's hand off logic to a function named help command and pass it the arguments along with the original message that was received next we will have to create the help command function let's do that now function help command and pass it arguments received message inside the help command we can inspect the argument list to see if any arguments were provided let's first check to see if the length is zero meaning no parameters were provided if arguments dot length equals equals zero then received message channel dot send I'm not sure what you need help with try exclamation help topic if the user didn't provide any arguments we'll let them know by responding with that message let's also add an else statement to handle the case when arguments are passed in this case we'll just respond saying it looks like you need help with plus arguments let's run this and try it out now try typing exclamation help and then exclamation help javascript and review the responses from the bots let's add a second command so you get the idea of how to add more commands back in the processed command function let's add an else if statement to check for another command named multiply if it is let's hand off logic to a function named multiply command let's also add an else statement to catch any unknown commands and suggest some possible commands to the user next we need to create the multiply command function function multiply command arguments received message the first thing we should do is check the arguments we will need at minimum two values to multiply together let's write an if statement to check if the arguments is less than two if it is less than two let's send a message back to the user and then exit the function if there are at Lee two arguments then the code will continue past this if statement let's calculate the product then let product equals one to start then arguments dot for each value arrow product equals product times parsefloat value now that we have the multiplication product we can return the answer to the user with received message channel dot send the product of arguments is product two string now let's test out the multiply command restart the bot and send exclamation x itself and then try exclamation multiply two point five ten and ten and it should return a result try adding your own custom command to the bot if you don't have any ideas try a simple one where if you write exclamation ping the bot will respond with pong if you need some other ideas for custom commands' how about an exclamation fortune command that will return a random fortune cookie quote or how about exclamation Bitcoin that will look up the Bitcoin price using an API and return the price to the user or her about exclamation whether that takes the zip code as an argument and returns the local weather that's all the code we're going to cover in this tutorial you're on your own now you should be able to take these building blocks and build better more complex BOTS one common question is how do I run the bot 24/7 all the time to keep a bot running all the time you'll need to leave the program running all the time you can do this by simply leaving your computer on all the time and never turning it off this is not practical for most people though an alternative is to rent a cheap $5 a month server from a provider like Linode or digitalocean they provide cheap Linux servers that run all the time in their data center the cloud as you call it you can run your code there another alternative is to use something like a Raspberry Pi from your house and leave that running all the time if you have any questions feel free to join the dev dungeon discord server and ask questions you can also check the comments here and leave comments here also make sure you bookmark the discord jas official documentation at discord j/s org that's going to be the best most definitive source for this library check out other dev dungeon tutorials on the youtube channel and on dev dungeon comm there are several other discord tutorials including how to write a discord bot in python thanks for watching and please subscribe to the channel
Info
Channel: freeCodeCamp.org
Views: 108,299
Rating: undefined out of 5
Keywords: javascript tutorial, nodejs tutorial, node.js tutorial, discord bot, discord bot tutorial, javascript tutorial for beginners, node.js tutorial for beginners, discord, discord.js
Id: 8o25pRbXdFw
Channel Id: undefined
Length: 27min 22sec (1642 seconds)
Published: Wed Nov 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.