Skip to content

Instantly share code, notes, and snippets.

@savelee
Created January 11, 2023 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savelee/77a1d8d082c91fd2064eb544d3b1f702 to your computer and use it in GitHub Desktop.
Save savelee/77a1d8d082c91fd2064eb544d3b1f702 to your computer and use it in GitHub Desktop.
Example Dialogflow CX webhook as Node JS cloud function
const functions = require('@google-cloud/functions-framework');
// Here's where you set the entry point, it gets the request from Dialogflow CX
// and it holds the response which will be sent back to Dialogflow
functions.http('orderState', (req, res) => {
let msg;
let results = {};
//let item;
//Let's log whatever we receive from Dialogflow CX to understand things better
console.log(req.body);
if(req.body.sessionInfo && req.body.sessionInfo.parameters){
// params will hold all the Dialogflow CX session parameters
let params = req.body.sessionInfo.parameters;
// For example, I can fetch an item name
//if(params.item) {
// item = params.item;
//}
}
if(req.body.fulfillmentInfo && req.body.fulfillmentInfo.tag){
let tag = req.body.fulfillmentInfo.tag;
switch (tag) {
case 'add':
let addResults = getAddToOrder(params);
msg = addResults.msg;
break;
case 'update':
let updateResults = getUpdateOrder(params);
msg = updateResults.msg;
break;
case 'remove':
let removeResults = getRemoveFromOrder(params);
msg = removeResults.msg;
break;
default:
let results = {
"success": false
}
msg = "Something went wrong. Please try again.";
}
}
// Build and return the response.
const response = {
fulfillmentResponse: {
messages: [
{
text: {
text: [
msg // this is the message for the agent to return
],
},
},
],
},
sessionInfo: {
parameters: results, // these are the parameters that will be set and returned to the agent
},
};
res.status(200).json(response);
});
function getAddToOrder(params){
// TODO do something with "item"
// set new parameters to the DFCX session
let results = {
"success": true,
"action": "add",
"orderId": "01222023"
}
results.msg = "Got it. I've added it to the order.";
return results;
}
function getUpdateOrder(params){
// TODO do something with "item"
// set new parameters to the DFCX session
let results = {
"success": true,
"action": "update",
"orderId": "01222023"
}
results.msg = "Got it. I've updated the order.";
return results;
}
function getRemoveFromOrder(params){
// TODO do something with "item"
// set new parameters to the DFCX session
let results = {
"success": true,
"action": "remove",
"orderId": "01222023"
}
results.msg = "Got it. I've removed it from your order.";
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment