Created
December 12, 2022 16:23
-
-
Save PamornT/e8809924e0467a0d45c58ea661024094 to your computer and use it in GitHub Desktop.
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
import * as functions from "firebase-functions"; | |
import * as dialogflow from "@google-cloud/dialogflow"; | |
const projectId = "multiple-env-pafg"; | |
// // Start writing Firebase Functions | |
// // https://firebase.google.com/docs/functions/typescript | |
let dialogflowEnv = ""; | |
// | |
export const webHook = functions.https.onRequest((request, response) => { | |
if (request.body.destination === "U19476f0931c6ac37972a6b7f4b4321c6") { | |
dialogflowEnv = "draft"; | |
} else if (request.body.destination === "U92a6f010a3fd78085b8763159a04772b") { | |
dialogflowEnv = "production"; | |
} | |
const events = request.body.events; | |
events.forEach( async (event: any) => { | |
console.log(event); | |
if (event.type === "message") { | |
const text = event.message.text; | |
const userId = event.source.userId; | |
const output = await detectIntent(text, userId); | |
console.log(output); | |
// Reply | |
} | |
}); | |
response.end(); | |
}); | |
/** | |
* detectIntent. | |
* @param {strint} message Input message. | |
* @param {strint} userId userId. | |
* @return {any} The result of DetectIntent from Dialogflow. | |
*/ | |
async function detectIntent(message: string, userId: string): Promise<any> { | |
const sessionId = userId; | |
const sessionClient = new dialogflow.SessionsClient({ | |
projectId, | |
keyFilename: "multiple-env-pafg-a9a11f6e8479.json", | |
}); | |
const sessionPath = `projects/${projectId}/agent/environments/${dialogflowEnv}/users/${sessionId}/sessions/${sessionId}`; | |
const request = { | |
session: sessionPath, | |
queryInput: { | |
text: { | |
text: message, | |
languageCode: "th-TH", | |
}, | |
}, | |
}; | |
// Send request and log result | |
const responses = await sessionClient.detectIntent(request); | |
const result = responses[0].queryResult; | |
return result?.fulfillmentText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment