Overview & Setup
This article will show how to create a discord bot. For an example of a Discord Bot that I wrote for an assignment while I was at UVU, follow this link. To start you will need to create a new Node.js environment. If you dont have Node downloaded and installed, do that first. In the root folder, create an index.js file. Next, you'll need to download a couple of of NPM packackages. In your terminal run npm install dotenv
and npm install discordjs
.
Getting Into It
To start, we will create a .env file in the root folder. This is a file that will contain environment variables. For now it should be empty, but wil will add to it later. Now, in your index.js file, you will need to import and use the packages that were just installed. Add the following code to the top of your index.js file.
//index.js
const dotenv = require("dotenv");
dotenv.config({ path: "./.env" });
const { env } = process;
const Discord = require("discord.js");
Now with everything imported we will get into the actual code for the bot. With the discordjs NPM package, its pretty simple to create the bot. In the index.js file add the following code:
//index.js
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
Thats it! With those few lines of code, your bot will spin up and log out 'Ready!'. This wouldn't work though yet because we haven't connected the bot code to an actual bot on discord, or authenticated the bot. So lets do that now.
Creating A Bot In Discord
First, log in or create a Discord account. Then follow this link to go to the developer portal. In the upper right hand corner click the button to create a new application.
This will bring you to the 'General Information' page for the application you just created. On the left hand side, you'll see a menu. One of the options is 'bot', click it.
Now you'll see this page, click on the 'Add Bot' button.
Discord will create the bot, and give it the same username as you named the application. You can change this here and can add a picture for the bot here as well. With the bot created now, you'll need to copy the bot token so you can add it to your application.
Back in the code, go to your .env file that we created earlier. This is where we will add the bot token that you just copied. IMPORTANT: The bot token is a secret, and should not be tracked on Github or anything like it. Be sure to add your .env file to a .gitignore before pushing it to Github This .env file should look like this:
//.env
BOT_TOKEN=<YOUR_TOKEN_HERE>
Now in the index.js file, at the bottom of the code, add the following line:
//index.js
client.login(env.BOT_TOKEN);
Now your code is actually logged in and connected to the discord bot you just created! All that needs to be done now is to add it to a server.
Adding Your Bot To A Server
Back in the Application Portal for your bot, in the menu bar, click the OAuth2 line.
This will bring you to the authentication settings. At the bottom of the page there is a 'scopes' section. Check the 'Bot' option. This will reveal a URL at the bottom of this section. Copy and paste that URL into a new browser tab. That URL is the invite link to add your bot to a Discord server.
As long as you have permission in a discord server to add bots, you can select the server and click 'Authorize'. When you do that, you've officially created and added your bot!
Now in back in your Node terminal, run node index.js
. In your node terminal you should see that it logged out 'Ready!'. But nothing would happen when you send messages yet. Next up we will add some functionality for the bot to interact with messages.
Adding Functionality To Your Bot
Having the bot created and added to a server is super cool, but likely you didn't want to create a bot to do nothing. Now we will add a prefix that the bot will look for and have it send a reply.
Just like before when we used the client.on()
method to log a message when the bot started up, we will use it now to see each message. Add the following code to your index.js file, above the login()
method.
//index.js
client.on("message", async (message) => {});
This will allow the bot to look at the messages that are sent to the channels that it has access to. Inside this method we can add logic to only make a prefix that the bot will only respond to messages that start with the prefix. We will make our prefix '@'. We can also make keywords that the bot can know how to respond to. We will do that now to. Add the following code inside the .on curly brackets.
//index.js
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.content.startsWith("@")) return;
const contentArr = message.content.split(" ");
if (contentArr[0] === "@marco") {
message.reply("Polo!.");
return;
} else if (contentArr[0] === "@polo") {
message.reply("Marco!");
return;
}
});
The first line there, will exit the method if the author of the message is the bot. This will protect us from an infinite loop when the bot sends a message in response to a command. The next line looks at a message to check if it starts with the prefix '@'. If either of those conditions are not true, the method returns. Finally we split the message content into an array and check if the first word in the array matches one of our key words. If it does, we send a message back.
If you stop your node app and rerun node index.js
and send a message of either '@marco' or '@polo', you should see the proper response in a message replied to you by the bot.
Conclusion
With that as the beginning, you have everything needed to make a bot to do whatever you would like it to. You can use different commands to do what you would like them to, and utilize Javascript to have the bot run functions when a keyword is sent. In the Github repo that I linked earlier in the post, you'll see how I had the bot call an API and return a response, send an email and send a text message.
Hopefully this into has helped you to create a cool Discord Bot! If you want to know more about the Discord NPM package, read the docs here.
Top comments (0)