DEV Community

loading...
Cover image for Lets make your first Discord Bot!

Lets make your first Discord Bot!

Nimit Savant
Canvasing for open source :D
・4 min read

Introduction:

Discord bots are fun to make because you can experiment with a lot of new things there. You're given a platform "Discord" and you integrate with almost all the tools available out there.

Let's start with the Prerequisites:

  1. Node.js and npm installed in mac/windows
  2. Create a new directory name it "pokemon-discordo" or anything you like :D

      npm init -y
    
  3. Open your cli/terminal/cmd we're installing three dependencies:

    • Discord.js for using discords API with Nodejs. This will help us to code our bot.
    • dotenv is a package we use to store our tokens and API keys so that we don't accidentally share them on GitHub. **node-fetch* a light-weight module that brings window.fetch to Node.js
      npm install discord.js dotenv node-fetch
    
  4. We'll also use nodemon, which helps you to load your changes continuously with changes in your files eg: JavaScript, JSON, Html/CSS, etc except ".env".

      npm i -g nodemon
    

Let's Start Coding

  1. Create a new js file "bot.js" and include all the libraries in it.

        const Discord = require('discord.js');
        require('dotenv').config();
        const fetch = require('node-fetch');
    
  2. Now let's declare our URL for the API and our bot object, in discord.js we have a way to do things if you want to include something you can include the class declared in the lib

      const URL = 'https://pokeapi.co/api/v2/pokemon';
      const bot = new Discord.Client();
    
  3. Discord.Client class has a lot of event listeners we are going to use "ready" and "message" in our bot.

      bot.on('ready', () => {
          console.log('Bot is up and running!');
      });
    
      bot.on('message', async (message) => {
      // some code
      })
    
  4. Let's add some code in our 'message' event listener, so essentially we want to listen to messages, and as soon as a message is starting with "pokemon" FYI(this message we're listening to is from a user who is using the bot on a server or directly talking to the bot).

      bot.on('message', async (message) => {
          if (message.content.startsWith('pokemon')) {
              const messageArray = message.content.split(' ');
              const result = await fetch(URL +     `/${messageArray[1]}`);
              const data = await result.json();
              const helpEmbedd = new Discord.MessageEmbed()
              .setTitle(`Name: ${data.name}`)
                .setImage(`${data.sprites.front_default}`);
              message.reply(helpEmbedd);
          }
      });
    

In the above code:
a. We're taking the string after pokemon for eg: pokemon Pikachu, the above code will send this name Pikachu to pokemon API and send back its information in response.
b. Further, the code will take out front_default from the response provided by pokemon API.
c. And this response is sent in message.embed form message.channel.send to the channel where the data was requested for.

  1. Let's now add our code to our bot token:

a. Go to https://discord.com/developers/applications
1
b. Open your newly created application
2
c. Click on BOT
3
d. Click on create your bot
4
e. Get your TOKEN :D
Create a new file ".env" and paste your bot token

BOT_TOKEN=<--YOUR BOT TOKEN-->
Enter fullscreen mode Exit fullscreen mode

f. In your bot.js file

bot.login(`${process.env.BOT_TOKEN}`);
Enter fullscreen mode Exit fullscreen mode

Full bot.js Code:

require('dotenv').config();
const fetch = require('node-fetch');
const Discord = require('discord.js');

const URL = 'https://pokeapi.co/api/v2/pokemon';

const bot = new Discord.Client();

bot.on('ready', () => {
    console.log('Bot is up and running!');
});

bot.on('message', async (message) => {
    if (message.content.startsWith('pokemon')) {
        const messageArray = message.content.split(' ');
        const result = await fetch(URL + `/${messageArray[1]}`);
        const data = await result.json();
        const helpEmbedd = new Discord.MessageEmbed()
            .setTitle(`Name: ${data.name}`)
            .setImage(`${data.sprites.front_default}`);
        message.reply(helpEmbedd);
    }
});

bot.login(`${process.env.BOT_TOKEN}`);
Enter fullscreen mode Exit fullscreen mode

Our Pokemons are here
Pikachu
Eevee

Full Repo

Pokemon Discord Bot

Introduction

Learn to build a Discord bot using Discord.js. This repository will help you get started with building a Discord bot that fetches data from the Pokemon API.

The bot listens to the command pokemon and fetches the infromation of the Pokemon specified after the command.

Installation

1. Clone the Repository

git clone https://github.com/harshil1712/pokemon-discord-bot.git
Enter fullscreen mode Exit fullscreen mode

2. Install Packages

yarn install
Enter fullscreen mode Exit fullscreen mode

or

npm install
Enter fullscreen mode Exit fullscreen mode

3. Create a .env file in the root directory of the project.

4. Paste the following in the .env file and add you bot token.

BOT_TOKEN=<--YOUR BOT TOKEN-->
Enter fullscreen mode Exit fullscreen mode

5. Start the Bot

yarn start
Enter fullscreen mode Exit fullscreen mode

or

npm start
Enter fullscreen mode Exit fullscreen mode

Make sure to add your bot to a server or open a direct message with it, to test the functionalities.

Learn more

We created this bot on a Twitch live stream! If you want to learn from the start you can checkout…



The Recording for the Twitch Live is available: Youtube

PS: Add your bot to your server and ask your friends to suggest some cute Pokemon :D

Socials of some wonderful people:

Discussion (2)

Collapse
krishsavani profile image
Krish Savani

Really great blog. :D

Collapse
nimit2801 profile image
Nimit Savant Author

Thanks Krish, I hope it was informative and detailed enough!
If you've any doubts ping me on my socials, would love to help you out :D