actions on google--unable to use app.tell to give response from JSON - actions-on-google

I am trying to get my webhook to return a parsed JSON response from an API. I can log it on the console, but when I try to use app.tell; it gives me: TypeError: Cannot read property 'tell' of undefined. I am basically able to successfully get the data from the API, but I'm not able to use it in a response for some reason. Thanks for the help!
[Actions.API_TRY] () {
var request = http.get(url2, function (response) {
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "",
data,
route;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
// finished transferring data
// dump the raw data
console.log(buffer);
console.log("\n");
data = JSON.parse(buffer);
route = data.routes[0];
// extract the distance and time
console.log("Walking Distance: " + route.legs[0].distance.text);
console.log("Time: " + route.legs[0].duration.text);
this.app.tell(route.legs[0].distance.text);
});
});
}

This looks to me to be more of a JavaScript scoping issue than anything else. The error message is telling you that app is undefined. Often in Actions, you find code like yours embedded in a function which is defined inside the intent handler which is passed the instance of your Actions app (SDK or Dialog Flow).

Related

parse response received from rememberCustomViewAsync from tableau javascript api

I am trying to save custom views using rememberCustomViewAsync and displaying the saved view using showCustomViewAsync, I want to parse the response received from executing rememberCustomViewAsync, it returns various details including the url of the view.
here is the code i am trying
$(document).on('click', '.new_dashboard_preference > [type="button"]', function() {
tableauViz.getWorkbook().rememberCustomViewAsync($('#dashboard_preference_name').val()).then(function(customView) {
console.log(customView.url); //this is what i am trying to access
jQuery(this).parent('form')[0].submit();
}).otherwise(function (err) {
console.log(err.message);
});
});
Can any please guide as to how the response received from rememberCustomViewAsync be parsed in javascript. Thanks.
If it is a JSON object you can use:
responseVariable = JSON.parse(responseVariable)
You can then use accessors like responseVariable.ItemYouWantToSee or array index accessors such as responseVariable[0].
To take this out of the 'click' event listener and make it a global object you can push the result to an array.

How to query firestore with the Dialogflow inline editor to get information

I am using the inline editor within Dialogflow with the aim of making queries to the database I have created within Firestore.
In short, the user requests a list of courses, I'd like the chatbot to then grab that information form the db and display that back to the user.
Below I have tried to create a function that will do this, I want to take the user input, say "Art Courses" and have my db return those results.
So far, I have created a function that is triggered when the intent is matched, like so;
function getCourses(agent){
let courseRequest = agent.parameters.courseRequest;
if (getCourses){
console.log('Here is the list you requested for ${getCourses}' + parameters.courseRequest);
return admin.firestore().collection('Course_Information').doc.where('CoureTypes').get();
}
}
Are there any notable things I need to add to my function to perform what I wish to achieve?
Thank you.
UPDATE
This code deploys fine, but when I communicate with my bot and trigger the CourseEnquiry intent, cloud Functions shows this error:
admin.collection is not a function
Whilst this seems self explanatory I can't make sure of what it means, I thought declaring const admin = require('firebase-admin');enables me to use admin.collection
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
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 getDate(agent){
var today = new Date();
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function test(agent){
agent.add("The test is successful");
}
function getCourses(agent){
// Get the database collection and document
const getCourseDoc = admin.collection('Course_Information').doc('Course_Types');
return getCourseDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data().entry);
}
return Promise.resolve('Here is the information you wanted');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
function getSubmissionDateSep(agent){
agent.add('Your next submission date is for coursework 1 is');
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Test_Test', test);
intentMap.set('CourseEnquiry', getCourses);
intentMap.set('Submission_Dates - sept', getSubmissionDateSep);
agent.handleRequest(intentMap);
});
UPDATE #2
Hey guys, still not got anywhere with this, I have tried adding:
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
According to this document but I get this error when deploying:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function.
You don't show how you're responding to the user with your results, but you'll want to make sure you handle that as part of the then() clause in a Promise. Since the get() in the firestore collection returns a Promise, and you are returning it from your function, you need to make sure that the calling function treats it as a Promise, has a then() clause, and sends back the result as part of something inside this clause.

GWT JSNI returning string from JSNI function

EDIT I think because it is an asychronous call that when I call the method data has not been set yet.
String theData = getData("trainer") // not set yet
I have the following JSNI function. The if I call this function it returns an empty string, however the console.log before it show that data is there. Seems data cannot be returned for some reason.
public native String getData(String trainerName)/*-{
var self = this;
$wnd.$.get( "http://testdastuff.dev/trainerstats", { trainer: trainerName} )
.fail(function() {
$wnd.console.log("error");
})
.done(function( data ) {
console.log("DATA IS: " + data);
return data;
});
}-*/;
Your thought that it is a asynchronous call is correct.
The return of the callback passed to done is not returned to the original call you made.
If you used the following code, you'll get 2 messages in the console, in the first you'll get empty data, and in the second, the correct data.
String theData = getData("trainer");
consoleLog("The data is " + theData);
// suppose consoleLog as a native function to console.log
Thus you should probably do your callback like this.
.done(function( data ) {
console.log("DATA IS: " + data);
theData = data; // if theData is within the same scope and you want to store
doSomethingWith(theData); // <-- here you can interact with theData
})
The doSomethingWith(theData) could even be an invocation to a Java method.

hello, is there a way for consuming a Rest service in an app for windows 8.1 using WinJS?

hello I'm trying to consume a REST service in an app for windows 8.1, I'm so gratefull if you can give me more information related about this topic, thanks !!
You could use the XMLHttpRequest object. But, since you are using WinsJS, the WinJS.xhr function would be more convenient.
Here's an example on how to use it:
(function () {
"use strict";
var app = WinJS.Application;
app.onactivated = function (args) {
// Change RSS feed URL as you need to.
var resDiv = document.getElementById("divResult"),
rssURL = "http://blogs.windows.com/windows/b/appbuilder/rss.aspx";
// Call WinJS.xhr to retrieve an XML feed from the Web.
WinJS.xhr({
url: rssURL,
responseType: "document"
}).done(
// When the result has completed, check the status.
function completed(result) {
if (result.status === 200) {
// Get the XML document from the results.
var xmlDocument = result.responseXML,
title = xmlDocument.getElementsByTagName('title')[0];
// Update the HTML in the app.
resDiv.style.backgroundColor = "lightGreen";
resDiv.innerText = "Downloaded RSS feed from the " + title.textContent + " blog.";
}
});
};
app.start();
})();

Not able to update data of ParseUser class in Unity3D using Javascript

I am using this code to update data of a Parse User, but the data is not updating nor am I able to retrieve the data.
I am able to do update and retrieve the data for a ParseObject class created by me. Can someone tell me where I am wrong on this?
Out of all the debugs I have set I am able to see only the 1st debug "parse GetSync function passed" and the rest are not printing.
var parseUser: ParseUser;
function FBtoParse(){
var query = ParseUser.Query;
query.GetAsync("Q0D9eBvRee").ContinueWith(GetSync);
Debug.Log("parse GetSync function passed");
Debug.Log("Object ID: "+ parseUser["objectId"]);
Debug.Log("username is : "+ parseUser["username"]);
Debug.Log("User Updated");
}
var GetSync = function (t:System.Threading.Tasks.Task.<ParseUser>){
parseUser = t.Result;
};
function OnGUI{
if (GUILayout.Button("Parse"))
{
FBtoParse();
Debug.Log("Pressed Parse");
}
}
Parse at the moment only allows ParseUsers to update their own object through authentication.
https://parse.com/docs/js/guide#users-security-for-user-objects