Last active
August 18, 2022 09:43
-
-
Save savelee/52b9c84c035b2e1ef4f8a84051a2803b to your computer and use it in GitHub Desktop.
Conditional Templating in Dialogflow with Custom Payloads and Google Cloud Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { | |
dialogflow | |
} = require('actions-on-google'); | |
const pug = require('pug'); | |
/* | |
* Uses Pug.js https://pugjs.org/language/plain-text.html | |
* Requires a Dialogflow custom payload like: | |
* { | |
"custom": { | |
"locals": { | |
"username": "$username" | |
}, | |
"pug": [ | |
"if username\n", | |
" | Hello $username\n", | |
"else\n", | |
" | Hello stranger" | |
] | |
} | |
} | |
*/ | |
const templateHelper = function(payload){ | |
var str = payload.custom.pug; | |
if(Array.isArray(payload.custom.pug)) { | |
str = payload.custom.pug.join(""); | |
}; | |
var fn = pug.compile(str); | |
var text = fn(payload.custom.locals); | |
return text; | |
} | |
const templateHandler = (conv) => { | |
console.log('Dialogflow Request headers: ' + JSON.stringify(conv.headers)); | |
console.log('Dialogflow Request body: ' + JSON.stringify(conv.body)); | |
var payload = conv.body.queryResult.fulfillmentMessages[0].payload; | |
var text = templateHelper(payload); | |
conv.ask(text); | |
}; | |
const app = dialogflow(); | |
app.intent('[templating] example', templateHandler); | |
exports.index = app; | |
/* package.json | |
{ | |
"name": "Dialogflow Conditionals", | |
"description": "Advanced Google Assistant with Dialogflow", | |
"version": "1.0.0", | |
"license": "Apache-2.0", | |
"author": "Lee Boonstra", | |
"engines": { | |
"node": "^6.11.5" | |
}, | |
"dependencies": { | |
"actions-on-google": "2.1.1", | |
"pug": "2.0.3" | |
} | |
} */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment