Getting Started

This chapter assumes you’re in the Getting Started chapter and your bot code devloping is about to start. 

Also, I have to say that “if you don’t understand the code you’re about to see, coding a bot might not be for you. Go to CodeAcademy and learn Javascript”!

const Discord = require("discord.js");
const client = new Discord.Client();
client.login(process.env.TOKEN);

client.on("ready", () => {
console.log("I am ready!");
});

client.on("message", (message)=> {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});

Introduction Events

Before we dive into any further coding, we need to first understand what an Event is.
This is an event:

client.on("message", (message)=> {
  
// This code runs when the event is triggered
});

This is, specifically, an event in discord.js but it’s similar to how other APIs handle events. This event triggers every time the bot sees a new message. This includes every channel the bot has access to as well as any direct or private message it receives. If someone sends 5 messages on a channel, this event fires 5 times.

Why is this important? Well, if you intend to use your bot on a large server, or if you want it to be on multiple servers, this becomes a large number of events triggering at every moment. I don’t want to go into too much optimization talk, but for a single point “use a single event function for each event”.

Discord.js contains a large number of events that can trigger under certain situations. For instance, the ready event triggers when the bot comes online. The guildMemberAdd event triggers when a new user joins a server shared with the bot. We will learn about these later and in detail.

Adding Commands

One of the first useful things you might want to learn is how to add a command to your bot. While there are better ways than what I’m about to show you, for the time being this will be enough.

Note: You have to add all your commands only in the message event.

if(message.content === "hello"){
message.channel.send('Hi!');
}

First, let me tell what this does.
First line check if content of message equals hello or not, if not then it will stop processing, if yes then it will send message Hi!(in the channel the message was sent).

And now your first bot is ready, and now we will understand everything in next chapters.