If you have a gaming hobby like me, chances are you have heard of or use the service Discord. For those not in the know, Discord is a voice-chat, messaging, and video streaming application. I have been using Discord for a few years now to chat and hang out with friends while gaming, but I was always intrigued by the bots that you can invite to your servers. These bots are programmed to perform specific actions in response to certain messages typed in text channels.
I always wanted to learn how to make my own, and now that I have the coding knowledge to do so, I decided to take a crack at it. In this post, I'll be walking through the process of setting up my very first Discord bot: demo-bot (original, I know). Granted, this is a very simple bot that just responds to specific messages with a random reply - but it's a great starting point for learning how coding a bot works. This walkthrough will be using JavaScript, specifically the discord.js
library. You will need to have Node installed if you'd like to code along.
Setup
Before we can get into actually coding, there are a few things we will need to set up first. The first thing you will need is a Discord account. If you don't have one, it's easy to sign up for free here. After creating an account and logging in, you will need to navigate to the developer portal at the bottom of the page.
Here you will find documentation as well as an applications tab. To create a new application, simply click on the "new application" button! You will be prompted to enter a name for your bot, and once you click save you should be able to access various settings for our new application.
There are a lot of settings here that you can feel free to play around with, but the first thing we want to do is add the actual bot to the application. You can do this by clicking the bot tab, then the create bot button, and confirm. You will see a hidden token that is very important for connecting to our bot in our code. We can grab this in a little bit. You will also want to navigate back to the "General Information" tab and copy the client id there. We will be using this to invite our bot to our server.
There is one last step before we get to coding - we have to invite the bot to a server! For this I recommend creating your own test server so that you don't clog up a shared server when testing and debugging. To invite just pop the following url in your browser, substituting your own Client ID. Select the server you want to invite to and hit ok!
https://discord.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&scope=bot
Let's Get to Coding!
The first thing we have to do is set up our environment. Run the command npm init
to generate your package.json
file. We will also need an index.js
file - this is where we will be writing all of our bot code.
At this point I would also recommend creating a .gitignore
and .env
file as well as installing dotenv
by running npm install dotenv
. If you are working on your own local environment for testing purposes this isn't necessary, but it is best practice to hide sensitive variables like our Bot ID - especially if you are backing up your work on github.
The last package we will need is discord.js
which will provide us an easy way to interface with the Discord API using JavaScript. Just run npm install discord.js
to install the package.
OK, Can We Actually Code Now?
Alright, the time has finally come! Open up that index.js
file and lets start getting things set up. The first thing we want to do is get discord.js
hooked up to our index file as well as create a client
variable that we can operate on and use to connect to our bot.
const Discord = require('discord.js');
const client = new Discord.Client();
I like to set up my global variables at the top as well, so under the above code I am also going to create a replies
variable that will be an array containing all of the replies that the bot can send.
// Variables
const replies = [
`Aye Aye, Captain! 🦀🦀🦀`,
`I can't hear youuuuu! 🦀🦀🦀 `,
`Who lives in a 🍍 under the sea?`
];
Next we are going to write some setup code that needs to run before anything else. We are first going to run our dotenv
config so that we can access the variables in our .env
file. Then we are going to call the login()
method on our client
variable to start our bot. This method will take our secret Bot Token as an argument so that it knows which bot to connect to.
// Setup
require('dotenv').config();
client.login(process.env.BOT_TOKEN);
At this point we are ready to run our bot! Granted it doesn't do anything yet, but we can still run it nonetheless. If you type node index.js
into your terminal it will launch the bot. You might notice that nothing is happening - let's go ahead and close the bot using ctrl + c
and add in an action that will let us know for sure our bot is ready.
For responding to events, we will be using the on()
method with our client
variable. This method is similar to event handlers in JavaScript and takes two arguments. The first is a string that is the type of event we will be responding to and the second is a callback that will be executed in response to the event.
Let's set it up so that when the bot is connected and ready we print out "Ready!" to the console.
client.on('ready', () => console.log("Ready!"));
Now if we try node index.js
again, after a second we should see "Ready!" pop up in the terminal!
The second action the we need to be concerned with is "message". This event is triggered when a message is received in a text channel. it will look like this:
client.on('message', replyMessage);
"message" here is the event we will be responding to and replyMessage
is the callback we will be passing in that will execute when the "message" event is triggered. This is the main functionality of our bot so I'm going to provide the function code and then walk through what it is doing.
// Functions
function replyMessage(msg){
if (msg.channel.id === process.env.TEST_CHANNEL && msg.content.toLowerCase() === "arrr you ready kids?!") {
const i = Math.floor(Math.random() * replies.length);
msg.reply(replies[i]);
}
}
So we can see that the function takes in a msg
object as an argument. This object contains a ton of metadata, and I suggest console logging it to get a better look at its properties, but for now we are only going to be concerned with two: channel.id
and content
.
The content property is pretty self explanatory, it is just the text of the message. We are using toLowerCase()
to make the check case insensitive and then checking in our if statement if it matches the message we want to respond to.
The channel.id property is optional, but in this case our if statement is also checking that the message came from a specific channel. We are doing this in this example to restrict the bot to responding only to a specific channel. If you have developer mode turned on in your Discord application, you can grab a channel's ID by right clicking on the channel name and selecting "copy id".
Now that we have checked to make sure the message that we have is the one we want our bot to respond to, we can dive into actually making the bot respond. First we create an index variable that will pick a random number within the range of the length of our replies
array. To reply, we simply call reply()
on our msg
object and pass in the message to respond with. In our case we will be passing in the index of our array equal to our randomly generated number.
This will send an @ reply to the user that posted the message with our bots response text. You can also do this without the @ reply, just sending a regular message to the chat. Instead of reply
we would use send
and it would look like this:
msg.channel.send(replies[i]);
This will simply send the reply to the same channel from which the bot received the message.
TaDa! Beep Boop 🤖
That's all there is to it! Granted this was a very simple "hello World" level application, but it covers the basics of getting started and can help you get started. There are so many more possibilities for building really robust bots that you can use within your own communities, or even publish for the public to invite to their servers. I hope you enjoyed, Happy Coding!
For a deeper look, check out the official documentation:
Discord
discord.js
You should also check out a great tutorial series that helped me get started:
The Coding Train
Top comments (0)