DEV Community

loading...
Cover image for Make a Discord bot in just 30 lines of code.

Make a Discord bot in just 30 lines of code.

Shreyas Pahune
Hey there 👋🏻, I am Shreyas Pahune a Full-Stack Web and a Flutter developer who loves to write blogs.
・Updated on ・6 min read

Hey everyone 👋🏻, today we are going to make a discord bot 🤖 which will send gifs according to the user in just 30 lines of code!

The way this bot will work is, if you write .gif happy then the bot will send a random happy gif.

What are we going to use to build this mini-project:

  • JavaScript
  • NPM Packages:
    • Discord.js
    • DOTENV
    • node-fetch

Okay so let's get started 🎉!!

Steps :

  1. We have to go to the discord developer portal and create a new application.

portal

  1. Then you have to create a new application ☝🏻. (the blue button on top-right corner) .
  2. Give a name to your application.
  3. Then on the left hand side, click on bot👇🏻 .
  4. second
  5. After clicking on bot, now click on Add Bot on the right hand side, and after this step you will have a screen like this 👇🏻.
  6. third
  7. Now the Token is something which you have to keep a secret and not reveal anywhere or to anyone.
  8. If you reveal it by mistake, no worries just regenerate it, but make sure you don't or else someone can take over your bot.
  9. Now we have to decide what permissions does our bot need, and after deciding this, just head to OAuth2 section on the right hand side of your screen.
  10. You will have a screen when many check boxes, and you have to click on the checkbox which says bot 👇🏻.
  11. four
  12. Then click on the permission you have to give to the bot.
  13. After that click on the link and copy it, after that paste it into a new tab and authorize it to add it to a new server.

Now we just have to code it!

Before explaining the code, let me explain you the folder structure 👇🏻.

folder

  1. There is a folder called src in which we have a main file called bot.js in which we are going to code our bot.
  2. Okay so you can see that there are two files and a folder, named as package-lock.json, package.json and node_modules respectively, they are basically of node packages and their information.
  3. There is also a .env file but we will discuss about it later in this blog.
  4. Okay so we have to use 3 packages to make a discord bot, they are as follows:
    1. discord.js (npm i discord.js)
    2. dotenv (npm i dotenv)
    3. node-fetch (npm i node-fetch)
  5. Now using this image as my reference, I am going to explain the code.
  6. code

As you can see ☝🏻, there are only 30 lines of code! How amazing it that?

Your own discord bot 🤖 in just 30 lines of code!

Okay so the first and the third line of code are the import statements which can also be written as :

import discord from 'discord.js;'

The second line of code is basically us initializing the client/user, which in this case will be our bot and the users themselves .

and the fourth line is importing the env package and configuring it, so basically .env files stores all your secrets, like your discord bot's token or your API Key, these things will not be uploaded on GitHub using the git ignore file.

Okay so in JavaScript there is this thing called addEventListner which helps us to react to certain events, like if a user clicks on something or double-tap on something a particular function should run.

In the same way here in discord.js addEventListner is more or less replaced by .on function.

All of the .on functions are called in regards to the client so we have to write client.on('event', callBackFunction).

On line number 6 you can see that I have written a function which is

ready

This basically means that, whenever the user is ready and logged in the console should log <Name of the Bot> is up and ready! and name of the bot is fetched by this inbuilt property known as .user.tag , which is to be called in regards to the client .

Now we have to make our bot login to the server. And for that we have another inbuilt method/function called .login .

So we can write : client.login(process.env.TOKEN)

Now you might wonder what is this process.env.TOKEN, this is the way we call variables from our .env file.
So let me show what is stored inside .env file.

env

Here in this file, we have to put our bot token inside a pair of single or double quotes and our tenor API key (you can generate it from here)

For example if you want to call the tenor api key inside your bot.js file, you just have to write process.env.TENOR.

And you can make a try-catch block around the client.login() function, so if any error occurs, we can catch it and show it on the console.

try-catch
So as of now, we have our boiler plate code ready with us, which is 👇🏻:

boiler

Let's code the main functionality of the bot now.

Now all the code discussed below will be in the reference to 👇🏻 this image.

main

Now let's understand the above code step-by-step:

  1. Creating an add event listener to react when the user sends message:
    1. addEve
    2. Here the parameter msg will contain the message which user has sent.
  2. Let's add a prefix to our bot, so it will only react if we write .gif.
    1. Just to be a little safe, I am going to write the main functionality inside a try-catch block.
    2. try
    3. msg.content helps us to fetch the content inside the msg. In leman's term, it is like .innerText in JavaScript.
    4. Here when the user will write .gif the code inside the if statement will be executed.
  3. Now let's get user's queries.
    1. Now if a user writes .gif batman then this will be considered as a string and a problem arises here, which is how do we separate the bot command and the user's query.
    2. We do that by an inbuilt function called .split(), which will help us to separate the whole string into two different values stored in an array, for example: if I write .gif batman then .split() will make an array : ['.gif', 'batman'].
    3. Let's see it's code.
    4. split
    5. We are going to compare the first index of query which will be .gif to the string .gif.
  4. Let's discuss about the API and Fetching it.
    1. I am using node-fetch to fetch the API.
    2. The base of the API is
      1. https://g.tenor.com/v1/search?q=USERQUERY&key=API-KEY
    3. And in order to take query from the user and give the key as your API Key we have to make this URL dynamic.
    4. We can do that by using template literals.
      1. https://g.tenor.com/v1/search?q=${query[1]}&key=${process.env.TENOR}
      2. And now the code looks like this.
      3. url
      4. And the query has to be the second value (First Index) in the array.
    5. Let's fetch the API now.
      1. We just have to put async in front of the callback function as you can see in the above image on line number 10.
      2. async will make your function, asynchronous and then we will use await to wait for the response from the API.
      3. without
      4. Now here we will have a problem, which is we will only receive one GIF every time.
      5. Now the API will return 20 GIFs and we have to pick a random one (on line 17).
      6. So to do this, we will make a random variable which will choose one GIF.
      7. Now the final code looks like 👇🏻
      8. final
  5. Let's run this.
    1. Just open the terminal, change the directory to the home directory and inside src folder, then write node bot.js.

Thank you for reading the whole blog 🎉!! If you liked it do share it with your developer friends and feel free to comment and give suggestions.


Discussion (6)

Collapse
nikolajsvendsen profile image
NikolajSvendsen

Gotta try this out, thanks for the tutorial! XD

Collapse
shreyazz profile image
Shreyas Pahune Author

More amazing tutorials on the way 🎉🔥
Thanks btw ✅!!

Collapse
agorushkin profile image
Arsenii Gorushkin

Nice tutorial, but I got to ask, what tool did you use for these code cards?

Collapse
shreyazz profile image
Shreyas Pahune Author

carbon.now.sh/ head to this website and copy-paste your code

Collapse
mattketmo profile image
Matt Ketmo

carbon.vercel.app/ is your friend ;)
and it's open source: github.com/carbon-app/carbon

Collapse
agorushkin profile image
Arsenii Gorushkin

Cheers