Skip to content

Instantly share code, notes, and snippets.

@kmelve
Last active March 12, 2018 05:57
Show Gist options
  • Select an option

  • Save kmelve/d16fd5e666f19bed613487eed7ecb254 to your computer and use it in GitHub Desktop.

Select an option

Save kmelve/d16fd5e666f19bed613487eed7ecb254 to your computer and use it in GitHub Desktop.
Webtask.io function for returning a fullfillment to Dialogflow.
/**
* @param context {WebtaskContext}
*/
/*
* Set up your Sanity client with an project id, and the
* name of your dataset. If you have set custom permissions
* you'll also need to set it up with a access token, which
* can be placed in webtask’s secrets. Note that in that case
* you should also add some authentication to incoming requests.
*/
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: 'YOUR_PROJECT_ID',
dataset: 'YOUR_DATASET_ID',
token: '',
useCdn: true
})
module.exports = function(context, cb) {
// This assumes a valid post request from Dialogflow
const intent = context.body.queryResult.intent.displayName
/*
* Query a list of the fullfillment strings from the posts referenced to
* by the intent entry.
*/
const query = `*[_type == 'intent' && intentName == $intent][0]{"fullfillments": fullfillments[0]->fullfillments}`;
// Fetch the data data from Sanity, matching the Display name from Dialogflow
client.fetch(query, { intent })
.then(data => {
const fullfillments = data.fullfillments
if (fullfillments) {
/*
* Pick one of the strings randomingly in order to create some
* basic variance.
*/
const randomFullfillment = fullfillments[Math.floor(Math.random() * fullfillments.length)];
// Return the string to Dialogflow.
return cb(null, { fulfillmentText: randomFullfillment });
}
return cb(null, { fulfillmentText: 'Sorry, I didn\'t get that.' });
}).catch(error => {
console.error(error);
return cb(null, { fulfillmentText: 'Sorry, something wrong happened.' });
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment