我正在以用户询问特定用户位置的方式进行firebase和alexa集成,alexa将存储该用户并将其与firebase用户进行比较。如果用户匹配,它将转到LocationData进行特定匹配,并从那里获取纬度和经度,并回复“UserName location is *******”。我的函数是用nodejs编写的:
'use strict';
var firebase = require('firebase');
var NodeGeocoder = require('node-geocoder');
var options = {
provider: 'google',
// Optional depending on the providers
httpAdapter: 'https', // Default
apiKey: 'AIzaSyAzXrVTbsfiBK19SxvJP5b8pJErfhKahcw ', // for Mapquest, OpenCage, Google Premier
formatter: null // 'gpx', 'string', ...
};
var geocoder = NodeGeocoder(options);
/**
* This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
* The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as
* testing instructions are located at http://amzn.to/1LzFrj6
*
* For additional samples, visit the Alexa Skills Kit Getting Started guide at
* http://amzn.to/1LGWsLG
*/
if(firebase.apps.length == 0) {
firebase.initializeApp({
serviceAccount: "************",
databaseURL: "****************"
});
}
function getLocationFromSession(intent, session, callback)
{
const FirstNameSlot = intent.slots.FName;
const firstName = FirstNameSlot.value;
const LastNameSlot = intent.slots.LName;
const lastName = LastNameSlot.value;
const fullName = firstName+" "+lastName;
const FullName = fullName.toLowerCase();
var rootRef2 = firebase.database().ref().child("ProfileData");
rootRef2.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.val();
var name = childKey.DisplayName.toLowerCase();
var key = childSnapshot.key;
if(name==FullName)
{
var query = firebase.database().ref('/LocationData').orderByKey().equalTo(key);
query.on( 'value', data => {
data.forEach(userSnapshot => {
var user = userSnapshot.val();
var latitude = user.Latitude;
var longitude = user.Longitude;
console.log(latitude);
geocoder.reverse({lat: latitude, lon: longitude})
.then(function(res) {
const repromptText = null;
const sessionAttributes = {};
let shouldEndSession = true;
let speechOutput = FullName+" location is "+res[0]['formattedAddress'];
callback(sessionAttributes,buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
firebase.database().goOffline();
}).catch(function(err) {
console.log(err);
});
});
});
// if ends here
}
});
});
}
// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `SessionSpeechlet - ${title}`,
content: `SessionSpeechlet - ${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '1.0',
sessionAttributes,
response: speechletResponse,
};
}
// --------------- Functions that control the skill's behavior -----------------------
function getWelcomeResponse(callback) {
// If we wanted to initialize the session to have some attributes we could add those here.
const sessionAttributes = {};
const cardTitle = 'Welcome';
const speechOutput = 'Welcome to the Alexa Skills Kit sample. ' +
"Please ask me location of a user by saying , for example whats alex location";
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
const repromptText = 'Please ask me location of a user by saying, ' +
"for example whats alex location";
const shouldEndSession = false;
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
function handleSessionEndRequest(callback) {
const cardTitle = 'Session Ended';
const speechOutput = 'Thank you for trying the Alexa Skills Kit sample. Have a nice day!';
// Setting this to true ends the session and exits the skill.
const shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
function createContactAttributes(contactInfo) {
return {
contactInfo,
};
}
/**
* Sets the contact in the session and prepares the speech to reply to the user.
*/
// --------------- Events -----------------------
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}
/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);
// Dispatch to your skill's launch.
getWelcomeResponse(callback);
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'MyContactIsIntent') {
setContactInSession(intent, session, callback);
} else if (intentName === 'WhatsMyLocationIntent') {
getLocationFromSession(intent, session, callback);
} else if (intentName === 'AMAZON.HelpIntent') {
getWelcomeResponse(callback);
} else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
handleSessionEndRequest(callback);
} else {
throw new Error('Invalid intent');
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
// Add cleanup logic here
}
// --------------- Main handler -----------------------
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function(event, context, callback) {
try {
console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);
/**
* Uncomment this if statement and populate with your skill's application ID to
* prevent someone else from configuring a skill that sends requests to this function.
*/
/*
if (event.session.application.applicationId !== 'amzn1.echo-sdk-ams.app.[unique-value-here]') {
callback('Invalid Application ID');
}
*/
if (event.session.new) {
onSessionStarted({ requestId: event.request.requestId }, event.session);
}
if (event.request.type === 'LaunchRequest') {
onLaunch(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'IntentRequest') {
onIntent(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'SessionEndedRequest') {
onSessionEnded(event.request, event.session);
callback();
}
} catch (err) {
callback(err);
}
};
我面临的唯一问题是关于alexa的输出,第一次当我询问用户位置时,它提供了正确的输出,但是当我问其他用户位置时,它说:
response is invalid
在日志中说:
START RequestId: fb182526-032b-11e7-b3ca-7556a3a89f6c Version: $LATEST
2017-03-07T11:48:29.621Z fb182526-032b-11e7-b3ca-7556a3a89f6c
event.session.application.applicationId=amzn1.ask.skill.[unique-value-
here]2017-03-07T11:48:29.621Z fb182526-032b-11e7-b3ca-7556a3a89f6c
onSessionStarted requestId=amzn1.echo-api.request.[unique-value-here],
sessionId=amzn1.echo-api.session.[unique-value-here]
2017-03-07T11:48:29.637Z fb182526-032b-11e7-b3ca-7556a3a89f6c
onLaunch requestId=amzn1.echo-api.request.[unique-value-here],
sessionId=amzn1.echo-api.session.[unique-value-here]
END RequestId: fb182526-032b-11e7-b3ca-7556a3a89f6c
REPORT RequestId: fb182526-032b-11e7-b3ca-7556a3a89f6c Duration: 18.36
ms Billed Duration: 100 ms Memory Size: 256 MB Max Memory Used: 34
MB
有人可以帮我解释一下代码,不知道它有什么不对吗?