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

时间:2019-03-09 16:51:11

标签: node.js api dialogflow

我的问题是有关 Webhook 中API的使用。我使用此代码使用ngrok从本地主机调用外部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://705861b5.ngrok.io/products';
  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);

});

1 个答案:

答案 0 :(得分:0)

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

尽管您可以将代码包装在返回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);
    });
}