0

所以我正在尝试使用需要外部 API 的 Dialogflow 进行谷歌操作。我一直使用 jQuery.getJSON()进行 API 调用,所以我不知道该怎么做。在网上搜索后,我找到了一种使用 vanilla javascript 的方法(我还在我的网站上测试了这种方法,效果很好)。代码如下:

function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {
      console.log(xmlhttp.responseText);
    }
  };

  xmlhttp.open("GET", "https://translate.yandex.net/api/v1.5/tr.json/translate?lang=en-es&key=trnsl.1.1.20190105T052356Z.7f8f950adbfaa46e.9bb53211cb35a84da9ce6ef4b30649c6119514a4&text=eat", true);
  xmlhttp.send();
}

该代码在我的网站上运行良好,但是一旦我将其添加到 Dialogflow,它就会给我错误

XMLHttpRequest 未定义

显然这是因为我从未定义它(使用var),除非它在我没有做任何事情的情况下工作。那么,我尝试添加这一行

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

到代码,它停止给我错误(因为我定义了 XMLHttpRequest)。但是,我的代码不起作用。

TL;DR:如何使用 Dialogflow 实现进行外部 API 调用?

4

2 回答 2

1

您可以使用https. 但请确保您升级到 Blaze Pay(或任何其他计划)以进行外部 API 调用,否则您将收到错误消息,例如

Error:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions.

进行外部api调用的代码,

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
"use strict";

const functions = require("firebase-functions");
const { WebhookClient } = require("dialogflow-fulfillment");
const { Card, Suggestion } = require("dialogflow-fulfillment");
const https = require("https");

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 getWeather() {
      return weatherAPI()
        .then(chat => {
          agent.add(chat);
        })
        .catch(() => {
          agent.add(`I'm sorry.`);
        });
    }

    function weatherAPI() {
      const url =
        "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";

      return new Promise((resolve, reject) => {
        https.get(url, function(resp) {
          var json = "";
          resp.on("data", function(chunk) {
            console.log("received JSON response: " + chunk);
            json += chunk;
          });

          resp.on("end", function() {
            let jsonData = JSON.parse(json);
            let chat = "The weather is " + jsonData.weather[0].description;
            resolve(chat);
          });
        });
      });
    }

    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?`);
    }

    let intentMap = new Map();
    intentMap.set("Default Welcome Intent", welcome);
    intentMap.set("Default Fallback Intent", fallback);
    intentMap.set("Weather Intent", getWeather);
    agent.handleRequest(intentMap);
  }
);
于 2019-03-05T09:00:16.707 回答
0

这篇文章是钻石!它确实有助于澄清 Dialogflow fullfilments 中发生了什么以及需要什么。

一个小建议是优雅地捕捉到 web 服务连接中的错误:

      function weatherAPI() {
        const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";

        return new Promise((resolve, reject) => {

            https.get(url, function(resp) {
                var json = "";
                resp.on("data", function(chunk) {
                    console.log("received JSON response: " + chunk);
                    json += chunk;
                });

                resp.on("end", function() {
                    let jsonData = JSON.parse(json);
                    let chat = "The weather is " + jsonData.weather[0].description;
                    resolve(chat);
                });

            }).on("error", (err) => {
                reject("Error: " + err.message);
            });

        });
      }
于 2019-06-21T06:57:20.973 回答