根据Dialogflow Fulfillment中的API调用结果填写intent

问题描述 投票:1回答:1

我正在努力为Dialogflow提供以下完整的代码:

'use strict';
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 testHandler(agent){
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    var theUrl = "http://xxxxx/sum?a=5&b=11";
    var url = proxyurl + theUrl;
    var result = "Init";

    getText = function(url, callback)
    {
      var request = new XMLHttpRequest();
      request.onload = function()
      {
        if (request.readyState == 4 && request.status == 200)
        {
          callback(request.responseText);
        }
      };
      request.open('GET', url);
      request.send();
    }

    function mycallback(data) {
      agent.add("DATA:" + data);
    }

    return getText(url, mycallback);
  }

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

线agent.add("DATA:" + data);没有任何影响。在浏览器中尝试代码并将agent.add("DATA:" + data)更改为document.write("DATA:" + data)时,一切正常。我是Dialogflow的新手;任何暗示为什么这个回调似乎不起作用?

javascript callback dialogflow
1个回答
1
投票

在执行异步操作(例如进行网络API调用)时,您的Intent Handler必须返回Promise,因此Handler Dispatcher知道在将响应发送给用户之前等待API的响应。在您的情况下,当响应返回时,它会尝试将其发送给用户,但由于已经发送了响应(没有任何内容),所以没有人看到它。

您的Web浏览器在本地处理所有内容,因此您不会看到相同的问题(即使它正在执行相同的操作)。

虽然您可以将代码包装在Promise中,但更简单的方法是使用request-promise-native之类的方法进行HTTP调用,在agent.add()块中调用then(),然后返回总体承诺。也许是这样的事情:

  function testHandlerPromise(agent){
    const rp = require('request-promise-native');

    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    var theUrl = "http://xxxxx/sum?a=5&b=11";
    var url = proxyurl + theUrl;

    return rp( url ).then( data => {
      agent.add("DATA:" + data);
    } );
  }
© www.soinside.com 2019 - 2024. All rights reserved.