首页 > 解决方案 > 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!");
  }
});
}

标签: node.jsdiscord.js

解决方案


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.");
})

推荐阅读