-
Notifications
You must be signed in to change notification settings - Fork 281
/
Copy pathactivityHandler.ts
322 lines (296 loc) · 12.2 KB
/
activityHandler.ts
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
/**
* @module botbuilder
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { Activity, ActivityTypes, TurnContext } from '.';
export type BotHandler = (context: TurnContext, next: () => Promise<void>) => Promise<any>;
/**
* Event-emitting base class bots.
*
* @remarks
* This provides an extensible base class for handling incoming
* activities in an event-driven way. Developers may bind one or
* more handlers for each type of event.
*
* To bind a handler to an event, use the `on<Event>()` method, for example:
*
* ```Javascript
* bot.onMessage(async (context, next) => {
* // do something
* // then `await next()` to continue processing
* await next();
* });
* ```
*
* A series of events will be emitted while the activity is being processed.
* Handlers can stop the propagation of the event by omitting a call to `next()`.
*
* * Turn - emitted for every activity
* * Type-specific - an event, based on activity.type
* * Sub-type - any specialized events, based on activity content
* * Dialog - the final event, used for processing Dialog actions
*
* A simple implementation:
* ```Javascript
* const bot = new ActivityHandler();
*
* server.post('/api/messages', (req, res) => {
* adapter.processActivity(req, res, async (context) => {
* // Route to main dialog.
* await bot.run(context);
* });
* });
*
* bot.onMessage(async (context, next) => {
* // do stuff
* await context.sendActivity(`Echo: ${ context.activity.text }`);
* // proceed with further processing
* await next();
* });
* ```
*/
export class ActivityHandler {
private readonly handlers: {[type: string]: BotHandler[]} = {};
/**
* Bind a handler to the Turn event that is fired for every incoming activity, regardless of type
* @remarks
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onTurn(handler: BotHandler): this {
return this.on('Turn', handler);
}
/**
* Receives all incoming Message activities
* @remarks
* Message activities represent content intended to be shown within a conversational interface.
* Message activities may contain text, speech, interactive cards, and binary or unknown attachments.
* Note that while most messages do contain text, this field is not always present!
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onMessage(handler: BotHandler): this {
return this.on('Message', handler);
}
/**
* Receives all ConversationUpdate activities, regardless of whether members were added or removed
* @remarks
* Conversation update activities describe a change in a conversation's members, description, existence, or otherwise.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onConversationUpdate(handler: BotHandler): this {
return this.on('ConversationUpdate', handler);
}
/**
* Receives only ConversationUpdate activities representing members being added.
* @remarks
* context.activity.membersAdded will include at least one entry.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onMembersAdded(handler: BotHandler): this {
return this.on('MembersAdded', handler);
}
/**
* Receives only ConversationUpdate activities representing members being removed.
* @remarks
* context.activity.membersRemoved will include at least one entry.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onMembersRemoved(handler: BotHandler): this {
return this.on('MembersRemoved', handler);
}
/**
* Receives only MessageReaction activities, regardless of whether message reactions were added or removed
* @remarks
* MessageReaction activities are sent to the bot when a message reacion, such as 'like' or 'sad' are
* associated with an activity previously sent from the bot.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onMessageReaction(handler: BotHandler): this {
return this.on('MessageReaction', handler);
}
/**
* Receives only MessageReaction activities representing message reactions being added.
* @remarks
* context.activity.reactionsAdded will include at least one entry.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onReactionsAdded(handler: BotHandler): this {
return this.on('ReactionsAdded', handler);
}
/**
* Receives only MessageReaction activities representing message reactions being removed.
* @remarks
* context.activity.reactionsRemoved will include at least one entry.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onReactionsRemoved(handler: BotHandler): this {
return this.on('ReactionsRemoved', handler);
}
/**
* Receives all Event activities.
* @remarks
* Event activities communicate programmatic information from a client or channel to a bot.
* The meaning of an event activity is defined by the `name` field.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onEvent(handler: BotHandler): this {
return this.on('Event', handler);
}
/**
* Receives event activities of type 'tokens/response'
* @remarks
* These events occur during the oauth flow
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onTokenResponseEvent(handler: BotHandler): this {
return this.on('TokenResponseEvent', handler);
}
/**
* UnrecognizedActivityType will fire if an activity is received with a type that has not previously been defined.
* @remarks
* Some channels or custom adapters may create Actitivies with different, "unofficial" types.
* These events will be passed through as UnrecognizedActivityType events.
* Check `context.activity.type` for the type value.
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onUnrecognizedActivityType(handler: BotHandler): this {
return this.on('UnrecognizedActivityType', handler);
}
/**
* onDialog fires at the end of the event emission process, and should be used to handle Dialog activity.
* @remarks
* Sample code:
* ```javascript
* bot.onDialog(async (context, next) => {
* if (context.activity.type === ActivityTypes.Message) {
* const dialogContext = await dialogSet.createContext(context);
* const results = await dialogContext.continueDialog();
* await conversationState.saveChanges(context);
* }
*
* await next();
* });
* ```
* @param handler BotHandler A handler function in the form async(context, next) => { ... }
*/
public onDialog(handler: BotHandler): this {
return this.on('Dialog', handler);
}
/**
* `run()` is the main "activity handler" function used to ingest activities into the event emission process.
* @remarks
* Sample code:
* ```javascript
* server.post('/api/messages', (req, res) => {
* adapter.processActivity(req, res, async (context) => {
* // Route to main dialog.
* await bot.run(context);
* });
* });
* ```
*
* @param context TurnContext A TurnContext representing an incoming Activity from an Adapter
*/
public async run(context: TurnContext): Promise<void> {
if (!context) {
throw new Error(`Missing TurnContext parameter`);
}
if (!context.activity) {
throw new Error(`TurnContext does not include an activity`);
}
if (!context.activity.type) {
throw new Error(`Activity is missing it's type`);
}
// Allow the dialog system to be triggered at the end of the chain
const runDialogs = async (): Promise<void> => {
await this.handle(context, 'Dialog', async () => {
// noop
});
};
// List of all Activity Types:
// https://github.com/Microsoft/botbuilder-js/blob/master/libraries/botframework-schema/src/index.ts#L1627
await this.handle(context, 'Turn', async () => {
switch (context.activity.type) {
case ActivityTypes.Message:
await this.handle(context, 'Message', runDialogs);
break;
case ActivityTypes.ConversationUpdate:
await this.handle(context, 'ConversationUpdate', async () => {
if (context.activity.membersAdded && context.activity.membersAdded.length > 0) {
await this.handle(context, 'MembersAdded', runDialogs);
} else if (context.activity.membersRemoved && context.activity.membersRemoved.length > 0) {
await this.handle(context, 'MembersRemoved', runDialogs);
} else {
await runDialogs();
}
});
break;
case ActivityTypes.MessageReaction:
await this.handle(context, 'MessageReaction', async () => {
if (context.activity.reactionsAdded && context.activity.reactionsAdded.length > 0) {
await this.handle(context, 'ReactionsAdded', runDialogs);
} else if (context.activity.reactionsRemoved && context.activity.reactionsRemoved.length > 0) {
await this.handle(context, 'ReactionsRemoved', runDialogs);
} else {
await runDialogs();
}
});
break;
case ActivityTypes.Event:
await this.handle(context, 'Event', async () => {
if (context.activity.name === 'tokens/response') {
await this.handle(context, 'TokenResponseEvent', runDialogs);
} else {
await runDialogs();
}
});
break;
default:
// handler for unknown or unhandled types
await this.handle(context, 'UnrecognizedActivityType', runDialogs);
break;
}
});
}
/**
* Used to bind handlers to events by name
* @param type string
* @param handler BotHandler
*/
protected on(type: string, handler: BotHandler) {
if (!this.handlers[type]) {
this.handlers[type] = [handler];
} else {
this.handlers[type].push(handler);
}
return this;
}
/**
* Used to fire events and execute any bound handlers
* @param type string
* @param handler BotHandler
*/
protected async handle(context: TurnContext, type: string, onNext: () => Promise<void>): Promise<any> {
let returnValue: any = null;
async function runHandler(index: number): Promise<void> {
if (index < handlers.length) {
const val = await handlers[index](context, () => runHandler(index + 1));
// if a value is returned, and we have not yet set the return value,
// capture it. This is used to allow InvokeResponses to be returned.
if (typeof(val) !== 'undefined' && returnValue === null) {
returnValue = val;
}
} else {
const val = await onNext();
if (typeof(val) !== 'undefined') {
returnValue = val;
}
}
}
const handlers = this.handlers[type] || [];
await runHandler(0);
return returnValue;
}
}