-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
354 lines (319 loc) · 14 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
var restify = require('restify');
var builder = require('botbuilder');
var prompts = require('./prompts');
var locationDialog = require('botbuilder-location');
var Client = require('node-rest-client').Client;
//=========================================================
// Bot Setup
//=========================================================
jsonObject = {
"AccessRequest": {
"AccessLicenseNumber": "AD245999B2916A98", "UserId": "shaikathaque4",
"Password": "UPSbot123!"
},
"LocatorRequest": {
"Request": {
"RequestAction": "Locator", "RequestOption": "1", "TransactionReference": {
"CustomerContext": "Find nearest UPS location" }
},
"OriginAddress": {
"PhoneNumber": "1234567891", "AddressKeyFormat": {
"AddressLine": "11 Times Square", "PoliticalDivision2": "New York City", "PoliticalDivision1": "NY", "PostcodePrimaryLow": "10036", "PostcodeExtendedLow": "", "CountryCode": "US"
} },
"Translate": { "Locale": "en_US"},
"UnitOfMeasurement": {
"Code": "MI" },
"LocationSearchCriteria": {
"SearchOption": {
"OptionType": { "Code": "01"},
"OptionCode": {
"Code": "002" }
},
"MaximumListSize": "5", "SearchRadius": "5"}
}
};
// 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.MICROSOFT_APP_ID,
// appPassword: process.env.MICROSOFT_APP_PASSWORD
appId: prompts.AppId,
appPassword: prompts.AppPass
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
//=========================================================
// Bots Dialogs
//=========================================================
var model = process.env.model;
var LocationKey = "DefaultLocation";
var ShippingStyleKey = "Shipping Style";
var async = require("async");
var recognizer = new builder.LuisRecognizer('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/fd9a76fa-9d70-47e3-828c-33ef63fa039f?subscription-key=9aefdc1486b744049db504427816d708');
bot.recognizer(recognizer);
bot.library(locationDialog.createLibrary("Ak2VZoOri8R263-z_IAqqGRcG55S3S5q71H9lSkCsU-1gjnHD1KRUkbeI-zLPp5O"));
bot.dialog('start', function(session){
session.send("Hi there!");
session.beginDialog('rootMenu');
}).triggerAction({matches: "Greetings"});
bot.dialog('rootMenu', [
function (session) {
builder.Prompts.choice(session, "Choose an option:", 'Pickup|Dropoff at UPS|Quit',{listStyle:3});
},
function (session, results) {
switch (results.response.index) {
case 0:
session.beginDialog('pickup');
break;
case 1:
session.beginDialog('dropoff');
break;
case 2:
session.beginDialog('quit');
break;
default:
session.endDialog();
break;
}
}
]).triggerAction({matches: /^menu/i});
bot.dialog('help', [
function(session){
session.send(prompts.helpMessage),
builder.Prompts.choice(session, "Do you want to start a new order?", "Yes|No",{listStyle:3})
},
function(session, results){
switch (results.response.index) {
case 0:
session.beginDialog('rootMenu');
break;
case 1:
session.beginDialog('quit');
break;
default:
session.endDialog();
break;
}
}]).triggerAction({matches: /^help/i});
bot.dialog('pickup', [
function (session) {
builder.Prompts.text(session, prompts.pickupAddressMessage);
},
function (session, result) {
if (validateAddress(result.response)) {
session.conversationData.pickupAddress = result.response;
session.send('Your address is: ' + session.conversationData.pickupAddress);
builder.Prompts.time(session, prompts.pickupTimeMessage);
} else {
session.send('Your address is not valid. Please try again');
session.beginDialog('pickup');
}
},
function (session, result) {
session.conversationData.pickupTime = builder.EntityRecognizer.resolveTime([result.response]);
session.send('Your pickup time is: ' + session.conversationData.pickupTime);
builder.Prompts.text(session, 'Would you like to continue with your shipment?');
},
function (session, result) {
if (result.response === 'yes') {
session.beginDialog('shipment');
} else {
session.beginDialog('help');
}
}
]).triggerAction({
matches: 'pickup',
onInterrupted: function (session) {
session.send('Please provide an address.');
}
});
bot.dialog('shipment', [
function(session, results){
builder.Prompts.text(session, prompts.shipToMessage);
},
function (session, results, next){
session.privateConversationData[LocationKey] = results.response
builder.Prompts.choice(session, "Great. What shipping speed would you like?", '2 Day Delivery|Ground Shipping|Cancel',{listStyle:3});
switch (results.response.index) {
case 0:
session.beginDialog('2DayShipping');
break;
case 1:
session.beginDialog('Ground Shipping');
break;
case 2:
session.beginDialog('quit');
break;
default:
session.endDialog();
break;
}}]).triggerAction({matches: /^shipment/i});
var returnVals = [];
// takes user address and find nearest location
bot.dialog('dropoff', [function(session){
var options = {
prompt: "Please enter your address.",
useNativeControl: true,
reverseGeocode: true,
requiredFields:
locationDialog.LocationRequiredFields.streetAddress |
locationDialog.LocationRequiredFields.locality |
locationDialog.LocationRequiredFields.postalCode
};
locationDialog.getLocation(session, options);
},
function (session, results) {
if (results.response) {
var place = results.response;
async.waterfall([
function(callback){
var client = new Client();
var responseData = [];
jsonObject["LocatorRequest"]["OriginAddress"]["AddressKeyFormat"]["AddressLine"] = place.streetAddress;
jsonObject["LocatorRequest"]["OriginAddress"]["AddressKeyFormat"]["PoliticalDivision1"] = place.region;
jsonObject["LocatorRequest"]["OriginAddress"]["AddressKeyFormat"]["PostcodePrimaryLow"] = place.postalCode;
console.log(jsonObject);
var args = {
data : JSON.stringify(jsonObject),
headers: {"Content-Type": "application/json"}
};
client.post("https://onlinetools.ups.com/rest/Locator", args, function (data, response) {
// parsed response body as js object
responseData = data;
dropLocations = responseData.LocatorResponse.SearchResults.DropLocation;
for(var i = 0; i < dropLocations.length; i++){
returnVals[i] = dropLocations[i].AddressKeyFormat.AddressLine;
};
callback(null, returnVals);
});
},
function(arg1, callback){
builder.Prompts.choice(session,"Which address do you want to select", returnVals, {listStyle:3});
}]);
}
},
function(session,results){
switch (results.response.index) {
case 0:
session.send("Great!");
session.beginDialog("shipment");
break;
case 1:
session.send("Great!");
session.beginDialog("shipment");
break;
case 2:
session.send("Great!");
session.beginDialog("shipment");
break;
default:
session.send("Great!");
session.beginDialog("shipment");
break;
}
}
]).triggerAction({
matches: 'dropoff',
onInterrupted: function (session) {
session.send('Please provide an address to find the closest UPS store.');
}
});
bot.dialog('quit', function(session){
session.endConversation("Have a nice day.")
}).triggerAction({matches: /^quit/i});
bot.dialog('2DayShipping', [
function(session){
session.privateConversationData[ShippingStyleKey] = '2 Day Shipping';
var val= 'You said you would like to send this package using' + ' ' + session.privateConversationData[ShippingStyleKey] +
" to " + session.privateConversationData[LocationKey]+ " is this correct?"
builder.Prompts.choice(session,val, "Yes|No", {listStyle:3})
},
function(session,results){
switch (results.response.index) {
case 0:
var card = createLabel(session);
var msg = new builder.Message(session).addAttachment(card);
session.send(msg);
session.beginDialog('reship');
break;
case 1:
session.send("Okay, lets start over.");
session.endDialog();
break;
}
}
]).triggerAction({matches: /^2 Day Delivery/i});
bot.dialog('GroundShipping', [
function(session){
session.privateConversationData[ShippingStyleKey] = 'Ground Shipping';
var val= 'You said you would like to send this package using' + ' ' + session.privateConversationData[ShippingStyleKey] +
" to " + session.privateConversationData[LocationKey]+ " is this correct?"
builder.Prompts.choice(session,val, "Yes|No", {listStyle:3})
},
function(session,results){
switch (results.response.index) {
case 0:
session.send("Great! Here is your shipping label.");
var card = createLabel(session);
var msg = new builder.Message(session).addAttachment(card);
session.send(msg);
session.beginDialog('reship');
break;
case 1:
session.send("Okay, lets start over.");
session.beginDialog("help");
break;
}
}
]).triggerAction({matches: /^Ground Shipping/i});
function createLabel(session){
return new builder.HeroCard(session)
.title("UPS")
.subtitle("Shipping Label")
.images([
builder.CardImage.create(session, "http://www.cuspdental.com/img/UPSLabel.jpg")
])
}
// bot.dialog('printlabel', [function(session){
// var picture = new builder.Message(session)
// .textFormat(builder.TextFormat.xml)
// .attachments([
// new builder.HeroCard(session)
// .title("UPS")
// .subtitle("Shipping Label")
// .images([
// builder.CardImage.create(session, "http://www.cuspdental.com/img/UPSLabel.jpg")
// ])
// ]);
// session.send(picture);
// },
// function(session){
// session.beginDialog('reship');
// }]).triggerAction({matches: /^printlabel/i})
bot.dialog('reship', [
function(session){
builder.Prompts.choice(session, 'Would you like to place another order?', 'Yes|No', {listStyle:3})
},
function (session, results) {
switch (results.response.index) {
case 0:
session.beginDialog('rootMenu');
break;
case 1:
session.beginDialog('quit');
break;
default:
session.beginDialog('quit');
}
}
]).triggerAction({matches: /^reship/i});
function validateAddress(string) {
if (isNaN(string.split(' ')[0])) {
return false;
}
return true;
}