如何将Discord机器人命令放入子文件夹并正常运行?
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
getCommandFilesfunction 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
nameproperty (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

