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