Google Action Webhook Inline Editor Returns Before the API call - actions-on-google

This is my first Google Action project. I have a simple slot after the invocation. User enters the value on prompt and slot invokes the webhook and make a call to API using the user input. All works fine. However the webhook returns to users even before the API call finish processing and returns the value (line 1 conv.add). I do see in the logs that everything from API is logged fine after the webhook returns to user. Below is the code I am using. I am using inline editor. What am I missing? Thanks for help in advance.
const { conversation } = require('#assistant/conversation');
const functions = require('firebase-functions');
var https = require('https');
const fetch = require('node-fetch');
const app = conversation({debug: true});
app.handle('SearchData', conv => {
const body = JSON.stringify({
val: "this is my body"
});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Auth' : 'MyAuthCreds'
};
fetch('https://host.domain.com/data', {
method: 'post',
body: body,
headers: postheaders,
})
.then(res => res.json())
.then(d => {
console.log(d);
var profile = d;//JSON.parse(d);
console.log(d.entries);
console.log("Length: "+ d.entries.length);
if(d.entries.length > 0)
{
console.log("Data found");
conv.add("Data found"); //line 1
}
else
{
console.log("no data found");
conv.add("no data found"); //line 1
}
})
.catch(function (err) {
// POST failed...
console.log(err);
});
});
exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);

Your issue is that your handler is making API calls which are asynchronous, but the Assistant Conversation library doesn't know that you're doing so. So as soon as the handler finishes, it tries to send back a response, but your asynchronous responses (the stuff in the then() blocks) haven't executed yet.
To address this, you need to return a Promise object so the library knows to wait till the Promise is fulfilled before it returns.
Fortunately, in your case, this should be pretty straightforward. fetch and all the .then() blocks return a Promise. So all you need to do is add a return statement in front of the call to fetch. So something like this:
return fetch('https://host.domain.com/data', {

Related

What is correct way to respond from webhook running nodejs?

Trying to implement web-hook (with V2 dialogflow) running nodejs. Received response "MalformedResponse 'final_response' must be set.". Below is the code. To the end of POST (app.post) code block was expecting conv.close would send SimpleResponse. But that's not happening. Need help understand why this error is seen and probable direction to solve it.
Thanks
const express = require('express');
const {
dialogflow,
Image,
SimpleResponse,
} = require('actions-on-google')
const bodyParser = require('body-parser');
const request = require('request');
const https = require("https");
const app = express();
const Map = require('es6-map');
// Pretty JSON output for logs
const prettyjson = require('prettyjson');
const toSentence = require('underscore.string/toSentence');
app.use(bodyParser.json({type: 'application/json'}));
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
console.log("Received GET request..!!");
//response.sendFile(__dirname + '/views/index.html');
response.end("Response from my server..!!");
});
// Handle webhook requests
app.post('/', function(req, res, next) {
console.log("Received POST request..!!");
// Log the request headers and body, to aide in debugging. You'll be able to view the
// webhook requests coming from API.AI by clicking the Logs button the sidebar.
console.log('======Req HEADERS================================================');
logObject('Request headers: ', req.headers);
console.log('======Req BODY================================================');
logObject('Request body: ', req.body);
console.log('======Req END================================================');
// Instantiate a new API.AI assistant object.
const assistant = dialogflow({request: req, response: res});
// Declare constants for your action and parameter names
//const PRICE_ACTION = 'price'; // The action name from the API.AI intent
const PRICE_ACTION = 'revenue'; // The action name from the API.AI intent
var price = 0.0
// Create functions to handle intents here
function getPrice(assistant) {
console.log('** Handling action: ' + PRICE_ACTION);
let requestURL = 'https://blockchain.info/q/24hrprice';
request(requestURL, function(error, response) {
if(error) {
console.log("got an error: " + error);
next(error);
} else {
price = response.body;
logObject('the current bitcoin price: ' , price);
// Respond to the user with the current temperature.
//assistant.tell("The demo price is " + price);
}
});
}
getPrice(assistant);
var reponseText = 'The demo price is ' + price;
// Leave conversation with SimpleResponse
assistant.intent(PRICE_ACTION, conv => {
conv.close(new SimpleResponse({
speech: responseText,
displayText: responseText,
}));
});
}); //End of app.post
// Handle errors.
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Oppss... could not check the price');
})
// Pretty print objects for logging.
function logObject(message, object, options) {
console.log(message);
console.log(prettyjson.render(object, options));
}
// Listen for requests.
let server = app.listen(process.env.PORT || 3000, function () {
console.log('Your app is listening on ' + JSON.stringify(server.address()));
});
In general, The "final_response" must be set error is because you didn't send anything back. You have a lot going on in your code, and while you're on the right track, there are a few things in the code that could be causing this error.
First - in the code, it looks like you are confused about how to send a response. You have both a call to conv.close() and the commented out assistant.tell(). The conv.close() or conv.ask() methods are the way to send a reply using this version of the library. The tell() method was used by a previous version and is no longer supported.
Next, your code looks like it is only setting up the assistant object when the routing function is called. While this can be done, it is not the usual way to do it. Typically you'll create the assistant object and setup the Intent handlers (using assistant.intent()) as part of the program initialization. This is a rough equivalent to setting up the express app and the routes for it before the request itself comes in.
The portion that sets up the Assistant and then hooks it into a route might look something like this:
const assistant = dialogflow();
app.post('/', assistant);
If you really wanted to examine the request and response objects first, you might do this as something like
const assistant = dialogflow();
app.post('/', function( req, res ){
console.log(JSON.stringify(req.body,null,1));
assistant( req, res );
});
Related to this appears to be that you're trying to execute code in the route handler and then trying to call the intent handler. Again, this might be possible, but isn't the suggested way to use the library. (And I haven't tried to debug your code to see if there are problems in how you're doing it to see if you're doing it validly.) More typical would be to call getPrice() from inside the Intent handler instead of trying to call it from inside the route handler.
But this leads to another problem. The getPrice() function calls request(), which is an asynchronous call. Async calls are one of the biggest problems that causes an empty response. If you are using an async call, you must return a Promise. The easiest way to use a Promise with request() is to use the request-promise-native package instead.
So that block of code might look something (very roughly) like this:
const rp = require('request-promise-native');
function getPrice(){
return rp.get(url)
.then( body => {
// In this case, the body is the value we want, so we'll just return it.
// But normally we have to get some part of the body returned
return body;
});
}
assistant.intent(PRICE_ACTION, conv => {
return getPrice()
.then( price => {
let msg = `The price is ${price}`;
conv.close( new SimpleResponse({
speech: msg,
displayText: msg
});
});
});
The important thing to note about both getPrice() and the intent handler are that they both return a Promise.
Finally, there are some odd aspects in your code. Lines such as res.status(500).send('Oppss... could not check the price'); probably won't do what you think they will do. It won't, for example, send a message to be spoken. Instead, the Assistant will just close the connection and say that something went wrong.
Many thanks to #Prisoner. Below is the V2 working solution based on above comments. Same has been verified on nodejs webhook (without firebase). V1 version of the code was referenced from https://glitch.com/~aog-template-1
Happy coding..!!
// init project pkgs
const express = require('express');
const rp = require('request-promise-native');
const {
dialogflow,
Image,
SimpleResponse,
} = require('actions-on-google')
const bodyParser = require('body-parser');
const request = require('request');
const app = express().use(bodyParser.json());
// Instantiate a new API.AI assistant object.
const assistant = dialogflow();
// Handle webhook requests
app.post('/', function(req, res, next) {
console.log("Received POST request..!!");
console.log('======Req HEADERS============================================');
console.log('Request headers: ', req.headers);
console.log('======Req BODY===============================================');
console.log('Request body: ', req.body);
console.log('======Req END================================================');
assistant(req, res);
});
// Declare constants for your action and parameter names
const PRICE_ACTION = 'revenue'; // The action name from the API.AI intent
var price = 0.0
// Invoke http request to obtain blockchain price
function getPrice(){
console.log('getPrice is invoked');
var url = 'https://blockchain.info/q/24hrprice';
return rp.get(url)
.then( body => {
// In this case, the body is the value we want, so we'll just return it.
// But normally we have to get some part of the body returned
console.log('The demo price is ' + body);
return body;
});
}
// Handle AoG assistant intent
assistant.intent(PRICE_ACTION, conv => {
console.log('intent is triggered');
return getPrice()
.then(price => {
let msg = 'The demo price is ' + price;
conv.close( new SimpleResponse({
speech: msg,
}));
});
});
// Listen for requests.
let server = app.listen(process.env.PORT || 3000, function () {
console.log('Your app is listening on ' + JSON.stringify(server.address()));
});

Nuxt Axios Module read status code

I'm calling a Rest API that returns at least 2 success status codes .
A normal 200 OK and a 202 Accepted status code.
Both return a Content in the body.
If I execute in postman my calls I might get something like
Status code: 202 Accepted. With Body "Queued" or some other values
or
Status code: 200 OK. With Body "ValueOfSomeToken"
Making the call with axios in my nuxt app:
this.$axios.$get('/Controller/?id=1')
.then((response)=>{
if(response=='Queued'){
//Do something
}
else if (response=='Expired'){
//Do something
}
else{
//Do something
}
})
.catch((error)=>{
console.log(error);
});
..works, but I actually would like to get the status code (because 202 has other values for the body responses)
I have no idea how to read the status codes.
I tried using (response,code) =>... but code is then nothing.
You can use non $-prefixed functions like this.$axios.get() instead of this.$axios.$get() to get the full response
// Normal usage with axios
let { data } = await $axios.get('...'));
// Fetch Style
let data = await $axios.$get('...');
(source)
You can extract the status codes from the response object in axios
if you print the response object (as shown in below image) you can see the all the objects inside the response object. One among them is status object
response.status will give you the status code that is sent from the server
axios.get("http://localhost:3000/testing").then((response)=>{
console.log("response ",response);
if(response.status == 200){
//do something
}
else if(response.status == 202){
//do something
}
else if(response.status == 301){
//do something
}
}).catch((err)=>{
console.log("err11 ",err);
})
In the server side, you can explicitly send any status code using res.status() method, for more details refer this documentation
app.get('/testing',(req, res)=> {
res.status(202).send({"res" : "hi"});
});
Update:
By default, #nuxtjs/axios returns response.data in the .then((response))
The $axios.onResponse event will have access to the complete response object.
You need to setup an interceptor to intercept the $axios.onResponse event and modify the response object
Under plugin directory create a plugin, plugin/axios.js
Update the plugins section plugins : ['~/plugins/axios']
in nuxt.config.js
export default function ({ $axios, redirect }) {
$axios.onResponse(res=>{
console.log("onResponse ", res);
res.data.status = res.status;
return res;
})
}
In the res object in this interceptor you will have the all the values (as it is shown in my first screenshot). But this res object is not returned as it is, only res.data is returned to our program.
We can update contents inside res.data and then return the res object as shown in my program res.data.status = res.status; .
Now when axios returns res.data we will have access to res.data.status value in response object in the .then((response)) promise
You can access the status using response.status inside this.$axios
this.$axios.$get("url").then((response) =>{
console.log("status ",response.status);
}).catch((err) => {
console.log("res err ",err);
});

Angular2 return data from validation service after Http call

I have build a validation service for my registration form and one of the static methods is checking if the entered email is available by calling my API the following:
static emailAvailable(control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let valid = "E-mail is available";
http.post('https://secretapi.com/email', JSON.stringify({ email: control.value }))
.map((res: Response) => res.json())
.subscribe(function(result){
if(result.success){
valid = result.success; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return null; //Doesn't do anything?
}else{
valid = result.error; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return { 'invalidEmailAddress': true }; //Doesn't do anything, just like the return above
}
});
console.log(valid); //Output always "E-mail is available"
}
It should return "null" to the form validator when the email is available. The last console.log at the bottom should output the message that it recieves in the subscribe call. This doesn't happen and I'm not sure why. For some reason everything that happens within the subscribe call is contained there and never reaches the validator. What should I change? I have no idea and been searching the web for hours now.
You have to return Observable or Promise from your validator:
return http.post('https://secretapi.com/email', ...
console.log(...) doesn't make any sense here, since it will be executed after the Observable has been created as an object, but not after the ajax call has bee made.
If you want to output something after a response has been received, you have to move it inside subscribe
So in the end this website had the right answer. Also important to notice with the Angular2 Form validator to put the Async validators in the third (3) parameter and not together in an array in the second (2) parameter. That took me about 3 hours to figure out.
function checkEmail(control: Control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
return new Observable((obs: any) => {
control
.valueChanges
.debounceTime(400)
.flatMap(value => http.post('https://secretapi.com/email', JSON.stringify({ email: control.value })))
.map((res: Response) => res.json())
.subscribe(
data => {
if(data.success){
obs.next(null);
obs.complete();
} else {
obs.next({ 'invalidEmailAddress': true });
obs.complete();
}
}
);
});
}
The validator should look something like this, with the first validators checking on required and if it's actually an email address and the last doing an async call to the server to see if it's not already in use:
this.registerForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator], ValidationService.emailAvailable],
});

Asynchronous Request to Facebook API with Redux

I am using Redux and trying to make a call to Facebook API with their JS SDK. I've only ever used promises with Redux and so since the method FB.getLoginStatus just returns a simple JS object, I'm not sure how to ensure that the payload doesn't return undefined.
With redux-promise, you add it to the applyMiddleware(ReduxPromise)... and then it ensures nothing is returned until the promise resolves. But I don't know how to do that here.
I've also used async/await functions with React Native without an issue, but I tried using them here and for some reason the code still returns the payload, before the asynchronous request (await ...) is finished. So I tried working with redux-await, but couldn't get it to work.
export function getLoginStatus() {
var res = FB.getLoginStatus(function(res) {
console.log(res);
});
console.log("res ", res);
return {
type: GET_LOGIN_STATUS,
payload: res
}
}
Hm, things can get a little tricky as I've not used redux-promise. And I can't tell exactly what else you have tried. But this would be my first shot:
async function _getLoginStatus() {
var payload = new Promise( (resolve, fail) => {
FB.getLoginStatus((res)=>resolve(res));
});
return {
type: GET_LOGIN_STATUS,
payload: payload
}
}
// Last time I exported an async function I needed this HYMMV
export let getLoginStatus = _getLoginStatus;
And then elsewhere in the code:
import {getLoginStatus} from 'whatever.js';
var payloadResult = await getLoginStatus();

FaceBook API: Get the Request Object for a request Id - logged into the account that sent the request. Using the "Requests Dialog" API

I am using the "Requests Dialog" to create Facebook requests. Inorder to get the user that the requests were sent to I need to access the Request object using the graph API. I have tried most of the permissions settings that seemed appropriate (read_requests and user_about_me) to get the request object, but instead I get a false in the response. Am I using the wrong permissions?
I am able to access the request object using the graph API from the account that the request was sent to.
http://developers.facebook.com/docs/reference/dialogs/requests/
Return Data - A comma-separated list
of the request_ids that were created.
To learn who the requests were sent
to, you should loop through the
information for each request object
identified by a request id.
I've been asking myself this question a while ago:
How to retrieve all the requests sent by me?
The answer: you can't!
You have two options:
Store the request_id returned when the user sent the request, so you can later access them and get the data you need
Knowing the receiver!
Proof of the above, you can check the friend_request table. The indexable field is the uid_to field!
This is if you want it in know Iframe mode as you don't need Iframe mode any more
function sendRequest() {
FB.ui({
method: 'apprequests',
title: 'Invite friends to join you',
message: 'Come play with me.'
},
function (res) {
if (res && res.request_ids) {
var requests = res.request_ids.join(',');
$.post('FBRequest.ashx',
{ request_ids: requests },
function (resp) { });
}
});
return false;
}
If you want to find out the user ids of the people you just sent a request to. Then this code is what you need:
var request = {
message: msg,
method: 'apprequests',
title: 'Select some of your friends'
};
FB.ui(request, function (data) {
if (data && data.request_ids) {
// Get the uid of the person(s) who was/were invited
var uids = new Array();
FB.api("/?ids=" + data.request_ids.join(), function(data2) {
for (i = 0; i<data.request_ids.length; i++) {
uids[i] = data2[data.request_ids[i]]['to']['id'];
}
# do something with uids here
});
}
});
Don't know if this helps, but here's how I handle it.
Javascript:
function sendRequest() {
FB.ui({
display: 'iframe',
method: 'apprequests',
title: 'Invite friends to join you',
message: 'Come play with me.'
},
function (res) {
if (res && res.request_ids) {
var requests = res.request_ids.join(',');
$.post('FBRequest.ashx',
{ request_ids: requests },
function (resp) { });
}
});
return false;
}
Server side (FBRequest.ashx):
// get operation and data
var ids = HttpContext.Current.Request["request_ids"];
// if we have data
if(ids != null) {
// make batch graph request for request details
var requestIds = ids.Split(',').Select(i => long.Parse(i)).ToList();
var fbApp = new FacebookWebClient([AppId],[AppSecret]);
dynamic parameters = new ExpandoObject();
parameters.ids = ids;
dynamic requests = fbApp.Get(parameters);
// cycle through graph results and do stuff
dynamic req = null;
for(int i=0;i<requestIds.Count;i++) {
try {
req = requests[requestIds[i].ToString()];
// do stuff with request, save to DB, etc.
} catch (Exception ex) {
// error in finding request, continue...
}
}
}
You can access the list of user id's as part of the return data
FB.ui({
method: 'apprequest',
message: 'Use this thing',
}, function(result){
//a list of ids are in here
result.to;
});