在Dialogflow Fulfillment中使用第三方API

Geo*_*ong 6 node.js firebase google-cloud-functions actions-on-google dialogflow-es

我有一个Dialogflow代理,我正在使用内联编辑器(由Firebase的Cloud Functions提供支持).当我尝试在Intent处理程序中嵌入HTTPS GET处理程序时,它会与日志条目"忽略已完成的函数中的异常"崩溃.也许有更好的方法来实现承诺,但我是新手.我可以看到它确实在升级到Blaze计划后执行外部查询,因此它不是计费帐户的限制.无论如何,这是代码:

'use strict';

const functions = require('firebase-functions');
//const rp = require('request-promise');
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 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?`);
  }

  function findWidget(agent) {

    const https = require("https");
    const url = "https://api.site.com/sub?query=";

    agent.add(`Found a widget for you:`);

    var widgetName = getArgument('Name');

    https.get(url + widgetName, res => {
      res.setEncoding("utf8");
      let body = "";
      res.on("data", data => {
        body += data;
      });
      res.on("end", () => {

        body = JSON.parse(body);

        agent.add(new Card({
            title: `Widget ` + body.name,
            text: body.description,
            buttonText: 'Open link',
            buttonUrl: body.homepage
          })
        );
      });
    });  
  }

// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Find Old Movie Intent', findOldMovie);
intentMap.set('Find Movie Intent', findMovie);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
Run Code Online (Sandbox Code Playgroud)

Pri*_*ner 7

不仅仅是有一种"更好"的方式来使用Promises - agent.handleRequest()如果你有任何异步调用的代码,则需要使用Promises.问题是您的findWidget函数在https.get完成运行之前返回,因此回复不会最终被发送.

我倾向于使用request-promise-native包来进行HTTP调用,因为它简化了很多事情.(但是,您可以自己将调用包装在Promise中.)因此,Promise版本可能看起来像这样(未经测试):

  var findWidget = function(agent) {

    const request = require('request-promise-native');
    const url = "https://api.site.com/sub?query=";

    agent.add(`Found a widget for you:`);

    var widgetName = getArgument('Name');

    return request.get( url+widgetName )
      .then( jsonBody => {
        var body = JSON.parse(jsonBody);
        agent.add(new Card({
          title: `Widget ` + body.name,
          text: body.description,
          buttonText: 'Open link',
          buttonUrl: body.homepage
        }));
        return Promise.resolve( agent ); 
      });
    });  
  }
Run Code Online (Sandbox Code Playgroud)

  • 你可以在 https://github.com/dialogflow/dialogflow-fulfillment-nodejs/blob/master/src/dialogflow-fulfillment.js 看到 `handleRequest()` 的代码,它会在那里得到响应,如果响应是不是承诺,它使它成为一个承诺。当承诺完成时,它会发送已设置的内容。因此,如果您正在执行异步操作,则需要在承诺中执行它们。 (2认同)