How To Develop Your Very Own Bot

How To Develop Your Very Own Bot

Building A Simple Discord Bot with Javascript

Be honest what is the first word that comes to your mind?

Maybe one out of: Complex, cool, amazing, discord, interesting, not for me, I wanna try it, robots, just how, and the list goes on...

Let's get some background first!

What is a Bot?

A robot or bot for short is simply a computer program(software application) that is intended to imitate human activities on the internet. It could be intended for automating tasks, or messaging like in chat bots for modern day businesses, or maybe moderation or monitoring or whatever at all, it doesn't really matter.

You can have a bot wake you up in the morning or remind you to have breakfast if you want. I guess that's what alarms are for right, and yes they are robots too!

Put it this way, anything that is tedious and repetitive, will most likely benefit from having a robot/bot do the same for you.

Why? Buys you some coffee and napping time I suppose!

Now that you know what a bot(robot) is and what they are intended for, let's get into some action, didn't really plan to do much talking here today you feel me.

Getting started

So, what's next? Well there are a couple of ways I can think of, but it all just comes down to a problem and the need for a solution, I guess that's where we will start from.

Example Problem Statement

I don't want to always have to greet everyone in my closed group every time someone joins the group. So can I have a way to automate that? And the answer is yes, we can have a bot do just that for us, get the idea?

So now we have a problem and the solution is to create a bot to greet everyone whenever they hop into the community.

However, what we are going to be building today is super simple, and by the end of this article, you should have a working discord bot that will be deployed on a cloud service.

Let's do this thing!

Note: Before we proceed any further, I want to re-emphasize that we are going to be building a discord bot and that this is not the only way to deploy or develop your bot, you can make twitter bots, slack bots, telegram bots, fb messenger bots, whatsApp bots, and even custom built bots. But discord is providing us the platform and the services and we just have to engineer the creation of the bot and the logic that makes it function the way it should, which I consider the soul/heart/brain of the bot, and without it, the bot is just a thought in the air, got it?

For simplicity, I will break down the tutorial into 2 phases. Let's go!

Phase 1

Since, we are going to be creating a discord bot we need to first create a discord server where our bot will be launched. One thing to keep in mind is that a discord bot is just another discord user account really.

So if that makes sense, then head on over to this link here https://discord.com/developers/applications and click on the button that says New Application at the top right hand corner of the page. A dialog will immediately appear on your screen, so then you have to type in the name for your bot host account, this could typically be exact same name as your bot, and we should call it buddy. Then click on Create button. This will create your bot application. There are some input fields in there but just ignore those for now, they are self explanatory actually and i'm sure you can figure that part out later if need be.

Then the next thing you have to do is to click on the Bot tab from the menu option on the left pane of the web page under the SETTINGS label. Then click on the Add Bot button, a pop up will appear, go ahead and smash the Let's do it button to create bot user account. Congratulations you now have a user bot account created but it is not installed anywhere yet. Take note this page you are currently is very sensitive and shouldn't be shared, it also has a token you need to copy once the bot is created for later use, but don't worry if you lost it, just click on the Reset Token button to generate a new one and copy it. This is your ownership of the bot, I mean the token, and this token is so powerful that it can be used to control your bot and also exploit wherever the bot have access to, more on that later. Leave every other thing on this page as it is until you are experienced enough to work with some of the options there if necessary for your bot. Anyways, look on the menu options again to the left and click on the OAuth2 tab it will dropdown some other options, click on URL Generator option from the dropdown, and select the bot under the scope label. Now under the bot permission this is what determines what your bot can do on your server, very very important not to give your bot administrative privileges if not absolutely necessary, because if the token is compromised, then there is a big problem if the person that has it is a bad guy. They can do whatever on your server as they choose.

That being said, select everything under Text Permission label except for the Send TTS message it is not necessary in this case. Then at the bottom of the page, there is a url there under generated url label, click on the copy button and open a new tab and paste it there then click enter to load it up. This is where you will invite your bot to your server as a user.

But we don't have a server yet, and I don't want to teach that in this article, it is a no brainer, so I will outsource to the internet to help you do that, just in case you can't. Head on over to this url https://www.ionos.com/digitalguide/server/know-how/how-to-set-up-a-discord-server/ it explains in details how to setup your server with guided steps and picture references as well. And when you are done, you can come back here to continue reading.

Now that you have your server, and you have loaded the url you copied from the bot creation page few steps behind, then you should see your server in the dropdown list on the page, select it, then click on continue. It will tell you to review the privileges of your bot and then when you are satisfied with the changes, click on authorize. Complete the human verification step (Captcha) and you are done.

Head over to your server and you should see the bot in there, but you will notice it is offline for now and inactive.

Phew, congratulations on completing phase 1 of this tutorial, you need to have a water break or something.

The next phase is pretty technical and more of the programming part of the bot to give it life and functionality by coding its logic on a cloud service, although this can be localhost if you wish, it doesn't have to be online at all, so you can follow along with your favorite code editor. But it is quite easier online without any extra setup.

Phase 2

Welcome to phase 2 of this tutorial, I hope you learnt something so far, well let's go on a joy ride if you are still motivated!

The cloud service I keep talking about is called repl.it it is like an online codesandbox/IDE but with more features than you can imagine, so I highly recommend using this for this phase though. Head on over to https://replit.com/ to create an account and read about the cool stuff there, when you have your account setup, you should be logged in and have a dashboard where you can find a create button somewhere to provision what we call a repl, but consider that basically to be a directory with an isolated file system powered by a powerful engine called Nix and before you create your repl, select a template first, type in nodejs, and give it a proper name like Buddy Bot or something like we gave it initially, it can be anything you want or you can just accept the default generated name if you want. You can always edit those later if you want, now just click on create repl button and wait for the provisioning then you should have an online IDE where you can manage your files and directories and write your code.

First thing you should see is an empty index.js file there on the left, then a pane where you can type code in the middle, and another where you can see the output like the terminal and shell on the right.

Before we write code, remember that token we had from the bot page right? Yeah, we need it now, if you copied it before and stored it then get it or if you didn't just got the bot page and click reset token, copy that and bring it to replit. Click on the lock icon where you can put in your secrets, by the way I am assuming most of you reading this are like atleast has some programming experience, so your environment variables can be stored here and it will be loaded into process.env you get the idea right. Enter a name like BOT_TOKEN or whatever and paste the token in the value field, click on add. and head back to the files icon.

Now with that out of the way, copy and paste this code in the index.js file.

const Discord = require('discord.js')
const client = new Discord.Client({
  intents: [
    'GUILDS',
    'GUILD_MESSAGES'
  ]
})

client.on('ready', () => {
  console.log(`${client.user.tag} is online!`)
})

client.login(process.env.DISCORD_BOT_TOKEN)

This basically brings your bot online and if you check your server, you can confirm that as well, but it does nothing special still.

What we are doing here is using a wrapper module called discord.js to create a client that will imitate our bot using the token we got. We initialized a new instance of the client and passing in some config options. It uses an event mechanism similar to how sockets and webhooks work. Here we are saying on ready log a message and we got the name of the bot from the client.user.tag or client.user.username property of the instance. Then we log the client in with the login() method passing in the token from the environment variables.

And now we are going to implement a simple logic to greet a user whenever they make a post in the server channels. Whenever a user types ping in any channel, the bot will reply pong to the user, and then sends another message to the channel.

Copy the code below and update the index.js file

const Discord = require('discord.js')
const client = new Discord.Client({
  intents: [
    'GUILDS',
    'GUILD_MESSAGES'
  ]
})

client.on('ready', () => {
  console.log(`${client.user.tag} is online!`)
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return

    if(msg.content === 'ping'){
      msg.reply('pong')
      msg.channel.send('Do it again!')
    }
})

client.login(process.env.DISCORD_BOT_TOKEN)

And now we listened for a new event trigger called messageCreate, it will then return to us the msg instance exposing several useful methods and properties. The first line says if the author of the message is the bot, it shouldn't do anything, that means if the bot responds or sends anything, it shouldn't take any action. Then we specified that if the content of the message is ping then we should reply the person that send the message a pong, then send a message to the channel.

That's it!

You have just created your very own bot, wow amazing!!!

You did a good job coming this far, you should be proud of yourself really, it is not as easy, if not everyone will be doing it.

Now, what you can do is to get familiar with the processes we followed, and replicate the same thing, I hoped you were following along anyway. That way you can remember for yourself, and also study the API library and figure out other cool things you can do. With the library and a cool idea, your bot should be shining already, share with the world and in the comments I will really love to hear about the cool ideas you come up with.

Thank you for reading!

If you have any questions, please ask in the comments, or on socials i'm everywhere around you :)

Resources used:

More articles on this series upcoming, stay curious...