Discord.js bots: organizing commands

If you want to better organize your command files, you can separate the commands with categories and then create a folder for each category inside the commands folder.

for example:

đź“‚commands
 ┣ 📂moderation
 â”— đź“‚fun

After that you can loop through each of these new folders and load the command files inside them the same way you’ve done with your command handler

// First get the category directories
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => join(source, name)).filter(isDirectory);

// Then load the commands
getDirectories(__dirname + '/commands').forEach(category => {
  const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));

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

Leave a Comment