I have created a node.js webhook for my facebook messenger bot. The bot is built in dialog flow and the database is connected to firebase. My question when a function is invoked in the webhook to log in, after logging in, I get a userID from the database, which I want to store it somewhere in the code so that userID info is available throughout the user session. I am storing it in a global variable. However, this works fine if only one user is using the bot. If another user is using the bot at the same time, this userID info is shared between users since this is stored in a global variable. How do I solve this? Please help.
var loggedIn = true;
for (i = 0; i < contexts.length; i++) {
console.log("Inside contexts for loop");
//Check for login details context.
if (contexts[i].name == "logindetails") {
if (contexts[0].parameters.loggedIn == "true") {
//set this true if found.
loggedIn = true;
}
}
}
if (loggedIn) {
showUserAccountOptions(sender);
} //else start the login flow and once logged in create the 'logindetails' contexts and set the loggedIn parameter as true.
else {
//Login
login(email, password);
//Post the logindetails contexts
console.log("Not found");
let url = "https://api.dialogflow.com/v1/contexts?sessionId=" + response.sessionId;
console.log("URL", url);
var con = {
method: 'POST',
url: url,
qs: { access_token: '****' },
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer' + ' ****'
},
body:
[
{
"lifespan": 25,
"name": "logindetails",
"parameters": {
"loggedIn": "true"
}
}
],
json: true
};
request(con, function (error, response, body) {
console.log("Inside api request");
if (error) {
console.log("Inside Error", error);
}
else{
//show user options
showUserAccountOptions(sender);
}
});
}
Sending contexts updates to dialogflow:
let apirespone = let apirespone = {
"contexts": [
{
"name": "logindetails",
"parameters": {},
"lifespan": 5
}
]
}
sendToApiAi(sender,apirespone);
function sendToApiAi(sender, text) {
sendTypingOn(sender);
let apiaiRequest = apiAiService.textRequest(text, {
sessionId: sessionIds.get(sender)
});
apiaiRequest.on('response', (response) => {
if (isDefined(response.result)) {
handleApiAiResponse(sender, response);
}
});
apiaiRequest.on('error', (error) => console.error(error));
apiaiRequest.end();
}