我一直在尝试通过Lambda函数使用Cloud Messaging发送推送通知。
起初,我尝试使用链接到Firebase的SNS。但是调用SNS.publish不会执行任何操作……没有错误,没有超时似乎只是忽略了该调用。这是哪里出错的摘要:
const intentName = event.request.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'Temperature') {
getPatientTemperature(intent, context,
function (internalcontext, speechOutput) {
//sns
//var outmessage = {Display: speechOutput};
var sns = new AWS.SNS({region:'us-east-1'});
//console.log(sns);
console.log('sending push');
sns.publish({
Message: speechOutput,
TopicArn: "arn:aws:sns:us-east-1:*************:MedicalAssistantDisplayUpdates",
Subject: "TestSNS"
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("SNS here 2");
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
console.log("SNS here 3");
});
context.succeed( buildResponse({}, buildSpeechletResponse("Sent",speechOutput, "no text", true)));
console.log("That's all folks");
});
} else {
throw new Error('Invalid intent');
}
完整代码:
/* eslint-disable func-names */
/* eslint-disable no-console */
//const Alexa = require('ask-sdk-core');
var mysql = require('mysql');
var AWS = require("aws-sdk");
var connection = mysql.createConnection({
host: "********************",
port: "****",
user: "*******",
password: "*****",
database: "**************"
});
//=========================================================================================================================================
//TODO: The items below this comment need your attention.
//=========================================================================================================================================
const SKILL_NAME = 'Medical Assistant';
const GET_TEMPERATURE_MESSAGE = '\'s temperature is ';
const HELP_MESSAGE = 'You can say tell me the latest tempearture of patient patient ID, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const FALLBACK_MESSAGE = 'The Medical Assistant can\'t help you with that. It can help you retrieve a patient\'s tempearture. What can I help you with?';
const FALLBACK_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `${title}`,
content: `${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '1.0',
sessionAttributes,
response: speechletResponse,
};
}
function getPatientTemperature(intent, context, callback) {
const cardTitle = intent.name;
const PatientID = intent.slots.PatientID.value;
console.log(PatientID);
let repromptText = '';
let sessionAttributes = {};
const shouldEndSession = false;
let speechOutput = '';
console.log('Then run MySQL code:');
//connection.connect(function(err) {
console.log('Inside connection.connect() callback');
//context.callbackWaitsForEmptyEventLoop = false;
//if (!err) {
console.log("Database is connected ... ");
connection.query("SELECT Temperature, Patient_Name FROM (SELECT * FROM (SELECT c.Temperature, p.Patient_Name, c.Recorded_Time FROM ConsultationRecords c, Patients p WHERE (c.Patient_ID = p.Patient_ID) AND c.Patient_ID = '"+ PatientID +"' AND c.Temperature IS NOT NULL)AS Alias ORDER BY Recorded_Time DESC LIMIT 1) AS RequiredTemp",
function(err, result) {
//connection.end();
console.log("Inside connection.query() callback")
if (!err) {
console.log("Query Successful! Ending Connection.");
//connection.end();
if (result.length > 0) {
if(result[0].Temperature == 'null'){
}
else{
speechOutput = result[0].Patient_Name+"'s temperature is "+result[0].Temperature;
console.log("Returning Response");
}
}
else{
speechOutput = "Patient ID not found in records";
console.log("Returning invalid ID Response");
}
callback(context, speechOutput);
} else {
console.log("Query error!");
}
});
// } else {
// console.log("Error connecting database ..." + err.message);
// connection.end();
// }
console.log("here end");
// });
}
function getWelcomeResponse(context) {
// 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 Medical Assistant. ' +
'You can ask for Patient information like Temperature';
// 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 = 'For example, say: what is the latest temparature of patient 1.';
const shouldEndSession = false;
console.log(`Send Welcome Response`);
context.succeed(buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
exports.handler = (event, context) => {
try {
if (event.session.new) {
// New Session
console.log("NEW SESSION");
}
// Fix for hardcoded context from simulator
//if(event.context && event.context.System.application.applicationId == 'applicationId'){
// event.context.System.application.applicationId = event.session.application.applicationId;
//}
switch (event.request.type) {
case "LaunchRequest":
console.log(`Launch Request`);
getWelcomeResponse(context);
console.log(`End Launch`);
break;
case "IntentRequest":
// Intent Request
console.log(`Intent Request`);
const intent = event.request.intent;
const intentName = event.request.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'Temperature') {
getPatientTemperature(intent, context,
function (internalcontext, speechOutput) {
//sns
//var outmessage = {Display: speechOutput};
var sns = new AWS.SNS({region:'us-east-1'});
//console.log(sns);
console.log('sending push');
sns.publish({
Message: speechOutput,
TopicArn: "arn:aws:sns:us-east-1:**********:MedicalAssistantDisplayUpdates",
Subject: "TestSNS"
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("SNS here 2");
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
console.log("SNS here 3");
});
context.succeed( buildResponse({}, buildSpeechletResponse("Sent",speechOutput, "no text", true)));
console.log("That's all folks");
});
} else {
throw new Error('Invalid intent');
}
break;
case "SessionEndedRequest":
// Session Ended Request
console.log(`SESSION ENDED REQUEST`);
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
}
} catch (error) {
context.fail(`Exceptiodn: ${error}`)
}
};
console.log('sending push')之后;它可以正确运行context.succeed和最终的console.log。
第二次尝试尝试使用Firebase Admin SDK更新Firebase数据库(图我可以将消息存储在此处,然后在插入时从Firebase触发推送通知)。我创建了一个全新的Lambda函数来进行测试,然后再次..似乎忽略了usersRef.set调用。这是该功能的完整代码:
var admin = require("firebase-admin");
var serviceAccount = require("medicalassistantviewer-firebase-adminsdk-7xw02-266915e453.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://****************.firebaseio.com"
});
// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref();
var usersRef = ref.child("Messages");
exports.handler = (event, context) => {
console.log("Let's start");
context.succeed(usersRef.set({
message2: {
Message: "testing again",
Token: "200"
},
message3: {
Message: "and again",
Token: "300"
}
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("messages not sent");
if (err) {
console.log(err.stack);
return;
}
console.log('messages sent');
console.log(data);
console.log("here");
}));
};