yandex-dialoger
Version:
Ещё одна библиотека/фреймворк для разработки навыков Алисы.
113 lines (112 loc) • 3.33 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReplyBuilder = void 0;
class ReplyBuilder {
constructor() {
this.text = '';
this.tts = '';
this.buttons = [];
}
get buttonsCount() {
return this.buttons.length;
}
withText(...speechParts) {
for (const part of speechParts) {
this.addSpace(part);
if (Array.isArray(part)) {
this.text += part[0];
this.tts += part[1];
}
else {
this.text += part;
this.tts += part;
}
}
}
withTts(...ttsParts) {
for (const part of ttsParts) {
this.addSpaceToTts();
this.tts += part;
}
}
withTextPluralized(count, one, some, many) {
const caseIndex = count % 10 == 1 && count % 100 != 11
? 0
: count % 10 >= 2 && count % 10 <= 4 && (count % 100 < 10 || count % 100 >= 20)
? 1
: 2;
this.withText([one, some, many][caseIndex]);
}
withButton(params) {
if (typeof params === 'string') {
this.buttons.push({ title: params });
}
else {
this.buttons.push(params);
}
}
withImage(imageId) {
if (this.imageId) {
throw new Error('Изображение уже задано.');
}
this.imageId = imageId;
}
selectRandom(fn, items, number = 1) {
if (number === 0 || items.length === 0) {
return;
}
const randomItem = items[Math.floor(Math.random() * items.length)];
fn(randomItem);
this.selectRandom(fn, items.filter((item) => item !== randomItem), number - 1);
}
build(sceneName, model, endSession) {
const card = this.imageId
? {
type: 'BigImage',
image_id: this.imageId,
description: this.text.substr(0, 255),
}
: undefined;
return {
response: {
text: this.text,
tts: this.tts,
card,
end_session: endSession,
buttons: this.buttons.map((item) => {
return {
title: item.title,
url: item.url,
hide: true,
};
}),
},
session_state: {
sceneName: sceneName,
data: model,
},
version: '1.0',
};
}
/**
* Добавляет пробелы в конце text и tts
* (нужно перед добавлением новой части)
*/
addSpace(part) {
const textPart = Array.isArray(part) ? part[0] : part;
const textPartString = textPart.toString();
if (this.text &&
!this.text.endsWith(' ') &&
!textPartString.startsWith(',') &&
!textPartString.startsWith('.')) {
this.text += ' ';
}
this.addSpaceToTts();
}
addSpaceToTts() {
if (this.tts && !this.tts.endsWith(' ')) {
this.tts += ' ';
}
}
}
exports.ReplyBuilder = ReplyBuilder;