我正在尝试让机器人回答从 API 收到的信息,但无法正常工作。在 firebase 控制台日志中,我可以看到 api 确实响应了我需要的信息。下面的所有代码:'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 statementsexports.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);});
1 回答

蛊毒传说
TA贡献1895条经验 获得超3个赞
最可能的原因是您没有使用 aPromise或async函数调用,因此您的 Handler 在您对 API 的调用完成之前没有返回任何内容。
要解决这个问题,callAPI()需要返回返回的 Promise axios.get()。同样,调用的 Intent Handler 也callAPI()需要返回该 Promise(或来自then()块的另一个 Promise )。
Dialogflow 库需要这样做,因此它知道在将任何内容返回给用户之前等待 API 调用完成(从而解决 Promise)。
在您的情况下,这就像将呼叫更改axios.get()为类似的东西一样简单
return axios.get(apiUrl).then((result) => {
// Rest of this call here
添加回答
举报
0/150
提交
取消