A Basic Command Handler

A Command Handler is essentially a way to separate your commands into different files, instead of having a bunch of if/else conditions inside your code (or a switch/case if you're being fancy).

In this case, the code shows you how to separate each command into its own file. This means that each command can be edited separately, and also reloaded without the need to restart your bot. Yes, really!

Want a better, updated version of this code? We're now maintaining this command handler at the community level. Guide Bot is on Github and not only can you use the code, you can also contribute if you feel proficient enough!

What you need to know

In order to correctly write and use a command handler, I would suggest you get familiar with a few things.

  • Check out Introduction to Modules for information on modules (which we'll use for each command)

  • Understand how Events work, and how each event has different arguments provided.

  • Have a good grasp of, at the very least, Commands with Arguments, which we'll be using as a base for most of our code.

Main File Changes

Because we're creating a separate file (module) for each event and each commands, our main file (app.js, or index.js, or whatever you're calling it) will change drastically from a list of commands to a simple file that loads other files.

Two main loops are needed to execute this master plan. First off, the one that will load all the events files. Each event will need to have a file in that folder, named exactly like the event itself. So for messageCreate we want ./events/messageCreate.js, for guildBanAdd we want ./events/guildBanAdd.js , etc.

// Read the Files in the Events Directory and filter files that ends with .js
const files = fs.readdirSync("./events").filter(file => file.endsWith(".js"));
// Loop over each file
for (const file of files) {
  // Split the file at its extension and get the event name
  const eventName = file.split(".")[0];
  // Require the file
  const event = require(`./events/${file}`);
    // super-secret recipe to call events with all their proper arguments *after* the `client` var.
    // without going into too many details, this means each event will be called with the client argument,
    // followed by its "normal" arguments, like message, member, etc etc.
    // This line is awesome by the way. Just sayin'.
  client.on(eventName, event.bind(null, client));
}

The second loop is going to be for the commands themselves. For a couple of reasons, we want to put the commands inside of a structure that we can refer to later - we'll use a Discord Collection:

Ok so with that being said, our main file now looks like this (how clean is that, really?):

Our first Event: Message

The messageCreate event is obviously the most important one, as it will receive all messages sent to the bot. Create the ./events/messageCreate.js file (make sure it's spelled exactly like that) and look at this bit of code:

There are more things we could do here, like get per-guild settings or check permissions before running the command, etc. Out of a desire to keep this page simple, I've avoided all that extra code, but you can still find it on the GuideBot repository!

Example commands

This would be the content of the ./commands/ping.js file, which is called with !ping (assuming ! as a prefix)

Another example would be the more complex ./commands/kick.js command, called using !kick @user

Notice the structure on the first line. exports.run is the "function name" that is exported, with 3 arguments: client (the client), message (the message variable from the handler) and args. Here, args is replaced by fancy destructuring that captures the reason (the rest of the message after the mention) in an array. See Commands with Arguments for details.

Other Events

Events are handled almost exactly in the same way, except that the number of arguments depends on which event it is. For example, the ready event:

Note that the ready event normally doesn't have any arguments, it's just (). But because we're in separate modules, it's necessary to "pass" the client variable to it or it would not be accessible. That's what our fancy bind is for in the main file!

Here's another example with the guildMemberAdd event:

Now we have client and also member which is the argument provided by the guildMemberAdd event.

BONUS: The "reload" command

Because of the way require() works in node, if you modify any of the command files in ./commands , the changes are not reflected immediately when you call that command again - because require() caches the file in memory instead of reading it every time. While this is great for efficiency, it means we need to clear that cached version if we change commands.

The Reload command does just that, simply deletes the cache so the next time that specific command is run, it'll refresh its code from the file.

Remember that all of this is just a fairly basic version of the GuideBot command handler which also has permissions, levels, per-guild configurations, and a whole lot of example commands and events! Head on over to Github to see the completed handler.

Next up is making this basic command handler better with the addition of slash commands.

Last updated