Lets make your first Discord Bot!
Tags: javascript, discordbot, discordjs, pokemon
Published: 2021-08-04 17:03:48


## 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
    ```cli
      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
    ```cli
      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".
    ```cli
      npm i -g nodemon
    ```

## Let's Start Coding
1. Create a new js file "bot.js" and include all the libraries in it.
    ```js
        const Discord = require('discord.js');
        require('dotenv').config();
        const fetch = require('node-fetch');
    ```
2. Now let's declare our URL for the [API](https://pokeapi.co/) and our bot object, in [discord.js](https://discord.js.org/#/docs/main/stable/general/welcome) we have a way to do things if you want to include something you can include the class declared in the lib 
    ```js
      const URL = 'https://pokeapi.co/api/v2/pokemon';
      const bot = new Discord.Client();
    ```
3. [Discord.Client](https://discord.js.org/#/docs/main/stable/class/Client) class has a lot of event listeners we are going to use "ready" and "message" in our bot. </br>
    ```js
      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).
    ```js
      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: </br>
a. We're taking the string after pokemon for eg: pokemon Pikachu, the above code will send this name Pikachu to [pokemon API](https://pokeapi.co/) and send back its information in response.</br>
b. Further, the code will take out front_default from the response provided by pokemon API. </br>
c. And this response is sent in `message.embed` form `message.channel.send` to the channel where the data was requested for.
5. Let's now add our code to our bot token: 

a. Go to https://discord.com/developers/applications
![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m32a6k28m7mjfhycjt08.PNG)
b. Open your newly created application
![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rpl669u34a8ffv8zcmv2.png)
c. Click on BOT </br>
![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/woofpb7zl94j0fr1ckgl.PNG) </br>
d. Click on create your bot </br>
![4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/209fb20jp7fq5qvawlvm.PNG) </br>
e. Get your TOKEN :D </br>
Create a new file ".env" and paste your bot token </br>
```env
BOT_TOKEN=<--YOUR BOT TOKEN-->
```
f. In your bot.js file
```js
bot.login(`${process.env.BOT_TOKEN}`);
```
Full bot.js Code:
```js
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}`);
```

Our Pokemons are here
![Pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m51e46qb5g4ykme25uw.png)
 ![Eevee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49y0xdz3t3tve0ax8ooy.png)

Full Repo {% github harshil1712/pokemon-discord-bot %}
The Recording for the Twitch Live is available: [Youtube](https://youtu.be/w6ce19rd4pg)

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

Socials of some wonderful people:
- Follow me on [twitter.com/SavantNimit](https://twitter.com/SavantNimit)
- Hey! Harshil Thanks for the amazing live stream invite 💖
- Follow Harshil on: [twitch.tv/harshil1712](https://www.twitch.tv/harshil1712) [twitter.com/harshil1712](https://twitter.com/harshil1712) [dev.to/harshil1712](https://dev.to/harshil1712) 
- Thanks Ashwin for the wonderful poster design ✨
- Follow Ashwin on [instagram.com/ashwin.adiga](https://www.instagram.com/ashwin.adiga) [behance/ashwinadiga](https://www.behance.net/ashwinadiga)
- Thanks Harsh(ObitoDarky) 👾 for all the awesome suggestions and guidance for writing this blog 
- Follow @obitodarky on [twitter/obitodarky](https://twitter.com/obitodarky)