forked from mtvg/August
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathalexaws.js
More file actions
90 lines (75 loc) · 2.13 KB
/
alexaws.js
File metadata and controls
90 lines (75 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function Alexa(request, response) {
var self = this;
var requestJSONBody = '';
var requestBody;
var respondObject = {
"version": "1.0",
"sessionAttributes": {},
"response": {
"shouldEndSession": true
}
};
this.sessionAttributes = {};
this.autoSend = true;
this.setShouldEndSession = function(endSession) {
respondObject.response.shouldEndSession = endSession?true:false;
}
this.setOutputSpeech = function(text) {
if (text) {
respondObject.response.outputSpeech = {
"type": "PlainText",
"text": text
};
} else {
delete respondObject.response.outputSpeech;
}
}
this.getSessionId = function() {
if (requestBody)
return requestBody.session.sessionId;
else return null;
}
this.isNewSession = function() {
if (requestBody)
return requestBody.session['new'];
else return null;
}
function parseJSONBody() {
var jsonParsed = true;
try {
requestBody = JSON.parse(requestJSONBody);
} catch (e) {
jsonParsed = false;
}
if (jsonParsed) {
self.sessionAttributes = requestBody.session.attributes;
if (requestBody.request.type == "LaunchRequest")
self.emit('launch');
if (requestBody.request.type == "IntentRequest")
self.emit('intent', requestBody.request.intent.name, parseSlots(requestBody.request.intent.slots));
if (requestBody.request.type == "SessionEndedRequest")
self.emit('end', requestBody.request.reason);
}
if (self.autoSend)
self.send();
}
function parseSlots(requestSlots) {
var args = {};
for (var o in requestSlots)
args[o] = requestSlots[o].value;
return args;
}
this.send = function() {
var payload = JSON.stringify(respondObject);
response.writeHead( 200, {"Content-Type": "application/json;charset=UTF-8", "Content-Length": Buffer.byteLength(payload, 'utf8')} );
response.end(payload);
}
request.on('data', function (data) {
requestJSONBody += data;
});
request.on('end', parseJSONBody);
}
util.inherits(Alexa, EventEmitter);
module.exports = Alexa;