在Dialogflow实现中使用第三方API [英] Using 3rd party API within Dialogflow Fulfillment

查看:163
本文介绍了在Dialogflow实现中使用第三方API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a Dialogflow agent for which I'm using the Inline Editor (powered by Cloud Functions for Firebase). When I try to embed an HTTPS GET handler within the Intent handler, it crashes with log entry "Ignoring exception from a finished function". Maybe there's a better way to do this with promises but I'm new to that. I can see that it does in fact execute the external query after upgrading to the Blaze plan so it's not a limitation of the billing account. Anyhow, here's the code:

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

推荐答案

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

It isn't just that there is a "better" way to do it with Promises - agent.handleRequest() requires you to use Promises if you have any code that is being called asynchronously. The issue is that your findWidget function is returning before the https.get finishes running, so the reply doesn't end up being sent.

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

I tend to use the request-promise-native package to do HTTP calls, since it simplifies many things. (However, you're free to wrap the call in a Promise yourself.) So the Promise version might look something like this (untested):

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

这篇关于在Dialogflow实现中使用第三方API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆