how to trace user reply to a specific chatbot message in node.js

751 views Asked by At

I wonder how to catch a user reply to a specific chatbot question? I mean for example if the user asks the chatbot for the weather and the chatbot responds back by asking the user for in which city. I would then like to trace what the user responds to that question. So that the city could be used for calling a weather api for the city. I don't know how to track the user reply to that question. Does anyone know if and how this is possible?

2

There are 2 answers

0
Danny Sullivan On BEST ANSWER

So that multiple users can access the chatbot simultaneously, it's best to keep track of each user, and each user's conversation state. In the case of the Messenger API, this would be:

const users = {}
const nextStates = {
    'What country are you in?': 'What city are you in?',
    'What city are you in?': 'Let me look up the weather for that city...'
}
const receivedMessage = (event) => {
    // keep track of each user by their senderId
    const senderId = event.sender.id
    if (!users[senderId].currentState){
        // set the initial state
        users[senderId].currentState = 'What country are you in?'
    } else {
        // store the answer and update the state
        users[senderId][users[senderId].currentState] = event.message.text
        users[senderId].currentState = nextStates[users[senderId.currentState]]
    }
    // send a message to the user via the Messenger API
    sendTextMessage(senderId, users[senderId].currentState)
}

Then you will have the answer for each user stored in the users object. You can also use a database to store this.

0
user3857472 On

..I solved it by setting a global variable when the chatbot asks the question

global.variable = 1;

When the user replies the incoming text message event is fired and I can check if the global flag is set. This indicates that this is the user reply after the question was asked. I can then get the message text city from that message. This works fine in my case but if anyone knows a better alternative please let me know