【发布时间】:2020-03-09 00:58:48
【问题描述】:
如果此处的“导出”不是正确的术语,请原谅我。我正在使用 javascript 和 discord.js 为我的机器人创建一个命令处理程序,它将命令作为文件夹中的单个文件读取,直到现在它一直运行良好,我正在尝试创建一个允许您“锁定”机器人的命令对特定频道的命令,这是我发现的技术。但是,由于某种原因,包含通道 ID 的变量 ticketChannels 中的数据在命令启动时会以某种方式变为 false。我确保它不会在任何地方重新定义,并使用 several console.logs 来确保变量在设置为所需通道时被正确定义,但不知何故是命令处理程序或其他东西一路上正在把它变成false。我尝试了几种不同的格式化锁定通道 ID 的方法,包括单个对象数组(因为我有一个用数组格式化的点系统,我可以在命令之间导出并对其进行更改就可以了,所以我想我会尝试另一个数组),尝试将其设置为通道本身而不是 ID,四重检查任何地方的任何重新定义,但没有。我难住了。有任何想法吗?
命令处理程序代码:
function readCMD() {
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
client.commands.deleteAll()
//deleteAll is here so that the commands list is refreshed properly everytime readCMD is called, as i have an update command that re-reads the folder using this function
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);
});
});
}
readCMD()
client.on('message', msg => {
if (msg.author.bot) return;
const prefix = '$'
const args = msg.content.slice(prefix.length).trim().split(/ +/g)
let command = args.shift().toLowerCase()
const cmd = client.commands.get(command)
我尝试在核心文件和核心文件外运行的命令:
if (msg.content.toLowerCase().startsWith('$setticketchannel')) {
const indArgs = msg.content.split(" ")
if (indArgs[1].toLowerCase() == 'on') {
var chosenChannel = msg.mentions.channels.first()
console.log(chosenChannel.id)
ticketChannels = chosenChannel.id
console.log(ticketChannels)
} else if (indArgs[1].toLowerCase() == 'off') {
ticketChannels = 0
}
}
执行:
try {
cmd.run(client, msg, args, bank, currentPoints, fs, duelon, ticketChannels)
}catch(e) {
console.log(e)
}
以及尝试检查 ID 的命令代码:
exports.run = (client, msg, args, bank, currentPoints, fs, ticketChannels) => {
console.log("$GAMBLE:")
console.log(ticketChannels)
if (ticketChannels !== 0) {
if (msg.channel.id !== ticketChannels) {
msg.reply(`Commands such as these can only be done in ${ticketChannels}`)
return
}
}
为了澄清,我使用命令处理程序导出的每个其他变量都可以正常工作,我可以在单个命令内外编辑和重新定义它们就好了。另外:不是 if 语句返回 false,而是 变量本身 正在变成 false,尽管没有这样定义它。
【问题讨论】:
-
我觉得你的问题是因为你比较弱的情况造成的。在代码
ticketChannels != 0中,您没有使用严格的比较器!==,这会导致JS 在检查条件之前尝试转换您的变量。我会说尝试用严格的比较替换你的弱比较,看看它是否能解决问题。 -
弱比较你的类型会导致非假值(undefined, null, 0)被解释为falsy。所以一个未定义的变量将
==到false。但不会===为假。 -
@Nicolas 在尝试使用严格比较器时,机器人在尝试使用
$gamble时确实会吐出错误消息,但无论我尝试在哪个频道执行它,它总是会出错,因为该变量仍被系统读取为false,而不是所需的通道 ID。
标签: javascript node.js event-handling boolean discord.js