I'm trying to get data from an external site triggered by the welcome intent. Right now I'm trying a simple GET request to google.com.
The agent works as expected except when called from insided the request callback. It sometimes works and sometimes desn't.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function search(agent){
var request = require("request");
var options = {
method: 'GET',
url: 'http://google.com'
};
console.log("Before request");
agent.add("Before request");
request(options, function (error, response, body){
console.log("Request completed");
agent.add("Request completed"); //<- This line doesn't show in agent
console.log("finished"); //<- This line shows in the log
});
console.log("Request sent");
agent.add(`Request sent`);
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', search);
agent.handleRequest(intentMap);
});
I have noticed in the log the message "Function execution took 1697 ms, finished with status code: 200" shows before the message "finished". I don't know if that means that process is closing and ignoring the agent.add() calls after that point.
Image: firebase log console showing function excecution finished before request compelted
The issue is with the callback/promise. You need to return a promise inside your search function.
function search(agent, query){
return new Promise((resolve, reject) => {
request.get(options, (error, response, body) => {
.....
agent.add(...)
resolve();
});
});
};
The original answer can be found in the following Github issue:
https://github.com/dialogflow/dialogflow-fulfillment-nodejs/issues/3
EDIT:
Got a little help from the DialogFlow support staff. I little varation was missing to the proposed code to work properly:
function search(agent, query){
return new Promise((resolve, reject) => {
request.get(options, (error, response, body) => {
.....
let output = agent.add(...)
resolve(output); //<- agent.add() should be passed as argument in resolve()
});
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With