How to Build a Discord Bot - Full JavaScript Chatbot Tutorial
Skills:
JavaScript Fundamentals90%
Key Takeaways
Builds a Discord bot using JavaScript, Node.js, and the Discord.js library
Full Transcript
hello this is nanodano at devdungeon.com and we're going to walk through the process of creating a discord bot in javascript with node.js there's a written tutorial on devdungeon if you prefer the blog post format check the description for a link we're going to 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 is a link and you can also find it in the video description and from the dev dungeon homepage the first thing you'll need to do is register and then login to discord go to https colon slash discord app dot com 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 discordapp.com 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 bot's name if you want to then under the tokens section of the bot page click on click to reveal and save this token this is essentially your bot's 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 discord 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 oauth 2 section on the left side of the page and then scroll down slightly to the scopes section check the bot 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 bot 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 will 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 nodejs installed on your system open your system terminal and run node dash dash 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.js get it from nodejs.org after you have installed node.js 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 mybot 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 mybot.js the next thing we need to do is install the discord.js module using npm go to view terminal and a terminal will open 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 discord.js 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 discord.js 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 okay 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.js 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 write the following code client dot on ready parentheses arrow console.log connected as plus client.user.tag then finally one more line where we call client.login pass your bot's secret token as the parameter to login if you need to get your bots token again go to discordapp.com 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 mybot.js 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 going to 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 devdungeon discord server or leave a comment here also check the comments to see if your question is already answered to terminate the program press ctrl 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 update its status to say that it's playing a game near the bottom of the on ready event write client.user.setactivity and pass it a string that says with javascript this will change the bot's 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.setactivity youtube and as a 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.guilds.4 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 write guild.channels.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 write let general channel equals client.channels.get and pass it the id of your channel as a string on the next line write generalchannel.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 dot 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 generalchannel.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 exit the function so it doesn't do anything do this by writing if received message dot equals equals client.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 write received message dot channel dot send message received plus received message dot content this will have the bot respond in the same channel and echo back the message that it got as acknowledgement 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 receivedmessage.author and convert it to a string update the sent message to include receivedmessage 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 bot add an emoji reaction to the user's 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 receivedmessage.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 q however discord 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 emojis 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 add the code receivedmessage.guild each custom emoji arrow console.log custom emoji name custom emoji id and then on the next line received message dot 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 dot guild dot emojis dot get and then the id on the next line add received receivedmessage.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 an action 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 going to walk through one way to create it that demonstrates making two commands a 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 receivedmessage.content.substir 1. 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 pass it a 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 write 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 1. 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 we'll use 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 equal to zero then received message dot 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 bot let's add a second command so you get the idea of how to add more commands back in the process 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 2. if it is less than 2 let's send a message back to the user and then exit the function if there are at least 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 four each value arrow product equals product times parse float value now that we have the multiplication product we can return the answer to the user with received message dot channel dot send the product of arguments is product dot tostring now let's test out the multiply command restart the bot and send exclamation multiply by itself and then try exclamation multiply 2.5 10 and 10 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 how about exclamation weather 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 five dollar 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.js official documentation at discord.js.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 devdungeon.com there are several other discord tutorials including how to write a discord bot in python thanks for watching and please subscribe to the channel
Original Description
Learn to code a Discord bot with JavaScript using Node.js.
🔗 Written Tutorial - https://www.devdungeon.com/content/javascript-discord-bot-tutorial
🔗 Unicode Emojis - https://unicode.org/emoji/charts/full-emoji-list.html
🔗 Official Documentation - https://discord.js.org
Tutorial by Dev Dungeon. Check out their YouTube channel: https://www.youtube.com/channel/UCgkG68BiCngkoV7I2BLtAVg
❤️ Try interactive JavaScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-JavaScript (Made possible by a grant from our friends at Scrimba)
--
Learn to code for free and get a developer job: https://www.freecodecamp.org
Read hundreds of articles on programming: https://medium.freecodecamp.org
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
Dates - Beau teaches JavaScript
freeCodeCamp.org
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
The Definition of Ready - Agile Software Development
freeCodeCamp.org
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
Working Agreement - Agile Software Development
freeCodeCamp.org
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
Definition of Done - Agile Software Development
freeCodeCamp.org
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
The INVEST approach to product backlog items
freeCodeCamp.org
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org
More on: JavaScript Fundamentals
View skill →
🎓
Tutor Explanation
DeepCamp AI