-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
324 lines (263 loc) · 12.1 KB
/
app.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// START Microsoft Bot Framework setup
//Install dependencies
"use strict";
var builder = require('botbuilder');
var restify = require('restify');
var request = require('request');
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
//Create chat bot
var connector = new builder.ChatConnector({
appId: process.env['MicrosoftAppId'],
appPassword: process.env['MicrosoftAppPassword']
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen())
// END Microsoft Bot Framework setup
// START TomTom API related Functions
// Convert String Address to Geo Location
var getGeo = function (location, func) {
// Return into func the actual Geo value of the string address.
request("https://api.tomtom.com/search/2/geocode/" + encodeURI(location) + ".json?key=" + process.env['TomTomAPIKey'],
function (error, response, body) {
//console.log('error:', error); // Print the error if one occurred
//console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
//console.log('body:', body); // Print what was returned
// TO DO: Add error checking
var value = JSON.parse(body);
console.log("DEBUG INFO: Called Geocode API on " + location + ", returned value:", value)
var position;
var freeformAddress;
if (value) {
if (value.results) {
if (value.results[0]) {
if (value.results[0].position) {
position = value.results[0].position.lat + "," + value.results[0].position.lon;
}
if (value.results[0].address) {
freeformAddress = value.results[0].address.freeformAddress;
}
}
}
}
if (position && freeformAddress)
func(freeformAddress, position);
else
func("ERROR", "ERROR"); // TO DO: Add better error messaging
});
}
// Bot dialog to display results
bot.dialog('/results', [
function (session, route) {
//console.log("DEBUG INFO: User " + session.message.user.id + " route var dump: " + JSON.stringify(route));
request("https://api.tomtom.com/routing/1/calculateRoute/" + route.startGeo + ":" + route.destGeo + "/json?key=" + process.env['TomTomAPIKey'] + "&computeTravelTimeFor=all&arriveAt=" + route.destTime,
function (error, response, body) {
//console.log('error:', error); // Print the error if one occurred
//console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
//console.log('body:', body); // Print what was returned
// TO DO: Add error checking
var value = JSON.parse(body);
console.log("DEBUG INFO: User " + session.message.user.id + " called Routing API, returned value:", value);
if (value) {
if (value.error) {
session.send("ERROR! TomTom API returned: " + value.error.description);
}
else {
var departureTime;
var noTrafficTravelTimeInSeconds, historicTrafficTravelTimeInSeconds, liveTrafficIncidentsTravelTimeInSeconds;
if (value.routes) {
if (value.routes[0]) {
if (value.routes[0].summary) {
console.log("DEBUG INFO: User " + session.message.user.id + " summary value:", value.routes[0].summary);
departureTime = value.routes[0].summary.departureTime;
noTrafficTravelTimeInSeconds = value.routes[0].summary.noTrafficTravelTimeInSeconds;
historicTrafficTravelTimeInSeconds = value.routes[0].summary.historicTrafficTravelTimeInSeconds;
liveTrafficIncidentsTravelTimeInSeconds = value.routes[0].summary.liveTrafficIncidentsTravelTimeInSeconds;
}
}
}
if (departureTime) {
var dateObject = new Date(departureTime);
session.send("Thanks to the TomTom Routing API, I know that (assuming no traffic) it will take you " + secondsToHHMMSS(noTrafficTravelTimeInSeconds) +
" to get there. However, historic traffic data suggests it will actually take " + secondsToHHMMSS(historicTrafficTravelTimeInSeconds) +
". Current live traffic reports estimate " + secondsToHHMMSS(liveTrafficIncidentsTravelTimeInSeconds) +
". Thus, in order to get to you destination on time, I suggest leaving by " + dateObject.toString() + "! ");
}
else {
session.send("ERROR! For some reason, I could not calculate departure time. Sorry!");
}
}
}
else {
session.send("ERROR! Bot did not get valid JSON back from TomTom API.");
}
session.endDialog();
});
}
]);
// END TomTom API related functions
// START Conversion Functions
var secondsToHHMMSS = function (str) {
var num = parseInt(str, 10);
var hours = Math.floor(num / 3600);
var minutes = Math.floor((num - (hours * 3600)) / 60);
var seconds = num - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = "0" + hours; }
if (minutes < 10) { minutes = "0" + minutes; }
if (seconds < 10) { seconds = "0" + seconds; }
return hours + ':' + minutes + ':' + seconds;
}
// END ConversionFunctions
// START Main Microsoft Bot Framework dialogs
// Initial dialog
bot.dialog('/', [
function (session) {
session.send("Hello! Welcome to the TomTom Online Routing API Bot Framework demo. I can tell you when you need to leave in order to arrive at your destination on time.");
if (session.userData.route == null) {
session.userData.route = {}
}
session.beginDialog("/demo")
}
]);
// Demo dialog
bot.dialog('/demo', [
function (session) {
//console.log("DEBUG INFO: User "+session.message.user.id+" Userdata dump: "+JSON.stringify(session.userData.route));
session.beginDialog("/getLocation", true);
},
function (session, results) {
session.beginDialog("/getLocation", false);
},
function (session, results) {
session.beginDialog("/getTime");
},
function (session, results) {
var dateObject = new Date(session.userData.route.destTime);
session.send("You want to arrive by " + dateObject.toString());
session.beginDialog("/results", session.userData.route);
},
function (session, results) {
builder.Prompts.choice(session, "Would you like to calculate another route?",
["Yes", "Yes, but forget everything I told you before", "No, not right now"]);
},
function (session, results) {
if (results.response.entity == "Yes") {
session.replaceDialog('/demo')
}
else if (results.response.entity == "Yes, but forget everything I told you before") {
session.userData.route = {};
session.replaceDialog('/demo');
}
else {
session.send("No? Ok! If you change your mind, send me another message");
session.endDialog();
}
}
]);
// A dialog to get a location
bot.dialog('/getLocation', [
function (session, direction, next) {
session.dialogData.direction = direction;
var str;
if (direction) {
session.dialogData.location = session.userData.route.start;
str = "Are you starting your journey from \"";
}
else {
session.dialogData.location = session.userData.route.dest;
str = "Are you traveling to \"";
}
if (session.dialogData.location) {
builder.Prompts.confirm(session, str + session.dialogData.location + "\" again?");
}
else {
next(); // Skip to asking if we don't have the location
}
},
function (session, results) {
if (results.response) {
session.endDialogWithResult({
response: { noChange: true }
});
}
else {
var str;
if (session.dialogData.direction) {
str = "you'd like to start from:";
}
else {
str = "of where you'd like to go:";
}
builder.Prompts.text(session, "Enter an address " + str);
}
},
function (session, results) {
if (results.response) {
getGeo(results.response, function (address, addressGeo) {
if (address == "ERROR") {
session.send("ERROR! Could not validate address.")
session.replaceDialog('/getLocation', session.dialogData.direction);
}
else {
if (session.dialogData.direction) {
session.userData.route.start = address;
session.userData.route.startGeo = addressGeo;
}
else {
session.userData.route.dest = address;
session.userData.route.destGeo = addressGeo;
}
session.send("Thanks to the TomTom Geocoding API, I think you mean \"" + address +
"\" which I know is located at " + addressGeo);
session.endDialogWithResult({
response: { input: results.response, address: address, addressGeo: addressGeo }
});
}
});
} else {
session.endDialogWithResult({
resumed: builder.ResumeReason.notCompleted
});
}
}
]);
// A dialog to get the desired arrive by time
bot.dialog('/getTime', [
function (session) {
builder.Prompts.time(session, "What time would you like to get there by?");
},
function (session, results) {
if (results.response) {
var t = builder.EntityRecognizer.resolveTime([results.response]);
var now = new Date();
if (t > now) {
session.dialogData.time = t.toISOString(); //Storing date object as String
// To get back as Date object: var dateObject = new Date(session.userData.route.time);
// Return time
if (session.dialogData.time) {
session.userData.route.destTime = session.dialogData.time;
session.endDialogWithResult({
response: { time: session.dialogData.time }
});
} else {
session.endDialogWithResult({
resumed: builder.ResumeReason.notCompleted
});
}
}
else {
session.send("ERROR! Time must be in the future. (My default timezone is GMT)");
session.replaceDialog('/getTime');
}
}
else {
// Possibly redundant?
session.send("ERROR! Could not understand time.");
session.replaceDialog('/getTime');
}
}
]);
// END Main Microsoft Bot Framework dialogs