dialogflow代理不从HTTP请求回调中输出文本

时间:2018-05-28 06:29:56

标签: node.js httprequest dialogflow

我正在尝试从欢迎意图触发的外部网站获取数据。现在我正在尝试向GET发送一个简单的google.com请求。

代理按预期工作,除非从请求回调中调用。它有时会起作用,有时甚至不起作用。

'use strict';    
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; 

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function search(agent){

          var request = require("request");
          var options = {
            method: 'GET',
            url: 'http://google.com'
          };

          console.log("Before request");
          agent.add("Before request");

          request(options, function (error, response, body){
            console.log("Request completed");
            agent.add("Request completed");     //<- This line doesn't show in agent
            console.log("finished");            //<- This line shows in the log
          });

          console.log("Request sent");
          agent.add(`Request sent`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', search);
  agent.handleRequest(intentMap);
});

我在日志中注意到消息"Function execution took 1697 ms, finished with status code: 200"在消息"finished"之前显示。我不知道这是否意味着流程正在关闭并忽略了agent.add()之后的调用。

Image: firebase log console showing function excecution finished before request compelted

1 个答案:

答案 0 :(得分:3)

问题在于回调/承诺。 您需要在搜索功能中返回一个承诺。

function search(agent, query){
    return new Promise((resolve, reject) => {
      request.get(options, (error, response, body) => {
      .....
      agent.add(...)
      resolve();
     });
   });
};

原始答案可以在以下Github问题中找到:

https://github.com/dialogflow/dialogflow-fulfillment-nodejs/issues/3

修改

得到DialogFlow支持人员的一些帮助。我提议的代码缺少一些正常工作:

function search(agent, query){
  return new Promise((resolve, reject) => {
    request.get(options, (error, response, body) => {
      .....
      let output = agent.add(...)
      resolve(output);  //<- agent.add() should be passed as argument in resolve()
    });
  });
};