Reputation: 159
I am making app for google assistant using dialog flow. My app uses the webhook (function is deployed on firebase). The Main point is -- I want to call a REST API URL(from index.js) that returns JSON, then parse the JSON Response and extract some value. Then do some operation on that value and send the value to google assistant.
The code is below:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
const App = require('actions-on-google').DialogflowApp;
const functions = require('firebase-functions');
// a. the action name from the make_name Dialogflow intent
const SOME_ACTION = 'some_action';
//----global variables-----
const http = require('https');
var body = "";
var value="";
exports.addressMaker = functions.https.onRequest((request, response) => {
const app = new App({request, response});
console.log('Request headers: ' + JSON.stringify(request.headers));
console.log('Request body: ' + JSON.stringify(request.body));
function makeMessage (app) {
var req = http.get("https://some_url_of_API", function(res)
{
res.writeHead(200, {"Content-Type": "application/json"});
res.on("data", function(chunk){ body += chunk; });
res.on('end', function()
{
if (res.statusCode === 200) {
try {
var data = JSON.parse(body);
value=data.word; //----getting the value----
} catch (e) {
console.log('Status:', res.statusCode);
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
});
app.tell('Alright, your value is '+value);
}
let actionMap = new Map();
actionMap.set(SOME_ACTION, makeMessage);
app.handleRequest(actionMap);
});
I am able get the message "Alright, your value is", but not the value. I think it is not calling the URL.
Upvotes: 2
Views: 2084
Reputation: 50701
You have two possible issues here.
The first is that you need to be on one of the paid versions of Firebase to make URL calls outside of Google. You can be on the "blaze" plan, which does require a credit card, but still has a free level of usage.
The second is that your code calls app.tell()
outside of the callback that gets the results from your REST call. So what is happening is that you are making the call, and then immediately calling app.tell()
before you get the results.
To do what you want, you probably want something more like this:
function makeMessage (app) {
var req = http.get("https://some_url_of_API", function(res)
{
var body = '';
res.writeHead(200, {"Content-Type": "application/json"});
res.on("data", function(chunk){ body += chunk; });
res.on('end', function()
{
if (res.statusCode === 200) {
try {
var data = JSON.parse(body);
value=data.word; //----getting the value----
// Send the value to the user
app.tell('Alright, your value is '+value);
} catch (e) {
console.log('Status:', res.statusCode);
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
});
}
Upvotes: 1