AdolfJames Urian
AdolfJames Urian

Reputation: 95

How to organize commands in Discord.js

I am trying to organize my commands in my bot, I have a folder commands and inside are my commands, however, I want it to be more organized like inside commands there are moderators, fun, global like:

commands >
  moderators >
    ./{all commands that involve moderator}.js
  fun >
    ./{all commands that is fun}.js
  global >
    ./{all commands for everyone}.js

main.js

and main.js outside the commands folder because its the one that will call the codes inside commands folder. Is there a way to do this??

Upvotes: 0

Views: 433

Answers (1)

nouvist
nouvist

Reputation: 1182

I uses this method.

Write middlewares like this.

export default async (msg, prefix, bot) => {
  if (msg.content == prefix + "ping") {
    await msg.channel.send("pong!")
    return true;
    // return true means for loop should stop
    // because the message already responded
    // check main js for more
  }
};

Create an middleware loader

import * as fs from "fs";

const mwLoader = (dir) =>
  fs
    .readdirSync(path.join(__dirname, dir))
    .filter((val) => val.endsWith(".js"))
    .map((val) => val.substr(0, val.length - 3))
    .map((val) => require(path.join(__dirname, dir, val))["default"]);

And then on the main javascript

const bot = new discord.Client();

const mwMod = mwLoader("./commands/moderator");
const mwFun = mwLoader("./commands/fun");
const mwGlobal = mwLoader("./commands/global");

bot.on("message", async (msg) => {
  if (!msg.guild) return;
  if (msg.author.bot) return;
  if (he is mod)
    for (let i of mwMod) {
      const m = await i(msg, ".", bot);
      if (m === true) break;
    }
  for (let i of mwFun) {
    const m = await i(msg, ".", bot);
    if (m === true) break;
  }
  for (let i of mwGlobal) {
    const m = await i(msg, ".", bot);
    if (m === true) break;
  }
});

Upvotes: 1

Related Questions