javascript - JavaScript 命令处理程序没有运行其他命令?
问题描述
我的不和谐机器人有一个命令处理程序。它可以很好地加载命令模块(并且控制台日志也显示了很多),但是我无法让它执行第一个命令模块之外的命令。这是代码:
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) {
(我还没有为此做别名,所以别名行要么是空的,要么被删除。)
解决方案
您在模板文字中错误地引用了您的变量,这意味着您的很多代码被忽略了,这可能是问题的全部,它应该如下所示:
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
}
推荐阅读
- c# - “IPhoneLine”不包含“PhoneLineStateChanged”的定义
- java - 使用 j2html 的登录表单示例
- java - java.lang.RuntimeException:命名空间“http://ws.abc.com/”的架构已经包含类型
- spring - 在 Spring Cloud Gateway 过滤器中引发自定义运行时异常
- html - 在相对定位的元素之前/之后对齐移动方向元素(上一个/下一个)(无 flexbox)
- java - 密码检查、验证和要求
- python - Windows Server上的Django MySQL连接错误
- python-3.x - 如何从另一个数据框中获取一个数据框中的公共列的值?
- ruby-on-rails - 无法在 Ruby on Rails 5 中显示数据库中的数据
- android - ExifInterface 返回错误的方向(因为它存储了多个冲突的属性)