making a command handler

This guide will shows you how to make a command handler.

Command Handler Features

Command handler allows you to have more organize code files and will have some special command like advanced help command for you to use.

Actual Part

Step #1 - importing required packages

Type in the following code and import required package from npm

index.js
const Enmap = require("enmap");//npm i enmap
const fs = require("fs");//npm i fs
const Discord = require("discord.js")
const client = new Discord.Client();

Step #2 - Put codes together for index.js

After all the importing stuff and your index.js code, type in the code below

index.js
fs.readdir("./events/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    const event = require(`./events/${file}`);
    let eventName = file.split(".")[0];
    client.on(eventName, event.bind(null, client));
  });
});

client.commands = new Enmap();

fs.readdir("./commands/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    if (!file.endsWith(".js")) return;
    let props = require(`./commands/${file}`);
    let commandName = file.split(".")[0];
    console.log(`Attempting to load command ${commandName}`);
    client.commands.set(commandName, props);
  });
});

Step #3 - creating nessecary folders

After this, create two folders with name events and commands.

Step #4 - add event

In the folder events , create a file with name message.js and type in the following codes:

Step #5 - adding commands

To add a command, create a file like: {command-name}.js Here is and example of the kick command

Last updated

Was this helpful?