UNPKG

42.5 kBPlain TextView Raw
1/**
2 * @module botkit
3 */
4/**
5 * Copyright (c) Microsoft Corporation. All rights reserved.
6 * Licensed under the MIT License.
7 */
8import { Botkit, BotkitMessage } from './core';
9import { BotWorker } from './botworker';
10import { BotkitDialogWrapper } from './dialogWrapper';
11import { Activity, ActivityTypes, TurnContext, MessageFactory, ActionTypes } from 'botbuilder';
12import { Dialog, DialogContext, DialogReason, PromptValidatorContext, ActivityPrompt, DialogTurnStatus } from 'botbuilder-dialogs';
13import * as mustache from 'mustache';
14import * as Debug from 'debug';
15
16const debug = Debug('botkit:conversation');
17
18/**
19 * Definition of the handler functions used to handle .ask and .addQuestion conditions
20 */
21interface BotkitConvoHandler {
22 (answer: string, convo: BotkitDialogWrapper, bot: BotWorker, message: BotkitMessage): Promise<any>;
23}
24
25/**
26 * Definition of the trigger pattern passed into .ask or .addQuestion
27 */
28interface BotkitConvoTrigger {
29 type?: string;
30 pattern?: string | RegExp;
31 handler: BotkitConvoHandler;
32 default?: boolean;
33}
34
35/**
36 * Template for definiting a BotkitConversation template
37 */
38interface BotkitMessageTemplate {
39 text: ((template: any, vars: any) => string) | string[];
40 action?: string;
41 execute?: {
42 script: string;
43 thread?: string;
44 };
45 quick_replies?: ((template: any, vars: any) => any[]) | any[];
46 attachments?: ((template: any, vars: any) => any[]) | any[];
47 blocks?: ((template: any, vars: any) => any[]) | any[];
48 attachment?: ((template: any, vars: any) => any) | any;
49 attachmentLayout?: string;
50 channelData?: any;
51 collect: {
52 key?: string;
53 options?: BotkitConvoTrigger[];
54 };
55}
56
57export interface BotkitConversationStep {
58 /**
59 * The number pointing to the current message in the current thread in this dialog's script
60 */
61 index: number;
62 /**
63 * The name of the current thread
64 */
65 thread: string;
66 /**
67 * The length of the current thread
68 */
69 threadLength: number;
70 /**
71 * A pointer to the current dialog state
72 */
73 state: any;
74 /**
75 * A pointer to any options passed into the dialog when it began
76 */
77 options: any;
78 /**
79 * The reason for this step being called
80 */
81 reason: DialogReason;
82 /**
83 * The results of the previous turn
84 */
85 result: any;
86 /**
87 * A pointer directly to state.values
88 */
89 values: any;
90 /**
91 * A function to call when the step is completed.
92 */
93 next: (stepResult) => Promise<any>;
94}
95
96/**
97 * An extension on the [BotBuilder Dialog Class](https://docs.microsoft.com/en-us/javascript/api/botbuilder-dialogs/dialog?view=botbuilder-ts-latest) that provides a Botkit-friendly interface for
98 * defining and interacting with multi-message dialogs. Dialogs can be constructed using `say()`, `ask()` and other helper methods.
99 *
100 * ```javascript
101 * // define the structure of your dialog...
102 * const convo = new BotkitConversation('foo', controller);
103 * convo.say('Hello!');
104 * convo.ask('What is your name?', async(answer, convo, bot) => {
105 * await bot.say('Your name is ' + answer);
106 * });
107 * controller.dialogSet.add(convo);
108 *
109 * // later on, trigger this dialog by its id
110 * controller.on('event', async(bot, message) => {
111 * await bot.beginDialog('foo');
112 * })
113 * ```
114 */
115export class BotkitConversation<O extends object = {}> extends Dialog<O> {
116 /**
117 * A map of every message in the dialog, broken into threads
118 */
119 public script: any; // TODO: define this with typedefs
120
121 private _prompt: string;
122 private _beforeHooks: {};
123 private _afterHooks: { (context: TurnContext, results: any): void }[];
124 private _changeHooks: {};
125 private _controller: Botkit;
126
127 /**
128 * Create a new BotkitConversation object
129 * @param dialogId A unique identifier for this dialog, used to later trigger this dialog
130 * @param controller A pointer to the main Botkit controller
131 */
132 public constructor(dialogId: string, controller: Botkit) {
133 super(dialogId);
134
135 this._beforeHooks = {};
136 this._afterHooks = [];
137 this._changeHooks = {};
138 this.script = {};
139
140 this._controller = controller;
141
142 // Make sure there is a prompt we can use.
143 // TODO: maybe this ends up being managed by Botkit
144 this._prompt = this.id + '_default_prompt';
145 this._controller.dialogSet.add(new ActivityPrompt(
146 this._prompt,
147 (prompt: PromptValidatorContext<Activity>) => Promise.resolve(prompt.recognized.succeeded === true)
148 ));
149
150 return this;
151 }
152
153 /**
154 * Add a non-interactive message to the default thread.
155 * Messages added with `say()` and `addMessage()` will _not_ wait for a response, will be sent one after another without a pause.
156 *
157 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
158 *
159 * ```javascript
160 * let conversation = new BotkitConversation('welcome', controller);
161 * conversation.say('Hello! Welcome to my app.');
162 * conversation.say('Let us get started...');
163 * ```
164 *
165 * @param message Message template to be sent
166 */
167 public say(message: Partial<BotkitMessageTemplate> | string): BotkitConversation {
168 this.addMessage(message, 'default');
169 return this;
170 }
171
172 /**
173 * An an action to the conversation timeline. This can be used to go to switch threads or end the dialog.
174 *
175 * When provided the name of another thread in the conversation, this will cause the bot to go immediately
176 * to that thread.
177 *
178 * Otherwise, use one of the following keywords:
179 * * `stop`
180 * * `repeat`
181 * * `complete`
182 * * `timeout`
183 *
184 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
185 *
186 * ```javascript
187 *
188 * // go to a thread called "next_thread"
189 * convo.addAction('next_thread');
190 *
191 * // end the conversation and mark as successful
192 * convo.addAction('complete');
193 * ```
194 * @param action An action or thread name
195 * @param thread_name The name of the thread to which this action is added. Defaults to `default`
196 */
197 public addAction(action: string, thread_name = 'default'): BotkitConversation {
198 this.addMessage({ action: action }, thread_name);
199 return this;
200 }
201
202 /**
203 * Cause the dialog to call a child dialog, wait for it to complete,
204 * then store the results in a variable and resume the parent dialog.
205 * Use this to [combine multiple dialogs into bigger interactions.](../conversations.md#composing-dialogs)
206 *
207 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
208 * ```javascript
209 * // define a profile collection dialog
210 * let profileDialog = new BotkitConversation('PROFILE_DIALOG', controller);
211 * profileDialog.ask('What is your name?', async(res, convo, bot) => {}, {key: 'name'});
212 * profileDialog.ask('What is your age?', async(res, convo, bot) => {}, {key: 'age'});
213 * profileDialog.ask('What is your location?', async(res, convo, bot) => {}, {key: 'location'});
214 * controller.addDialog(profileDialog);
215 *
216 * let onboard = new BotkitConversation('ONBOARDING', controller);
217 * onboard.say('Hello! It is time to collect your profile data.');
218 * onboard.addChildDialog('PROFILE_DIALOG', 'profile');
219 * onboard.say('Hello, {{vars.profile.name}}! Onboarding is complete.');
220 * ```
221 *
222 * @param dialog_id the id of another dialog
223 * @param key_name the variable name in which to store the results of the child dialog. if not provided, defaults to dialog_id.
224 * @param thread_name the name of a thread to which this call should be added. defaults to 'default'
225 */
226 public addChildDialog(dialog_id: string, key_name?: string, thread_name = 'default'): BotkitConversation {
227 this.addQuestion({
228 action: 'beginDialog',
229 execute: {
230 script: dialog_id
231 }
232 }, [], { key: key_name || dialog_id }, thread_name);
233
234 return this;
235 }
236
237 /**
238 * Cause the current dialog to handoff to another dialog.
239 * The parent dialog will not resume when the child dialog completes. However, the afterDialog event will not fire for the parent dialog until all child dialogs complete.
240 * Use this to [combine multiple dialogs into bigger interactions.](../conversations.md#composing-dialogs)
241 *
242 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
243 * ```javascript
244 * let parent = new BotkitConversation('parent', controller);
245 * let child = new BotkitConversation('child', controller);
246 * parent.say('Moving on....');
247 * parent.addGotoDialog('child');
248 * ```
249 *
250 * @param dialog_id the id of another dialog
251 * @param thread_name the name of a thread to which this call should be added. defaults to 'default'
252 */
253 public addGotoDialog(dialog_id: string, thread_name = 'default'): BotkitConversation {
254 this.addMessage({
255 action: 'execute_script',
256 execute: {
257 script: dialog_id
258 }
259 }, thread_name);
260
261 return this;
262 }
263
264 /**
265 * Add a message template to a specific thread.
266 * Messages added with `say()` and `addMessage()` will be sent one after another without a pause.
267 *
268 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
269 * ```javascript
270 * let conversation = new BotkitConversation('welcome', controller);
271 * conversation.say('Hello! Welcome to my app.');
272 * conversation.say('Let us get started...');
273 * // pass in a message with an action that will cause gotoThread to be called...
274 * conversation.addAction('continuation');
275 *
276 * conversation.addMessage('This is a different thread completely', 'continuation');
277 * ```
278 *
279 * @param message Message template to be sent
280 * @param thread_name Name of thread to which message will be added
281 */
282 public addMessage(message: Partial<BotkitMessageTemplate> | string, thread_name: string): BotkitConversation {
283 if (!thread_name) {
284 thread_name = 'default';
285 }
286
287 if (!this.script[thread_name]) {
288 this.script[thread_name] = [];
289 }
290
291 if (typeof (message) === 'string') {
292 message = { text: [message] };
293 }
294
295 this.script[thread_name].push(message);
296
297 return this;
298 }
299
300 /**
301 * Add a question to the default thread.
302 * In addition to a message template, receives either a single handler function to call when an answer is provided,
303 * or an array of handlers paired with trigger patterns. When providing multiple conditions to test, developers may also provide a
304 * handler marked as the default choice.
305 *
306 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
307 * ```javascript
308 * // ask a question, handle the response with a function
309 * convo.ask('What is your name?', async(response, convo, bot, full_message) => {
310 * await bot.say('Oh your name is ' + response);
311 * }, {key: 'name'});
312 *
313 * // ask a question, evaluate answer, take conditional action based on response
314 * convo.ask('Do you want to eat a taco?', [
315 * {
316 * pattern: 'yes',
317 * type: 'string',
318 * handler: async(response_text, convo, bot, full_message) => {
319 * return await convo.gotoThread('yes_taco');
320 * }
321 * },
322 * {
323 * pattern: 'no',
324 * type: 'string',
325 * handler: async(response_text, convo, bot, full_message) => {
326 * return await convo.gotoThread('no_taco');
327 * }
328 * },
329 * {
330 * default: true,
331 * handler: async(response_text, convo, bot, full_message) => {
332 * await bot.say('I do not understand your response!');
333 * // start over!
334 * return await convo.repeat();
335 * }
336 * }
337 * ], {key: 'tacos'});
338 * ```
339 *
340 * @param message a message that will be used as the prompt
341 * @param handlers one or more handler functions defining possible conditional actions based on the response to the question.
342 * @param key name of variable to store response in.
343 */
344 public ask(message: Partial<BotkitMessageTemplate> | string, handlers: BotkitConvoHandler | BotkitConvoTrigger[], key: {key: string} | string | null): BotkitConversation {
345 this.addQuestion(message, handlers, key, 'default');
346 return this;
347 }
348
349 /**
350 * Identical to [ask()](#ask), but accepts the name of a thread to which the question is added.
351 *
352 * [Learn more about building conversations &rarr;](../conversations.md#build-a-conversation)
353 * @param message A message that will be used as the prompt
354 * @param handlers One or more handler functions defining possible conditional actions based on the response to the question
355 * @param key Name of variable to store response in.
356 * @param thread_name Name of thread to which message will be added
357 */
358 public addQuestion(message: Partial<BotkitMessageTemplate> | string, handlers: BotkitConvoHandler | BotkitConvoTrigger[], key: {key: string} | string | null, thread_name: string): BotkitConversation {
359 if (!thread_name) {
360 thread_name = 'default';
361 }
362
363 if (!this.script[thread_name]) {
364 this.script[thread_name] = [];
365 }
366
367 if (typeof (message) === 'string') {
368 message = { text: [message as string] };
369 }
370
371 message.collect = {};
372
373 if (key) {
374 message.collect = {
375 key: typeof (key) === 'string' ? key : key.key
376 };
377 }
378
379 if (Array.isArray(handlers)) {
380 message.collect.options = handlers;
381 } else if (typeof (handlers) === 'function') {
382 message.collect.options = [
383 {
384 default: true,
385 handler: handlers
386 }
387 ];
388 } else {
389 throw new Error('Unsupported handlers type: ' + typeof (handlers));
390 }
391
392 // ensure all options have a type field
393 message.collect.options.forEach((o) => { if (!o.type) { o.type = 'string'; } });
394
395 this.script[thread_name].push(message);
396
397 // add a null message where the handlers for the previous message will fire.
398 this.script[thread_name].push({ action: 'next' });
399
400 return this;
401 }
402
403 /**
404 * Register a handler function that will fire before a given thread begins.
405 * Use this hook to set variables, call APIs, or change the flow of the conversation using `convo.gotoThread`
406 *
407 * ```javascript
408 * convo.addMessage('This is the foo thread: var == {{vars.foo}}', 'foo');
409 * convo.before('foo', async(convo, bot) => {
410 * // set a variable here that can be used in the message template
411 * convo.setVar('foo','THIS IS FOO');
412 *
413 * });
414 * ```
415 *
416 * @param thread_name A valid thread defined in this conversation
417 * @param handler A handler function in the form async(convo, bot) => { ... }
418 */
419 public before(thread_name: string, handler: (convo: BotkitDialogWrapper, bot: BotWorker) => Promise<any>): void {
420 if (!this._beforeHooks[thread_name]) {
421 this._beforeHooks[thread_name] = [];
422 }
423
424 this._beforeHooks[thread_name].push(handler);
425 }
426
427 /**
428 * This private method is called before a thread begins, and causes any bound handler functions to be executed.
429 * @param thread_name the thread about to begin
430 * @param dc the current DialogContext
431 * @param step the current step object
432 */
433 private async runBefore(thread_name: string, dc: DialogContext, step: BotkitConversationStep): Promise<void> {
434 debug('Before:', this.id, thread_name);
435
436 if (this._beforeHooks[thread_name]) {
437 // spawn a bot instance so devs can use API or other stuff as necessary
438 const bot = await this._controller.spawn(dc);
439
440 // create a convo controller object
441 const convo = new BotkitDialogWrapper(dc, step);
442
443 for (let h = 0; h < this._beforeHooks[thread_name].length; h++) {
444 const handler = this._beforeHooks[thread_name][h];
445 await handler.call(this, convo, bot);
446 }
447 }
448 }
449
450 /**
451 * Bind a function to run after the dialog has completed.
452 * The first parameter to the handler will include a hash of all variables set and values collected from the user during the conversation.
453 * The second parameter to the handler is a BotWorker object that can be used to start new dialogs or take other actions.
454 *
455 * [Learn more about handling end of conversation](../conversations.md#handling-end-of-conversation)
456 * ```javascript
457 * let convo = new BotkitConversation(MY_CONVO, controller);
458 * convo.ask('What is your name?', [], 'name');
459 * convo.ask('What is your age?', [], 'age');
460 * convo.ask('What is your favorite color?', [], 'color');
461 * convo.after(async(results, bot) => {
462 *
463 * // handle results.name, results.age, results.color
464 *
465 * });
466 * controller.addDialog(convo);
467 * ```
468 *
469 * @param handler in the form async(results, bot) { ... }
470 */
471 public after(handler: (results: any, bot: BotWorker) => void): void {
472 this._afterHooks.push(handler);
473 }
474
475 /**
476 * This private method is called at the end of the conversation, and causes any bound handler functions to be executed.
477 * @param context the current dialog context
478 * @param results an object containing the final results of the dialog
479 */
480 private async runAfter(context: DialogContext, results: any): Promise<void> {
481 debug('After:', this.id);
482 if (this._afterHooks.length) {
483 const bot = await this._controller.spawn(context);
484 for (let h = 0; h < this._afterHooks.length; h++) {
485 const handler = this._afterHooks[h];
486 await handler.call(this, results, bot);
487 }
488 }
489 }
490
491 /**
492 * Bind a function to run whenever a user answers a specific question. Can be used to validate input and take conditional actions.
493 *
494 * ```javascript
495 * convo.ask('What is your name?', [], 'name');
496 * convo.onChange('name', async(response, convo, bot) => {
497 *
498 * // user changed their name!
499 * // do something...
500 *
501 * });
502 * ```
503 * @param variable name of the variable to watch for changes
504 * @param handler a handler function that will fire whenever a user's response is used to change the value of the watched variable
505 */
506 public onChange(variable: string, handler: (response, convo, bot) => Promise<any>): void {
507 if (!this._changeHooks[variable]) {
508 this._changeHooks[variable] = [];
509 }
510
511 this._changeHooks[variable].push(handler);
512 }
513
514 /**
515 * This private method is responsible for firing any bound onChange handlers when a variable changes
516 * @param variable the name of the variable that is changing
517 * @param value the new value of the variable
518 * @param dc the current DialogContext
519 * @param step the current step object
520 */
521 private async runOnChange(variable: string, value: any, dc: DialogContext, step: BotkitConversationStep): Promise<void> {
522 debug('OnChange:', this.id, variable);
523
524 if (this._changeHooks[variable] && this._changeHooks[variable].length) {
525 // spawn a bot instance so devs can use API or other stuff as necessary
526 const bot = await this._controller.spawn(dc);
527
528 // create a convo controller object
529 const convo = new BotkitDialogWrapper(dc, step);
530
531 for (let h = 0; h < this._changeHooks[variable].length; h++) {
532 const handler = this._changeHooks[variable][h];
533 await handler.call(this, value, convo, bot);
534 }
535 }
536 }
537
538 /**
539 * Called automatically when a dialog begins. Do not call this directly!
540 * @ignore
541 * @param dc the current DialogContext
542 * @param options an object containing initialization parameters passed to the dialog. may include `thread` which will cause the dialog to begin with that thread instead of the `default` thread.
543 */
544 public async beginDialog(dc: DialogContext, options: any): Promise<any> {
545 // Initialize the state
546 const state = dc.activeDialog.state;
547 state.options = options || {};
548 state.values = { ...options };
549
550 // Run the first step
551 return await this.runStep(dc, 0, state.options.thread || 'default', DialogReason.beginCalled);
552 }
553
554 /**
555 * Called automatically when an already active dialog is continued. Do not call this directly!
556 * @ignore
557 * @param dc the current DialogContext
558 */
559 public async continueDialog(dc: DialogContext): Promise<any> {
560 // Don't do anything for non-message activities
561 if (dc.context.activity.type !== ActivityTypes.Message) {
562 return Dialog.EndOfTurn;
563 }
564
565 // Run next step with the message text as the result.
566 return await this.resumeDialog(dc, DialogReason.continueCalled, dc.context.activity);
567 }
568
569 /**
570 * Called automatically when a dialog moves forward a step. Do not call this directly!
571 * @ignore
572 * @param dc The current DialogContext
573 * @param reason Reason for resuming the dialog
574 * @param result Result of previous step
575 */
576 public async resumeDialog(dc, reason, result): Promise<any> {
577 // Increment step index and run step
578 if (dc.activeDialog) {
579 const state = dc.activeDialog.state;
580 return await this.runStep(dc, state.stepIndex + 1, state.thread || 'default', reason, result);
581 } else {
582 return Dialog.EndOfTurn;
583 }
584 }
585
586 /**
587 * Called automatically to process the turn, interpret the script, and take any necessary actions based on that script. Do not call this directly!
588 * @ignore
589 * @param dc The current dialog context
590 * @param step The current step object
591 */
592 private async onStep(dc, step): Promise<any> {
593 // Let's interpret the current line of the script.
594 const thread = this.script[step.thread];
595
596 if (!thread) {
597 throw new Error(`Thread '${ step.thread }' not found, did you add any messages to it?`);
598 }
599
600 // Capture the previous step value if there previous line included a prompt
601 const previous = (step.index >= 1) ? thread[step.index - 1] : null;
602 if (step.result && previous && previous.collect) {
603 if (previous.collect.key) {
604 // capture before values
605 const index = step.index;
606 const thread_name = step.thread;
607
608 // capture the user input value into the array
609 if (step.values[previous.collect.key] && previous.collect.multiple) {
610 step.values[previous.collect.key] = [step.values[previous.collect.key], step.result].join('\n');
611 } else {
612 step.values[previous.collect.key] = step.result;
613 }
614
615 // run onChange handlers
616 await this.runOnChange(previous.collect.key, step.result, dc, step);
617
618 // did we just change threads? if so, restart this turn
619 if (index !== step.index || thread_name !== step.thread) {
620 return await this.runStep(dc, step.index, step.thread, DialogReason.nextCalled);
621 }
622 }
623
624 // handle conditions of previous step
625 if (previous.collect.options) {
626 const paths = previous.collect.options.filter((option) => { return !option.default === true; });
627 const default_path = previous.collect.options.filter((option) => { return option.default === true; })[0];
628 let path = null;
629
630 for (let p = 0; p < paths.length; p++) {
631 const condition = paths[p];
632 let test;
633 if (condition.type === 'string') {
634 test = new RegExp(condition.pattern, 'i');
635 } else if (condition.type === 'regex') {
636 test = new RegExp(condition.pattern, 'i');
637 }
638 // TODO: Allow functions to be passed in as patterns
639 // ie async(test) => Promise<boolean>
640
641 if (step.result && typeof (step.result) === 'string' && step.result.match(test)) {
642 path = condition;
643 break;
644 }
645 }
646
647 // take default path if one is set
648 if (!path) {
649 path = default_path;
650 }
651
652 if (path) {
653 if (path.action !== 'wait' && previous.collect && previous.collect.multiple) {
654 // TODO: remove the final line of input
655 // since this would represent the "end" message and probably not part of the input
656 }
657
658 const res = await this.handleAction(path, dc, step);
659 if (res !== false) {
660 return res;
661 }
662 }
663 }
664 }
665
666 // was the dialog canceled during the last action?
667 if (!dc.activeDialog) {
668 return await this.end(dc);
669 }
670
671 // Handle the current step
672 if (step.index < thread.length) {
673 const line = thread[step.index];
674
675 // If a prompt is defined in the script, use dc.prompt to call it.
676 // This prompt must be a valid dialog defined somewhere in your code!
677 if (line.collect && line.action !== 'beginDialog') {
678 try {
679 return await dc.prompt(this._prompt, await this.makeOutgoing(dc, line, step.values));
680 } catch (err) {
681 console.error(err);
682 await dc.context.sendActivity(`Failed to start prompt ${ this._prompt }`);
683 return await step.next();
684 }
685 // If there's nothing but text, send it!
686 // This could be extended to include cards and other activity attributes.
687 } else {
688 // if there is text, attachments, or any channel data fields at all...
689 if (line.type || line.text || line.attachments || line.attachment || line.blocks || (line.channelData && Object.keys(line.channelData).length)) {
690 await dc.context.sendActivity(await this.makeOutgoing(dc, line, step.values));
691 } else if (!line.action) {
692 console.error('Dialog contains invalid message', line);
693 }
694
695 if (line.action) {
696 const res = await this.handleAction(line, dc, step);
697 if (res !== false) {
698 return res;
699 }
700 }
701
702 return await step.next();
703 }
704 } else {
705 // End of script so just return to parent
706 return await this.end(dc);
707 }
708 }
709
710 /**
711 * Run a dialog step, based on the index and thread_name passed in.
712 * @param dc The current DialogContext
713 * @param index The index of the current step
714 * @param thread_name The name of the current thread
715 * @param reason The reason given for running this step
716 * @param result The result of the previous turn if any
717 */
718 private async runStep(dc: DialogContext, index: number, thread_name: string, reason: DialogReason, result?: any): Promise<any> {
719 // Update the step index
720 const state = dc.activeDialog.state;
721 state.stepIndex = index;
722 state.thread = thread_name;
723 // Create step context
724 const nextCalled = false;
725 const step = {
726 index: index,
727 threadLength: this.script[thread_name].length,
728 thread: thread_name,
729 state: state,
730 options: state.options,
731 reason: reason,
732 result: result && result.text ? result.text : result,
733 resultObject: result,
734 values: state.values,
735 next: async (stepResult): Promise<any> => {
736 if (nextCalled) {
737 throw new Error(`ScriptedStepContext.next(): method already called for dialog and step '${ this.id }[${ index }]'.`);
738 }
739 return await this.resumeDialog(dc, DialogReason.nextCalled, stepResult);
740 }
741 };
742
743 // did we just start a new thread?
744 // if so, run the before stuff.
745 if (index === 0) {
746 await this.runBefore(step.thread, dc, step);
747
748 // did we just change threads? if so, restart
749 if (index !== step.index || thread_name !== step.thread) {
750 return await this.runStep(dc, step.index, step.thread, DialogReason.nextCalled); // , step.values);
751 }
752 }
753
754 // Execute step
755 const res = await this.onStep(dc, step);
756
757 return res;
758 }
759
760 /**
761 * Automatically called when the the dialog ends and causes any handlers bound using `after()` to fire. Do not call this directly!
762 * @ignore
763 * @param dc The current DialogContext
764 * @param value The final value collected by the dialog.
765 */
766 public async end(dc: DialogContext): Promise<DialogTurnStatus> {
767 // TODO: may have to move these around
768 // shallow copy todo: may need deep copy
769 // protect against canceled dialog.
770 if (dc.activeDialog && dc.activeDialog.state) {
771 const result = {
772 ...dc.activeDialog.state.values
773 };
774 await dc.endDialog(result);
775 await this.runAfter(dc, result);
776 } else {
777 await dc.endDialog();
778 }
779
780 return DialogTurnStatus.complete;
781 }
782
783 /**
784 * Translates a line from the dialog script into an Activity. Responsible for doing token replacement.
785 * @param line a message template from the script
786 * @param vars an object containing key/value pairs used to do token replacement on fields in the message template
787 */
788 private async makeOutgoing(dc: DialogContext, line: any, vars: any): Promise<any> {
789 let outgoing;
790 let text = '';
791
792 // if the text is just a string, use it.
793 // otherwise, if it is an array, pick a random element
794 if (line.text && typeof (line.text) === 'string') {
795 text = line.text;
796 // If text is a function, call the function to get the actual text value.
797 } else if (line.text && typeof (line.text) === 'function') {
798 text = await line.text(line, vars);
799 } else if (Array.isArray(line.text)) {
800 text = line.text[Math.floor(Math.random() * line.text.length)];
801 }
802
803 /*******************************************************************************************************************/
804 // use Bot Framework's message factory to construct the initial object.
805 if (line.quick_replies && typeof (line.quick_replies) !== 'function') {
806 outgoing = MessageFactory.suggestedActions(line.quick_replies.map((reply) => { return { type: ActionTypes.PostBack, title: reply.title, text: reply.payload, displayText: reply.title, value: reply.payload }; }), text);
807 } else {
808 outgoing = MessageFactory.text(text);
809 }
810
811 outgoing.channelData = outgoing.channelData ? outgoing.channelData : {};
812 if (line.attachmentLayout) {
813 outgoing.attachmentLayout = line.attachmentLayout;
814 }
815 /*******************************************************************************************************************/
816 // allow dynamic generation of quick replies and/or attachments
817 if (typeof (line.quick_replies) === 'function') {
818 // set both formats of quick replies
819 outgoing.channelData.quick_replies = await line.quick_replies(line, vars);
820 outgoing.suggestedActions = { actions: outgoing.channelData.quick_replies.map((reply) => { return { type: ActionTypes.PostBack, title: reply.title, text: reply.payload, displayText: reply.title, value: reply.payload }; }) };
821 }
822 if (typeof (line.attachment) === 'function') {
823 outgoing.channelData.attachment = await line.attachment(line, vars);
824 }
825 if (typeof (line.attachments) === 'function') {
826 // set both locations for attachments
827 outgoing.attachments = outgoing.channelData.attachments = await line.attachments(line, vars);
828 }
829 if (typeof (line.blocks) === 'function') {
830 outgoing.channelData.blocks = await line.blocks(line, vars);
831 }
832
833 /*******************************************************************************************************************/
834 // Map some fields into the appropriate places for processing by Botkit/ Bot Framework
835
836 // Quick replies are used by Facebook and Web adapters, but in a different way than they are for Bot Framework.
837 // In order to make this as easy as possible, copy these fields for the developer into channelData.
838 if (line.quick_replies && typeof (line.quick_replies) !== 'function') {
839 outgoing.channelData.quick_replies = JSON.parse(JSON.stringify(line.quick_replies));
840 }
841
842 // Similarly, attachment and blocks fields are platform specific.
843 // handle slack Block attachments
844 if (line.blocks && typeof (line.blocks) !== 'function') {
845 outgoing.channelData.blocks = JSON.parse(JSON.stringify(line.blocks));
846 }
847
848 // handle facebook attachments.
849 if (line.attachment && typeof (line.attachment) !== 'function') {
850 outgoing.channelData.attachment = JSON.parse(JSON.stringify(line.attachment));
851 }
852
853 // set the type
854 if (line.type) {
855 outgoing.type = JSON.parse(JSON.stringify(line.type));
856 }
857
858 // copy all the values in channelData fields
859 if (line.channelData && Object.keys(line.channelData).length > 0) {
860 const channelDataParsed = this.parseTemplatesRecursive(JSON.parse(JSON.stringify(line.channelData)), vars);
861
862 outgoing.channelData = {
863 ...outgoing.channelData,
864 ...channelDataParsed
865 };
866 }
867
868 /*******************************************************************************************************************/
869 // Handle template token replacements
870 if (outgoing.text) {
871 outgoing.text = mustache.render(outgoing.text, { vars: vars });
872 }
873
874 // process templates in native botframework attachments and/or slack attachments
875 if (line.attachments && typeof (line.attachments) !== 'function') {
876 outgoing.attachments = this.parseTemplatesRecursive(JSON.parse(JSON.stringify(line.attachments)), vars);
877 }
878
879 // process templates in slack attachments in channelData
880 if (outgoing.channelData.attachments) {
881 outgoing.channelData.attachments = this.parseTemplatesRecursive(outgoing.channelData.attachments, vars);
882 }
883 if (outgoing.channelData.blocks) {
884 outgoing.channelData.blocks = this.parseTemplatesRecursive(outgoing.channelData.blocks, vars);
885 }
886
887 // process templates in facebook attachments
888 if (outgoing.channelData.attachment) {
889 outgoing.channelData.attachment = this.parseTemplatesRecursive(outgoing.channelData.attachment, vars);
890 }
891
892 // process templates in quick replies
893 if (outgoing.channelData.quick_replies) {
894 outgoing.channelData.quick_replies = this.parseTemplatesRecursive(outgoing.channelData.quick_replies, vars);
895 }
896 // process templates in quick replies
897 if (outgoing.suggestedActions) {
898 outgoing.suggestedActions = this.parseTemplatesRecursive(outgoing.suggestedActions, vars);
899 }
900
901 return new Promise((resolve, reject) => {
902 // run the outgoing message through the Botkit send middleware
903 this._controller.spawn(dc).then((bot) => {
904 this._controller.middleware.send.run(bot, outgoing, (err, bot, outgoing) => {
905 if (err) {
906 reject(err);
907 } else {
908 resolve(outgoing);
909 }
910 });
911 }).catch(reject);
912 });
913 }
914
915 /**
916 * Responsible for doing token replacements recursively in attachments and other multi-field properties of the message.
917 * @param attachments some object or array containing values for which token replacements should be made.
918 * @param vars an object defining key/value pairs used for the token replacements
919 */
920 private parseTemplatesRecursive(attachments: any, vars: any): any {
921 if (attachments && attachments.length) {
922 for (let a = 0; a < attachments.length; a++) {
923 for (const key in attachments[a]) {
924 if (typeof (attachments[a][key]) === 'string') {
925 attachments[a][key] = mustache.render(attachments[a][key], { vars: vars });
926 } else {
927 attachments[a][key] = this.parseTemplatesRecursive(attachments[a][key], vars);
928 }
929 }
930 }
931 } else {
932 for (const x in attachments) {
933 if (typeof (attachments[x]) === 'string') {
934 attachments[x] = mustache.render(attachments[x], { vars: vars });
935 } else {
936 attachments[x] = this.parseTemplatesRecursive(attachments[x], vars);
937 }
938 }
939 }
940
941 return attachments;
942 }
943
944 /**
945 * Handle the scripted "gotothread" action - requires an additional call to runStep.
946 * @param thread The name of the thread to jump to
947 * @param dc The current DialogContext
948 * @param step The current step object
949 */
950 private async gotoThreadAction(thread: string, dc: DialogContext, step: BotkitConversationStep): Promise<any> {
951 step.thread = thread;
952 step.index = 0;
953
954 return await this.runStep(dc, step.index, step.thread, DialogReason.nextCalled, step.values);
955 }
956
957 /**
958 * Accepts a Botkit script action, and performs that action
959 * @param path A conditional path in the form {action: 'some action', handler?: some handler function, maybe_other_fields}
960 * @param dc The current DialogContext
961 * @param step The current stpe object
962 */
963 private async handleAction(path, dc, step): Promise<any> {
964 let worker = null;
965 if (path.handler) {
966 const index = step.index;
967 const thread_name = step.thread;
968 const result = step.result;
969 const response = result == null ? null : (result.text || (typeof (result) === 'string' ? result : null));
970
971 // spawn a bot instance so devs can use API or other stuff as necessary
972 const bot = await this._controller.spawn(dc);
973
974 // create a convo controller object
975 const convo = new BotkitDialogWrapper(dc, step);
976
977 const activedialog = dc.activeDialog.id;
978
979 await path.handler.call(this, response, convo, bot, dc.context.turnState.get('botkitMessage') || dc.context.activity);
980
981 if (!dc.activeDialog) {
982 return false;
983 }
984
985 // did we change dialogs? if so, return an endofturn because the new dialog has taken over.
986 if (activedialog !== dc.activeDialog.id) {
987 return Dialog.EndOfTurn;
988 }
989
990 // did we just change threads? if so, restart this turn
991 if (index !== step.index || thread_name !== step.thread) {
992 return await this.runStep(dc, step.index, step.thread, DialogReason.nextCalled, null);
993 }
994
995 return false;
996 }
997
998 switch (path.action) {
999 case 'next':
1000 // noop
1001 break;
1002 case 'complete':
1003 step.values._status = 'completed';
1004 return await this.end(dc);
1005 case 'stop':
1006 step.values._status = 'canceled';
1007 return await this.end(dc);
1008 case 'timeout':
1009 step.values._status = 'timeout';
1010 return await this.end(dc);
1011 case 'execute_script':
1012 worker = await this._controller.spawn(dc);
1013
1014 await worker.replaceDialog(path.execute.script, {
1015 thread: path.execute.thread,
1016 ...step.values
1017 });
1018
1019 return { status: DialogTurnStatus.waiting };
1020 case 'beginDialog':
1021 worker = await this._controller.spawn(dc);
1022
1023 await worker.beginDialog(path.execute.script, {
1024 thread: path.execute.thread,
1025 ...step.values
1026 });
1027 return { status: DialogTurnStatus.waiting };
1028 case 'repeat':
1029 return await this.runStep(dc, step.index - 1, step.thread, DialogReason.nextCalled);
1030 case 'wait':
1031 // reset the state so we're still on this step.
1032 step.state.stepIndex = step.index - 1;
1033 // send a waiting status
1034 return { status: DialogTurnStatus.waiting };
1035 default:
1036 // the default behavior for unknown action in botkit is to gotothread
1037 if (this.script[path.action]) {
1038 return await this.gotoThreadAction(path.action, dc, step);
1039 }
1040 console.warn('NOT SURE WHAT TO DO WITH THIS!!', path);
1041 break;
1042 }
1043
1044 return false;
1045 }
1046}