Madhvan soni
Madhvan soni

Reputation: 21

How to use subfolders in a command handler

I want to make command sub folders but my bot doesn't read commands inside the folders. There is no error.

const fs = require('node:fs');
const Discord = require('discord.js')

module.exports = (client) => {
  client.commands = new Discord.Collection();
  const commandFolders = fs.readdirSync('./commands')

  const commands = [];
  for (const folder of commandFolders) {
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
    for (const file of command_files) {
      const command = require(`../commands/${folder}/${file}`);
      client.commands.set(command.name, command);  
    }
  }
}

Upvotes: 1

Views: 115

Answers (2)

新Acesyyy
新Acesyyy

Reputation: 1198

Why do you still need to storage your commands on array? You're already using a collection.

module.exports = (client) => {
    
    client.commands = new Discord.Collection();
    const commandFolders = fs.readdirSync('./commands')

    for (const folder of commandFolders) {
        const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
        for (const file of command_files) {
            const command = require(`../commands/${folder}/${file}`);
            client.commands.set(command.name, command);
        }
    }
}

//your folders should read with readdirSync too then find all of your filtered file.endsWith('.js')

Upvotes: 0

suptower
suptower

Reputation: 11

You need to adapt your readdirSync arguments

const command_files = fs.readdirSync('./commands/' + folder);

This will give you all your files. Then you need to:

for (const file of command_files) {
    const command = require('./commands/' + folder + '/' + file);
    client.commands.set(command.name, command);        
}

Upvotes: 1

Related Questions