how to call a event in the dialogflow v2 :nodejs - node.js

I'm using dialogflow v2 using npm. I just want call a welcome event in dialogflow. How can I do it in the nodejs. I'm pretty new to it.
This is my code
const projectId = "xxxxxx";
const LANGUAGE_CODE = 'en-US';
const sessionId = req.body.sessionId;
var query = req.body.query;
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId,sessionId);
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: LANGUAGE_CODE,
},
},
};
sessionClient.detectIntent(request).then(response => {
console.log('intent detected');
const result = response[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if(result.fulfillmentText) {
console.log(result.fulfillmentText);
return res.json({reply: result.fulfillmentText})
}
// if(result.intent) {
// console.log(` Intent: ${result.intent.displayName}`)
// }
else {
console.log('no intent found');
}
}).catch(err => {
console.log('error '+err);
})
As I open the chat page I just want to throw a welcome message. In order to do that, i read that i have to call the event. How can I do that? I have taken the reference from here

The Request body should be like this:
let eventName='WELCOME'; //name of the event
let request = {
session: sessionPath,
queryInput: {
event: {
name: eventName,
languageCode: 'en-US'
},
},
};
checkout- https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/detect.js#L96
let me know if you find any difficulties :)

I would suggest using actions-on-google as it is much easier to build nodejs backend for dialogflow link : actions on google
And for sample project refer Number genie project
Hope this would help you.

Related

Dialogflow API - DetectIntent is not responding and ends up being time out

I'm working on communicating with Dialogflow API.
`
const dialogflow = require('#google-cloud/dialogflow-cx');
const uuid = require('uuid');
const config = require('./devkey');
const projectId = 'test';
const location = 'northamerica-northeast1';
const agentId = 'test';
const sessionId = uuid.v4();
async function runIntent(text) {
const sessionClient = new dialogflow.SessionsClient({
apiEndpoint: 'northamerica-northeast1-dialogflow.googleapis.com',
credentials: {
private_key: config.private_key,
client_email: config.client_email
}
});
const sessionPath = sessionClient.projectLocationAgentSessionPath(
projectId,
location,
agentId,
sessionId
);
console.log('sessionPath: ', sessionPath, 'sessionId: ', sessionId);
const intentRequest = {
session: sessionPath,
queryInput: {
text: {
text: text
},
languageCode: 'en'
}
}
try {
const [response] = await sessionClient.detectIntent(intentRequest);
console.log('response: ', response);
console.log('resonse.text: ', response.queryResult.responseMessages[0].text.text[0]);
return response.queryResult.responseMessages[0].text.text[0];
} catch (err) {
console.log('error: ', err);
return err;
}
}
`
My question is regarding detectIntent method.
Usually it is working fine, however, sometimes it's not responding at all and ends up getting time out error.
Not sure what to do for this.
Any recommendation would be appreciated.
Thanks,
`
GoogleError: Total timeout of API google.cloud.dialogflow.cx.v3.Sessions exceeded 220000 milliseconds before any response was received.
at repeat (C:\google-dialogflow\poc-dialogflow2\backend\node_modules\google-gax\build\src\normalCalls\retries.js:66:31)
at Timeout._onTimeout (C:\google-dialogflow\poc-dialogflow2\backend\node_modules\google-gax\build\src\normalCalls\retries.js:101:25)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
code: 4
}
`
Normally the detectIntent method is working, but sometimes it's responding at all, and only throws time out error at the end.
No idea what goes wrong.

How to make context request in dialogoflow via nodejs sdk?

I would like to know how to create a context dialog, but I don't think anything about how to make this request... can anyone help me?
i'm using a lib sdk dialogflow
I searched how to do this, but I don't find anything, I don't know how to implement this..
me code
class DialogFlowController {
public dialogID: string
public sessionID: string
public sessionClient: SessionsClient
constructor () {
this.dialogID = 'chatbot-asxj'
this.sessionID = v4()
this.sessionClient = new dialogflow.SessionsClient({
credentials: {
type: config.gooogleType,
client_id: config.googleClientId,
private_key: config.googlePrivateKey,
client_email: config.googleCLientEmail,
token_url: config.googleTokenUrl
}
})
}
public async interactor (req: Request, res: Response): Promise<Response> {
console.log(teste)
const messagem = req.body.goMessage
try {
// Create a new session
const sessionPath = this.sessionClient.projectAgentSessionPath(this.dialogID, this.sessionID)
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: messagem,
// The language used by the client (en-US)
languageCode: 'en-US'
}
}
}
const response = await this.sessionClient.detectIntent(request)
Socket.io.emit('returnMessage', response[0].queryResult?.fulfillmentText)
return res.status(200).json()
} catch (err) {
return res.status(500).json(err)
}
}
}

Unable to get input contexts through to dialogflow using node js

I have been trying to get input contexts to flow into dialogflow via node.js but i cant seem to get it working in any way. Here is what I have so far and sorry I am not at node so any pointers would be a massive help.
It doesnt fail or say there is an error I just never see the input contexts hit the back end.
Thanks for you time
Steve
async function createContext(sessionId, contextId, parameters, lifespanCount = 1) {
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
const contextsClient = new dialogflow.ContextsClient();
const contextPath = contextsClient.contextPath(
projectId,
sessionId,
contextId
);
const request = {
parent: sessionPath,
context: {
name: contextPath,
parameters: struct.encode(parameters),
lifespanCount: lifespanCount
}
};
const [context] = await contextsClient.createContext(request);
return context;
}
// hook it up to the question and answer through the chatbot api
async function detectIntent(
projectId,
sessionId,
query,
contexts,
languageCode
) {
// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
queryParams: {
contexts: [contexts],
}
};
const responses = await sessionClient.detectIntent(request);
return responses[0];
}
async function requestChatBot(textdata) {
let intentResponse;
let context = "";
const parameters = {
welcome: true
};
context = await createContext(callId, 'welcome-context', parameters);
intentResponse = await detectIntent(
projectId,
callId,
textdata,
context,
languageCode
);
}
modify your "request" to
const request = {
session: sessionPath,
queryParams: {
contexts: [{
name: 'projects/' + projectId + '/agent/sessions/' + sessionId + '/contexts/' + "Name of the context you want to pass",
lifespanCount: provide life span of your context (Integer Value),
}]
},
queryInput: {
text: {
// The query to send to the dialogflow agent
text: userQuery,
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
This works.

Auth error:TypeError: URL is not a constructor

I am getting this error while deploying in AWS:
"Auth error:TypeError: URL is not a constructor" "DF ERROR:14
UNAVAILABLE: Getting metadata from plugin failed with error: URL is
not a constructor"
Although locally it is working fine.
Not getting any response after it calls to Dialogflow.
My code is :
// Instantiate a DialogFlow client.
var dialogflow = require('dialogflow');
var sessionClient = new dialogflow.SessionsClient({
credentials: {
private_key: config.dialogflow.privateKey,
client_email: config.dialogflow.clientEmail
}
}
);
// Define session path
var sessionPath = sessionClient.sessionPath(config.dialogflow.projectId, req.sessionID);
// The text query request.
var request = {
session: sessionPath,
queryInput: {},
};
if (chatBotEvent.text.text){
request.queryInput.text = {
text:chatBotEvent.text.text,
languageCode: chatBotEvent.text.languageCode
};
}
if (chatBotEvent.event.name){
var dialogflowService = new DialogflowService();
request.queryInput.event = {
name:chatBotEvent.event.name,
parameters:dialogflowService.jsonToStructProto(chatBotEvent.event.parameters),//event.parameters,
languageCode: chatBotEvent.event.languageCode,
};
}
// Send request and log result
return sessionClient
.detectIntent(request)
.then(function(responses){
var incidentData = $this.analyseResponse(responses[0].queryResult);
if (incidentData){
responses[0].queryResult.incident = incidentData;
}
return responses[0].queryResult;
})
.catch(function(err){
console.error('ERROR:', err);
});

Triggering intent in Dialogflow?(Using V2 api)

How to trigger an intent in Dialogflow?I need to trigger an intent without response from user. I know we need to call an event here, but don't know how to do the same in V2 api?
You trigger event from dialogflow, it's as easy to detectIntent
const dialogflow = require('dialogflow');
const config = require('../config');
// Import the JSON to gRPC struct converter
const credentials = {
client_email: config.GOOGLE_CLIENT_EMAIL,
private_key: config.GOOGLE_PRIVATE_KEY,
};
const sessionClient = new dialogflow.SessionsClient(
{
projectId: config.GOOGLE_PROJECT_ID,
credentials
}
);
module.exports = {
async sendEventToDialogFlow(event, params = {}) {
const sessionPath = sessionClient.sessionPath(config.GOOGLE_PROJECT_ID, sessionId);
const request = {
session: sessionPath,
queryInput: {
event: {
name: event,
languageCode: config.DF_LANGUAGE_CODE,
},
}
};
const responses = await sessionClient.detectIntent(request);
return responses[0].queryResult;
}
}

Resources