Skip to content

Instantly share code, notes, and snippets.

@jedfonner
Created August 2, 2021 23:54
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 jedfonner/a2521a4c2155d1690c7ded2bb0c0e4ec to your computer and use it in GitHub Desktop.
Save jedfonner/a2521a4c2155d1690c7ded2bb0c0e4ec to your computer and use it in GitHub Desktop.
Example of a Firebase Cloud Function integrating with DialogFlow
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const uuid = require('uuid');
// https://cloud.google.com/dialogflow/es/docs/reference/libraries/nodejs
// https://googleapis.dev/nodejs/dialogflow/latest/index.html
const dialogflow = require('@google-cloud/dialogflow');
// The ID of the GCP project where your Dialogflow agent is deployed
const PROJECT_ID = 'your-project-id';
exports.talkToDialogFlowAgent = functions.https.onRequest(async (req, res) => {
return cors(req, res, async () => {
functions.logger.info('Query data:', JSON.stringify(req.query));
const sessionId = uuid.v4();
// https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance
// https://cloud.google.com/docs/authentication/production#create_service_account
const options = {
keyFilename: './service-account.json',
};
const sessionClient = new dialogflow.SessionsClient(options);
const sessionPath = sessionClient.projectAgentSessionPath(PROJECT_ID, sessionId);
const queryText = req.query.text;
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the Dialogflow agent
text: queryText,
languageCode: 'en-US',
},
},
};
// Send request and log result
console.log('Sending query:', queryText);
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(' No intent matched.');
}
// Respond with the fullfillment text
const fulfillmentText = result.fulfillmentText;
console.log('Returning fulfillmentText:', fulfillmentText);
res.status(200).json({
result: {
fulfillment: {
speech: fulfillmentText,
},
},
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment