Section titled Event handlingEvent 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 Client documentation to see the full list of events.
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.
At this point, your index.js
file has code for loading commands, and listeners for two events: ClientReady
and InteractionCreate
.
Currently, all of this code is in the index.js
file. Client#ready emits once when the Client
becomes ready for use, and Client#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.
Section titled Individual event filesIndividual event files
Your project directory should look something like this:
_10discord-bot/_10├── commands/_10├── node_modules/_10├── config.json_10├── deploy-commands.js_10├── index.js_10├── package-lock.json_10└── 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.
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.
Section titled Reading event filesReading 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. 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']
.
_22import { readdir } from 'node:fs/promises';_22import { join } from 'node:path';_22import { fileURLToPath } from 'node:url';_22import { Client, GatewayIntentBits } from 'discord.js';_22import config from './config.json' assert { type: 'json' };_22_22const client = new Client({ intents: [GatewayIntentBits.Guilds] });_22_22const eventsPath = fileURLToPath(new URL('events', import.meta.url));_22const eventFiles = await readdir(eventsPath).then((files) => files.filter((file) => file.endsWith('.js')));_22_22for (const file of eventFiles) {_22 const filePath = join(eventsPath, file);_22 const event = await import(filePath);_22 if (event.data.once) {_22 client.once(event.data.name, (...args) => event.execute(...args));_22 } else {_22 client.on(event.data.name, (...args) => event.execute(...args));_22 }_22}_22_22client.login(config.token);
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 Client class in discord.js extends the EventEmitter
class. Therefore, the client
object exposes the .on()
and .once()
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, then calls event.execute()
while passing in the args
array using the ...
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.
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.