問題:
嘿,伙計們,我想知道如何將我的命令分類到檔案中,而不是將它們全部放在commands檔案中。例如,檔案布局如下所示:
discord-bot/
├── node_modules
├── src/
├── commands/
└── Moderation/
└── command.js
├── Data/
└── config.json
├── .env
└── index.js
├── package-lock.json
└── package.json
我的 index.js 代碼:
client.once('ready', () => {
incrementVersionNumber(config.version, ".");
console.log(`Successfully logged in as ${client.user.tag}`);
// Where the main part of adding the command files begins
const commands = [];
const commands_information = new Collection();
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));
const clientId = process.env.CLIENTID;
for(const file of commandFiles){
const command = require(`./commands/${file}`);
console.log(`Command loaded: ${command.data.name}`);
commands.push(command.data.toJSON());
commands_information.set(command.data.name, command);
}
// Where getting the command files ends
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, 'guildId'),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
console.log('-----------------------------------------------');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (!commands_information.has(commandName)) return;
try {
await commands_information.get(commandName).execute(client, interaction, config);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
});
我想知道的:
我知道這個顯示有點亂,但├── ── commands/請注意我是如何添加另一個檔案夾并將命令放入其中而不是將命令放入├── ── commands/其自身中的。如何自定義我的index.js檔案以查看檔案夾中的每個檔案commands夾,然后獲取檔案夾中的每個檔案category?我試圖添加一個*以查看它是否會抓取每個檔案夾,但它只是拋出一個錯誤,說commands/*不是目錄。那么我該怎么做呢?我以前也見過這樣做,所以我知道這是可能的。
uj5u.com熱心網友回復:
對于這種型別的檔案匹配,您需要使用glob。它回傳一個東西陣列,你可以使用commands/**/*它的模式來作業。
uj5u.com熱心網友回復:
我想通了,并能夠通過使用以下代碼來解決這個問題:
client.once('ready', () => {
incrementVersionNumber(config.version, ".");
console.log(`Successfully logged in as ${client.user.tag}`);
client.user.setActivity(`${client.guilds.fetch.length} Servers`, {type: 'WATCHING'});
categories = [
"Config",
"Entertainment",
"Games",
"Information",
"Miscellaneous",
"Moderation",
"Music",
];
const commands = [];
for (var i = 0; i < fs.readdirSync('./src/commands').length - 1; i ) {
const commands_information = new Collection();
const commandFiles = fs.readdirSync(`./src/commands/${categories[i]}`).filter(file => file.endsWith(".js"));
for(const file of commandFiles){
const command = require(`./commands/${categories[i]}/${file}`);
console.log(`Command loaded: ${command.data.name}`);
commands.push(command.data.toJSON());
commands_information.set(command.data.name, command);
}
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, '910339489770111036'),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
console.log('-----------------------------------------------');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (!commands_information.has(commandName)) return;
try {
await commands_information.get(commandName).execute(client, interaction, config);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
});
uj5u.com熱心網友回復:
如果我理解正確,您可以使用動態匯入來完成您想要做的事情。我猜你沒有使用工具鏈來構建它,而是直接從 CLI 執行腳本,所以我不打算進行轉譯。
嘗試按照以下步驟操作,這些只是建議,因此請隨意實施,但最適合您的專案:
找一個可以幫助你檢索檔案串列的庫,glob是一個不錯的開始選擇。
在您的腳本中,首先創建一個函式來注冊命令,假設該函式的簽名是
registerFileCommand(filename: string, handler: () => void)檢索并回圈遍歷您的模塊,每次迭代都匯入和注冊它們:
glob("./commands/*.js", {}, (err, files) => { files.forEach(async file => { const cmd = generateCommandName(file); registerFileCommand(file, (await import(file)).default); }); });
- 使用這種方法時需要注意以下幾點:
registerFileCommand應該處理命令注冊邏輯,這意味著命令模塊的默認匯出應該是呼叫命令時由 DiscordJS 執行的函式。立即匯入所有模塊可能會出現問題,因此您可能希望按需匯入命令,而不是在啟動時匯入。看起來像這樣:
registerFileCommand(file, params => { import(file).then(({ default }) => default(...params)); });您將需要實作額外的邏輯來將模塊名稱決議為命令名稱。這完全取決于您的命名方案。例如,我們選擇以 kebab case (my-command) 命名我們的命令模塊。
如果您想提供記錄命令可能用法的提示或幫助對話框,您可能還需要在匯出中實作其他邏輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442106.html
標籤:javascript 节点.js 不和谐 不和谐.js fs
