UNPKG

umbot

Version:

Мультиплатформенный фреймворк для создания голосовых навыков и чат-ботов с единой бизнес-логикой. Встроенная поддержка ВКонтакте, Telegram, Viber, MAX, Яндекс Алисы, Маруси и Сбера SmartApp. Архитектура на адаптерах позволяет подключать любые другие платф

145 lines (130 loc) 5.2 kB
/** * Created by umbot * Date: {{date}} * Time: {{time}} */ import { BotController, Text, WELCOME_INTENT_NAME, IUserData, SoundConstants } from 'umbot'; interface IQuestion { text: string; variants: string[]; success: string; } interface IMyUserData extends IUserData { question_id: number; } /** * Шаблон для контроллера викторины * Class __className__Controller */ export class __className__Controller extends BotController<IMyUserData> { public question: IQuestion[]; protected readonly START_QUESTION = 'start'; protected readonly GAME_QUESTION = 'game'; public constructor() { super(); this.question = [ { text: 'Луна это', // Вопрос variants: ['Спутник', 'Хлопья', 'Звезда'], // Возможные варианты ответа success: 'Спутник', // Правильный ответ }, ]; } /** * Получаем вопрос и отображаем его пользователю * * @param {number} id Идентификатор записи */ protected _setQuestionText(id: number) { if (this.question[id] === undefined) { id = 0; } this.userData.question_id = id; this.text = this.question[id].text; this.question[id].variants.forEach((variant) => { this.buttons.addBtn(variant); }); } /** * Проверяем правильно ответил пользователь или нет * * @param {string} text пользовательский ответ * @param {number} questionId номер вопроса */ protected _isSuccess(text: string | null, questionId: number) { if (Text.isSayText(this.question[questionId].success, text || '')) { const successTexts = ['Совершенно верно!']; this.text = Text.getText(successTexts); this.tts = this.text + SoundConstants.S_AUDIO_GAME_WIN; questionId++; } else { const failTexts = ['Ты ошибся... Попробуй ещё раз.']; this.text = Text.getText(failTexts); this.tts = this.text + SoundConstants.S_AUDIO_GAME_LOSS; } this._setQuestionText(questionId); } /** * Начат квест */ protected _quiz() { this.thisIntentName = this.GAME_QUESTION; if (this.userData.question_id !== undefined) { this._isSuccess(this.userCommand, this.userData.question_id); } else { this._setQuestionText(0); } } /** * Отображаем пользователю текст помощи. */ protected _help() { this.text = Text.getText(this.appContext?.platformParams.help_text || ''); } /** * Обработка пользовательских команд. * * Если intentName === null, значит не удалось найти обрабатываемых команд в тексте. * В таком случае стоит смотреть либо на предыдущую команду пользователя(которая сохранена в бд). * Либо вернуть текст помощи. * * Обрабатываем приветствие и команду повтори. * * @param {string} intentName Название действия. */ public action(intentName: string): void { switch (intentName) { case WELCOME_INTENT_NAME: this.thisIntentName = this.START_QUESTION; this.buttons.addBtn('Да').addBtn('Нет'); break; case 'replay': this.text = 'Повторяю предыдущий вопрос:\n'; this._setQuestionText(this.userData.question_id); break; default: switch (this.userData.oldIntentName) { case this.START_QUESTION: if (Text.isSayTrue(this.userCommand || '')) { this.text = 'Отлично!\nТогда начинаем!\n'; this._quiz(); this.thisIntentName = this.GAME_QUESTION; } else if (Text.isSayFalse(this.userCommand || '')) { this.text = 'Хорошо!\nПоиграем в другой раз.'; this.isEnd = true; } else { this.text = 'Скажи, ты готов начать игру?'; this.buttons.addBtn('Да').addBtn('Нет'); } break; case this.GAME_QUESTION: this._quiz(); break; default: this._help(); break; } break; } } }