如何从 REST 输出信息 API

How to output the information from REST API

我想让我的代理说出从 REST API 获得的信息。 但是下面的代码无法响应任何消息,这意味着 "queryResult.fulfillmentMessages.text" 为空。

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 intent1(agent) {
    callApi().then((output) => {
        //This log is correctly outputted to firebase console 
        console.log('output: ' + output);
        
        //But this method doesn't work and the Agent says nothing
        agent.add('output: ' + output);
    });
  }

  function callApi(){
    return new Promise((resolve, reject) => {
        let req = http.get('http://xxx', (res) => {
          let chunk = '';
          res.on('data', (d) => {
            chunk = d;
          });
          res.on('end', () => {
            let response = JSON.parse(chunk);
            let output = response['results'][0];
            
            resolve(output);
          });
        });
    });
  }

  let intentMap = new Map();
  intentMap.set('intent1', intent1);
  agent.handleRequest(intentMap);
});

我尝试了另一个代码如下,它表明回调函数不影响 "agent.add" 方法。 所以,我认为问题是由 API 请求过程或其他原因引起的...

'use strict';
 
const functions = require('firebase-functions');
const App = require('actions-on-google').DialogflowApp;
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

const http = require('http');
 
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 intent1(agent) {
    callApi().then((output) => {
        //This method works and the Agent says "output: abc"
        agent.add('output:' + output);
    });
  }

  function callApi(){
    return new Promise((resolve, reject) => {
        let output = "abc";
        resolve(output);
    });
  }

  let intentMap = new Map();
  intentMap.set('intent1', intent1);
  agent.handleRequest(intentMap);
});

有谁知道解决问题的方法或从 REST 输出信息的其他方法 API?

您的 intent1 函数还必须 return Promise,并在您将响应添加到代理后解决它。

function intent1(agent) {
    return new Promise((resolve, reject) => {
        callApi().then((output) => {
            //This method works and the Agent says "output: abc"
            agent.add('output:' + output);
            resolve();
        });
    }); 
}

此外,在 callApi 函数中,每次接收到一些数据时,都会为块变量分配一个新值。您应该将接收到的数据添加到变量的当前值(只需在等号前添加一个“+”):

res.on('data', (d) => {
    chunk += d;
});