Discord.js | Creating a bot for Discord 🤖 
Published: 2020-04-09 23:42:04

## 0.0 Introduction
Welcome to my short tutorial on creating a bot for Discord. Just as a note, this tutorial won't be going too in depth on every single bit of code being written, it's meant to serve as a quick guide to getting starting creating your own Discord bots. Think of this as a template. 

## Table Of Contents
* [Creating the Bot in Discord](#chapter-1)
* [Setting Up Our Environment](#chapter-2)
* [Writing the Bot](#chapter-3)
* [Running the Bot](#chapter-4)
* [Adding the Bot to a server](#chapter-5)

## 1.Creating the Bot in Discord <a name="chapter-1"></a>
Let's get started by creating a Discord Application
#### 1.1 Visit the [Discord Developer Portal](https://discordapp.com/developers/applications) and click "New Application"
![Discord making an app](https://dev-to-uploads.s3.amazonaws.com/i/akp7ke5wi569z55x7k8o.png)
#### 1.2 Go to "Bot", the click "Add Bot"
![bot settings](https://dev-to-uploads.s3.amazonaws.com/i/rlk1vtke1ulipkor7viu.png)
After creating the bot, we're met with a screen that gives as access to some of the bots settings. We don't need to worry too much about anything here besides our "TOKEN". We'll need this so our bot will be able to connect to the Discord API. Click "copy" paste this somewhere safe for a moment.

## 2. Setting Up Our Environment<a name="chapter-2"></a>
Now we've creating essentially the Discord account our bot will run on. We now need to start writing some code to give some life to our bot. However before we do, we need to setup our environment.

In your terminal, run the follow commands
```
mkdir my-app
cd my-app
```
```
yarn init
// or npm init
```
```
touch index.js config.json && mkdir client commands
touch client/Client.js commands/help.js
```
Nice! Now we have almost all the files we need. Now we need to install the Discord.js module. 

```
yarn add discord.js
```

And there we go. We've got our environment setup. Now time to add some code...

## 3. Writing the Bot<a name="chapter-3"></a>
####3.1 The config.json File
In <code>./config</code> we need to add a few lines that configure our app.
```json
{
  "prefix": "#", //set to what you want your command prefix to be
  "token": "YOUR-TOKEN"
}
```
The <code>"prefix"</code> is the character(s) you want your bots to listen for and <code>"token"</code> is the token you copied from the Discord Bot 

#### 3.2 The index.js File
```javascript
const fs = require('fs');
const Discord = require('discord.js');
const Client = require('./client/Client');
const { prefix, token } = require('./config.json');

const client = new Client();
client.commands = new Discord.Collection();
```
The first few lines will just we requiring a few files. Don't worry too much about these lines, except take a look at the line <code>const { prefix, token } = require('./config.json')</code>. This is [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring) our <code>config.json</code> file and setting it to const variables we can use later.

```javascript
const commandFiles = fs
	.readdirSync('./commands')
	.filter((file) => file.endsWith('.js'));

for (const file of commandFiles) {
	const command = require(`./commands/${file}`);
	client.commands.set(command.name, command);
}
```
Again some lines that just paired with a quick explanation. Here we are setting commands that are available to our client.

```javascript
console.log(client.commands);

client.once('ready', () => {
	console.log('Ready!');
});

client.once('reconnecting', () => {
	console.log('Reconnecting!');
});

client.once('disconnect', () => {
	console.log('Disconnect!');
});
```
Here we're logging to our console our client commands and the status of our bot.

```javascript
client.on('message', async (message) => {
	const args = message.content.slice(prefix.length).split(/ +/);
	const commandName = args.shift().toLowerCase();
	const command = client.commands.get(commandName);

	if (message.author.bot) return;
	if (!message.content.startsWith(prefix)) return;

	try {
		if (commandName == 'ban' || commandName == 'userinfo') {
			command.execute(message, client);
		} else {
			command.execute(message);
		}
	} catch (error) {
		console.error(error);
		message.reply('There was an error trying to execute that command!');
	}
});
```
Finally, on to an interesting part. Here the bot is listening for a <code>'message'</code> event and running some code based on that message.

```javascript
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
```
Here we're parsing out our command.

```javascript
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
```
These lines are just checking if the message is first, send by out bot, and if the message starts with our set <code>prefix</code>, <code>prefix</code> coming from our <code>./config.json</code>. If the conditions for the statement are true. Then we <code>return</code>.

```javascript
try {
	command.execute(message);
} catch (error) {
	console.error(error);
	message.reply('There was an error trying to execute that command!');
}
```
Now finally, finally, the part that actually runs the command. First we try to run the command with <code>command.execute(message)</code>, if that didn't work, our <code>catch()</code> will tell our user something went wrong.

#### 3.3 The Client.js file
```javascript
const { Client, Collection } = require('discord.js');

module.exports = class extends Client {
	constructor(config) {
		super({
			disabledEvents: ['TYPING_START'],
		});

		this.commands = new Collection();

		this.queue = new Map();

		this.config = config;
	}
};

```
Here's a short and sweet file. All we are doing here is exporting our Client class that basically holds on to our commands and other info. If you check back at line 3 on index.js, you'll see we're requiring this file <code>const Client = require('./client/Client');</code>

#### 3.4 The Commands
```javascript
const fs = require('fs');

module.exports = {
	name: 'help',
	description: 'List all available commands.',
	execute(message) {
		let str = '';
		const commandFiles = fs
			.readdirSync('./commands')
			.filter((file) => file.endsWith('.js'));

		for (const file of commandFiles) {
			const command = require(`./${file}`);
			str += `Name: ${command.name}, Description: ${command.description} \n`;
		}

		message.channel.send(str);
	},
};
```
This is a simple 'help' command, feel free to copy and paste this for your own bot. But let's go over something a little simpler.

```javascript
module.exports = {
	name: 'command-name',
	description: 'a bit about the command',
	execute(message) {
		let str = 'hello world';
		message.channel.send(str);
	},
};
```
Here's a command template you can use for your own bot. Since you'll be spending most your time in this type of file. I'll go a little more in-depth. 

Let's start with <code>name:</code> here's were you want to set what you want to command to run by. 
<code>description:</code> It's a bit optional, but helpful for when your users use the 'help' command. Just set this to a string that describes the command.
<code>execute(message){//your code}</code> now for the meat of our command. Between those curly braces, you'll want to add the code that'll be executed once the command is called.

All of this gets wrapped in a JavaScript object that then get's exported with <code>module.exports = {//object you created}</code>

Now all you have to do when creating a new command is follow this template and write the code you'd want to execute within that <code>execute()</code> function.

## 4. Running the Bot<a name="chapter-4"></a>
Finally, to run our bot, we'll want to open our <code>package.json</code> file and include a <code>scripts</code> object.

Something like this
```json
	"scripts": {
		"start": "node index.js"
	}
```
We'll want to add so our entire file looks something like
```json
{
	"name": "my-bot",
	"version": "1.0.0",
	"main": "index.js",
	"author": "your-name",
	"license": "MIT",
	"dependencies": {
		"discord.js": "^12.1.1"
	},
	"scripts": {
		"start": "node index.js"
	}
}
```
Then in our command line, just run
```
yarn start
//or npm start
```
You now have a fully functioning Discord Bot.

##5. Adding the Bot to a server<a name="chapter-5"></a>
Adding the bot to a server is very easy
- Make sure your an admin/owner of the server you're trying to add the bot to.
- Visit your [bot's application](https://discordapp.com/developers/applications) again
- Go to the "OAuth2" tab 
- In the "OAuth2 Generator" check "bot" and copy the link
![bot link](https://dev-to-uploads.s3.amazonaws.com/i/bkent8uqjjoilevieexl.png)
- Finally, visit the link and add the bot to your sever.

##6. Conclusion 
Thanks for reading. This was an extreme overview of creating a Discord Bot. I'll link more examples and below and some documentation.

[Discord.js](https://discord.js.org/#/docs/main/stable/class/Message)
[Bot I learned from](https://github.com/TannerGabriel/discord-bot)
[JavaScript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)