Created
June 5, 2018 03:02
-
-
Save nvtuan305/e89f3a16cd50b15dbfcb907bc17105b8 to your computer and use it in GitHub Desktop.
Detect Dialogflow intent that supports multiple agents using API v2
This file contains hidden or 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'; | |
// @ts-ignore | |
const dialogflow = require('dialogflow'); | |
const fs = require('fs'); | |
/** | |
* Detect dialogflow intent | |
* @param {String} botId | |
* @param {String} sessionId | |
* @param {String} text | |
* @param {String} languageCode | |
*/ | |
function detectIntent(botId, sessionId, text, languageCode) { | |
return Promise.resolve().then((r) => { | |
// Update the Google Application Credential | |
// before creating new session client | |
if (!updateGAC(botId)) { | |
return Promise.reject(new Error('GAC file does not exist')); | |
} | |
// Create session client | |
const projectId = getProjectId(botId); | |
const sessionClient = new dialogflow.SessionsClient(); | |
const sessionPath = sessionClient.sessionPath(projectId, sessionId); | |
// Create request. For example, I will create a text request | |
const request = { | |
session: sessionPath, | |
queryInput: { | |
text: { | |
text: text, | |
languageCode: languageCode, | |
}, | |
}, | |
}; | |
// Detect intent | |
return sessionClient | |
.detectIntent(request) | |
.then((responses) => { | |
console.log(`> Detected intent for ${botId}`); | |
const result = responses[0].queryResult; | |
console.log(` Query: ${result.queryText}`); | |
console.log(` Response: ${result.fulfillmentText}`); | |
}).catch((err) => { | |
console.error(err); | |
}); | |
}); | |
} | |
/** | |
* Update Google Application Credential for the bot by bot id | |
* @param {String} botId | |
* @return {Boolean} | |
*/ | |
function updateGAC(botId) { | |
const gacPath = `./path/to/google-application-credential-${botId}.json`; | |
if (process.env.GOOGLE_APPLICATION_CREDENTIALS === gacPath) { | |
return true; | |
} | |
if (!fs.existsSync(gacPath)) { | |
return false; | |
} | |
process.env.GOOGLE_APPLICATION_CREDENTIALS = gacPath; | |
return true; | |
} | |
/** | |
* Get project id by bot id | |
* @param {String} botId | |
* @return {String} | |
*/ | |
function getProjectId(botId) { | |
// Get your Dialogflow project id from database... | |
return 'project-id'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will this work in the case of 50 simultaneous call ?