-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
492 lines (461 loc) · 19.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// This loads the environment variables from the .env file
require('dotenv-extended').load();
var builder = require('botbuilder');
var restify = require('restify');
var Store = require('./store');
var spellService = require('./spell-service');
var prompts = require('./prompts');
var http = require('http');
var userMail = "";
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3979, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create connector and listen for messages
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector, function (session) {
session.send('Sorry, I did not understand \'%s\'. Type \'help\' if you need assistance.', session.message.text);
});
// Send welcome when conversation with bot is started, by initiating the root dialog
bot.on('conversationUpdate', function (message) {
if (message.membersAdded) {
message.membersAdded.forEach(function (identity) {
if (identity.id === message.address.bot.id) {
bot.beginDialog(message.address, 'Grretings');
}
});
}
});
// You can provide your own model by specifing the 'LUIS_MODEL_URL' environment variable
// This Url can be obtained by uploading or creating your model from the LUIS portal: https://www.luis.ai/
var recognizer = new builder.LuisRecognizer(process.env.LUIS_MODEL_URL);
bot.recognizer(recognizer);
var dialog = new builder.IntentDialog({ recognizer: [recognizer] });
bot.dialog('Grretings', [
function (session) {
// if (session.userData.userName && session.userData.email && session.userData.mobile) {
// //session.send("Hello " +session.userData.userName);
// session.beginDialog('ServiceOption');
// //session.beginDialog('UserProfile');
// }
// else if (session.userData.userName && !session.userData.email) {
// session.send("Hello " + session.userData.userName);
// session.beginDialog('Email');
// }
// else if (session.userData.userName && session.userData.email && !session.userData.mobile) {
// session.send("Hello " + session.userData.userName);
// session.beginDialog('Mobile');
// }
// else {
//builder.Prompts.text(session, "Hello, my name is Mayara. I can help you schedule a car service. Do you want me to help you?");
//}
builder.Prompts.choice(session, "Hello, my name is Mayara. I can help you schedule a car service. Do you want me to help you?", "Yes|No", { listStyle: builder.ListStyle.button });
},
function (session, results) {
if (results.response.entity == 'No') {
session.userData = null;
session.endDialog("No problem. Please feel free to tap on the chat box any time you want");
session.endConversation("");
}
if (results.response.entity == 'Yes') {
if (session.userData.userName){
session.beginDialog('ServiceOption');
}
else
builder.Prompts.text(session,"May I know your name?")
}
},
function (session, results) {
session.userData.userName = results.response;
session.beginDialog('ServiceOption');
//session.beginDialog('Email');
}
]).triggerAction({
matches: 'Grretings'
});
bot.dialog('Email', [
function (session, results) {
builder.Prompts.text(session, "Please provide an email so that I can send you a confirmation for your service");
},
function (session, results) {
session.userData.email = results.response;
ValidateEmail(session);
//builder.Prompts.text(session,"Kindly provide your mobile number for communication");
}
]);
bot.dialog('InvalidEmail', [
function (session, results) {
builder.Prompts.text(session, "Invalid Email,Kindly provide valid email");
},
function (session, results) {
session.userData.email = results.response;
ValidateEmail(session);
}
]);
bot.dialog('InvalidMobileNum', [
function (session, results) {
builder.Prompts.text(session, "Invalid number,Kindly provide valid 10 digit number");
},
function (session, results) {
session.userData.mobile = results.response;
ValidateMobileNum(session);
}
]);
bot.dialog('Mobile', [
function (session, results) {
// if (!session.userData.mobile)
builder.Prompts.text(session, "Please provide a phone number incase a service agent needs to reach you");
//else session.beginDialog('ServiceOption');
},
function (session, results) {
session.userData.mobile = results.response;
ValidateMobileNum(session);
}
]);
bot.dialog('ServiceOption', [
function (session, results) {
var servicesOption = ['Car service', 'Car wash'];
builder.Prompts.choice(session, "Hi " + session.userData.userName + ", please select one of the service options below", servicesOption, { listStyle: builder.ListStyle.button });
},
function (session, results) {
session.userData.serviceType = results.response.entity;
session.beginDialog("SearchCarServiceCenter");
}
]);
bot.dialog('UserProfile', [
function (session, args, next) {
if (!session.userData.userName) {
var nameEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'Name');
session.userData.userName = nameEntity ? nameEntity.entity : "";
session.beginDialog('ServiceOption');
}
else if(!session.userData.email){
var email = builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.email');
session.userData.email = email.entity;
ValidateEmail(session);
}
}
]).triggerAction({
matches: 'UserProfile'
});
bot.dialog('Goodbye', [
function (session) {
builder.Prompts.text(session, "Bye. Looking forward to our next awesome conversation already.");
session.userData = null;
}
]).triggerAction({
matches: 'Goodbye'
});
bot.dialog('Booking', [
function (session, results) {
GetAvailableDates(session);
}
]).triggerAction({
matches: 'Booking'
});
bot.dialog('SearchCarServiceCenter', [
function (session, args, next) {
if (session.userData.userName) {
//session.send(session.userData.userName + ', I am analyzing your message: \'%s\'', session.message.text);
//builder.Prompts.text(session, 'Please enter your destination');
// try extracting entities
var cityEntity = args && args.intent && args.intent.entities.length ? builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.geography.city') : null;
var airportEntity = args && args.intent && args.intent.entities.length ? builder.EntityRecognizer.findEntity(args.intent.entities, 'AirportCode') : null;
if (cityEntity) {
// city entity detected, continue to next step
session.dialogData.searchType = 'city';
next({ response: cityEntity.entity });
} else if (airportEntity) {
// airport entity detected, continue to next step
session.dialogData.searchType = 'airport';
next({ response: airportEntity.entity });
} else {
//no entities detected, ask user for a destination
builder.Prompts.text(session, 'Please enter a location (address or zip code) so that I can look for a service center closest to you');
}
}
else{
//session.send("I need your name before proceding");
session.beginDialog("Grretings");
}
// else {
// if (!session.userData.userName) {
// session.send("Kindly provide your details first");
// session.beginDialog("Grretings");
// }
// else if (session.userData.userName && !session.userData.email) {
// session.send(session.userData.userName + ", Kindly provide your few details before preceding");
// session.beginDialog("Email");
// }
// else if (session.userData.userName && session.userData.email && session.userData.mobile) {
// session.send(session.userData.userName + ", Kindly provide your few details before preceding");
// session.beginDialog("Mobile");
// }
// }
},
function (session, results) {
var destination = results.response;
var message = 'Looking for Car Service Center....';
// if (session.dialogData.searchType === 'airport') {
// message += ' near %s airport...';
// } else {
message += ' near %s...';
//}
session.send(message, destination);
// Async search
Store
.searchHotels(destination)
.then(function (hotels) {
// args
session.send('I found %d Car Service Center:', hotels.length);
var message = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(hotels.map(hotelAsAttachment));
builder.Prompts.choice(session, message, "select:100|select:101|select:102");
//session.send(message);
// End
//session.endDialog();
});
},
function (session, results) {
session.userData.ServiceCentre = results.response.entity;
session.beginDialog("Booking");
}
]).triggerAction({
matches: 'SearchCarServiceCenter'
// onInterrupted: function (session) {
// session.send('Please provide a destination');
//}
});
bot.dialog('GetDates', [
function (session, result) {
builder.Prompts.choice(session, "I have the following dates available for the selected service center: ", session.userData.availableDates, { listStyle: builder.ListStyle.button });
},
function (session, results) {
session.userData.selectedDate = results.response.entity;
GetAvailableSlots(session);
}
]);
bot.dialog('GetSlots', [
function (session, result) {
builder.Prompts.choice(session, "I have the following slot available for the selected service center: ", session.userData.availableSlots, { listStyle: builder.ListStyle.button });
},
function (session, results) {
session.userData.selectedSlot = results.response.entity;
builder.Prompts.choice(session,"You've asked for a "+session.userData.serviceType+" on "+session.userData.selectedDate+" at "+session.userData.selectedSlot+". Please confirm if this is correct","Confirm|Cancel",{ listStyle: builder.ListStyle.button });
//BookSlot(session);
},
function(session,results){
if (results.response.entity == 'Confirm') {
session.send("Thank you, your reservation is confirmed. You will receive an email with the details")
BookSlot(session);
}
if (results.response.entity == 'Cancel') {
session.userData = null;
session.endDialog("No problem. Please feel free to tap on the chat box any time you want");
session.endConversation("");
}
}
]);
bot.dialog('BookingConfirmed', [
function (session, results) {
userMail = session.userData.email;
var message = new builder.Message(session)
.addAttachment(BookingConfirmedAsAttachemnt(session));
session.send(message);
session.send('Sending confirmation email to '+session.userData.email);
SendEmail(session);
},
]);
bot.dialog('Confirmation', [
function (session, results) {
builder.Prompts.choice(session, session.userData.userName + ", would you like to continue?", "Yes|No", { listStyle: builder.ListStyle.button });
},
function (session, results) {
if (results.response.entity == 'No') {
session.userData = null;
session.endDialog("Ending Conversation, Happy to help");
session.endConversation("");
}
if (results.response.entity == 'Yes') {
session.send(session.userData.userName + ", how can we help you?")
}
}
]);
bot.dialog('ShowCarServiceCentersReviews', function (session, args) {
// retrieve hotel name from matched entities
var hotelEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'Car');
if (hotelEntity) {
session.send('Looking for reviews of \'%s\'...', hotelEntity.entity);
Store.searchHotelReviews(hotelEntity.entity)
.then(function (reviews) {
var message = new builder.Message()
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(reviews.map(reviewAsAttachment));
session.endDialog(message);
});
}
}).triggerAction({
matches: 'ShowCarServiceCentersReviews'
});
bot.dialog('Help', function (session) {
session.endDialog('Hi! Try asking me things like \'search car service\', \'search wash\' or \'show me the reviews of The Bot Resort\'');
}).triggerAction({
matches: 'Help'
});
// Spell Check
if (process.env.IS_SPELL_CORRECTION_ENABLED === 'true') {
bot.use({
botbuilder: function (session, next) {
spellService
.getCorrectedText(session.message.text)
.then(function (text) {
session.message.text = text;
next();
})
.catch(function (error) {
console.error(error);
next();
});
}
});
}
// Helpers
function hotelAsAttachment(hotel) {
return new builder.HeroCard()
.title(hotel.name)
.subtitle('%d stars. %d reviews. min charges $%d.', hotel.rating, hotel.numberOfReviews, hotel.priceStarting)
.images([new builder.CardImage().url(hotel.image)])
.buttons([
new builder.CardAction()
.title('Show in Map')
.type('openUrl')
.value('http://maps.google.com/?q=' + encodeURIComponent(hotel.location)),
new builder.CardAction()
.title('Book a slot')
.type('imBack')
.value('Book a slot for ' + hotel.name)
]);
}
function reviewAsAttachment(review) {
return new builder.ThumbnailCard()
.title(review.title)
.text(review.text)
.images([new builder.CardImage().url(review.image)]);
}
function BookingConfirmedAsAttachemnt(session) {
return new builder.HeroCard()
.title(session.userData.userName + " your booking for " + session.userData.serviceType + " on " + session.userData.selectedDate + " at " + session.userData.selectedSlot + " has been confirmed.")
.subtitle("Your communication details")
.text("Email- " + session.userData.email + " Mobile Number- " + session.userData.mobile)
.images("http://realtimedashbord20170501102742.azurewebsites.net/Content/Confirmation.png");
}
function SendEmail(session) {
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'Bhanu@05',
xoauth2: xoauth2.createXOAuth2Generator({
user: '[email protected]',
clientId: '930280742263-93q1mjdoq2m02r3timeg8iajj6223imf.apps.googleusercontent.com',
clientSecret: 'b7BXcr2oKpbGY154bHkPwsSH',
refreshToken: '1/oBialtTpd09pFkkxnwTUgjAvviSz0WNYxdvZ5ifY4t8',
accessToken: 'ya29.GltVBBdxXr_AFmi9qnpKO54tzp1hyLIinKlzQsZZ0Sr1MU7QXvAc37I0l0UHXYJl8mnyVUXyYWebJ_Ixl5HVFmkJuenG7ns1GVaSj9oZawmNW7INiNX-OrMG6AVh'
})
}
});
var mailOptions = {
from: '[email protected]',
to: session.userData.email,
subject: 'Booking for ' + session.userData.serviceType + ' confirmed',
//text: 'text'
html: '<p>Hi '+ session.userData.userName+',</p></br><p>Your booking for '+ session.userData.serviceType+' on ' + session.userData.selectedDate+' at ' + session.userData.selectedSlot+' has been confirmed.</p><p>Happy to help</p></br></br><h3>Regards</h3><h3>Hughes</h3>'
}
transporter.sendMail(mailOptions, function (err, res) {
if (err) {
session.send('Oops, something went wrong in sending email, will be sent later');
console.log(err);
session.beginDialog('Confirmation');
}
else {
session.send('Booking confirmed, confirmation email sent to ' + session.userData.email);
session.beginDialog('Confirmation');
}
})
}
/**
*
*API call function starts
*/
function GetAvailableDates(session) {
http.get("http://webapilearning20170517094105.azurewebsites.net/api/Employee/GetAvailableDates", function (res) {
res.on('data', function (data) {
session.userData.availableDates = JSON.parse(data);
session.beginDialog("GetDates");
});
})
};
function GetAvailableSlots(session) {
var url = "http://webapilearning20170517094105.azurewebsites.net/api/Employee/GetAvailableSlots/" + session.userData.selectedDate;
http.get(url, function (res) {
res.on('data', function (data) {
session.userData.availableSlots = JSON.parse(data);
if (session.userData.availableSlots.length == 0) {
session.send("Currently no slot avialable,Kindly selected some other date");
session.beginDialog("GetDates");
}
else {
session.beginDialog("GetSlots");
}
});
})
};
function BookSlot(session) {
var hour = String(session.userData.selectedSlot).substring(0, 2);
var min = String(session.userData.selectedSlot).substring(3, 5);
var url = "http://webapilearning20170517094105.azurewebsites.net/api/Employee/BookAppoitment/" + session.userData.selectedDate + "/" + hour + "/" + min + "/" + session.userData.userName + "/" + session.userData.email + "/" + session.userData.mobile;
http.get(url, function (res) {
res.on('data', function (data) {
//session.userData.availableSlots = JSON.parse(data);
session.beginDialog("Email");
});
})
};
/**
*
*API call function End
*/
/**
*
*Validate function starts
*/
function ValidateEmail(session) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(session.userData.email)) {
session.beginDialog("Mobile");
}
else {
session.beginDialog("InvalidEmail");
}
}
function ValidateMobileNum(session) {
var re = /^\d{10}$/;
if (re.test(session.userData.mobile)) {
session.beginDialog("BookingConfirmed");
}
else {
session.beginDialog("InvalidMobileNum");
}
}
/**
*
*API call function Ends
*/