Skip to content

Instantly share code, notes, and snippets.

@parnurzeal
Last active August 6, 2017 08:36
Show Gist options
  • Save parnurzeal/779e9d75c4b3b5091efddeea3f38fd66 to your computer and use it in GitHub Desktop.
Save parnurzeal/779e9d75c4b3b5091efddeea3f38fd66 to your computer and use it in GitHub Desktop.
Stop api.ai from chatting
const admin = require('firebase-admin');
const auth = require('basic-auth')
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
exports.webhook = functions.https.onRequest((req, res) => {
// Check if api.ai provides a correct user/pass
const credentials = auth(req);
if (!credentials || credentials.name != 'username' || credentials.pass != 'password') {
console.log('Incorrect authentication header');
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
}
const fbMessageInfo = req.body.originalRequest;
if (!fbMessageInfo || fbMessageInfo.source !== 'facebook') {
console.log('No fb message info attached with the request.\n' +
'Check whether your message are actually coming from FB?');
return res.send(400);
}
const userId = fbMessageInfo.data.sender.id;
const pageId = fbMessageInfo.data.recipient.id;
const timestamp = fbMessageInfo.data.timestamp;
const routingOnDb = `/${pageId}/${userId}`;
admin.database().ref(routingOnDb).once('value').then((snapshot) => {
const userDataOnDb = snapshot.val();
if (userDataOnDb) {
// Clear a user record on DB if it is already more than the desired wait time.
const dataOnDatabase = snapshot.val();
const endTimestamp = dataOnDatabase.endTimestamp;
const userWaitTime = dataOnDatabase.waitTime;
if (timestamp > endTimestamp) {
console.log('Wait time is over. Release a user.');
return admin.database().ref(routingOnDb).set(null).then(snapshot => {
return res.send(400);
});
}
return res.json({
speech: ' ',
displayText: ' ',
source: 'firebase-functions',
});
} else {
const action = req.body.result.action;
console.log(`Received action ${action}`);
if (action !== 'action.wait') {
return res.send(400);
}
// Put user to a wait state.
// Also, record the end timestamp when we want to release the user.
const waitTime = req.body.result.parameters.waitTime;
return admin.database().ref(routingOnDb).set({
userId,
pageId,
endTimestamp: timestamp + waitTime * 1000,
waitTime,
}).then(snapshot => {
console.log('1st time - push a user record to DB');
const text = `Stop bot for ${waitTime} seconds`;
return res.json({
speech: text,
displayText: text,
source: 'firebase-functions',
});
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment