簡體   English   中英

Dialogflow 實現內聯編輯器 api 請求

[英]Dialogflow fulfillment inline editor api request

我試圖讓機器人回答從 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 控制台日志:

查看 imgur.com 上的帖子

最可能的原因是您沒有使用Promiseasync function 調用,因此在您對 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM