Basic Discord Bot

A simple discord bot guide

Prerequisites

In order to run JavaScript code outside the browser we will use a Node.js. Make sure to install it for the correct operating system.

Use command: "node -v" in your terminal to check that you have successfully installed node.js on your system.

It is also important that you create a bot account and add the bot to your server.

In order to code we will require a code editor. I highly recommend Visual Studio Code but you may use any that you prefer.

Setup

Go ahead a create a folder for your bot. We will be creating 2 files. index.js + config.json

In order to communicate with the Discord we will be using a library called discord.js. You can install it with the following command: npm i discord.js

Code

index.js
//import modules
const Discord = require('discord.js');
const config = require('./config.json');
//initialize client
const client = new Discord.Client();
//ready event
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
client.user.setActivity(`${config.prefix}help`, {type: 'PLAYING'})
});
//message event
client.on('message', message => {
//to reduce code
var cmd = message.content.slice(prefix.length);
if (cmd === 'ping') {
message.channel.send(`Pong! \`${Math.floor(client.ping)}ms\``);
} else if (cmd ==='help') {
//create new embed using this constructor
helpEmbed = new Discord.RichEmbed()
helpEmbed
.setDescription('Help has arrived!');
message.channel.send(helpEmbed);
} else if (cmd === 'reboot') {
if (message.author.id !== config.ownerId) return;
message.channel.send('Rebooting...');
setTimeout(() => {
process.exit();
}, 1000);
};
});
//token is hidden in config.json
client.login(config.token);

The credentials in config.json are for example only. Please replace them with your own.

config.json
{
"prefix": "$",
"ownerId": "123456789012345678",
"token": "iafpiq3n8vi90navrnqwvrv21i.asdasdi3asdsgddag"
}

Beware that revealing your token to anyone allows them to full access to your bot.

Run

In order to run the bot use command: node index.js

Links

Here are some links that I personally find helpful with coding discord bots: