-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
385 lines (349 loc) · 14.9 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
const path = require('path');
const restify = require('restify');
const expressSession = require('express-session');
const builder = require('botbuilder');
const azure = require('botbuilder-azure');
const azureStorage = require('azure-storage');
const AuthHelper = require('./auth');
const cfg = require('./config');
const useEmulator = (process.env.NODE_ENV == 'development');
/*-----------------------------------------------------------------------------
A simple echo bot for the Microsoft Bot Framework.
-----------------------------------------------------------------------------*/
'use strict';
const storageConnectionString = process.env.storageConnectionString;
console.log(`storage: ${storageConnectionString}`);
var documentDbOptions = {
host: process.env.docDbHost,
masterKey: process.env.docDbKey,
database: process.env.docDbName || 'botdocdb',
collection: process.env.docDbCollection ||'botdata'
};
//This is an old version of the node docDbClient, the new version is not compatible with the AzureBotStorage library.
var botDocDbClient = new azure.DocumentDbClient(documentDbOptions);
var tableStorage = new azure.AzureBotStorage({ gzipData: false }, botDocDbClient);
console.log('create connector');
// Create chat connector for communicating with the Bot Framework Service
// We don't need to have these environment variables set in the development environment
var connector = new builder.ChatConnector({
appId: process.env.azAppId,
appPassword: process.env.azAppPassword,
stateEndpoint: process.env.BotStateEndpoint,
openIdMetadata: process.env.BotOpenIdMetadata
});
// Setup Restify Server
console.log('create 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);
});
// Listen for messages from users
console.log('listen for message posts');
server.post('/api/messages', connector.listen());
// Serve the magic code page for login.
console.log('code page registered');
server.get('/code', restify.plugins.serveStatic({
'directory': path.join(__dirname, 'public'),
'file': 'code.html'
}));
console.log('add restify plugins');
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());
// Setup the server with the bot secret
console.log('add secret to session');
server.use(expressSession({
secret: cfg.BOTAUTH_SECRET,
resave: true,
saveUninitialized: false
}));
/*----------------------------------------------------------------------------------------
* Bot Storage: This is a great spot to register the private state storage for your bot.
* We provide adapters for Azure Table, CosmosDb, SQL Azure, or you can implement your own!
* For samples and documentation, see: https://github.com/Microsoft/BotBuilder-Azure
* ---------------------------------------------------------------------------------------- */
// Create your bot with a function to receive messages from the user
// Using document DB for bot storage
console.log('configure storage');
var bot = new builder.UniversalBot(connector)
.set('storage',tableStorage);
console.log('add auth to bot');
const auth = AuthHelper.configure(server, bot);
console.log('registering dialogs and triggers');
// Intercept trigger event (ActivityTypes.Trigger)
bot.on('trigger', function (message) {
// handle message from trigger function
const payload = message.value;
// This is handy to see the full message that you got back from the Azure Function.
// const msg = new builder.Message()
// .address(payload.address)
// .text('Here\s the raw message: ' + JSON.stringify(payload));
// bot.send(msg);
switch(payload.action)
{
case 'WEBHOOK_REGISTERED':
bot.beginDialog(payload.address, '/hookRegistered', payload.subscriptionId);
break;
case 'NOTIFICATION_RECIEVED':
bot.beginDialog(payload.address, '/meetingRequested', payload);
break;
default:
var reply = new builder.Message()
.address(message.address)
.text('default message: ' + message.text);
bot.send(reply);
}
});
bot.on('conversationUpdate', function(update) {
console.log('Converastion update started');
if(update.membersAdded) {
console.log('Members added');
update.membersAdded.forEach(member => {
if(member.id !== update.address.bot.id) {
console.log('starting /intro dialog');
bot.beginDialog(update.address, '/intro');
}
});
}
});
bot.dialog("/intro", (session) => {
var reply = new builder.Message()
.address(session.message.address)
.text(`Hey, I can't do much, I suggest you start my signing in. Say intro to get this dialog again`)
.suggestedActions(
new builder.SuggestedActions()
.addAction(new builder.CardAction()
.title('Logout')
.type('postBack')
.value('logout'))
.addAction(new builder.CardAction()
.title('Signin to get help with your calendar')
.type('imBack')
.value('signin'))
);
bot.send(reply);
session.endDialog();
});
// Handle message from user
bot.dialog("/", new builder.IntentDialog()
.matches(/logout/, "/logout")
.matches(/signin/, "/signin")
.matches(/intro/, '/intro')
.onDefault((session, args) => {
session.endDialog("welcome");
})
);
bot.dialog('/hookRegistered', (session, args) => {
console.log('Hook registration completed');
session.userData.subscriptionId = args;
session.send(`I'm now watching for new meetings and will help you book travel time`);
session.endDialog();
});
bot.dialog('/meetingRequested', [
(session, args) => {
console.log('Meeting request received');
session.userData.meetingRequest = args;
// Use this to debug your messages sent to the bot
// session.send('here\s what I know about that meeting');
// session.send(JSON.stringify(args));
const start = new Date(args.start);
const end = new Date(args.end);
session.send(`${args.organizer} wants to have a meeting on ${start.toDateString()} from ${start.toTimeString()} until ${end.toTimeString()} at ${args.location} about ${args.subject}` );
builder.Prompts.choice(session, 'Would you like to accept?', ['Yes', 'No']);
},
(session, results) => {
if (results.response.entity !== 'Yes') {
session.send('Ok, have a nice day');
session.endDialog();
}
session.send(`I'll accept that meeting for you.`);
// enqueue a message to accept the meeting
var queueSvc = azureStorage.createQueueService(storageConnectionString);
queueSvc.createQueueIfNotExists('accept-meeting', function(err, result, response){
const message = {
accessToken: session.userData.accessToken,
meeting: session.userData.meetingRequest.resource
}
const msg = JSON.stringify(message);
const queueMessageBuffer = new Buffer(msg).toString('base64');
queueSvc.createMessage('accept-meeting', queueMessageBuffer, function(err, result, response){
if (err) {
console.error(err);
}
});
});
builder.Prompts.choice(session, 'Would you like to block some travel time?', ['Yes', 'No']);
},
(session, results) => {
if (results.response.entity !== 'Yes') {
session.send('Ok, have a nice day');
session.endDialog();
}
session.send(`Ok, let's find out about how much time to book.`)
session.beginDialog('/requestTravelTime');
},
(session, results) => {
session.send(`Ok, I'm blocking ${results.response} minutes of travel time for you`);
const durationInMinutes = results.response;
// enqueue messages to block some time.
var queueSvc = azureStorage.createQueueService(storageConnectionString);
queueSvc.createQueueIfNotExists('add-travel-meeting', function(err, result, response){
const MS_PER_MINUTE = 60000;
const start = new Date(session.userData.meetingRequest.start);
const messages =[ {
accessToken: session.userData.accessToken,
start: session.userData.meetingRequest.end,
durationInMins: durationInMinutes
},{
accessToken: session.userData.accessToken,
meeting: session.userData.meetingRequest.resource,
start: new Date(start - durationInMinutes * MS_PER_MINUTE).toISOString(),
durationInMins: durationInMinutes
}]
for (let message of messages) {
const msg = JSON.stringify(message);
console.log(msg);
const queueMessageBuffer = new Buffer(msg).toString('base64');
queueSvc.createMessage('add-travel-meeting', queueMessageBuffer, function(err, result, response){
if (err) {
console.error(err);
}
});
}
});
session.endDialog();
}
])
.beginDialogAction('meetingRequestedHelpAction', '/meetingRequestedHelp', { matches: /^help$/i });;
bot.dialog('/meetingRequestedHelp', function(session, args, next) {
session.endDialog('Contextual help for this dialog');
})
// Once triggered, will restart the dialog.
.reloadAction('startOver', 'Ok, starting over.', {
matches: /^start over$/i
});
bot.dialog('/requestTravelTime',[
session => {
builder.Prompts.choice(session, 'How much time? ', ['15 minutes', '30 minutes', '1 hour', 'Other']);
},
(session, results) => {
if (results.response.entity === 'Other') {
// use a dialog here to gather the infomation on how long.
session.beginDialog('/customTravelLength');
}
if (results.response.index === 0) {
session.endDialogWithResult({ response: 15 });
}
if (results.response.index === 1) {
session.endDialogWithResult({ response: 30 });
}
if (results.response.index === 2) {
session.endDialogWithResult({ response: 60 });
}
},
(session, results) => {
// this returns the results of the /customTravelLength Dialog.
session.endDialogWithResult(results);
}
]);
bot.dialog('/customTravelLength', [
(session, args) => {
if (args && args.reprompt) {
builder.Prompts.text(session, `Sorry, can you try telling me in hours or minutes, that's all I know about yet`);
} else {
builder.Prompts.text(session, 'How long should I block for travel time?');
}
},
(session, results) => {
const userInput = results.response;
let minutes = 0;
if ('string' === (typeof userInput)) {
if (userInput.indexOf('min') > 1) {
minutes = userInput.split(' ')[0];
}
if (userInput.indexOf('hour') > 1) {
minutes = userInput.split(' ')[0]*60;
}
}
if (minutes === 0) {
session.replaceDialog('/customTravelLength', {reprompt: true});
} else {
session.endDialogWithResult({ response: minutes});
}
}
]);
bot.dialog("/logout", (session) => {
auth.logout(session, "aadv2");
session.endDialog("logged_out");
});
bot.dialog("/signin", [].concat(
auth.authenticate("aadv2"),
(session, args, skip) => {
let user = auth.profile(session, "aadv2");
// persist some userful means of finding a user.
session.userData.oid = user.oid;
session.userData.address= session.message.address;
session.userData.accessToken = user.accessToken;
session.userData.refreshToken = user.refreshToken;
session.sendTyping();
if (session.userData.subscriptionId) {
session.send(`All set up and ready to go, I'll let you know when you get some meeting requests` );
session.endDialog();
return;
}
var queueSvc = azureStorage.createQueueService(storageConnectionString);
queueSvc.createQueueIfNotExists('bot-hook-registration', function(err, result, response){
if(!err){
// enqueue a message to register a webhook.
const raw = JSON.parse(user._raw);
let message = {
accessToken: user.accessToken,
userId: user.oid,
address: session.message.address
}
let msg = JSON.stringify(message);
console.log(msg)
var queueMessageBuffer = new Buffer(msg).toString('base64');
queueSvc.createMessage('bot-hook-registration', queueMessageBuffer, function(err, result, response){
if(!err){
// Message inserted
session.send(`I'm just getting setup to watch your calendar for changes`);
} else {
// this should be a log for the dev, not a message to the user
session.send('There was an error inserting your message into queue: '+ err);
console.error(err);
}
session.endDialog();
});
} else {
// this should be a log for the dev, not a message to the user
session.send('There was an error creating your queue: '+ err);
console.error(err);
session.endDialog();
}
});
session.send(`Hi ${user.displayName}`);
}
));
bot.dialog('help', function (session, args, next) {
session.send("I'll watch your calendar and let you know when you get new meeting requests.");
session.send("If you want to start over a section, try saying restart");
session.endDialog("If you need to exit a conversation try using the cancel or exit command.");
})
.triggerAction({
matches: /^help$/i,
onSelectAction: (session, args, next) => {
// Add the help dialog to the dialog stack
// (override the default behavior of replacing the stack)
session.beginDialog(args.action, args);
}
});
bot.dialog('exit', function (session, args, next) {
session.endConversation('exiting...');
})
.triggerAction({
matches: /^(exit)|(cancel)|(quit)$/i,
onSelectAction: (session, args, next) => {
// Add the exit dialog to the dialog stack
session.beginDialog(args.action, args);
}
});