You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Discord机器人命令放入子文件夹并正常运行?

Organizing Discord Bot Commands into Subfolders

No problem at all—let's tweak your existing code to support subfolders without breaking command execution. The issue with your current setup is that fs.readdirSync('./commands') only looks at files directly in the commands root directory, not nested subfolders. Here's how to fix that:

Step-by-Step Solution

First, we'll add a recursive function to scan every folder (and subfolder) under ./commands and collect all your .js command files. We'll also use the path module to handle file paths consistently across different operating systems.

Updated Full Code

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

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

// Recursive function to fetch all command files, including those in subfolders
function getCommandFiles(dir) {
  const files = fs.readdirSync(dir);
  let commandFiles = [];

  for (const file of files) {
    const fullFilePath = path.join(dir, file);
    const fileStats = fs.statSync(fullFilePath);

    if (fileStats.isDirectory()) {
      // If it's a folder, dig deeper and add its files to our list
      commandFiles = commandFiles.concat(getCommandFiles(fullFilePath));
    } else if (file.endsWith('.js')) {
      // If it's a .js file, add it to our command list
      commandFiles.push(fullFilePath);
    }
  }

  return commandFiles;
}

// Get all command files (including subfolders)
const commandFiles = getCommandFiles('./commands');

// Load each command into the client's collection
for (const file of commandFiles) {
  const command = require(file);
  client.commands.set(command.name, command);
}

// Don't forget to log in your bot!
client.login('YOUR_BOT_TOKEN');

Key Changes Explained

  • Recursive File Scanning: The getCommandFiles function checks every item in a directory. If it finds a subfolder, it runs itself again on that folder to collect nested files. This ensures no command file gets missed, no matter how deep you nest your folders.
  • Path Handling: Using path.join() ensures your file paths work correctly whether you're on Windows, macOS, or Linux—no more issues with / vs \ separators.
  • No Breaking Changes: Your existing command files don't need any modifications! As long as each command exports a name property (like you already do), the code will load them exactly as before.

Quick Note

Make sure all your command names are unique! If two commands (even in different subfolders) have the same command.name, the later one loaded will overwrite the earlier one in the client.commands collection.

内容的提问来源于stack exchange,提问作者QuazArxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:52:42