node.js - NodeJS bot 没有转义 if 语句
问题描述
所以,我对编码有点陌生,我正在尝试在 NodeJS 中制作一个不和谐的机器人,代码似乎可以正常工作,直到你输入“yes”或“no”,这会给出正确的响应但是之后输入是或否会继续给出响应,而它们应该只给出一次。这可能是一个非常简单的问题,但我就是想不通。
if (
msg.author.id == config.ownerID &&
msg.content.startsWith(config.prefix + "reset")
) {
msg.reply(
"Are you sure you'd like to reset all inventories and nation assignments? (Reply by saying yes or no)"
);
client.on("message", msg => {
if (msg.author.id == config.ownerID && msg.content.startsWith("yes")) {
// INSERT RESET CODE HERE
return msg.reply("All inventories and assignments have been reset.");
} else if (
msg.author.id == config.ownerID &&
msg.content.startsWith("no")
) {
return msg.reply("Restart aborted. Have a nice day!");
}
});
}
解决方案
message event
每次运行该命令时,您都会创建一个新命令。这意味着,从那时起,它将在每条消息上运行。有一个非常简单的解决方案,您可以简单地删除整个message event
并实现一个message collector
,它只会运行您想要的次数。
文档:消息收集器
//Create a Message Collector that waits for 1 minute and takes in 1 message
message.channel.awaitMessages(m => m.author.id === <Whatever IDS you want>, {max: 1, time: 60000, errors:['time'] })
//When a message is received
.then(collected => {
//response is what message the collector received from the user
let response = `${collected.first()}`;
// code whatever you want to do with the user response here
console.log(response);
})
//Will throw an error when time runs out
.catch(collected => {
message.channel.send("Times up, no response received.");
})
推荐阅读
- python - 如何检查函数的输入是否在数据类型限制内?
- reactjs - 修复 React-script 版本漏洞导致 webpack 依赖错误
- angular - 运行 npm install 时的 CWD ENOENT
- python - Python分组一个百分比范围内的增量并计算组数
- java - java.lang.IllegalArgumentException:不是托管类型:classTestEntity
- python - 如何从以特定字符序列开头的列表行中删除子字符串并生成输出文件
- json - 将多个 API 字段序列化为一个。姜戈
- openssl - 在 Windows 上构建 PCL 时出现 OpenSSL 错误
- google-maps - Google Maps View Android 额外边距,不带图块
- java - `TreeMap` 按字母顺序排序