UNPKG

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