DEV Community

Cover image for Building Discord Bot using Nodejs - Project 01
Vishnu Dileesh
Vishnu Dileesh

Posted on

Building Discord Bot using Nodejs - Project 01

Project Idea:
Inspiration quotes are as important as your daily dose of coffee to keep yourself motivated enough to deal with your day to day challenges.
So let's build a bot, which gives a dose of random inspiration quote every time a user types in the command !inspire in our discord server.

The basic steps required to be done in the Discord's Application Dashboard before jumping into coding is written in the below-linked Article

Building a Discord Bot (Basic Setups)

Okay, so we have gone through all the steps mentioned in the above article. Now it's time to jump into doing some actual coding.

  • Step 1:

Open your terminal and create a new project folder.
Inside the project folder initialize npm

npm init -y

When the initialization is done you will have a package.json file in your folder.

Great now let's install discordjs and dotenv npm packages.

discord.js is a powerful node.js module that allows you to interact with the Discord API very easily.

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.

Run the below command to install the packages
npm install discord.js dotenv

Awesome, so now we have the packages installed.
Now let's make two files in our project folder.
This is the time to open the project in your choice of text editor.

The first file is the .env file, We will store our bot token in this file. This file is never pushed to Github or not the content of the files is shared with anyone. Anyone who gets access to that secret token can log in to your server as the bot and can do malicious activities.

BOT_TOKEN=<copy-pasted-token-value-here>
Enter fullscreen mode Exit fullscreen mode

Alt Text

The token is found on Discord's Application dashboard under the bot information page.

Great, so now our .env file is all set. Let's move on to the real action.

Create a new file named index.js

const Discord = require('discord.js')
const client = new Discord.Client()

const config = require('dotenv').config()
Enter fullscreen mode Exit fullscreen mode

In the above code, we are first importing the discord.js package, initializing it, and storing it in a constant named client.
Then we are importing and activating dotenv to deal with our secrets.

const quotes = [
  'Chase the vision, not the money; the money will end up following you. — Tony Hsieh',
  'Don’t worry about failure; you only have to be right once. — Drew Houston',
  'Ideas are commodity. Execution of them is not. — Michael Dell',
  'If you are not embarrassed by the first version of your product, you’ve launched too late. — Reid Hoffman',
  'I knew that if I failed I wouldn’t regret that, but I knew the one thing I might regret is not trying. — Jeff Bezos',
]

const randomQuote = () => quotes[Math.floor(Math.random() * quotes.length)]

Enter fullscreen mode Exit fullscreen mode

Okay, now it's time to set up our inspirational quotes. If you want you could get innovative and use some available inspiration quotes API services. Here, am going humble, and gonna store the quotes in an Array named quotes. Also created a simple anonymous function named randomQuote to do some magic and pickup random quote from the array of quotes.

client.on('ready', () => {
  console.log('Inspire Bot running')
  console.log(randomQuote())
})
Enter fullscreen mode Exit fullscreen mode

Client.on ready function lets us do stuff when the bot successfully logs in and is ready to go wild in our server. Here, am just console logging a message and a random quote because am superstitious. You could also get innovative and maybe make the bot add a message to your channel saying, the bot is all ready to spread some motivational vibes.

const prefix = "!"
Enter fullscreen mode Exit fullscreen mode

Okay, so what is the prefix? Well, prefix could literally be anything. It is all about how we want our bot to be invoked by the users. Here we are going for the exclamation point, I might have just gone ahead with maybe a dollar symbol?. It doesn't matter, just choose one.

client.on('message', (msg) => {

  if(msg.author.bot) return
  if(!msg.content.startsWith(prefix)) return

  const commandBody = msg.content.slice(prefix.length)

  const command = commandBody.toLowerCase()

  if(command === 'inspire'){
    msg.reply(randomQuote())
  }

})
Enter fullscreen mode Exit fullscreen mode

Just like client.on ready, client.on message, let us do some stuff when someone writes a message on our server. So, what do we wanna do, when a new message comes up?

First, let's check if the author of the message is a bot. If so do nothing, stay quiet.

Second, If the message doesn't start with a prefix (the exclamation point in our case) just ignore and do nothing.

Third, let's extract the command from the message by removing the prefix from the start of the message. So if the message was !inspire, we will extract the word inspire and will store it in a variable named commandBody.

Fourth, This is an optional step, oftentimes, your bot will have multiple commands to deal with so this step just allows you to do that check. So we are converting the commandBody to lowercase and storing it in a variable named command. Then we are doing an if check to see if the command is equal to the word inspire. Again you could come up with any command names, here am just choosing to call my command inspire.

When the command is - inspire, we are replying to the message with our randomly generated inspirational quote.
msg.reply will make sure that the bot replies directly to the user who invoked and asked for the inspirational vibe.

Alt Text

Now our bot is all set to spread some inspirational vibes in our discord server. All that now required to do is to let the bot login to our server.

client.login(process.env.BOT_TOKEN)
Enter fullscreen mode Exit fullscreen mode

Bot needs the secret token to do the login. Remember we have the token all hidden on our .env file. To use it in our index.js file and pass it to client.login function we have earlier imported and activated dotenv package. That lets us call the token here without revealing it to anyone by calling process.env.BOT_TOKEN.

To run the bot locally on your system, open your terminal in the project folder and run the below command

node index.js

Also in the package.json file, we will add a start script.

"scripts": {
 "start": "node index.js"
}
Enter fullscreen mode Exit fullscreen mode

Now you can run the bot by using either of the below commands

node index.js

or

npm run

Once the bot successfully logs in and all ready to go, we will see our console message, also in the discord server, the bot will appear online.

Alt Text

Try invoking the bot by sending the below message to your discord server.

Alt Text

And if all went well, you will get an inspirational quoted reply from your bot. If you are getting errors, no worries, errors are part of the journey. Google is your friend, try some googling and scavaging around StackOverflow.

Full source code on GitHub

Still not able to resolve the error and get the bot working?
Well free to connect and let's figure it out.

Connect on LinkedIn
Connect on Instagram

Comment below your thoughts and bugs

Happy Coding
Keep Coding

Top comments (0)