Reputation: 13
I'am tryng to get the bot to answer information that received from a API , can't get it working tho.
In firebase console log I can see the api indeed respond with the information that I need .
All the code below:
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function callAPI(agent){
const food = agent.parameters.Food;
const subject = agent.parameters.Subject;
const number = agent.parameters.number;
const question = subject + " "+number +" "+food;
const questionReady = question.replace(/ /g, '+');
const apiKey = "key";
const baseUrl = "https://api.spoonacular.com/recipes/quickAnswer?q=";
const apiUrl = baseUrl + questionReady + "&apiKey=" + apiKey;
axios.get(apiUrl).then((result) => {
console.log(result);
console.log(result.data);
console.log(result.data.answer);
agent.add(result);
agent.add(result.data);
agent.add(result.data.answer);
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('food', callAPI);
agent.handleRequest(intentMap);
});
Firebase console log:
Upvotes: 1
Views: 1182
Reputation: 50741
The most likely reason is that you're not using a Promise
or an async
function call, so your Handler is returning nothing before your call to the API completes.
To fix this, callAPI()
needs to return the Promise that axios.get()
returns. Similarly, your Intent Handler that calls callAPI()
needs to return that Promise (or another promise from the then()
block) as well.
The Dialogflow library requires this so it knows to wait for the API call to be completed (and the Promise to thus be resolved) before returning anything to the user.
In your case, this is as simple as changing the call to axios.get()
to something like
return axios.get(apiUrl).then((result) => {
// Rest of this call here
Upvotes: 1