How JavaScript works

Discord bots are mostly written in JavaScript. Everything you need to know to write a bot rests on a few ideas: values, functions, objects, events and waiting.

Documentation / Learn to write a bot / How JavaScript works

  1. Values go into boxes

    You give a value a name with const: const name = "Aegis".

  2. Functions do work

    A function takes input, does something and returns a result.

  3. The bot listens to events

    When someone uses a command, Discord sends an event and your function runs.

JavaScript is a language that is read line by line, from top to bottom. A Discord bot is really a JavaScript program that stays running on your computer or on a server. Node.js runs that program outside the browser; discord.js is a library that makes talking to Discord easier. In this lesson you will learn enough JavaScript to read the code.

Values and variables

Everything in a program is a value: text, numbers, true/false. You use const to give a value a name. If it will change later, you use let.

degerler.jsjavascript
const botName = "Aegis";        // text (string)
const memberCount = 425;        // number
const protectionOn = true;      // true/false (boolean)

let warnings = 0;               // let: the value can change later
warnings = warnings + 1;

console.log(botName, memberCount, protectionOn, warnings);
// Prints: Aegis 425 true 1

console.log prints text to the terminal; it is the easiest way to see what your code does.

  • Lines that start with // are comments; the computer does not read them. Use them to leave notes for yourself.

Functions

A function packs up a piece of work so you can run it whenever you want. What goes inside the parentheses is the input; return gives the result back.

fonksiyon.jsjavascript
function greet(name) {
  return "Hello, " + name + "!";
}

// The short way to write the same thing (arrow function):
const greet2 = (name) => `Hello, ${name}!`;

console.log(greet("Deniz"));   // Hello, Deniz!
console.log(greet2("Mert"));   // Hello, Mert!

Inside backticks (`) you can put a value into the text by writing ${...}.

Objects and arrays

An object keeps related values together and is read with a dot. An array is an ordered list. Everything in discord.js (members, messages, channels) is an object.

nesne.jsjavascript
const member = {
  username: "deniz_dev",
  roles: ["Member", "Staff"],   // array
  bot: false,
};

console.log(member.username);         // deniz_dev
console.log(member.roles[0]);         // Member (counting starts at 0)
console.log(member.roles.length);     // 2
console.log(member.roles.includes("Staff")); // true

Conditions

With if you say "if this is true, do that". === checks whether two values are the same; ! flips something to its opposite.

kosul.jsjavascript
const message = "discord.gg/free-nitro";

if (message.includes("discord.gg/")) {
  console.log("There is an invite link, delete the message.");
} else if (message.length > 2000) {
  console.log("The message is too long.");
} else {
  console.log("All good.");
}

Events

A bot does nothing on its own; it waits for something to happen. When you write client.on("event", function) you are saying "when this event happens, run this function". This function is called a callback.

olay.jsjavascript
const { Client, Events, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// Runs once when the bot connects to Discord
client.once(Events.ClientReady, (c) => {
  console.log(`${c.user.tag} is online!`);
});

// Runs every time someone uses a slash command
client.on(Events.InteractionCreate, (interaction) => {
  console.log("A command came in:", interaction.commandName);
});

once runs only the first time; on runs every time.

Waiting: async and await

Sending a message to Discord goes over the internet and takes a little time. Work like this returns a Promise. To wait for the result, you write async before the function and await before the work you are waiting for.

bekle.jsjavascript
client.on(Events.InteractionCreate, async (interaction) => {
  // await: wait until Discord replies, then continue
  await interaction.reply("One second...");
  await interaction.editReply("Done, ready!");
});

await can only be used inside an async function.

  • If something goes wrong, await throws an error. You can catch it with try { ... } catch (error) { ... } so the bot does not crash.

All together: an example command

Now let's put what you learned together. When the /dice command comes in, this code rolls a random number from 1 to 6. You can now read every line.

zar.jsjavascript
client.on(Events.InteractionCreate, async (interaction) => {
  // If it is not a slash command (e.g. a button), do nothing
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === "dice") {
    const number = Math.floor(Math.random() * 6) + 1; // 1-6
    await interaction.reply(`Dice: **${number}**`);
  }
});

Math.random() gives a number between 0 and 1; multiply by 6, round down and add 1, and you get 1-6.

In the next lesson we will turn this code into a real bot.