Skip to content

Instantly share code, notes, and snippets.

@jedfonner
Created Aug 2, 2021
Embed
What would you like to do?
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