Alexa skill for asking questions - alexa

I am developing Alexa skill in which I have few questions. For two of the questions (Q1, Q2) Alexa is answering the correct answer (Answer1, Answer2) but for the other questions (Q3, Q4) it is answering (Answer1, Answer2).
Here is my code:
'use strict';
var APP_ID = ' ';
var CLIMATE_OUTPUT = 'Bangalore has a tropical savanna climate with distinct wet and dry seasons.';
var BENGALURU_DETAILS_OUTPUT = 'Bangalore, officially known as Bengaluru, is the capital of the Indian state of Karnataka. ';
var POPULATION_OUTPUT = 'It has a population of over ten million';
var POLLUTION_OUTPUT = 'Bangalore generates about 3,000 tonnes of solid waste per day';
var skill = require('./Skill.js');
var Service = function() {
skill.call(this, APP_ID);
};
Service.prototype = Object.create(skill.prototype);
var detailsResponseFunction = function(intent, session, response) {
response.tell(BENGALURU_DETAILS_OUTPUT);
};
var populationResponseFunction = function(intent, session, response) {
response.tell(POPULATION_OUTPUT);
};
var climateResponseFunction = function(intent, session, response) {
response.tell(CLIMATE_OUTPUT);
};
var pollutionResponseFunction = function(intent, session, response) {
response.tell(POLLUTION_OUTPUT);
};
Service.prototype.intentHandlers = {
'bengaluruDetails': detailsResponseFunction,
'population': populationResponseFunction,
'climate': climateResponseFunction,
'pollution': pollutionResponseFunction
};
exports.handler = function(event, context) {
var service = new Service();
service.execute(event, context);
};

The way of questioning was wrong. For any custom skill we have to ask questions like---"ask {invocation name} {question}.

Related

Facebook messenger that sends a message manually if the user subscribed

I'm making a bot that let my students get a school meal menu. I'd like it to send a list of menu to students 10 minutes before the lunch time.
How should I make a code for this in JavaScript?
The main problem I encountered with was how to check the time so that my bot can send a message at that time.
I also wonder if its code always runs on the Facebook server, so I can use while loop that always check a time.
I'd appreciate an advice. (I use MongoDB and node)
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var hey = ["Yeah! 😃"]
var reply;
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
app.get("/", function (req, res) {
res.send("Deployed!");
});
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
if (data.object === 'page') {
if(d.getHours() === 10 && d.getMinutes() === 5)
sendTextMessage(senderID, "Success!");
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if(event.postback){
receivedPostback(event);
}
else {
console.log("Webhook received unknown event: ", event);
}
});
});
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
psid = senderID;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
switch (messageText) {
case 'Check':
sendTextMessage(senderID, "isSub: " + isSub);
sendTextMessage(senderID, "gamerNumber: " + gamerNumber);
sendTextMessage(senderID, "psid: " + senderID);
break;
----(and more)
function sendGenericMessage(recipientId, payload) {
var titlee
var subs
var image
switch(payload){
case "pmorning":
titlee = "Breakfast"
subs = //***this is the part where the db value goes in.***
image = "https://cdn.arstechnica.net/wp-content/uploads/sites/3/2016/10/Oculus-Rift-vs-HTC-Vive-vs-PlayStation-VR-1.jpg"
break;
---and more
}]
}]
}
}
}
};
sendTypingOn(recipientId);
callSendAPI(messageData);
}
Take a look at node-cron, which enables you to schedule jobs for running at specific times, specified by a CRON expression

creating a service which holds values to be updated later with separate controllers

I am trying to create a service which holds values that I want to be able to update from other controllers. It's a fake financial tracker which allows me to update the values in this service. I can't get it to work and I know I may be setting it up incorrectly. Can someone help me out with this?
My code:
(function () {
"use strict";
var Bkbank = angular.module('Bkbank' []);
Bkbank.controller('dashboardCtlr', function ($scope, dashboardSrvs) {
/*User Data*/
$scope.userName = dashboardSrvs.userName;
$scope.acctNum = dashboardSrvs.acctNum;
$scope.startDate = dashboardSrvs.startDate;
$scope.checkingsTotal = dashboardSrvs.checkingsTotal;
$scope.savingsTotal = dashboardSrvs.savingsTotal;
$scope.investTotal = dashboardSrvs.investTotal;
$scope.ouncesUpdate = dashboardSrvs.ouncesUpdate;
$scope.debtBalance = dashboardSrvs.debtBalance;
$scope.goldSpot = dashboardSrvs.goldSpot;
/*Section Titles*/
$scope.userTitle = dashboardSrvs.userTitle;
$scope.servicesTitle = dashboardSrvs.servicesTitle;
$scope.checkingsTitle = dashboardSrvs.checkingsTitle;
$scope.savingsTitle = dashboardSrvs.savingsTitle;
$scope.investTitle = dashboardSrvs.investTitle;
$scope.debtTitle = dashboardSrvs.debtTitle;
$scope.savingsUpdateTitle = dashboardSrvs.savingsUpdateTitle;
});
Bkbank.service('dashboardSrvs', function () {
/*User Data*/
this.userName = "Tim Willson";
this.acctNum = 554887;
this.startDate = "01/12/75";
this.checkingsTotal = "56458.00";
this.savingsTotal = "98187.00";
this.investTotal = "34143.00";
this.ouncesUpdate = "30";
this.debtBalance = "10000.00";
this.goldSpot = "1138.10";
/*Section Titles*/
this.userTitle = "User";
this.servicesTitle = "Financial Services";
this.checkingsTitle = "Checkings";
this.savingsTitle = "Savings";
this.investTitle = "Investments";
this.debtTitle = "debt";
this.savingsUpdateTitle = "Update Savings Account";
});
}());
I am not fully clear with the question you have asked but what I understood is you want to get/set attribute values into service so that updates available to all the consumer controller(s). In such scenario you can create service as e.g.
app.service('dashboardSrvs', function() {
var userName = "Tim Willson"; //Set some default Value
return {
get userName() {
return userName;
},
set userName(val) {
userName = val;
}
}
});
And inside the controller you can update the userName as -
testService.userName = 'Mike Tyson';
Angular merge to the rescue!
I advise you in advance to read this great article about Angular copy / extend / merge objects. Article link here
var demoApp = angular.module("demoApp", []);
demoApp.service("dashboardService", function () {
var configObj = {
"userData": {
"userName": "A",
"acctNum": "B",
"startDate": "C"
}
};
return configObj;
});
demoApp.controller("appController", function ($scope, dashboardService) {
// Override the new values of the service with a new object
var newConfigValues = {
"userData": {
"userName": "X",
"acctNum": "Z"
}
};
var newConfigObj = angular.merge({}, dashboardService, newConfigValues);
console.log(newConfigObj); // "userName": "X", "acctNum": "Z", "startDate": "C"
});
As you can see, you can override all or just some values. If you do the latter, the original values in your service will be kept.
JSFiddle here

Multiple Queries with Parse Cloud Code Using Promises

I have two questions:
Is the below example the right way to execute multiple Parse queries in a single Cloud Code function?
Is the below example going to provide all the data I'm querying with one HTTP request (when I call logbookEntries) and then count as two Parse requests on my account because it's two Parse queries?
Here's the code:
Parse.Cloud.define("logbookEntries", function(request, response) {
//::: Query 1 :::
var firstQuery = new Parse.Query("Logbook");
var returnData = [];
firstQuery.find().then(function(firstResults) {
returnData[0] = firstResults;
}).then(function(result) {
//::: Query 2 :::
var secondQuery = new Parse.Query("Logbook");
secondQuery.find().then(function(secondResults))
returnData[1] = secondResults;
}).then(function(result) {
response.success(returnData);
}, function(error) {
response.error(error);
});
});
Thanks in advance.
It's one way, though not quite correct.
Yes
Your code should really be:
Parse.Cloud.define("logbookEntries", function(request, response) {
//::: Query 1 :::
var firstQuery = new Parse.Query("Logbook");
var returnData = [];
firstQuery.find().then(function(firstResults) {
returnData[0] = firstResults;
var secondQuery = new Parse.Query("Logbook");
return secondQuery.find();
}).then(function(result) {
returnData[1] = result;
response.success(returnData);
}, function(error) {
response.error(error);
});
});
Or, a better way to structure it would be:
Parse.Cloud.define("logbookEntries", function(request, response) {
var firstQuery = new Parse.Query("Logbook");
var secondQuery = new Parse.Query("Logbook");
var promises = [];
promises.push(firstQuery.find());
promises.push(secondQuery.find());
Parse.Promise.when(promises).then(function(result1, result2) {
var returnData = [];
returnData[1] = result1;
returnData[2] = result2;
response.success(returnData);
}, function(error) {
response.error(error);
});
}
Just to update Wain's structured code:
Promise.when returns array when supplied with an array, so the correct code would be
Parse.Promise.when(promises).then(function([result1, result2]) {
and since there is no need to repack the array, it would simply be
Parse.Promise.when(promises).then(function(result) {
response.success(result);
See here for more info.

authwithcustomtoken not working

In my project I am writing e2e tests in node.js and I have a test firebase I am using. So I create a token in node before each describe in the test runs and then I send it to the front end(angular.js) and then I use the authWithCustomToken function to authenticate the person.
The problem is for some reason it isn't even calling the function because I put a console.log statement in the callback and every time my code runs it enters the if $location.search condition but the console.log doesn't print out anything. I dont seem to know what the problem is.
var Firebase = require('firebase');
var FirebaseTokenGenerator = require('firebase-token-generator');
var rootRef = new Firebase('https://xxxxx');
var data = require('./data_helper.js');
rootRef.child('users').set(data.users[0]);
var credentials = {
nonAdmin: {
uid: 'google',
email: 'xxxx'
},
admin: {
uid: 'google',
email: 'xxxxx'
}
};
var logInAndThen = function(options) {
var secret = 'sdmdfmdsjwdsjwjwwewewe';
var tokenGenerator = new FirebaseTokenGenerator(secret);
var token = tokenGenerator.createToken(credentials[options.userType || 'admin']);
browser.get('/login?token=' + token);
var alertDiv = by.className('alert');
//browser.wait(function(){});
var waitOnFirebase = browser.wait(function() {
return browser.isElementPresent(alertDiv);
});
waitOnFirebase.then(function(data) {
console.log('-------', data);
options.cb(data);
});
};
module.exports = logInAndThen;
--------- FRONT END ANGULAR CODE PUT IN APPLICATION.RUN---------------------
if($location.search().token) {
console.log(Refs.root.toString());
Refs.root.authWithCustomToken($location.search().token, function(err, authData) {
console.log(err,authData);
}, {scope: 'email'});
}
I would appreciate it if someone could help me with this
Try getting the token like this (put this in your .run):
var loc = $location.path();
if(loc.search('login?token') > 0) {
token = loc.splice(13)
//now incorporate the 'token' into whatever auth functions you need to.
}
Not entirely sure if this is the most technically 'correct' way of grabbing the token, but it should work for you.

How do I test variables in a Angular JS factory using Jasmine

I want to test the questionsBucket in this facotry
.factory('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
var questionsBucket = answersBucket;
var questionToRemove, answers, question;
var QA = {
answers: function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
},
question: function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
}
};
return QA;
});
As you can see the questionsBucket is a variable which is not returned in the QA object, I do not want to it be exposed to anything using it.
In Ruby there are a number of ways to get this data or access private methods, but I can't see how to do it in Angular.
Here is how I'd like to write my test in Jasmine.
it('should remove a question from the questionsBucket',
inject(function(QA){
var answers = QA.answers(5);
var question = Qa.question();
//I can't access the questionBucket :(
expect(QA.questionsBucket).toEqual(4);
}));
If you want to test it in your factory, return it or return a function to get it.
.factory('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
var questionsBucket = answersBucket;
var questionToRemove, answers, question;
var QA = {
//return it-->
questionsBucket: questionsBucket,
//return a way to get it-->
getQuestionsBucket: function(){
return questionsBucket;
},
answers: function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
},
question: function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
}
};
return QA;
});
An alternative option would be to use a service instead and return questionsBucket as a member of the service:
.service('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
this.questionsBucket = answersBucket;
var questionToRemove, answers, question;
this.answers= function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
};
this.question= function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
};
});
Or - you could create another service/provider/factory and inject that into your QA service/factory:
app.service('Buckets', function(RandWords){
this.answers = RandWords.get(9);
this.questions = answersBucket;
});
app.service('QA', function(ShuffleArray, Buckets){
this.answersBucket = Buckets.answers;
this.questionsBucket = Buckets.questions;
/*all the rest here - omitted for brevity*/
});

Resources