代码之家  ›  专栏  ›  技术社区  ›  Aniket G

Dialogflow Fulfillment(Javascript)中的API请求

  •  0
  • Aniket G  · 技术社区  · 7 年前

    因此,我试图使用Dialogflow创建一个需要外部API的google操作。我一直使用jQuery .getJSON() 进行API调用,所以我不知道该怎么做。在网上搜索之后,我找到了一种使用香草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,它就会给我错误

    很明显那是因为我从来没有定义它(使用 var ),但我什么也没做就成功了。所以,我试着加上这一行

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

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

    TL;博士: 如何使用Dialogflow fulfillment进行外部API调用?

    0 回复  |  直到 7 年前
        1
  •  1
  •   shradha    7 年前

    你可以用 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);
      }
    );
    
        2
  •  0
  •   Mauro Lodi    7 年前

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

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