最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用get方法从Dialog Flow调用API?

运维笔记admin16浏览0评论

如何使用get方法从Dialog Flow调用API?

如何使用get方法从Dialog Flow调用API?

我的问题是关于在Webhook中使用API​​。我使用此代码使用ngrok从我的localhost调用外部API。我也尝试了Using 3rd party API within Dialogflow Fulfillment,但仍然不适合我的情况。这是我的代码 -

'use strict';

var https = require ('https');

const functions = require('firebase-functions');

const {WebhookClient} = require('dialogflow-fulfillment');

const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug';

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 get_products(agent){
  var url = '';
  https.get(url, function(res){
    var body = '';
    res.on('data', function(chunk){
      body += chunk;
    });
    res.on('end', function(){
     var respose_jquery = JSON.parse(body);
     agent.add("Got a response: ", respose_jquery.product_name);
    });
  }).on('error', function(e){
    agent.add("Got an error: ", e);
  });   
}

let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('show_products', get_products);
agent.handleRequest(intentMap);

});
回答如下:

问题是对话框实现库假设您在执行任何异步功能时将返回Promise,例如get_products()函数中的https调用。

虽然您可以将代码包装在返回Promise的内容中,但最简单的方法是使用类似request-promise-native库的内容。它可能看起来像这样(未经测试):

const rp = require('request-promise-native');

function get_products(agent){
  var url = 'https://705861b5.ngrok.io/products';
  var options = {
    uri: url,
    json: true
  };
  return rp.get( options )
    .then( body => {
      agent.add("Got a response: "+body.product_name);
    })
    .error( err => {
      agent.add("Got an error: " + e);
    });
}
发布评论

评论列表(0)

  1. 暂无评论