Discord is without doubt one of the hottest chat apps right now for developers and gamers alike. Millions swear by its efficiency and smoothness, and simply consider it to be a better choice among the myriads of chat applications out there. It is also cross-platform and free, which are just two more things adding to its appeal. One of the cool things that Discord allows you to do is create bots and integrate them into servers. This allows you to automate the operations and interactions of a chat group. This can be particularly useful when you’re moderating a large group or a group of strangers. In this article, we will teach you how to make a discord bot. We will guide you through the full process of setting up the Bot and deploying it.
Let’s get started!
How To Make A Discord Bot
- What you need to know, before you get started
- Setting up a local project
- Creating a Discord app
- Grabbing a token to use Discord’s API
- Creating a test server
- Adding our bot to this test server
- Testing our Discord bot
- Deploying the Bot Code
- Conclusion
What you need to know, before you get started:
If you’re worried this is going to be complicated and beyond your scope, don’t worry. If you follow the steps carefully, this won’t be nearly as daunting as it seems to be. But before you get started, there are a few things that we expect you to know/have beforehand:
- First, you obviously need to have a Discord account. Also, you need to have a desktop client for the application installed on your computer.
- You will need some sort of a text editor for code (Sublime, Atom etc.).
- We expect you to have very fundamental knowledge of JavaScript (or Node JS) and on how to use the command line (on Windows) or terminal (on Apple/Linux).
- You need to have Node JS (version 8.0.0 or higher) installed on your computer. To check if you have Node JS installed or which version you have, open up the terminal or command line (windows) on your computer, type “node –v” and hit enter. If nothing shows up, you need to install Node JS.
How to create a discord bot, the steps:
We will first guide you through the steps on how to create a discord bot. You will:
- First, setup a local project.
- Second, create a Discord app.
- Third, grab a token to use Discord’s API.
- Fourth, create a test server.
- Fifth, add the bot to this test server.
- Final, test your bot.
Once you’ve followed these steps and successfully created a Discord bot, we’ll be looking into some of the things you can do with it. These include tasks that you can now automate in order to passively manage a chat group.
Now let’s get started with setting up the Bot:
Setting up a local project
Before you do anything else, you will first need to setup a local project in your computer. For this open up command prompt/terminal and type in the following:
- mkdir my-bot
- cd my-bot
- npm init –y
- npm install discord.js
The first code creates a local directory by the name of “new-bot”. The second code takes you into that directory. Once in that directory, the third code generates a minimal package.json file. The final line imports the JS wrapper discord.js into our project. This will let us to interact with the Discord API.
Now, in your directory create a new file called index.js. Click on this link and from it, copy and paste the following code.
The code above is a sample code provided by the developers of discord.js, taken from their website. It first initializes the discord.js library by calling Client(). Next, the code enables us to listen to events such as ready or message, and the callback function allows us to define how we want to respond to these events. Finally, the login function at the end allows us to establish a websocket connection between our code and Discord. But to access Discord’s API, we will require a token. We will be grabbing one in the coming steps.
Creating a Discord app
Now you’ll need to create an “application” on Discord to make your bot work. This takes a little doing, but it’s not too complex. The goal here is to get an “authorization token” for the bot so that Discord recogn`izes your code and adds it to the bot on its servers.
First, head to discordapp.com/developers/applications/me. Your account should be logged in, so you’ll go straight to your account’s list of applications.
Head over to Discord’s developer page and click on Create an application.
Fill the NAME field and choose an avatar if you want. In my case, I chose to name it Tommy the Bot and to make it look like Wall-E. Then click on Save changes. You should see a feedback message telling “All your edits have been carefully recorded.”
On the left panel, click on Bot, then click on ADD BOT.
A popup should appear, click on Yes, do it!. Depending on the name of your app, you can see an error message telling you “Too many users have this username, please try another.”. In that case, choose another name for your app. (I’m sorry for you if one of your fancy names was taken ????)
After that, you should see a success message telling you “A wild bot has appeared!”.
Grabbing a token to use Discord’s API
Finally, the login function at the end allows us to establish a websocket connection between our code and Discord. But to access Discord’s API, we will require a token. We will be grabbing one in the coming steps.
Below TOKEN, click on COPY and paste it in index.js as a parameter of the loginmethod. Voilà! You are now the happy owner of a Discord bot token.
When you grabbed your token, you may have noticed that Discord hid it by default. They did it because it’s a sensitive data. Indeed, you can do whatever you want with the bot with that token. So if somebody steals it, bad things can happen. As a consequence, we need to hide our token from the source code in case you push it on GitHub for example.
To hide data, we use what we call environmental variables. Basically, we put what we want to hide or configuration variables into a file whose name is .env. This file should never be pushed on a public repository if it contains sensitive data. Create a new file called .env and paste the following:
BOT_TOKEN=YOUR_TOKEN_HERE
Of course, don’t literally paste YOUR_TOKEN_HERE. Paste your own token.
The next step is to load this variable into our app. Indeed, you may have added a .env file, it will mean nothing to Node when it will run your index.js file. For that, we will add a package called dotenv. As their docs say, dotenv is a module that loads environment variables from a .env file into process.env.:
- Run npm install dotenv
- At the very top of your index.js file, add this line:
require(‘dotenv’).config()
- Replace your token with process.env.BOT_TOKEN:
client.login(process.env.BOT_TOKEN)Go back to your server and make sure your bot is still online. Alternatively, you can also check your terminal and double-check you didn’t get any errors.
Creating a test server
Now, we are going to add the bot to a server, but for that, we need at least one server. If you don’t have yet created a server, here is how to do it (I recommend you to create a test server):
After you logged in in Discord, click on the + icon on your servers list:
A popup should appear. Click on Create a server.
Fill in the SERVER NAME field and choose the SERVER REGION depending on your location (the closest, the better).
Great. Now we’re ready to add our bot to our server:
Adding our bot to this test server
Go back to the developer portal and click on OAuth2 in the left panel. Under SCOPES, select bot. Finally, click on Copy.
Open a new tab and paste in the URL the one you’ve just copied. Select your server and click on Authorize.
Your bot is added! Go in the Discord app and check for your bot in the list of users.
Our bot is on our server but it’s offline. So let’s make it alive. For development purposes, we will add nodemon. It will allow us to reload our code as soon as it changes:
npm install nodemon –save-dev
Then, we will add some scripts to our package.json to make our life easier. One will be called start and the other one dev. Paste the following in your package.json file:
{
“name”: “my-bot”,
“version”: “1.0.0”,
“main”: “index.js”,
“scripts”: {
“start”: “node index.js”,
“dev”: “nodemon index.js”
},
“dependencies”: {
“discord.js”: “^11.4.2”
},
“devDependencies”: {
“nodemon”: “^1.18.9”
}
}
https://pastebin.com/ZLhfjGSH
Ladies and gentlemen, this is the moment you’ve been waiting for. Your bot is going to be brought online! Run this command:
npm run dev
If all went well, you should see this in your terminal:
Go back to your Discord test server, you should see your bot online. Send ping in the general channel, your bot will reply Pong!. Amazing!
Testing our Discord bot
Now that you have everything setup, it’s time to test and deploy your bot.
The Welcome Message
Right now, all we have is a bot that responds with “Pong!” if anyone says “Ping”. Let’s give our bot a bit more character. Perhaps we would like it to send some sort of a welcome messageor group guideline as soon as someone new joins our server. To do this, add the following code:
client.on(‘guildMemberAdd’, member => {
member.send( `Welcome friend! Have fun, and please follow the community guideline. Spams, pornography, trolling or bullying will not be tolerated. ` )
})
What this code basically does is that it emits a special event called the guildMemberAdd as soon as someone joins the server. It then passes the new member as an argument and using the send method, sends the welcome message and the server instructions as a direct message between the bot and the user.
You might want to test this feature once you have added the code. To do this, invite someone to the server and see if they get the message. Click on the server name and select “Invite People”. Now copy the invitation link and send it to someone you know. Ask them if they receive a direct welcome message from your bot.
Kicking users out
Love it or hate it, one of the most fun part of a group conversation is the ability to kick users out. But you, as the moderator/administrator of the server can’t handle all requests. This is where out bot starts to come handy. In this section, we will train our bot to kick users when instructed to do so. For this, we have defined a command called “%kick @user” that will instruct the bot to kick to kick the tagged user.
To achieve this, add the following code:
client.on(‘message’, message => {
if (message.content.startsWith(‘%kick’)) {
const member = message.mentions.members.first()
if (!member) {
returnmessage.reply(
`Do you want to kick someone out? You have to mention their name.`
)
}
if (!member.kickable) {
returnmessage.reply(`This user cannot be kicked!`)
}
return member
.kick()
.then(() =>message.reply(`${member.user.tag} was kicked from the group.`))
.catch(error =>message.reply(`There was an error.`))
}
})
What this code basically does is that it processes any message that begins with %kick. It then checks the username that follows the %kick command.
If there is no username, it will send this message: “Do you want to kick someone out? You have to mention their name.”
If the user tagged to the %kick command cannot be kicked (maybe they’re the server administrator or the bot itself), the bot will send a message saying: “This user cannot be kicked!”.
If all goes well, and the bot implements the kick() method to kick the tagged member out of the conversation. It will them send a message declaring the successful kick. If instead, it encounters some error, it will send an error message.
Your bot might, however, not be able to kick users out just yet. This code will only work if your bot has permission to kick users. In the following section, we will be giving our bot some special privileges.
Giving the Bot permissions
So far we have setup a function bot on Discord. But this bot still doesn’t have the necessary permission to do a lot of things, like kicking someone. To give permission to our bot, we first need to create a bot role. We can then assign this bot role to the bot we have created.
- On Discord, find your server’s name and click on it. Then select Server settings and Roles.
- Click on the ‘+’ button. Give the role a name, something like ‘kicking’.
- In the list of permissions, select the permission that you want to give to the bot. For this example, find and turn on permission for ‘King Members’.
- Now on the Members menu on the left, find your bot and click on the ‘+’ button next to it. Now add the bot role (‘kicking’).
You can repeat this process for any kind of permission that you would like to give your bot. For now, you can go back to the Discord group and try and kick users and see if the bot does its job.
Optimizing the Bot Code
So far, we have a very minimal bot. There are only three events that are linked to it. The ready event for when the bot is ready, the guildMemberAdd event for when someone new joins the server and the messageevent for when a message is sent to the server. But we may want to add more events to it, and when we do that, we many not want all of our code to be in the same index.js file. So in this section, we will try to optimize the bot code.
For this, we will create two folders. One will be called Events, and it will contain three files, ready.js, message.js and guildMemberAdd.js. The other folder will be called Commands, and it will contain the .js files of all the bot commands. For now it will contain one file kick.js, to handle the kicking command.
Index.js
- Since we will be working with files, we must import the fs module onto our index.js file. Open index.js and add the following code on the top:
const fs = require(‘fs’)
- Now we have to make sure we can read all of the files of the events folder. We will be using two callback arguments err and files. Also inside these callback functions, each event handler will be required using the filenames. Now this code has to listen to these events and add the corresponding event handler.
To do all this add the following code just below const client = new Discord.Client()in index.js.
fs.readdir(‘./events/’, (err, files) => {
files.forEach(file => {
consteventHandler = require(`./events/${file}`)
consteventName = file.split(‘.’)[0]
client.on(eventName, arg =>eventHandler(client, arg))
})
})
Now all you have to do is update the three event handler files with their functions and make them exportable.
ready.js
Add the following code to the ready.js file:
module.exports = client => {
console.log(`Logged in as ${client.user.tag}!`)
}
guildMemberAdd.js
Add the following code to the ready.js file:
module.exports = (client, member) => {
member.send(
`Welcome friend! Have fun, and please follow the community guideline. Spams, pornography, trolling or bullying will not be tolerated. `
)
}
message.js
We will not be adding the entire code to message.js right away. The very point of refactoring the bot code was to make sure the code is easy to understand and maintain. But the bulk of the bot command will be packed into the message.js file. This will only keep getting bigger once we introduce new commands like bans.
Hence, this is where we create a new folder called ‘Commands’. In the commands folder, create a file called ‘kick.js’ for the kick command we have implemented so far.
Now on, message.js add the following code:
const kick = require(‘../commands/kick’)
module.exports = (client, message) => {
if (message.content.startsWith(‘!kick’)) {
return kick(message)
}
}
Commands/kick.js
In the commands folder, you have created a file called kick.js. Add the following code to it:
module.exports = message => {
const member = message.mentions.members.first()
if (!member) {
returnmessage.reply(`Do you want to kick someone out? You have to mention their name.`)
}
if (!member.kickable) {
returnmessage.reply(`This user cannot be kicked!`)
}
return member
.kick()
.then(() =>message.reply(`${member.user.tag} was kicked from the group.`))
.catch(error =>message.reply(`There was an error.`))
Deploying the Bot Code
You have now successfully created a Discord Bot. Congratulations! But there is technically one last step that is necessary to give life to your Bot.
Your Bot is currently running on your own computer. And while there is nothing wrong with that, you may not like the idea of having to leave your computer on all the time just to give your bot a life. While this is totally optional, you may want to get a server and deploy your bot to it. In a way you would be giving it a life of your own.
Conclusion
This concludes our tutorial on how to create a discord bot. We discussed the entire process from creating the bot to deploying it to a server. We also talked about how you can optimize your bot code. Hope you found this article useful.