Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-folder command handler

I'm trying to make my command handler that allows to have files inside folders. For example, I'd have a folder named ./commands/moderation or maybe one named ./commands/fun, etc. How can I do it?

My code looks like this but it only handles JavaScript files inside my ./commands folder.

for (const file of commandFiles) {
    const command = require(`./commands/${file}`)
    client.commands.set(command.name, command)
}

// ...

if (!client.commands.has(command)) return;
try {
    client.commands.get(command).execute(message, args);
}
// ...
like image 693
Tetie Avatar asked May 21 '26 14:05

Tetie


1 Answers

At the moment, your commandFiles only contain files inside your ./commands folder. To create a folder structure like the one below, you'll also need to read content of the folders inside ./commands.

- commands
  - fun
    - game-1.js
    - game-2.js
  - moderation
    - kick.js
    - snipe.js

So, first, you read the content of the commands folder using readdirSync and for every returned folder you'll also need to grab the files where the extension is js. Check out the code below:

const client = new Discord.Client();
client.commands = new Discord.Collection();

const commandFolders = fs.readdirSync('./commands');

for (const folder of commandFolders) {
  const commandFiles = fs
    .readdirSync(`./commands/${folder}`)
    .filter((file) => file.endsWith('.js'));

  for (const file of commandFiles) {
    const command = require(`./commands/${folder}/${file}`);
    client.commands.set(command.name, command);
  }
}
// ...
like image 186
Zsolt Meszaros Avatar answered May 23 '26 03:05

Zsolt Meszaros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!