如何从REST API输出信息

时间:2018-08-02 12:31:08

标签: node.js dialogflow actions-on-google

我想让我的经纪人说从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输出信息的另一种方法?

1 个答案:

答案 0 :(得分:2)

您的intent1函数还必须返回一个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;
});