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>
BIN
apps/guide/public/assets/after-sorting.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
apps/guide/public/assets/before-sorting.png
Normal file
After Width: | Height: | Size: 8.8 KiB |
BIN
apps/guide/public/assets/bot-auth-page.png
Normal file
After Width: | Height: | Size: 39 KiB |
BIN
apps/guide/public/assets/bot-authorized.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
apps/guide/public/assets/bot-in-memberlist.png
Normal file
After Width: | Height: | Size: 6.6 KiB |
BIN
apps/guide/public/assets/bot-user.png
Normal file
After Width: | Height: | Size: 75 KiB |
BIN
apps/guide/public/assets/create-app.png
Normal file
After Width: | Height: | Size: 64 KiB |
|
@ -1,231 +0,0 @@
|
|||
---
|
||||
title: Initial files
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Initial files
|
||||
|
||||
Once you [add your bot to a server](preparations/adding-your-bot-to-servers.md), the next step is to start coding and get it online! Let's start by initializing your package.json, creating a config file for your client token, and a main file for your bot application.
|
||||
|
||||
## Creating package.json
|
||||
|
||||
This command creates a _`package.json`_ file for you, which will keep track of the dependencies your project uses, as well as other information.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```sh npm
|
||||
npm init -y; npm pkg set type="module"
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn add dotenv
|
||||
# You must go into your package.json file and add "type": "module"
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm init; pnpm pkg set type="module"
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
Once you're done with that, onto the next step!
|
||||
|
||||
## Using config.json
|
||||
|
||||
As explained in the ["What is a token, anyway?"](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.
|
||||
|
||||
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.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```json config.json
|
||||
{
|
||||
"token": "your-token-goes-here"
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
You can then access your token inside other files by using _`import`_.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```ts
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
console.log(config.token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Caution" type="danger">
|
||||
If you're using Git, you should not commit this file and should [ignore it via
|
||||
_`.gitignore`_](/creating-your-bot/#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>
|
||||
|
||||
```shellscript Command line
|
||||
A=123 B=456 DISCORD_TOKEN=your-token-goes-here node index.js
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```js Usage
|
||||
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, preload the package to load your _`.env`_ file and attach the variables to _`process.env`_:
|
||||
|
||||
##### Installing dotenv
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```sh npm
|
||||
npm install dotenv
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn add dotenv
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm add dotenv
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
##### Defining your variables
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```text .env
|
||||
A=123
|
||||
B=456
|
||||
DISCORD_TOKEN=your-token-goes-here
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Caution" type="danger">
|
||||
If you're using Git, you should not commit this file and should [ignore it via
|
||||
_`.gitignore`_](/creating-your-bot/#git-and-gitignore).
|
||||
</Alert>
|
||||
|
||||
##### Utilizing your variables
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```sh node
|
||||
node --require dotenv/config yourFile.js
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn node --require dotenv/config yourFile.js
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```ts yourFile
|
||||
console.log(process.env.A); // 123
|
||||
console.log(process.env.B); // 456
|
||||
console.log(process.env.DISCORD_TOKEN); // your-token-goes-here
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Section title="Online editors (Glitch, Heroku, Replit, etc.)" defaultClosed padded background gutter>
|
||||
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)
|
||||
|
||||
</Section>
|
||||
|
||||
### 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:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```
|
||||
node_modules
|
||||
.env
|
||||
config.json
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<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>
|
||||
|
||||
## Creating the main file
|
||||
|
||||
Open your code editor and create a new file. We suggest that you save the file as _`index.ts`_, or _`index.js`_, depending on whether you use TypeScript. You may name it whatever you wish, however.
|
||||
|
||||
Here's the base code to get you started:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```ts index.ts
|
||||
// Import the necessary structures.
|
||||
import { Client, Events, GatewayIntentBits } from 'discord.js';
|
||||
import config from './config.json';
|
||||
|
||||
// Create a new client instance.
|
||||
const client = new Client({ intents: GatewayIntentBits.Guilds });
|
||||
|
||||
// When the client is ready, run this code (only once).
|
||||
client.once(Events.ClientReady, () => {
|
||||
console.log('Ready!');
|
||||
});
|
||||
|
||||
// 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 login to Discord. The _`GatewayIntentBits.Guilds`_ intents option is necessary for your client to work properly, as it ensures that the caches for guilds, channels and roles are populated and available for internal use.
|
||||
|
||||
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).
|
||||
|
||||
Open your terminal, compile your code (JavaScript users do not do this), and run _`node index.js`_ to start the process. If you see "Ready!" after a few seconds, you're good to go!
|
||||
|
||||
<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 <kbd>⌃ Control</kbd>{' '}
|
||||
<kbd>C</kbd>, you can press <kbd>↑</kbd> on your keyboard to bring up the latest commands you've run. Pressing{' '}
|
||||
<kbd>↑</kbd> then <kbd>⏎ Enter</kbd> after closing the process is a quick way to start it up again.
|
||||
</Alert>
|
||||
|
||||
## Resulting code
|
||||
|
||||
<ResultingCode path="creating-your-bot/initial-files" />
|
||||
|
||||
Code is indeed a result of code. That being said, it's being worked on. With code. Definitely.
|
|
@ -1,246 +0,0 @@
|
|||
---
|
||||
title: Creating commands
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Creating commands
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
This page is a follow-up and bases its code on [the previous page](/creating-your-bot/).
|
||||
</Alert>
|
||||
|
||||
<DiscordMessages rounded>
|
||||
<DiscordMessage
|
||||
interaction={{
|
||||
author: {
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
},
|
||||
command: 'ping',
|
||||
}}
|
||||
author={{
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
time: 'Today at 21:00',
|
||||
}}
|
||||
>
|
||||
Pong!
|
||||
</DiscordMessage>
|
||||
</DiscordMessages>
|
||||
|
||||
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. Before being able to reply to a command, you must first register it.
|
||||
|
||||
## Registering commands
|
||||
|
||||
This section will cover only the bare minimum to get you started, but you can refer to our [in-depth page on registering slash commands](/interactions/slash-commands.md#registering-slash-commands) for further details. It covers guild commands, global commands, options, option types, and choices.
|
||||
|
||||
### Command deployment script
|
||||
|
||||
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.
|
||||
|
||||
Since commands only need to be registered once, and updated when the definition (description, options etc) is changed, it's not necessary to connect a whole client to the gateway or do this on every _`ready`_ event. As such, a standalone script using the lighter REST manager is preferred.
|
||||
|
||||
Below is a deployment script you can use. Focus on these variables:
|
||||
|
||||
- _`clientId`_: Your application's client id
|
||||
- _`guildId`_: Your development server's id
|
||||
- _`commands`_: An array of commands to register. The [slash command builder](/popular-topics/builders.md#slash-command-builders) from _`discord.js`_ is used to build the data for your commands
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
In order to get your application's client id, go to [Discord Developer
|
||||
Portal](https://discord.com/developers/applications) and choose your application. Find the id under "Application ID"
|
||||
in General Information subpage. To get guild id, open Discord and go to your settings. On the "Advanced" page, turn on
|
||||
"Developer Mode". This will enable a "Copy ID" button in the context menu when you right-click on a server icon, a
|
||||
user's profile, etc.
|
||||
</Alert>
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js deploy-commands.js mark=4,6:10
|
||||
const { REST, SlashCommandBuilder, Routes } = require('discord.js');
|
||||
const { clientId, guildId, token } = require('./config.json');
|
||||
|
||||
const commands = [
|
||||
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
|
||||
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
|
||||
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
|
||||
].map((command) => command.toJSON());
|
||||
|
||||
const rest = new REST({ version: '10' }).setToken(token);
|
||||
|
||||
rest
|
||||
.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
|
||||
.then((data) => console.log(`Successfully registered ${data.length} application commands.`))
|
||||
.catch(console.error);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```json config.json mark=2:3
|
||||
{
|
||||
"clientId": "123456789012345678",
|
||||
"guildId": "876543210987654321",
|
||||
"token": "your-token-goes-here"
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
Once you fill in these values, run _`node deploy-commands.js`_ in your project directory to register your commands to a single guild. It's also possible to [register commands globally](/interactions/slash-commands.md#global-commands).
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
You only need to run `node deploy-commands.js` once. You should only run it again if you add or edit existing
|
||||
commands.
|
||||
</Alert>
|
||||
|
||||
## Replying to commands
|
||||
|
||||
Once you've registered your commands, you can listen for interactions via <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> in your _`index.js`_ file.
|
||||
|
||||
You should first check if an interaction is a chat input command via <DocsLink type="class" parent="BaseInteraction" symbol="isChatInputCommand" brackets>_`.isChatInputCommand()`_</DocsLink>, and then check the <DocsLink type="class" parent="CommandInteraction" symbol="commandName">_`.commandName`_</DocsLink> property to know which command it is. You can respond to interactions with <DocsLink type="class" parent="CommandInteraction" symbol="reply" brackets>_`.reply()`_</DocsLink>.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js mark=5:16
|
||||
client.once('ready', () => {
|
||||
console.log('Ready!');
|
||||
});
|
||||
|
||||
client.on('interactionCreate', async (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
const { commandName } = interaction;
|
||||
if (commandName === 'ping') {
|
||||
await interaction.reply('Pong!');
|
||||
} else if (commandName === 'server') {
|
||||
await interaction.reply('Server info.');
|
||||
} else if (commandName === 'user') {
|
||||
await interaction.reply('User info.');
|
||||
}
|
||||
});
|
||||
client.login(token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
### Server info command
|
||||
|
||||
Note that servers are referred to as "guilds" in the Discord API and discord.js library. _`interaction.guild`_ refers to the guild the interaction was sent in (a <DocsLink type="class" parent="Guild" /> instance), which exposes properties such as _`.name`_ or _`.memberCount`_.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js focus=7
|
||||
client.on('interactionCreate', async (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
const { commandName } = interaction;
|
||||
if (commandName === 'ping') {
|
||||
await interaction.reply('Pong!');
|
||||
} else if (commandName === 'server') {
|
||||
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
|
||||
} else if (commandName === 'user') {
|
||||
await interaction.reply('User info.');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<DiscordMessages rounded>
|
||||
<DiscordMessage
|
||||
interaction={{
|
||||
author: {
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
},
|
||||
command: 'server',
|
||||
}}
|
||||
author={{
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
time: 'Today at 21:00',
|
||||
}}
|
||||
>
|
||||
<p>Server name: discord.js Guide</p>
|
||||
<p>Total members: 2</p>
|
||||
</DiscordMessage>
|
||||
</DiscordMessages>
|
||||
|
||||
You could also display the date the server was created, or the server's verification level. You would do those in the same manner – use _`interaction.guild.createdAt`_ or _`interaction.guild.verificationLevel`_, respectively.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
Refer to the <DocsLink type="class" parent="Guild" /> documentation for a list of all the available properties and
|
||||
methods!
|
||||
</Alert>
|
||||
|
||||
### User info command
|
||||
|
||||
A "user" refers to a Discord user. _`interaction.user`_ refers to the user the interaction was sent by (a <DocsLink type="class" parent="User" /> instance), which exposes properties such as _`.tag`_ or _`.id`_.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js focus=9
|
||||
client.on('interactionCreate', async (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
const { commandName } = interaction;
|
||||
if (commandName === 'ping') {
|
||||
await interaction.reply('Pong!');
|
||||
} else if (commandName === 'server') {
|
||||
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
|
||||
} else if (commandName === 'user') {
|
||||
await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<DiscordMessages rounded>
|
||||
<DiscordMessage
|
||||
interaction={{
|
||||
author: {
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
},
|
||||
command: 'user',
|
||||
}}
|
||||
author={{
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
time: 'Today at 21:00',
|
||||
}}
|
||||
>
|
||||
<p>Your tag: User#0001</p>
|
||||
<p>Your id: 123456789012345678</p>
|
||||
</DiscordMessage>
|
||||
</DiscordMessages>
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
Refer to the <DocsLink type="class" parent="User" /> documentation for a list of all the available properties and
|
||||
methods!
|
||||
</Alert>
|
||||
|
||||
And there you have it!
|
||||
|
||||
## The problem with if/else if
|
||||
|
||||
If you don't plan on making more than a couple commands, then using an _`if`_/_`else if`_ chain is fine; however, this isn't always the case. Using a giant _`if`_/_`else if`_ chain will only hinder your development process in the long run.
|
||||
|
||||
Here's a small list of reasons why you shouldn't do so:
|
||||
|
||||
- Takes longer to find a piece of code you want;
|
||||
- Easier to fall victim to [spaghetti code](https://en.wikipedia.org/wiki/Spaghetti_code);
|
||||
- Difficult to maintain as it grows;
|
||||
- Difficult to debug;
|
||||
- Difficult to organize;
|
||||
- General bad practice.
|
||||
|
||||
Next, we'll be diving into something called a "command handler" – code that makes handling commands easier and much more efficient. This allows you to move your commands into individual files.
|
||||
|
||||
## Resulting code
|
||||
|
||||
<ResultingCode />
|
|
@ -0,0 +1,102 @@
|
|||
---
|
||||
title: Installing Node.js and discord.js
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Installing Node.js and discord.js
|
||||
|
||||
## Installing Node.js
|
||||
|
||||
To use discord.js, you'll need to install [Node.js](https://nodejs.org/). discord.js v14 requires Node v16.9.0 or higher.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
To check if you already have Node installed on your machine \(e.g., if you're using a VPS\), run _`node -v`_ in your
|
||||
terminal. If it outputs _`v16.9.0`_ or higher, then you're good to go! Otherwise, continue reading.
|
||||
</Alert>
|
||||
|
||||
On Windows, it's as simple as installing any other program. Download the latest version from [the Node.js website](https://nodejs.org/), open the downloaded file, and follow the steps from the installer.
|
||||
|
||||
On macOS, either:
|
||||
|
||||
- Download the latest version from [the Node.js website](https://nodejs.org/), open the package installer, and follow the instructions
|
||||
- Use a package manager like [Homebrew](https://brew.sh/) with the command _`brew install node`_
|
||||
|
||||
On Linux, you can consult [this page](https://nodejs.org/en/download/package-manager/) to determine how you should install Node. Native package managers often default to outdated versions of Node, so make sure you follow the recommended approach for your chosen Linux distribution carefully.
|
||||
|
||||
## Preparing the essentials
|
||||
|
||||
To use discord.js, you'll need to install it via npm \(Node's package manager\). npm comes with every Node installation, so you don't have to worry about installing that. However, before you install anything, you should set up a new project folder.
|
||||
|
||||
Navigate to a suitable place on your machine and create a new folder named _`discord-bot`_ (or whatever you want). Next you'll need to open your terminal.
|
||||
|
||||
### Opening the terminal
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
If you use [Visual Studio Code](https://code.visualstudio.com/), you can press <kbd>Ctrl + `</kbd> (backtick) to open
|
||||
its integrated terminal.
|
||||
</Alert>
|
||||
|
||||
On Windows, either:
|
||||
|
||||
- <kbd>Shift + Right-click</kbd> inside your project directory and choose the "Open command window here" option
|
||||
- Press <kbd>Win + R</kbd> and run _`cmd.exe`_, and then _`cd`_ into your project directory
|
||||
|
||||
On macOS, either:
|
||||
|
||||
- Open Launchpad or Spotlight and search for "Terminal"
|
||||
- In your "Applications" folder, under "Utilities", open the Terminal app
|
||||
|
||||
On Linux, you can quickly open the terminal with <kbd>Ctrl + Alt + T</kbd>.
|
||||
|
||||
With the terminal open, run the _`node -v`_ command to make sure you've successfully installed Node.js. If it outputs _`v16.9.0`_ or higher, great!
|
||||
|
||||
### Initiating a project folder
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```sh npm
|
||||
npm init; npm pkg set type="module"
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn init
|
||||
# You must go into your package.json file and add "type": "module"
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm init; pnpm pkg set type="module"
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
This is the next command you'll be running. This command creates a _`package.json`_ file for you, which will keep track of the dependencies your project uses, as well as other info.
|
||||
|
||||
This command will ask you a sequence of questions–you should fill them out as you see fit. If you're not sure of something or want to skip it as a whole, leave it blank and press enter. Setting the package type as _`module`_ tells Node that you'll be writing this project using ESM \(ECMAScript modules\), supporting the latest JavaScript syntax and features.
|
||||
|
||||
Once you're done with that, you're ready to install discord.js!
|
||||
|
||||
## Installing discord.js
|
||||
|
||||
Now that you've installed Node.js and know how to open your console and run commands, you can finally install discord.js! Run the following command in your terminal:
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```sh npm
|
||||
npm install discord.js
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn add discord.js
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm add discord.js
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
And that's it! With all the necessities installed, you're almost ready to start coding your bot.
|
||||
|
||||
## Installing a linter
|
||||
|
||||
While you are coding, it's possible to run into numerous syntax errors or code in an inconsistent style. You should [install a linter](./setting-up-a-linter) to ease these troubles. While code editors generally can point out syntax errors, linters coerce your code into a specific style as defined by the configuration. While this is not required, it is advised.
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
title: Setting up a linter
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
TODO: Rewrite. Placeholder page for ordering.
|
|
@ -0,0 +1,61 @@
|
|||
---
|
||||
title: Setting up a bot application
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Setting up a bot application
|
||||
|
||||
## Creating your bot
|
||||
|
||||
Now that you've installed Node, discord.js, and hopefully a linter, you're almost ready to start coding! The next step you need to take is setting up an actual Discord bot application via Discord's website.
|
||||
|
||||
It's effortless to create one. The steps you need to take are as follows:
|
||||
|
||||
1. Open the [Discord developer portal](https://discord.com/developers/applications) and log into your account.
|
||||
2. Click on the "New Application" button.
|
||||
3. Enter a name and confirm the pop-up window by clicking the "Create" button.
|
||||
|
||||
You should see a page like this:
|
||||
|
||||
![Successfully created application](/assets/create-app.png)
|
||||
|
||||
You can edit your application's name, description, and avatar here. Once you've saved your changes, move on by selecting the "Bot" tab in the left pane.
|
||||
|
||||
## Your bot's token
|
||||
|
||||
<Alert title="Important" type="danger">
|
||||
This section is critical, so pay close attention. It explains what your bot token is, as well as the security aspects
|
||||
of it.
|
||||
</Alert>
|
||||
|
||||
On the bot tab, you'll see a section like this:
|
||||
|
||||
![Bot application](/assets/bot-user.png)
|
||||
|
||||
In this panel, you can give your bot a snazzy avatar, set its username, and make it public or private. Your bot's token will be revealed when you press the "Reset Token" button and confirm. When we ask you to paste your bot's token somewhere, this is the value that you need to put in. If you happen to lose your bot's token at some point, you need to come back to this page and reset your bot's token again which will reveal the new token, invalidating all old ones.
|
||||
|
||||
### What is a token, anyway?
|
||||
|
||||
A token is essentially your bot's password; it's what your bot uses to login to Discord. With that said, **it is vital that you do not ever share this token with anybody, purposely or accidentally**. If someone does manage to get a hold of your bot's token, they can use your bot as if it were theirs—this means they can perform malicious acts with it.
|
||||
|
||||
Tokens look like this: _`NzkyNzE1NDU0MTk2MDg4ODQy.X-hvzA.Ovy4MCQywSkoMRRclStW4xAYK7I`_ (don't worry, we immediately reset this token before even posting it here!). If it's any shorter and looks more like this: _`kxbsDRU5UfAaiO7ar9GFMHSlmTwYaIYn`_, you copied your client secret instead. Make sure to copy the token if you want your bot to work!
|
||||
|
||||
### Token leak scenario
|
||||
|
||||
Let's imagine that you have a bot on over 1,000 servers, and it took you many, many months of coding and patience to get it on that amount. Your bot's token gets leaked somewhere, and now someone else has it. That person can:
|
||||
|
||||
- Spam every server your bot is on;
|
||||
- DM spam as many users as possible;
|
||||
- Delete as many channels as possible;
|
||||
- Kick or ban as many server members as possible;
|
||||
- Make your bot leave all of the servers it has joined;
|
||||
|
||||
All that and much, much more. Sounds pretty terrible, right? So make sure to keep your bot's token as safe as possible!
|
||||
|
||||
In the [configuration files](../creating-your-bot/configuration-files) page of the guide, we cover how to safely store your bot's token in a configuration file.
|
||||
|
||||
<Alert title="Compromised tokens" type="danger">
|
||||
If your bot token has been compromised by committing it to a public repository, posting it in discord.js support etc.
|
||||
or otherwise see your bot's token in danger, return to this page and press "Reset Token". This will invalidate all old
|
||||
tokens belonging to your bot. Keep in mind that you will need to update your bot's token where you used it before.
|
||||
</Alert>
|
|
@ -0,0 +1,52 @@
|
|||
---
|
||||
title: Adding your bot to servers
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Adding your bot to servers
|
||||
|
||||
After you [set up a bot application](./setting-up-a-bot-application), you'll notice that it's not in any servers yet. So how does that work?
|
||||
|
||||
Before you're able to see your bot in your own (or other) servers, you'll need to add it by creating and using a unique invite link using your bot application's client id.
|
||||
|
||||
## Bot invite links
|
||||
|
||||
The basic version of one such link looks like this:
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```
|
||||
https://discord.com/api/oauth2/authorize?client_id=123456789012345678&permissions=0&scope=bot%20applications.commands
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
The structure of the URL is quite simple:
|
||||
|
||||
- _`https://discord.com/api/oauth2/authorize`_ is Discord's standard structure for authorizing an OAuth2 application (such as your bot application) for entry to a Discord server.
|
||||
- _`client_id=...`_ is to specify _which_ application you want to authorize. You'll need to replace this part with your client's id to create a valid invite link.
|
||||
- _`permissions=...`_ describes the permissions that your bot will request to be granted by default upon joining the server you are adding it to.
|
||||
- _`scope=bot%20applications.commands`_ specifies that you want to add this application as a Discord bot, with the ability to create slash commands.
|
||||
|
||||
<Alert title="Warning" type="warning">
|
||||
If you get an error message saying "Bot requires a code grant", head over to your application's settings and disable
|
||||
the "Require OAuth2 Code Grant" option. You shouldn't enable this option unless you know why you need to.
|
||||
</Alert>
|
||||
|
||||
## Creating and using your invite link
|
||||
|
||||
To create an invite link, head back to the [My Apps](https://discord.com/developers/applications/me) page under the "Applications" section, click on your bot application, and open the OAuth2 page.
|
||||
|
||||
In the sidebar, you'll find the OAuth2 URL generator. Select the _`bot`_ and _`applications.commands`_ options. Once you select the _`bot`_ option, a list of permissions will appear, allowing you to configure the permissions your bot needs.
|
||||
|
||||
Grab the link via the "Copy" button and enter it in your browser. You should see something like this (with your bot's username and avatar):
|
||||
|
||||
![Bot Authorization page](/assets/bot-auth-page.png)
|
||||
|
||||
Choose the server you want to add it to and click "Authorize". Do note that you'll need the "Manage Server" permission on a server to add your bot there. This should then present you a nice confirmation message:
|
||||
|
||||
![Bot authorized](/assets/bot-authorized.png)
|
||||
|
||||
Congratulations! You've successfully added your bot to your Discord server. It should show up in your server's member list somewhat like this:
|
||||
|
||||
![Bot in server's member list](/assets/bot-in-memberlist.png)
|
|
@ -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>
|
|
@ -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" />
|
|
@ -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 />
|
|
@ -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!
|
|
@ -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" />
|
|
@ -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 />
|