Build A Discord Bot
Building a discord bot can be a cool way to extend the functionality of a discord server. It can welcome a new member, etc amongst a host of others. it is a cool way to automate tasks as an owner of a discord server. The discord bot will be built with discord.js. A node module for interacting with the Discord API.
PREREQUISITE
To Build the discord bot with Discord.js, ensure that node and npm are installed by typing the following command in the terminal.
node -v && npm -v
This should output into the console
v12.8.1
6.14.4
Other than that install node here and npm here.
PROJECT SETUP
From the terminal, create a directory and open the directory
mkdir discordbot && cd discordbot
Create package.json to keep track of dependencies with:
npm init -y
Install discord.js
npm install discord.js
BOT SETUP
- Navigate to the developer portal: here
- Click on the button ‘New Application’ a modal will pop up
- Enter a name for the bot and click on the create button.
- On the sidebar beneath the OAuth2, select the Bot
- Click on the button to copy the token
- Add the bot to a server with the invite link
https://discord.com/oauth2/authorize?client_id=<clientId>&scope=bot
7. Copy the discord bot’s client Id from the developer portal and replace it in the link. Navigate to the link, choose a preferred server and BINGO!!!!!!
BUILDING THE BOT
In the folder discordbot, create a file called .env in the terminal run the command below to install dotenv
npm install dotenv
In the .env file add the token you copied for the bot
.env file
TOKEN=kahjEQKNRKQ-0E0kdhuiPIS98-19U9U84Q
Create a file called index.js and create commands for the discord bot as well as responses.
const dotenv = require('dotenv');
dotenv.config();
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Yay I am ready with a bang!');
});client.on('message', message => {
if (message.content === 'Heya friend') {
//respond to the message
message.channel.send('Hello good friend!');
}
});
client.login(process.env.TOKEN);
To run the code, in the terminal run
node index.js
This code above, creates a new discord client. Once the client is ready, it logs the message, “Yay, I am ready with a bang!” to the terminal.
To test the bot, in the terminal where the bot was installed, type the message “Heya friend”. The bot will respond with “Hello good friend”.
For more documentation on creating a discord bot, Check it out in the discord.js documentation.