Dialogflow履行内联编辑器api请求

我正在尝试让漫游器回答从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 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控制台日志:

View post on imgur.com

luoyelhj 回答:Dialogflow履行内联编辑器api请求

最可能的原因是您没有使用Promiseasync函数调用,因此在对API的调用完成之前,处理程序未返回任何内容。

要解决此问题,callAPI()需要返回axios.get()返回的Promise。同样,调用callAPI()的Intent Handler也需要返回该Promise(或then()块中的另一个Promise)。

Dialogflow库需要这样做,因此它知道在向用户返回任何内容之前要等待API调用完成(从而解决Promise)。

对于您而言,这就像将对axios.get()的呼叫更改为类似的

return axios.get(apiUrl).then((result) => {
  // Rest of this call here
本文链接:https://www.f2er.com/3127151.html

大家都在问