3

Here is the funuction I have written, the console shows the output but the final answer(in the dialogflow agent) prints only the first statement - ' You will get your stock prices here soon...'. I am trying to understand as to how do I send this value back to the dialogflow agent to be printed as a response to the user query.

function getStockprice(agent) { agent.add('Hi, you will soon see the stock prices here! God only knows how though!');

    const companyName = agent.parameters['company_name'];
    const priceType = agent.parameters['price_type'];
    const date = agent.parameters['date'];

    console.log("Company Name is: "+ companyName);
    console.log("Price Type is: "+ priceType);
    console.log("Date is: " + date);

    var tickerMap = {
        "Apple" : "AAPL",
        "Microsoft" : "MSFT",
        "IBM" : "IBM",
        "Google" : "GOOG",
        "Facebook" : "FB",
        "Amazon" : "AMZN" 
     };

    var priceMap = {
         "opening" : "open_price",
         "closing" : "close_price",
         "maximum" : "high_price",
         "minimum" : "low_price"
     };

    var stockPriceTicker = tickerMap[companyName];
    var priceTypeCode = priceMap[priceType];

    var pathString = "/historical_data?ticker="+stockPriceTicker+"&item="+priceTypeCode;

    console.log("Path String" + pathString);

    var username = "#";
    var password = "#";

    var auth = "Basic " + new Buffer(username + ":" + password).toString('base64');
    console.log('Authorizarion: ' + auth);
    var request = https.get({
        host : "api.intrinio.com",
        path : pathString,
        headers : {
            "Authorization" : auth
        }
    }, function(response) {
            var json = "";
            response.on('data', function(chunk){
                console.log("received response: " + chunk);
                json += chunk;
            });

            response.on('end', function () {
                var jsonData = JSON.parse(json);
                var stockPrice = jsonData.data[0].value;

                console.log("The stock price received is: "+ stockPrice);

                var chat = "The" + priceType + "price for" + companyName + "on"
                + date + "was" + stockPrice;

                agent.add('Here is your information. ${chat}');

            });

    });   
    agent.add('Here is your information.');
}

intentMap.set('GetStockPrice', getStockprice);

1 Answers1

2

Check the answer to the post here. You need to pass a Promise from the webhook like

function dialogflowHanlderWithRequest(agent) {
  return new Promise((resolve, reject) => {
    request.get(options, (error, response, body) => {
      JSON.parse(body)
      // processing code
      agent.add(...)
      resolve();
    });
  });
};
Abhinav Tyagi
  • 5,158
  • 3
  • 30
  • 60