forked from madhurbhargava/AlexaSkillsProjects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChapter3_HandsFreeMessenger_index.js
104 lines (86 loc) · 2.75 KB
/
Chapter3_HandsFreeMessenger_index.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var token = '4bXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var sender = '+31XXXXXXXXXX';
var https = require('https');
var queryString = require('querystring');
exports.handler = function (event, context) {
try {
if (event.request.type === "LaunchRequest") {
onLaunch(function callback(speechletResponse) {
context.succeed(buildResponse(speechletResponse));
});
} else if (event.request.type === "IntentRequest") {
onIntent(event.request,
function callback(speechletResponse) {
context.succeed(buildResponse(speechletResponse));
});
}
} catch (e) {
context.fail("Exception: " + e);
}
};
function SendMessage(to, body, callback) {
var message = {
To: to,
From: sender,
Body: body
};
var messageString = queryString.stringify(message);
var options = {
host: 'api.twilio.com',
port: 443,
path: '/2010-04-01/Accounts/' + sid + '/Messages.json',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(messageString),
'Authorization': 'Basic ' + new Buffer(sid + ':' + token).toString('base64')
}
};
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
res.on('end', function () {
var speechOutput = "Message sent.";
var shouldEndSession = true;
callback(buildSpeechletResponse(speechOutput, shouldEndSession));
});
});
req.write(messageString);
req.end();
}
function onLaunch(callback) {
var output = "Welcome to HandsFree Messenger.";
var endSession = false;
callback(buildSpeechletResponse(output, endSession));
}
function onIntent(intentRequest, callback) {
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
if("SendMessage" === intentName){
var text = intent.slots.Text.value;
var recipient = '+31XXXXXXXXXX';
SendMessage(recipient, text,callback);
} else {
throw "Intent not recognized";
}
}
//-------Helper Methods---------//
function buildSpeechletResponse(output, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(speechletResponse) {
return {
version: "1.0",
response: speechletResponse
};
}