feat(guide): port and update lots of stuff (#9385)

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
This commit is contained in:
Ryan Munro
2023-04-28 04:58:25 +10:00
committed by GitHub
parent 36216c0e1a
commit 78fe247fc4
23 changed files with 1226 additions and 477 deletions

View File

@@ -0,0 +1,132 @@
---
title: Configuration files
category: Creating your bot
---
# Configuration files
Once you [add your bot to a server](../installations-and-preparations/adding-your-bot-to-servers), the next step is to start coding and get it online! Let's start by creating a config file to prepare the necessary values your client will need.
As explained in the ["What is a token, anyway?"](../installations-and-preparations/setting-up-a-bot-application.md#what-is-a-token-anyway) section, your token is essentially your bot's password, and you should protect it as best as possible. This can be done through a _`config.json`_ file or by using environment variables.
Open your application in the [Discord Developer Portal](https://discord.com/developers/applications) and go to the "Bot" page to copy your token.
## Using config.json
Storing data in a _`config.json`_ file is a common way of keeping your sensitive values safe. Create a _`config.json`_ file in your project directory and paste in your token. You can access your token inside other files by importing this file.
<CH.Code lineNumbers={false}>
```json config.json
{
"token": "your-token-goes-here"
}
```
```js index.js
import config from './config.json' assert { type: 'json' };
console.log(config.token);
```
</CH.Code>
<Alert title="Danger" type="danger">
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
</Alert>
## Using environment variables
Environment variables are special values for your environment (e.g., terminal session, Docker container, or environment variable file). You can pass these values into your code's scope so that you can use them.
One way to pass in environment variables is via the command line interface. When starting your app, instead of _`node index.js`_, use _`TOKEN=your-token-goes-here node index.js`_. You can repeat this pattern to expose other values as well.
You can access the set values in your code via the _`process.env`_ global variable, accessible in any file. Note that values passed this way will always be strings and that you might need to parse them to a number, if using them to do calculations.
<CH.Code lineNumbers={false} rows={3}>
```sh Shell
A=123 B=456 DISCORD_TOKEN=your-token-goes-here node index.js
```
```js index.js
console.log(process.env.A);
console.log(process.env.B);
console.log(process.env.DISCORD_TOKEN);
```
</CH.Code>
### Using dotenv
Another common approach is storing these values in a _`.env`_ file. This spares you from always copying your token into the command line. Each line in a _`.env`_ file should hold a _`KEY=value`_ pair.
You can use the [`dotenv` package](https://www.npmjs.com/package/dotenv) for this. Once installed, require and use the package to load your _`.env`_ file and attach the variables to _`process.env`_:
<CH.Code lineNumbers={false}>
```sh npm
npm install dotenv
```
```sh yarn
yarn add dotenv
```
```sh pnpm
pnpm add dotenv
```
</CH.Code>
<CH.Code lineNumbers={false} rows={7}>
```sh .env
A=123
B=456
DISCORD_TOKEN=your-token-goes-here
```
```js index.js
import { config } from 'dotenv';
config();
console.log(process.env.A);
console.log(process.env.B);
console.log(process.env.DISCORD_TOKEN);
```
</CH.Code>
<Alert title="Danger" type="danger">
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
</Alert>
<Alert title="Online editors (Glitch, Heroku, Replit, etc.)" type="info">
While we generally do not recommend using online editors as hosting solutions, but rather invest in a proper virtual private server, these services do offer ways to keep your credentials safe as well! Please see the respective service's documentation and help articles for more information on how to keep sensitive values safe:
- Glitch: [Storing secrets in .env](https://glitch.happyfox.com/kb/article/18)
- Heroku: [Configuration variables](https://devcenter.heroku.com/articles/config-vars)
- Replit: [Secrets and environment variables](https://docs.replit.com/repls/secrets-environment-variables)
</Alert>
## Git and .gitignore
Git is a fantastic tool to keep track of your code changes and allows you to upload progress to services like [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [Bitbucket](https://bitbucket.org/product). While this is super useful to share code with other developers, it also bears the risk of uploading your configuration files with sensitive values!
You can specify files that Git should ignore in its versioning systems with a*`.gitignore`* file. Create a _`.gitignore`_ file in your project directory and add the names of the files and folders you want to ignore:
```
node_modules
.env
config.json
```
<Alert title="Tip" type="success">
Aside from keeping credentials safe, _`node_modules`_ should be included here. Since this directory can be restored based on the entries in your _`package.json`_ and _`package-lock.json`_ files by running _`npm install`_, it does not need to be included in Git.
You can specify quite intricate patterns in _`.gitignore`_ files, check out the [Git documentation on `.gitignore`](https://git-scm.com/docs/gitignore) for more information!
</Alert>

View File

@@ -0,0 +1,60 @@
---
title: Creating the main file
category: Creating your bot
---
# Creating the main file
<Alert title="Tip" type="success">
This page assumes you've already prepared the [configuration files](./configuration-files) from the previous page.
We're using the _`config.json`_ approach, however feel free to substitute your own!
</Alert>
Open your code editor and create a new file. We suggest that you save the file as _`index.js`_, but you may name it whatever you wish.
Here's the base code to get you started:
<CH.Code>
```js
// Require the necessary discord.js classes
import { Client, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Log in to Discord with your client's token
client.login(config.token);
```
</CH.Code>
This is how you create a client instance for your Discord bot and log in to Discord. The _`GatewayIntentBits.Guilds`_ intents option is necessary for the discord.js client to work as you expect it to, as it ensures that the caches for guilds, channels, and roles are populated and available for internal use.
<Alert title="Tip" type="success">
The term "guild" is used by the Discord API and in discord.js to refer to a Discord server.
</Alert>
Intents also define which events Discord should send to your bot, and you may wish to enable more than just the minimum. You can read more about the other intents on the [Intents topic](../popular-topics/intents).
## Running your application
Open your terminal and run _`node index.js`_ to start the process. If you see "Ready!" after a few seconds, you're good to go! The next step is to start adding [slash commands](./adding-commands) to develop your bot's functionality.
<Alert title="Tip" type="success">
You can open your _`package.json`_ file and edit the _`"main": "index.js"`_ field to point to your main file. You can then run _`node .`_ in your terminal to start the process!
After closing the process with _`Ctrl + C`_, you can press the up arrow on your keyboard to bring up the latest commands you've run. Pressing up and then enter after closing the process is a quick way to start it up again.
</Alert>
#### Resulting code
<ResultingCode path="creating-your-bot/initial-files" />

View File

@@ -0,0 +1,147 @@
---
title: Adding commands
category: Creating your bot
---
# Creating slash commands
Discord allows developers to register [slash commands](https://discord.com/developers/docs/interactions/application-commands), which provide users a first-class way of interacting directly with your application.
Slash commands provide a huge number of benefits over manual message parsing, including:
- Integration with the Discord client interface.
- Automatic command detection and parsing of the associated options/arguments.
- Typed argument inputs for command options, e.g. "String", "User", or "Role".
- Validated or dynamic choices for command options.
- In-channel private responses (ephemeral messages).
- Pop-up form-style inputs for capturing additional information.
...and many more!
<Alert title="Read first!" type="info">
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
1. The individual command files, containing their definitions and functionality.
2. The [command handler](command-handling.html), which dynamically reads the files and executes the commands.
3. The [command deployment script](command-deployment.html), to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
On this page, you'll complete Step 1. Make sure to also complete the other pages linked above!
</Alert>
## Before you continue
Assuming you've followed the guide so far, your project directory should look something like this:
```:no-line-numbers
discord-bot/
├── node_modules
├── config.json
├── index.js
├── package-lock.json
└── package.json
```
## Individual command files
Create a new folder named _`commands`_, which is where you'll store all of your command files.
At a minimum, the definition of a slash command must have a name and a description. Slash command names must be between 1-32 characters and contain no capital letters, spaces, or symbols other than _`-`_ and _`_`_. Using the builder, a simple _`ping`\_ command definition would look like this:
<CH.Code>
```js
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
```
</CH.Code>
A slash command also requires a function to run when the command is used, to respond to the interaction. Using an interaction response method confirms to Discord that your bot successfully received the interaction, and has responded to the user. Discord enforces this to ensure that all slash commands provide a good user experience (UX). Failing to respond will cause Discord to show that the command failed, even if your bot is performing other actions as a result.
The simplest way to acknowledge and respond to an interaction is the _`interaction.reply()`_ method. Other methods of replying are covered on the [Response methods](../slash-commands/response-methods) page later in this section.
<CH.Code>
```js
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
Put these two together by creating a `commands/ping.js` file for your first command. Inside this file, you're going to define and export two items.
- The `data` property, which will provide the command definition shown above for registering to Discord.
- The `execute` method, which will contain the functionality to run from our event handler when the command is used.
The _`export`_ keyword ensures these values can be imported and read by other files; namely the command loader and command deployment scripts mentioned earlier.
<CH.Code>
```js commands/ping.js
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
<Alert title="Tip" type="success">
[`module.exports`](https://nodejs.org/api/modules.html#modules_module_exports) is how you export data in Node.js so that you can [`require()`](https://nodejs.org/api/modules.html#modules_require_id) it in other files.
If you need to access your client instance from inside a command file, you can access it via `interaction.client`. If you need to access external files, packages, etc., you should `require()` them at the top of the file.
</Alert>
That's it for your basic ping command. Below are examples of two more commands we're going to build upon throughout the guide, so create two more files for these before you continue reading.
<CH.Code>
```js commands/user.js
export const data = {
name: 'user',
description: 'Provides information about the user.',
};
export async function execute(interaction) {
// interaction.user is the object representing the User who ran the command
// interaction.member is the GuildMember object, which represents the user in the specific guild
await interaction.reply(
`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`,
);
}
```
```js commands/server.js
export const data = {
name: 'server',
description: 'Provides information about the server.',
};
export async function execute(interaction) {
// interaction.guild is the object representing the Guild in which the command was run
await interaction.reply(`This server is ${interaction.guild.name} and has
${interaction.guild.memberCount} members.`);
}
```
</CH.Code>
#### Next steps
You can implement additional commands by creating additional files in the _`commands`_ folder, but these three are the ones we're going to use for the examples as we go on. For now let's move on to the code you'll need for command handling, to load the files and respond to incoming interactions.
#### Resulting code
<ResultingCode />

View File

@@ -0,0 +1,292 @@
---
title: Handling command interactions
category: Creating your bot
---
# Command handling
Unless your bot project is small, it's not a very good idea to have a single file with a giant _`if`_/_`else if`_ chain for commands. If you want to implement features into your bot and make your development process a lot less painful, you'll want to implement a command handler. Let's get started on that!
<Alert title="Read first!" type="info">
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
1. The [individual command files](slash-commands), containing their definitions and functionality.
2. The command handler, which dynamically reads the files and executes the commands.
3. The [command deployment script](command-deployment), to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
This page details how to complete **Step 2**. Make sure to also complete the other pages linked above!
</Alert>
## Loading command files
Now that your command files have been created, your bot needs to load these files on startup.
In your _`index.js`_ file, make these additions to the base template:
<CH.Code rows={14}>
```js JavaScript focus=1:3,9
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
// focus[18:28]
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = new Collection();
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
```
```ts TypeScript focus=1:3,9:14
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
// focus[18:28]
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
interface CommandModule {
data: RESTPostAPIChatInputApplicationCommandsJSONBody;
execute(interaction: ChatInputCommandInteraction): Promise<void>;
}
const commands = new Collection<string, CommandModule>();
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
```
</CH.Code>
<Alert title="Tip" type="info">
- The [`fs`](https://nodejs.org/api/fs.html) module is Node's native file system module. _`readdir`_ is used to read
the _`commands`_ directory and identify our command files. - The [`path`](https://nodejs.org/api/path.html) module is
Node's native path utility module. _`join`_ helps construct paths to access files and directories. One of the
advantages of _`path.join`_ is that it automatically detects the operating system and uses the appropriate joiners. -
The [`url`](https://nodejs.org/api/url.html) module provides utilities for URL resolution and parsing.
_`fileURLToPath`_ ensuring a cross-platform valid absolute path string.
- The{' '}
<DocsLink type="class" parent="Collection" /> class extends JavaScript's native
[_`Map`_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class, and includes
more extensive, useful functionality. _`Collection`_ is used to store and efficiently retrieve commands for execution.
</Alert>
Next, using the modules imported above, dynamically retrieve your command files with a few more additions to the _`index.js`_ file:
<CH.Code>
```js JavaScript focus=3:15
const commands = new Collection();
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
```
```ts TypeScript focus=3:15
const commands = new Collection<string, CommandModule>();
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
```
</CH.Code>
First, [url.fileURLToPath()](https://nodejs.org/api/url.html) helps to construct a path to the _`commands`_ directory. The [fs.readdir()](https://nodejs.org/api/fs.html#fspromisesreaddirpath-options) method then reads the path to the directory and returns a Promise which resolves to an array of all the file names it contains, currently _`['ping.js', 'server.js', 'user.js']`_. To ensure only command files get processed, _`Array.filter()`_ removes any non-JavaScript files from the array.
With the correct files identified, the last step is to loop over the array and dynamically set each command into the _`commands`_ Collection. For each file being loaded, check that it has at least the _`data`_ and _`execute`_ properties. This helps to prevent errors resulting from loading empty, unfinished or otherwise incorrect command files while you're still developing.
## Receiving command interactions
Every slash command is an _`interaction`_, so to respond to a command, you need to create a listener for the <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event that will execute code when your application receives an interaction. Place the code below in the _`index.js`_ file you created earlier.
<CH.Code>
```js
client.on(Events.InteractionCreate, (interaction) => {
console.log(interaction);
});
```
</CH.Code>
Not every interaction is a slash command (e.g. _`MessageComponent`_ interactions). Make sure to only handle slash commands in this function by making use of the <DocsLink type="class" parent="BaseInteraction" symbol="isChatInputCommand" brackets /> method to exit the handler if another type is encountered. This method also provides type guarding for TypeScript users, narrowing the type from _`BaseInteraction`_ to <DocsLink type="class" parent="ChatInputCommandInteraction" />.
<CH.Code>
```js focus=2
client.on(Events.InteractionCreate, (interaction) => {
if (!interaction.isChatInputCommand()) return;
console.log(interaction);
});
```
</CH.Code>
## Executing commands
When your bot receives a <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event, the interaction object contains all the information you need to dynamically retrieve and execute your commands!
Let's take a look at the _`ping`_ command again. Note the _`execute()`_ function that will reply to the interaction with "Pong!".
<CH.Code>
```js
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
First, you need to get the matching command from the _`commands`_ Collection based on the _`interaction.commandName`_. If no matching command is found, log an error to the console and ignore the event.
With the right command identified, all that's left to do is call the command's _`.execute()`_ method and pass in the _`interaction`_ variable as its argument. Note that the event listener has been made _`async`_, allowing Promises to be awaited. In case something goes wrong and the Promise rejects, catch and log any error to the console.
<CH.Code>
```js focus=4:20
// focus[37:42]
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
```
</CH.Code>
## Command categories
So far, all of your command files are in a single _`commands`_ folder. This is fine at first, but as your project grows, the number of files in the _`commands`_ folder will too. Keeping track of that many files can be a little tough. To make this a little easier, you can categorize your commands and put them in subfolders inside the _`commands`_ folder. You will have to make a few changes to your existing code in _`index.js`_ for this to work out.
If you've been following along, your project structure should look something like this:
![Project structure before sorting](/assets/before-sorting.png)
After moving your commands into subfolders, it will look something like this:
![Project structure after sorting](/assets/after-sorting.png)
<Alert title="Warning" type="warning">
Make sure you put every command file you have inside one of the new subfolders. Leaving a command file directly under
the _`commands`_ folder will create problems.
</Alert>
It is not necessary to name your subfolders exactly like we have named them here. You can create any number of subfolders and name them whatever you want. Although, it is a good practice to name them according to the type of commands stored inside them.
Back in your _`index.js`_ file, where the code to [dynamically read command files](#loading-command-files) is, use the same pattern to read the subfolder directories, and then require each command inside them.
<CH.Code>
```js JavaScript focus=3:7,19
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
```ts Typescript mark=3:7,19
const commands = new Collection<string, CommandModule>();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
</CH.Code>
That's it! When creating new files for commands, make sure you create them inside one of the subfolders (or a new one) in the _`commands`_ folder.
#### Next steps
Your command files are now loaded into your bot, and the event listener is prepared and ready to respond. In the next section, we cover the final step - a command deployment script you'll need to register your commands so they appear in the Discord client.
#### Resulting code
<ResultingCode />
It also includes some bonus commands!

View File

@@ -0,0 +1,155 @@
---
title: Registering slash commands
category: Creating your bot
---
# Registering slash commands
<Alert title="Read first!" type="info">
For fully functional slash commands, you need three important pieces of code:
1. The [individual command files](slash-commands), containing their definitions and functionality.
2. The [command handler](command-handling), which dynamically reads the files and executes the commands.
3. The command deployment script, to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
This page details how to complete **Step 3**. Make sure to also complete the other pages linked above!
</Alert>
## Command registration
Slash commands can be registered in two ways; in one specific guild, or for every guild the bot is in. We're going to look at single-guild registration first, as this is a good way to develop and test your commands before a global deployment.
Your application will need the _`applications.commands`_ scope authorized in a guild for any of its slash commands to appear, and to be able to register them in a specific guild without error.
Slash commands only need to be registered once, and updated when the definition (description, options etc) is changed. As there is a daily limit on command creations, it's not necessary nor desirable to connect a whole client to the gateway or do this on every _`ClientReady`_ event. As such, a standalone script using the lighter REST manager is preferred.
This script is intended to be run separately, only when you need to make changes to your slash command **definitions** - you're free to modify parts such as the execute function as much as you like without redeployment.
### Guild commands
Create a _`deploy-commands.js`_ file in your project directory. This file will be used to register and update the slash commands for your bot application.
Add two more properties to your _`config.json`_ file, which we'll need in the deployment script:
- _`clientId`_: Your application's client id ([Discord Developer Portal](https://discord.com/developers/applications) > "General Information" > application id)
- _`guildId`_: Your development server's id ([Enable developer mode](https://support.discord.com/hc/en-us/articles/206346498) > Right-click the server title > "Copy Server ID")
<CH.Code lineNumbers={false}>
```json
{
"token": "your-token-goes-here",
"clientId": "your-application-id-goes-here",
"guildId": "your-server-id-goes-here"
}
```
</CH.Code>
With these defined, you can use the deployment script below:
<CH.Code>
```js deploy-commands.js
import { REST, Routes } from 'discord.js';
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import config from './config.json' assert { type: 'json' };
const { clientId, guildId, token } = config;
const commands = [];
// Grab all the command files from the commands directory you created earlier
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
```
</CH.Code>
Once you fill in these values, run _`node deploy-commands.js`_ in your project directory to register your commands to the guild specified. If you see the success message, check for the commands in the server by typing _`/`_! If all goes well, you should be able to run them and see your bot's response in Discord!
### Global commands
Global application commands will be available in all the guilds your application has the _`applications.commands`_ scope authorized in, and in direct messages by default.
To deploy global commands, you can use the same script from the [guild commands](#guild-commands) section and simply adjust the route in the script to _`.applicationCommands(clientId)`_
Test
<CH.Code rows="focus">
```js focus=5
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(Routes.applicationCommands(clientId), { body: commands });
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
```
</CH.Code>
### Where to deploy
<Alert title="Tip" type="success">
Guild-based deployment of commands is best suited for development and testing in your own personal server. Once you're satisfied that it's ready, deploy the command globally to publish it to all guilds that your bot is in.
You may wish to have a separate application and token in the Discord Dev Portal for your dev application, to avoid duplication between your guild-based commands and the global deployment.
</Alert>
#### Further reading
You've successfully sent a response to a slash command! However, this is only the most basic of command event and response functionality. Much more is available to enhance the user experience including:
- applying this same dynamic, modular handling approach to events with an [Event handler](./event-handling).
- utilising the different [Response methods](../slash-commands/response-methods) that can be used for slash commands.
- expanding on these examples with additional validated option types in [Advanced command creation](../slash-commands/advanced-creation).
- adding formatted [Embeds](../popular-topics/embeds) to your responses.
- enhancing the command functionality with [Buttons](../interactions/buttons) and [Select Menus](../interactions/select-menus).
- prompting the user for more information with [Modals](../interactions/modals).
#### Resulting code
<ResultingCode path="creating-your-bot/command-deployment" />

View File

@@ -0,0 +1,219 @@
---
title: Event handling
category: Creating your bot
---
# Event handling
Node.js uses an event-driven architecture, making it possible to execute code when a specific event occurs. The discord.js library takes full advantage of this. You can visit the <DocsLink type="class" parent="Client" /> documentation to see the full list of events.
<Alert title="Tip" type="success">
This page assumes you've followed the guide up to this point, and created your _`index.js`_ and individual slash
commands according to those pages.
</Alert>
At this point, your `index.js` file has code for loading commands, and listeners for two events: `ClientReady` and `InteractionCreate`.
<CH.Code>
```js Commands
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
```js ClientReady
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
```
```js InteractionCreate
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
});
```
</CH.Code>
Currently, all of this code is in the _`index.js`_ file. <DocsLink type="class" parent="Client" symbol="e-ready" /> emits once when the _`Client`_ becomes ready for use, and <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> emits whenever an interaction is received.
Moving the event listener code into individual files is simple, and we'll be taking a similar approach to the [command handler](./handling-command-interactions).
## Individual event files
Your project directory should look something like this:
```
discord-bot/
├── commands/
├── node_modules/
├── config.json
├── deploy-commands.js
├── index.js
├── package-lock.json
└── package.json
```
Create an _`events`_ folder in the same directory. You can then move the code from your event listeners in _`index.js`_ to separate files: _`events/ready.js`_ and _`events/interactionCreate.js`_. The _`InteractionCreate`_ event is responsible for command handling, so the command loading code will move here too.
<CH.Code>
```js events/interactionCreate.js
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Collection, Events } from 'discord.js';
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
export const data = {
name: Events.InteractionCreate,
};
export async function execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
```
```js events/ready.js
import { Events } from 'discord.js';
export const data = {
name: Events.ClientReady,
once = true,
};
export async function execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
}
```
```js index.js
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.login(config.token);
```
</CH.Code>
The _`name`_ property states which event this file is for, and the _`once`_ property holds a boolean value that specifies if the event should run only once. You don't need to specify this in _`interactionCreate.js`_ as the default behavior will be to run on every event instance. The _`execute`_ function holds your event logic, which will be called by the event handler whenever the event emits.
## Reading event files
Next, let's write the code for dynamically retrieving all the event files in the _`events`_ folder. We'll be taking a similar approach to our [command handler](./handling-command-interactions). Place the new code highlighted below in your _`index.js`_.
_`fs.readdir()`_ combined with _`array.filter()`_ returns an array of all the file names in the given directory and filters for only _`.js`_ files, i.e. _`['ready.js', 'interactionCreate.js']`_.
<CH.Code>
```js focus=9:20
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = fileURLToPath(new URL('events', import.meta.url));
const eventFiles = await readdir(eventsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of eventFiles) {
const filePath = join(eventsPath, file);
const event = await import(filePath);
if (event.data.once) {
client.once(event.data.name, (...args) => event.execute(...args));
} else {
client.on(event.data.name, (...args) => event.execute(...args));
}
}
client.login(config.token);
```
</CH.Code>
You'll notice the code looks very similar to the command loading above it - read the files in the events folder and load each one individually.
The <DocsLink type="class" parent="Client" /> class in discord.js extends the [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) class. Therefore, the _`client`_ object exposes the [`.on()`](https://nodejs.org/api/events.html#events_emitter_on_eventname_listener) and [`.once()`](https://nodejs.org/api/events.html#events_emitter_once_eventname_listener) methods that you can use to register event listeners. These methods take two arguments: the event name and a callback function. These are defined in your separate event files as _`name`_ and _`execute`_.
The callback function passed takes argument(s) returned by its respective event, collects them in an _`args`_ array using the _`...`_ [rest parameter syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), then calls _`event.execute()`_ while passing in the _`args`_ array using the _`...`_ [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). They are used here because different events in discord.js have different numbers of arguments. The rest parameter collects these variable number of arguments into a single array, and the spread syntax then takes these elements and passes them to the _`execute`_ function.
After this, listening for other events is as easy as creating a new file in the _`events`_ folder. The event handler will automatically retrieve and register it whenever you restart your bot.
<Alert title="Tip" type="success">
In most cases, you can access your _`client`_ instance in other files by obtaining it from one of the other discord.js
structures, e.g. _`interaction.client`_ in the _`InteractionCreate`_ event. You do not need to manually pass it to
your events.
</Alert>
## Resulting code
<ResultingCode />