我的 Discord 机器人有一个命令处理程序。它可以很好地加载命令模块,(控制台日志也表明了这一点),但是我无法让它执行第一个命令模块之外的命令。代码如下:
const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();
const prefix = "f$";
const fs = require("fs");
try {
const files = fs.readdirSync("./commands/");
let jsFiles = files.filter(filename => filename.split(".").pop() === "js");
for (const filename of jsFiles) {
let command = require(`./commands/${filename}`);
if (!command) return console.error(`Command file '${filename}' doesn't export an object.`);
client.commands.set(command.name, command);
console.log(`Loaded command: ${command.name}`);
}
} catch (err) {
console.error(`Error loading command: '${err}'`);
}
console.log("Finished loading\n");
client.on("ready", () => {
console.log("Client ready!");
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
//console.log(args);
let cmdName = args.shift().toLowerCase();
for (const command of client.commands.values()) {
console.log(command.name);
console.log(cmdName);
console.log(command === cmdName);
if (command.name !== cmdName /*&& !command.aliases.includes(cmdName)*/) return;
try {
await command.executor(message, args, client);
} catch (err) {
console.error(`Error executing command ${command.name}: '$```{err.message}'`);
}
}
});
client.login(TOKEN).catch(err => console.log(`Failed to log in: ${err}`));
并且在每个命令模块中你都有这个位:
module.exports = {
name: "command",
description: "description of command",
aliases: [],
executor: async function (message, args, client) {
(我还没有为此做别名,所以别名行要么是空的,要么被重新删除。)
答案 0 :(得分:0)
您在模板文字中错误地引用了您的变量,这意味着您的很多代码都被忽略了,这可能是问题的全部,它应该如下所示:
console.error(`Error executing command ${command.name}: ${err.message}`);
有关模板文字的指导,请使用 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals。如果您想使用 ``` 但忽略它们,请使用以下代码:
console.error(`Error executing command ${command.name}: \`\`\` ${err.message} \`\`\` `);
此外,在您的执行函数上,您没有右大括号,因此应该是:
module.exports = {
name: "command",
description: "description of command",
aliases: [],
executor: async function (message, args, client) {
// code to be executed
}