#discord.js
#discord.js
Вопрос:
Я пытаюсь создать другой обработчик команд, более продвинутый. Я уже видел несколько типов кодов, объясняющих команду обработчика с помощью папок / вложенных папок / command, но я все еще не совсем понимаю, как это сделать.
Я уже пробовал использовать fs, и я хотел использовать его для этого, но все равно не смог.
Это мой текущий код (без попыток).
const Discord = require("discord.js");
const client = new Discord.Client();
const db = require('quick.db');
const fs = require("fs");
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
client.events = new Discord.Collection();
const utils = require("./utils/utils");
const config = require("./utils/config.json");
fs.readdir("./src/events/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
let eventFunction = require(`./src/events/${file}`);
let eventStart = eventFunction.run.bind(null, client);
let eventName = file.split(".")[0];
client.events.set(eventName, eventStart);
client.on(eventName, (...args) => eventFunction.run(client, utils, ...args));
});
});
fs.readdir('./src/commands/', (err, files) => {
if (err) console.error(err);
files.forEach(f => {
let props = require(`./src/commands/${ f }`);
props.fileName = f;
client.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
client.aliases.set(alias, props.help.name);
});
});
});
client.on("message", async message => {
try {
let prefix = await db.fetch(`prefixo_${message.guild.id}`);
if (prefix === null) prefix = "m!";
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ /g);
let command = args.shift().toLowerCase();
if (client.aliases.has(command)) command = client.commands.get(client.aliases.get(command)).help.name;
if (client.commands.get(command).config.restricted == true) {
if (message.author.id !== config.ownerID) return utils.errorEmbed(message, 'No permission.');
}
if (client.commands.get(command).config.args == true) {
if (!args[0]) return utils.errorEmbed(message, `Invalid arguments. Use: ${prefix 'help ' client.commands.get(command).help.name}`);
}
let commandFile = require(`./src/commands/${command}.js`);
commandFile.run(client, message, args, utils);
} catch (err) {
if (err.message === `Cannot read property 'config' of undefined`) return;
if (err.code == "MODULE_NOT_FOUND") return;
console.error(err);
}
});
client.login(config.token);
Ответ №1:
Я тоже хотел то же самое, и мне потребовалось некоторое время, чтобы понять это! Вот мой обработчик команд, который находится в моем ready.js
(готовом событии):
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
const stuff = ['dev','donators', 'fun', 'misc', 'moderation']; //my subfolders (i.e: modules)
stuff.forEach(c => { //loop through each module in the array
readdir(`./commands/${c}/`, (err, files) => { //use fs to read the directory with module name as path
if (err) throw err;
console.log(`Loading a total of ${files.length} commands (${c})`);
files.forEach(f => {
if (!f.endsWith(".js")) return;
client.loadCommand(`${f}`, `./commands/${c}/${f}`);
});
});
});
Мой client.loadCommand()
метод принимает имя файла f
и путь к файлу для этого файла ./commands/${c}/${f}
и использует ваш props
метод запроса пути к файлу и добавления props.help.name
client.commands
.
Имейте в виду, файловая структура вашего проекта должна быть такой, где имена модулей ( const stuff = ["module", "anothermod"]
) точно соответствуют именам вложенных папок, все в родительской папке commands
.