node.js - 如果未找到命令,则回复消息
问题描述
我试图让我的机器人检查每条消息,如果一个是命令,检查命令是否正确,如果不是,回复“无效的命令,键入 z!help 以获取命令列表”。
是)我有的:
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let commandName = file.split(".")[0];
console.log(`Attempting to load command ${commandName}`);
client.commands.set(commandName, props);
});
});
client.on('message', message => {
if (message.content.startsWith("z!")){
if (message.content !== commandName){
message.reply("Invalid command")
}
}
})
但我明白了
ReferenceError: commandName is not defined
任何帮助表示赞赏!
解决方案
您能否提供更多信息,例如错误出现在哪一行以及这个 commandName 最初定义在哪里?
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let commandName = file.split(".")[0];
console.log(`Attempting to load command ${commandName}`);
client.commands.set(commandName, props);
});
});
client.on('message', (message, files) => {
if (message.content.startsWith("z!")){
files.forEach(file => {
if (message.content !== file.split(".")[0]){
message.reply("Invalid command")
}
});
}
})
可能这里的代码不起作用,所以,这是另一个想法:
let globalFile;
function passFile(file) { // Generally speaking, that's a bad idea.
globalFile = file
return file
}
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let commandName = passFile(file.split(".")[0]);
console.log(`Attempting to load command ${commandName}`);
client.commands.set(commandName, props);
});
});
client.on('message', message => {
if (message.content.startsWith("z!")){
files.forEach(file => {
if (message.content !== globalFile){ // Check if globalFile is something
message.reply("Invalid command")
}
});
}
})
推荐阅读
- dax - Dax 度量以突出切片器之间的差异
- reactjs - 安装旧版 Storybook
- snowflake-cloud-data-platform - 使用复制授权作为选项创建临时表
- angular - 使用组件注入时传递 formGroup
- python - 在python中合并两个列表
- java - 调整文本大小时在底部保留 JScrollPane (JTextPane) 滚动条?
- powershell - 如何通过使用带有 powershell 的 Octopus deploy 来触发 Jenkins 作业?
- vue.js - 如何编辑 vue-loader 以支持音频文件?
- python - 将 Python 中的 PSD 图旋转 90 度 - 第 2 部分
- excel - 有没有办法将 iframe 嵌入到 Teams 聊天/对话中?