Search code examples
javascriptnode.jschatbotstatements

How to use if statements inside each other to make chatbot(Node.js)


I am trying to create simple chatbot with node.js but I am having trouble getting if statements to work. I want the if statements to be inside of each other so that the user can only chat "How are you?" if he has already said "Hello". The current method I'm using not work at all. I am not sure if there could be different method to doing this or I am just doing it wrong?? Thank you much in advance!

if (message == "Hello") {
chat.respond(id, "Hi!")
if (message == "How are you?") {
chat.respond(id, "Very good sir!")
}
}

Solution

  • I think your code should be like this:

    if (message == "Hello") {
      chat.response(id, "Hi!")
    } else if (message == "How are you?") {
      chat.response(id, "Very good sir!")
    }
    

    The problem with your original code is that if message is already "Hello", then it will never equal "How are you?", hence the inner if will never be executed.

    And if you want the "How are you?" to be after the "Hello", then you can do something like:

    // place this variable in an outer scope
    var receivedHello = false
    
    // your if statement
    if (message == "Hello") {
      receivedHello = true
      chat.response(id, "Hi!")
    } else if (receivedHello && (message == "How are you?")) {
      chat.response(id, "Very good sir!")
    }