@2byte/tgbot-framework 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +300 -300
  2. package/bin/2byte-cli.ts +97 -84
  3. package/package.json +6 -2
  4. package/src/cli/CreateBotCommand.ts +181 -181
  5. package/src/cli/GenerateCommand.ts +195 -111
  6. package/src/cli/InitCommand.ts +107 -107
  7. package/src/console/migrate.ts +82 -82
  8. package/src/core/ApiService.ts +21 -0
  9. package/src/core/ApiServiceManager.ts +63 -0
  10. package/src/core/App.ts +1113 -1042
  11. package/src/core/BotArtisan.ts +79 -79
  12. package/src/core/BotMigration.ts +30 -30
  13. package/src/core/BotSeeder.ts +66 -66
  14. package/src/core/Model.ts +84 -80
  15. package/src/core/utils.ts +2 -2
  16. package/src/illumination/Artisan.ts +149 -149
  17. package/src/illumination/InlineKeyboard.ts +61 -44
  18. package/src/illumination/Message2Byte.ts +255 -254
  19. package/src/illumination/Message2ByteLiveProgressive.ts +278 -278
  20. package/src/illumination/Message2bytePool.ts +107 -107
  21. package/src/illumination/Migration.ts +186 -186
  22. package/src/illumination/RunSectionRoute.ts +85 -85
  23. package/src/illumination/Section.ts +410 -430
  24. package/src/illumination/SectionComponent.ts +64 -64
  25. package/src/illumination/Telegraf2byteContext.ts +32 -32
  26. package/src/index.ts +35 -33
  27. package/src/libs/TelegramAccountControl.ts +738 -523
  28. package/src/types.ts +188 -186
  29. package/src/user/UserModel.ts +297 -288
  30. package/src/user/UserStore.ts +119 -119
  31. package/src/workflow/services/MassSendApiService.ts +80 -0
  32. package/templates/bot/.env.example +18 -17
  33. package/templates/bot/artisan.ts +8 -8
  34. package/templates/bot/bot.ts +79 -77
  35. package/templates/bot/database/dbConnector.ts +4 -4
  36. package/templates/bot/database/migrate.ts +9 -9
  37. package/templates/bot/database/migrations/001_create_users.sql +18 -18
  38. package/templates/bot/database/seed.ts +14 -14
  39. package/templates/bot/package.json +30 -30
  40. package/templates/bot/sectionList.ts +9 -7
  41. package/templates/bot/sections/ExampleInputSection.ts +85 -0
  42. package/templates/bot/sections/ExampleLiveTaskerSection.ts +60 -0
  43. package/templates/bot/sections/HomeSection.ts +63 -65
  44. package/templates/bot/workflow/services/ExampleServise.ts +24 -0
package/src/core/App.ts CHANGED
@@ -1,1042 +1,1113 @@
1
- import { Telegraf, Markup } from "telegraf";
2
- import path from "node:path";
3
- import { Telegraf2byteContext, Telegraf2byteContextExtraMethods } from "../illumination/Telegraf2byteContext";
4
- import { Section } from "../illumination/Section";
5
- import { RunSectionRoute } from "../illumination/RunSectionRoute";
6
- import { UserModel } from "../user/UserModel";
7
- import { UserStore } from "../user/UserStore";
8
- import {
9
- AppConfig,
10
- EnvVars,
11
- RunnedSection,
12
- SectionEntityConfig,
13
- SectionList,
14
- SectionOptions,
15
- UserRegistrationData,
16
- } from "../types";
17
- import { nameToCapitalize } from "./utils";
18
-
19
- export class App {
20
- private config: AppConfig = {
21
- accessPublic: true,
22
- apiUrl: null,
23
- envConfig: {},
24
- botToken: null,
25
- telegrafConfigLaunch: null,
26
- settings: null,
27
- userStorage: null,
28
- builderPromises: [],
29
- sections: {},
30
- components: {},
31
- debug: false,
32
- devHotReloadSections: false,
33
- telegrafLog: false,
34
- mainMenuKeyboard: [],
35
- hears: {},
36
- terminateSigInt: true,
37
- terminateSigTerm: true,
38
- keepSectionInstances: false,
39
- };
40
-
41
- private bot!: Telegraf<Telegraf2byteContext>;
42
- private sectionClasses: Map<string, typeof Section> = new Map();
43
- private runnedSections: WeakMap<UserModel, RunnedSection | Map<string, RunnedSection>> =
44
- new WeakMap();
45
- private middlewares: CallableFunction[] = [];
46
-
47
- // Система управления фоновыми задачами
48
- private runningTasks: Map<
49
- string,
50
- {
51
- task: Promise<any>;
52
- cancel?: () => void;
53
- status: "running" | "completed" | "failed" | "cancelled";
54
- startTime: number;
55
- endTime?: number;
56
- error?: Error;
57
- ctx: Telegraf2byteContext;
58
- controller?: {
59
- signal: AbortSignal;
60
- sendMessage: (message: string) => Promise<void>;
61
- onMessage: (handler: (message: string, source: 'task' | 'external') => void) => void;
62
- receiveMessage: (message: string) => Promise<void>;
63
- };
64
- messageQueue?: Array<{ message: string; source: 'task' | 'external' }>;
65
- }
66
- > = new Map();
67
-
68
- constructor() {
69
- this.middlewares.push(this.mainMiddleware.bind(this));
70
- }
71
-
72
- static Builder = class {
73
- public app: App;
74
-
75
- constructor() {
76
- this.app = new App();
77
- }
78
-
79
- accessPublic(isPublic: boolean = true): this {
80
- this.app.config.accessPublic = isPublic;
81
- return this;
82
- }
83
-
84
- accessPrivate(isPrivate: boolean = true): this {
85
- this.app.config.accessPublic = !isPrivate;
86
- return this;
87
- }
88
-
89
- apiUrl(url: string): this {
90
- this.app.config.apiUrl = url;
91
- return this;
92
- }
93
-
94
- botToken(token: string): this {
95
- this.app.config.botToken = token;
96
- return this;
97
- }
98
-
99
- telegrafConfigLaunch(config: Record<string, any>): this {
100
- this.app.config.telegrafConfigLaunch = config;
101
- return this;
102
- }
103
-
104
- settings(settings: Record<string, any>): this {
105
- this.app.config.settings = settings;
106
- return this;
107
- }
108
-
109
- userStorage(storage: UserStore): this {
110
- this.app.config.userStorage = storage;
111
- return this;
112
- }
113
-
114
- debug(isDebug: boolean = true): this {
115
- this.app.config.debug = isDebug;
116
- return this;
117
- }
118
-
119
- devHotReloadSections(isReload: boolean = true): this {
120
- this.app.config.devHotReloadSections = isReload;
121
- return this;
122
- }
123
-
124
- telegrafLog(isLog: boolean = true): this {
125
- this.app.config.telegrafLog = isLog;
126
- return this;
127
- }
128
-
129
- mainMenuKeyboard(keyboard: any[][]): this {
130
- this.app.config.mainMenuKeyboard = keyboard;
131
- return this;
132
- }
133
-
134
- hears(hearsMap: Record<string, string>): this {
135
- this.app.config.hears = hearsMap;
136
- return this;
137
- }
138
-
139
- terminateSigInt(isTerminate: boolean = true): this {
140
- this.app.config.terminateSigInt = isTerminate;
141
- return this;
142
- }
143
-
144
- terminateSigTerm(isTerminate: boolean = true): this {
145
- this.app.config.terminateSigTerm = isTerminate;
146
- return this;
147
- }
148
-
149
- sections(sectionsList: SectionList): this {
150
- this.app.config.sections = sectionsList;
151
- return this;
152
- }
153
-
154
- /**
155
- *
156
- * @param keep Whether to keep section instances in memory after they are run.
157
- * If true, sections will not be reloaded on each request, improving performance for frequently accessed sections.
158
- * If false, sections will be reloaded each time they are accessed, ensuring the latest version is used.
159
- * Default is true.
160
- * @returns
161
- */
162
- keepSectionInstances(keep: boolean = true): this {
163
- this.app.config.keepSectionInstances = keep;
164
- return this;
165
- }
166
-
167
- envConfig(config: EnvVars): this {
168
- this.app.config.envConfig = config;
169
- return this;
170
- }
171
-
172
- build(): App {
173
- return this.app;
174
- }
175
- };
176
-
177
- async init(): Promise<this> {
178
- if (!this.config.botToken) {
179
- throw new Error("Bot token is not set");
180
- }
181
-
182
- this.bot = new Telegraf<Telegraf2byteContext>(this.config.botToken);
183
-
184
- if (this.config.telegrafLog) {
185
- this.bot.use(Telegraf.log());
186
- }
187
-
188
- this.debugLog("AppConfig", this.config);
189
-
190
- await this.registerSections();
191
-
192
- this.middlewares.forEach((middleware: CallableFunction) => {
193
- middleware();
194
- });
195
-
196
- this.registerActionForCallbackQuery();
197
- this.registerHears();
198
- this.registerCommands();
199
- this.registerMessageHandlers();
200
-
201
- return this;
202
- }
203
-
204
- async launch(): Promise<this> {
205
- if (!this.bot) {
206
- throw new Error("Bot is not initialized");
207
- }
208
-
209
- this.bot.catch((err) => {
210
- this.debugLog("Error in bot:", err);
211
- if (this.config.debug && err instanceof Error) {
212
- this.debugLog("Stack trace:", err.stack);
213
- }
214
- });
215
-
216
- await this.bot.launch(this.config.telegrafConfigLaunch || {});
217
-
218
- if (this.config.terminateSigInt) {
219
- process.once("SIGINT", () => {
220
- this.bot?.stop("SIGINT");
221
- });
222
- }
223
-
224
- if (this.config.terminateSigTerm) {
225
- process.once("SIGTERM", () => {
226
- this.bot?.stop("SIGTERM");
227
- });
228
- }
229
-
230
- return this;
231
- }
232
-
233
- async mainMiddleware() {
234
- this.bot.use(async (ctx: Telegraf2byteContext, next: () => Promise<void>) => {
235
- const tgUsername = this.getTgUsername(ctx);
236
-
237
- if (!tgUsername) {
238
- return ctx.reply("Username is not set");
239
- }
240
-
241
- if (!this.config.userStorage) {
242
- throw new Error("User storage is not set");
243
- }
244
-
245
- if (!this.config.userStorage.exists(tgUsername)) {
246
- if (!this.config.accessPublic) {
247
- const requestUsername = this.getTgUsername(ctx);
248
- this.debugLog("Private access mode. Checking username:", requestUsername);
249
- const checkAccess = this.config.envConfig.ACCESS_USERNAMES && this.config.envConfig.ACCESS_USERNAMES.split(",").map(name => name.trim());
250
- if (checkAccess && checkAccess.every(name => name !== requestUsername)) {
251
- return ctx.reply("Access denied. Your username is not in the access list.");
252
- }
253
- }
254
-
255
- if (!ctx.from) {
256
- return ctx.reply("User information is not available");
257
- }
258
-
259
- const userRefIdFromStart = ctx.startPayload ? parseInt(ctx.startPayload) : 0;
260
-
261
- await this.registerUser({
262
- user_refid: userRefIdFromStart,
263
- tg_id: ctx.from.id,
264
- tg_username: tgUsername,
265
- tg_first_name: ctx.from.first_name || tgUsername,
266
- tg_last_name: ctx.from.last_name || "",
267
- role: 'user',
268
- language: ctx.from.language_code || "en",
269
- })
270
- }
271
-
272
- ctx.user = this.config.userStorage.find(tgUsername);
273
- ctx.userStorage = this.config.userStorage;
274
- ctx.userSession = this.config.userStorage.findSession(ctx.user);
275
- Object.assign(ctx, Telegraf2byteContextExtraMethods);
276
-
277
- this.config.userStorage.upActive(tgUsername);
278
-
279
- if (ctx.msgId) {
280
- this.config.userStorage.storeMessageId(tgUsername, ctx.msgId, 10);
281
- }
282
-
283
- return next();
284
- });
285
- }
286
-
287
- async registerActionForCallbackQuery() {
288
- // Register actions
289
- this.bot.action(/(.+)/, async (ctx: Telegraf2byteContext) => {
290
- let actionPath = (ctx as any).match?.[1];
291
- const actionParamsString = actionPath.match(/\[(.+)\]/);
292
- let actionParams: URLSearchParams = new URLSearchParams();
293
-
294
- if (actionParamsString && actionParamsString[1]) {
295
- actionParams = new URLSearchParams(actionParamsString[1]);
296
-
297
- actionPath = actionPath.split("[")[0];
298
- }
299
-
300
- this.debugLog(
301
- `Run action ${actionPath} with params ${actionParams.toString()} for user ${
302
- ctx.user.username
303
- }`
304
- );
305
-
306
- if (!actionPath) return;
307
-
308
- // Assuming SectionData is a class to parse actionPath, but it's missing, so we will parse manually here
309
- const actionPathParts = actionPath.split(".");
310
-
311
- if (actionPathParts.length >= 2) {
312
- const sectionId = actionPathParts[0];
313
-
314
- let sectionClass = this.sectionClasses.get(sectionId);
315
-
316
- if (!sectionClass) {
317
- throw new Error(`Section class not found for sectionId ${sectionId}`);
318
- }
319
-
320
- const method = sectionClass.actionRoutes[actionPath];
321
-
322
- if (!method) {
323
- throw new Error(`Method ${actionPath} not found in section ${sectionId}`);
324
- }
325
-
326
- const sectionRoute = new RunSectionRoute()
327
- .section(sectionId)
328
- .method(method)
329
- .actionPath(actionPath);
330
-
331
- this.runSection(ctx, sectionRoute).catch((err) => {
332
- this.debugLog("Error running section:", err);
333
- });
334
- }
335
- });
336
- }
337
-
338
- registerHears() {
339
- // Register hears
340
- Object.entries(this.config.hears).forEach(([key, sectionMethod]) => {
341
- this.bot.hears(key, async (ctx: Telegraf2byteContext) => {
342
-
343
- const [sectionId, method] = sectionMethod.split(".");
344
- const sectionRoute = new RunSectionRoute().section(sectionId).method(method).hearsKey(key);
345
-
346
- this.debugLog(`Hears matched: ${key}, running section ${sectionId}, method ${method}`);
347
-
348
- this.runSection(ctx, sectionRoute).catch((err) => {
349
- this.debugLog("Error running section:", err);
350
- });
351
- });
352
- });
353
- }
354
-
355
- registerMessageHandlers() {
356
- // Register message handler for text messages
357
- this.bot.on("text", async (ctx: Telegraf2byteContext) => {
358
- this.debugLog("Received text message:", (ctx.update as any).message?.text);
359
- const messageText = (ctx.update as any).message?.text;
360
- if (!messageText) return;
361
-
362
- await this.handleUserInput(ctx, messageText, "text");
363
- });
364
-
365
- // Register message handler for documents/files
366
- this.bot.on("document", async (ctx: Telegraf2byteContext) => {
367
- const document = (ctx.update as any).message?.document;
368
- if (!document) return;
369
-
370
- await this.handleUserInput(ctx, document, "file");
371
- });
372
-
373
- // Register message handler for photos
374
- this.bot.on("photo", async (ctx: Telegraf2byteContext) => {
375
- const photo = (ctx.update as any).message?.photo;
376
- if (!photo || !photo.length) return;
377
-
378
- // Берем фото с наибольшим разрешением
379
- const largestPhoto = photo[photo.length - 1];
380
- await this.handleUserInput(ctx, largestPhoto, "photo");
381
- });
382
- }
383
-
384
- private async handleUserInput(
385
- ctx: Telegraf2byteContext,
386
- inputValue: any,
387
- inputType: "text" | "file" | "photo"
388
- ) {
389
- // Обработка awaitingInputPromise (для requestInputWithAwait)
390
- if (ctx.userSession.awaitingInputPromise) {
391
- this.debugLog("Handling input for awaitingInputPromise");
392
- const awaitingPromise = ctx.userSession.awaitingInputPromise;
393
- const {
394
- key,
395
- validator,
396
- errorMessage,
397
- allowCancel,
398
- retryCount = 0,
399
- resolve,
400
- reject,
401
- } = awaitingPromise;
402
-
403
- try {
404
- const isValid = await this.validateUserInput(
405
- inputValue,
406
- validator,
407
- inputType,
408
- awaitingPromise.fileValidation
409
- );
410
-
411
- this.debugLog(`Input validation result for key ${key}:`, isValid);
412
-
413
- if (isValid) {
414
- // Сохраняем ответ в сессии
415
- ctx.userSession[key] = inputValue;
416
- // Очищаем состояние ожидания
417
- delete ctx.userSession.awaitingInputPromise;
418
- // Разрешаем Promise
419
- resolve(inputValue);
420
- } else {
421
- // Увеличиваем счетчик попыток
422
- awaitingPromise.retryCount = retryCount + 1;
423
-
424
- // Отправляем сообщение об ошибке
425
- let errorMsg = errorMessage;
426
- if (awaitingPromise.retryCount > 1) {
427
- errorMsg += ` (попытка ${awaitingPromise.retryCount})`;
428
- }
429
-
430
- if (allowCancel) {
431
- errorMsg += '\n\nИспользуйте кнопку "Отмена" для отмены ввода.';
432
- }
433
-
434
- await ctx.reply(errorMsg, {
435
- ...Markup.inlineKeyboard([
436
- [
437
- Markup.button.callback(
438
- "Отмена",
439
- ctx?.userSession?.previousSection?.route?.getActionPath() ?? "home.index"
440
- ),
441
- ],
442
- ]),
443
- });
444
-
445
- // НЕ очищаем состояние ожидания - пользователь остается в режиме ввода
446
- // Состояние будет очищено только при успешном вводе или отмене
447
- }
448
- } catch (error) {
449
- await ctx.reply(`Ошибка валидации: ${error}`);
450
- if (allowCancel) {
451
- await ctx.reply('Используйте кнопку "Отмена" для отмены ввода.');
452
- }
453
- }
454
- return;
455
- }
456
-
457
- // Обработка awaitingInput (для requestInput с callback)
458
- if (ctx.userSession.awaitingInput) {
459
- const awaitingInput = ctx.userSession.awaitingInput;
460
- const {
461
- key,
462
- validator,
463
- errorMessage,
464
- allowCancel,
465
- retryCount = 0,
466
- runSection,
467
- } = awaitingInput;
468
-
469
- try {
470
- const isValid = await this.validateUserInput(
471
- inputValue,
472
- validator,
473
- inputType,
474
- awaitingInput.fileValidation
475
- );
476
-
477
- if (isValid) {
478
- // Сохраняем ответ в сессии
479
- ctx.userSession[key] = inputValue;
480
- // Очищаем состояние ожидания
481
- delete ctx.userSession.awaitingInput;
482
-
483
- // Если указан runSection, выполняем его
484
- if (runSection) {
485
- await this.runSection(ctx, runSection);
486
- }
487
- } else {
488
- // Увеличиваем счетчик попыток
489
- awaitingInput.retryCount = retryCount + 1;
490
-
491
- // Отправляем сообщение об ошибке
492
- let errorMsg = errorMessage;
493
- if (awaitingInput.retryCount > 1) {
494
- errorMsg += ` (попытка ${awaitingInput.retryCount})`;
495
- }
496
- if (allowCancel) {
497
- errorMsg += '\n\nИспользуйте кнопку "Отмена" для отмены ввода.';
498
- }
499
-
500
- await ctx.reply(errorMsg, {
501
- ...Markup.inlineKeyboard([
502
- [
503
- Markup.button.callback(
504
- "Отмена",
505
- ctx?.userSession?.previousSection?.route?.getActionPath() ?? "home.index"
506
- ),
507
- ],
508
- ]),
509
- });
510
-
511
- // НЕ очищаем состояние ожидания - пользователь остается в режиме ввода
512
- }
513
- } catch (error) {
514
- await ctx.reply(`Ошибка валидации: ${error}`);
515
- if (allowCancel) {
516
- await ctx.reply('Используйте кнопку "Отмена" для отмены ввода.');
517
- }
518
- }
519
- return;
520
- }
521
- }
522
-
523
- private async validateUserInput(
524
- value: any,
525
- validator?: "number" | "phone" | "code" | "file" | ((value: any) => boolean | Promise<boolean>),
526
- inputType?: "text" | "file" | "photo",
527
- fileValidation?: { allowedTypes?: string[]; maxSize?: number; minSize?: number }
528
- ): Promise<boolean> {
529
- if (!validator) return true;
530
-
531
- if (typeof validator === "function") {
532
- const result = validator(value);
533
- return result instanceof Promise ? await result : result;
534
- }
535
-
536
- switch (validator) {
537
- case "number":
538
- if (inputType !== "text") return false;
539
- return !isNaN(Number(value)) && value.trim() !== "";
540
-
541
- case "phone":
542
- if (inputType !== "text") return false;
543
- // Remove all non-digit characters
544
- const cleanNumber = value.replace(/\D/g, "");
545
- // Check international phone number format:
546
- // - Optional '+' at start
547
- // - May start with country code (1-3 digits)
548
- // - Followed by 6-12 digits
549
- // This covers most international formats including:
550
- // - Russian format (7xxxxxxxxxx)
551
- // - US/Canada format (1xxxxxxxxxx)
552
- // - European formats
553
- // - Asian formats
554
- const phoneRegex = /^(\+?\d{1,3})?[0-9]{6,12}$/;
555
- return phoneRegex.test(cleanNumber);
556
-
557
- case "code":
558
- if (inputType !== "text") return false;
559
- // Проверяем код подтверждения (обычно 5-6 цифр)
560
- const codeRegex = /^[0-9]{5,6}$/;
561
- return codeRegex.test(value);
562
-
563
- case "file":
564
- if (inputType !== "file" && inputType !== "photo") return false;
565
-
566
- // Валидация файла
567
- if (fileValidation) {
568
- // Проверка типа файла
569
- if (fileValidation.allowedTypes && fileValidation.allowedTypes.length > 0) {
570
- const mimeType = value.mime_type || "";
571
- if (!fileValidation.allowedTypes.includes(mimeType)) {
572
- throw new Error(
573
- `Неподдерживаемый тип файла. Разрешены: ${fileValidation.allowedTypes.join(", ")}`
574
- );
575
- }
576
- }
577
-
578
- // Проверка размера файла
579
- const fileSize = value.file_size || 0;
580
- if (fileValidation.maxSize && fileSize > fileValidation.maxSize) {
581
- throw new Error(
582
- `Файл слишком большой. Максимальный размер: ${Math.round(
583
- fileValidation.maxSize / 1024 / 1024
584
- )} МБ`
585
- );
586
- }
587
-
588
- if (fileValidation.minSize && fileSize < fileValidation.minSize) {
589
- throw new Error(
590
- `Файл слишком маленький. Минимальный размер: ${Math.round(
591
- fileValidation.minSize / 1024
592
- )} КБ`
593
- );
594
- }
595
- }
596
-
597
- return true;
598
-
599
- default:
600
- return true;
601
- }
602
- }
603
-
604
- registerCommands() {
605
- // Register command handlers
606
- // Register commands according to sections, each section class has static command method
607
- Array.from(this.sectionClasses.entries()).forEach(([sectionId, sectionClass]) => {
608
- const command = (sectionClass as any).command;
609
- this.debugLog(`Register command ${command} for section ${sectionId}`);
610
- if (command) {
611
- this.bot.command(command, async (ctx: Telegraf2byteContext) => {
612
- const sectionRoute = new RunSectionRoute().section(sectionId).method("index");
613
- await this.runSection(ctx, sectionRoute);
614
- });
615
- }
616
- });
617
- }
618
-
619
- async loadSection(sectionId: string, freshVersion: boolean = false): Promise<typeof Section> {
620
- const sectionParams = Object.entries(this.config.sections).find(
621
- ([sectionId]) => sectionId === sectionId
622
- )?.[1] as SectionEntityConfig;
623
-
624
- if (!sectionParams) {
625
- throw new Error(`Section ${sectionId} not found`);
626
- }
627
-
628
- let pathSectionModule =
629
- sectionParams.pathModule ??
630
- path.join(process.cwd(), "./sections/" + nameToCapitalize(sectionId) + "Section");
631
-
632
- this.debugLog('Path to section module: ', pathSectionModule);
633
-
634
- if (freshVersion) {
635
- pathSectionModule += "?update=" + Date.now();
636
- }
637
-
638
- const sectionClass = (await import(pathSectionModule)).default;
639
-
640
- this.debugLog("Loaded section", sectionId);
641
-
642
- return sectionClass;
643
- }
644
-
645
- async registerSections() {
646
- // Register sections routes
647
- for (const sectionId of Object.keys(this.config.sections)) {
648
- this.debugLog("Registration section: " + sectionId);
649
-
650
- try {
651
- this.sectionClasses.set(sectionId, await this.loadSection(sectionId));
652
- } catch (err) {
653
- this.debugLog('Error stack:', err instanceof Error ? err.stack : 'No stack available');
654
- throw new Error(`Failed to load section ${sectionId}: ${err instanceof Error ? err.message : err}`);
655
- }
656
- }
657
- }
658
-
659
- async runSection(ctx: Telegraf2byteContext, sectionRoute: RunSectionRoute): Promise<void> {
660
- const sectionId = sectionRoute.getSection();
661
- const method = sectionRoute.getMethod();
662
-
663
- this.debugLog(`Run section ${sectionId} method ${method}`);
664
-
665
- if (!sectionId || !method) {
666
- throw new Error("Section or method is not set");
667
- }
668
-
669
- let sectionClass: typeof Section;
670
-
671
- if (this.config.devHotReloadSections) {
672
- sectionClass = await this.loadSection(sectionId, true);
673
- } else {
674
- if (!this.sectionClasses.has(sectionId)) {
675
- throw new Error(`Section ${sectionId} not found`);
676
- }
677
- sectionClass = this.sectionClasses.get(sectionId) as typeof Section;
678
- }
679
-
680
- const sectionInstance: Section = new sectionClass({
681
- ctx,
682
- bot: this.bot,
683
- app: this,
684
- route: sectionRoute,
685
- } as SectionOptions);
686
-
687
- let runnedSection;
688
- let userRunnedSections: Map<string, RunnedSection> | RunnedSection | undefined;
689
- let sectionInstalled = false;
690
-
691
- if (this.config.keepSectionInstances) {
692
- userRunnedSections = this.runnedSections.get(ctx.user);
693
- if (userRunnedSections instanceof Map) {
694
- runnedSection &&= userRunnedSections.get(sectionId);
695
- }
696
- } else {
697
- runnedSection &&= this.runnedSections.get(ctx.user);
698
- }
699
- if (runnedSection) {
700
- this.debugLog(`Restored a runned section for user ${ctx.user.username}:`, runnedSection);
701
- }
702
-
703
- if (!runnedSection && this.config.keepSectionInstances) {
704
- if (userRunnedSections instanceof Map) {
705
- userRunnedSections.set(sectionId, {
706
- instance: sectionInstance,
707
- route: sectionRoute,
708
- });
709
- sectionInstalled = true;
710
- } else if (userRunnedSections === undefined) {
711
- userRunnedSections = new Map<string, RunnedSection>([
712
- [
713
- sectionId,
714
- {
715
- instance: sectionInstance,
716
- route: sectionRoute,
717
- },
718
- ],
719
- ]);
720
- sectionInstalled = true;
721
- }
722
- }
723
-
724
- if (!runnedSection && !this.config.keepSectionInstances) {
725
- this.runnedSections.set(ctx.user, {
726
- instance: sectionInstance,
727
- route: sectionRoute,
728
- });
729
- sectionInstalled = true;
730
- }
731
-
732
- if (!(sectionInstance as any)[method]) {
733
- throw new Error(`Method ${method} not found in section ${sectionId}`);
734
- }
735
-
736
- /**
737
- * Run section methods in the following order:
738
- * 1. setup (if section is installed)
739
- * 2. up
740
- * 3. method (action)
741
- * 4. down (if section is installed)
742
- * 5. unsetup (if section is installed and previous section is different)
743
- */
744
-
745
- const setupMethod = sectionInstance.setup;
746
- const upMethod = sectionInstance.up;
747
- const downMethod = sectionInstance.down;
748
- const unsetupMethod = sectionInstance.unsetup;
749
-
750
- // Run setup if section is installed
751
- if (sectionInstalled && setupMethod && typeof setupMethod === "function") {
752
- if (sectionInstalled) {
753
- this.debugLog(`[Setup] Section ${sectionId} install for user ${ctx.user.username}`);
754
- await sectionInstance.setup();
755
- this.debugLog(`[Setup finish] Section ${sectionId} installed for user ${ctx.user.username}`);
756
- }
757
- }
758
-
759
- // Run up method
760
- if (upMethod && typeof upMethod === "function") {
761
- this.debugLog(`[Up] Section ${sectionId} up for user ${ctx.user.username}`);
762
- await sectionInstance.up();
763
- this.debugLog(`[Up finish] Section ${sectionId} up for user ${ctx.user.username}`);
764
- }
765
-
766
- try {
767
- await (sectionInstance as any)[method]();
768
- } catch (error) {
769
- this.debugLog(`[Error] Section ${sectionId} error for user ${ctx.user.username}:`, error);
770
- }
771
-
772
- // Run down method if section is installed
773
- const previousSection = (ctx.userSession.previousSection = runnedSection as RunnedSection);
774
-
775
- if (downMethod && typeof downMethod === "function") {
776
- this.debugLog(`[Down] Section ${sectionId} down for user ${ctx.user.username}`);
777
- await sectionInstance.down();
778
- this.debugLog(`[Down finish] Section ${sectionId} down for user ${ctx.user.username}`);
779
- }
780
-
781
- // Run unsetup method if section is installed and previous section is different
782
- if (previousSection && previousSection.constructor.name !== sectionInstance.constructor.name) {
783
- this.debugLog(
784
- `Previous section ${previousSection.constructor.name} is different from current section ${sectionInstance.constructor.name}`
785
- );
786
-
787
- if (unsetupMethod && typeof unsetupMethod === "function") {
788
- this.debugLog(
789
- `[Unsetup] Section ${previousSection.instance.constructor.name} unsetup for user ${ctx.user.username}`
790
- );
791
- await previousSection.instance.unsetup();
792
- this.debugLog(
793
- `[Unsetup finish] Section ${previousSection.instance.constructor.name} unsetup for user ${ctx.user.username}`
794
- );
795
- }
796
- }
797
- }
798
-
799
- getRunnedSection(user: UserModel): RunnedSection | Map<string, RunnedSection> {
800
- const section = this.runnedSections.get(user);
801
-
802
- if (!section) {
803
- throw new Error("Section not found");
804
- }
805
-
806
- return section;
807
- }
808
-
809
- async registerUser(data: UserRegistrationData): Promise<UserModel | null> {
810
- try {
811
- const user = await UserModel.register(data);
812
-
813
- if (this.config.userStorage) {
814
- this.config.userStorage.add(data.tg_username, user);
815
- }
816
-
817
- return user;
818
- } catch (error) {
819
- console.error("User registration error:", error);
820
- return null;
821
- }
822
- }
823
-
824
- /**
825
- * Runs a task with bidirectional communication support
826
- * @param ctx Telegram context
827
- * @param task Function that performs the task with message handlers
828
- * @param options Configuration options for the task
829
- * @returns Task controller object with methods for communication and control
830
- */
831
- runTask(
832
- ctx: Telegraf2byteContext,
833
- task: (controller: {
834
- signal: AbortSignal;
835
- sendMessage: (message: string) => Promise<void>;
836
- onMessage: (handler: (message: string, source: 'task' | 'external') => void) => void;
837
- }) => Promise<any>,
838
- options: {
839
- taskId?: string;
840
- notifyStart?: boolean;
841
- notifyComplete?: boolean;
842
- startMessage?: string;
843
- completeMessage?: string;
844
- errorMessage?: string;
845
- silent?: boolean;
846
- } = {}
847
- ) {
848
- const {
849
- taskId = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
850
- notifyStart = true,
851
- notifyComplete = true,
852
- startMessage = "Задача запущена и будет выполняться в фоновом режиме.",
853
- completeMessage = "Задача успешно завершена!",
854
- errorMessage = "Произошла ошибка при выполнении задачи.",
855
- silent = false,
856
- } = options;
857
-
858
- // Create abort controller for task cancellation
859
- const abortController = new AbortController();
860
-
861
- // Message handling setup
862
- const messageHandlers: ((message: string, source: 'task' | 'external') => void)[] = [];
863
- const messageQueue: Array<{ message: string; source: 'task' | 'external' }> = [];
864
-
865
- // Create task controller interface
866
- const taskController = {
867
- signal: abortController.signal,
868
- // Send message from task to handlers
869
- sendMessage: async (message: string) => {
870
- if (!silent) {
871
- await ctx.reply(`[Задача ${taskId}]: ${message}`).catch(console.error);
872
- }
873
- messageQueue.push({ message, source: 'task' });
874
- messageHandlers.forEach(handler => handler(message, 'task'));
875
- },
876
- // Handle incoming messages to task
877
- onMessage: (handler: (message: string, source: 'task' | 'external') => void) => {
878
- messageHandlers.push(handler);
879
- // Process any queued messages
880
- messageQueue.forEach(({ message, source }) => handler(message, source));
881
- },
882
- // Receive message from external source
883
- receiveMessage: async (message: string) => {
884
- messageQueue.push({ message, source: 'external' });
885
- messageHandlers.forEach(handler => handler(message, 'external'));
886
- if (!silent) {
887
- await ctx.reply(`[Внешнее сообщение для задачи ${taskId}]: ${message}`).catch(console.error);
888
- }
889
- }
890
- };
891
-
892
- // Send start notification if enabled
893
- if (notifyStart && !silent) {
894
- ctx.reply(startMessage).catch(console.error);
895
- }
896
-
897
- // Create and run task promise
898
- const taskPromise = Promise.resolve().then(() => {
899
- return task(taskController);
900
- });
901
-
902
- // Save task information
903
- this.runningTasks.set(taskId, {
904
- task: taskPromise,
905
- cancel: () => abortController.abort(),
906
- status: "running",
907
- startTime: Date.now(),
908
- ctx,
909
- controller: taskController,
910
- messageQueue
911
- });
912
-
913
- // Handle task completion and errors
914
- taskPromise
915
- .then((result) => {
916
- const taskInfo = this.runningTasks.get(taskId);
917
- if (taskInfo) {
918
- taskInfo.status = "completed";
919
- taskInfo.endTime = Date.now();
920
- if (notifyComplete && !silent) {
921
- ctx.reply(completeMessage).catch(console.error);
922
- }
923
- }
924
- return result;
925
- })
926
- .catch((error) => {
927
- const taskInfo = this.runningTasks.get(taskId);
928
- if (taskInfo) {
929
- taskInfo.status = error.name === "AbortError" ? "cancelled" : "failed";
930
- taskInfo.endTime = Date.now();
931
- taskInfo.error = error;
932
-
933
- if (error.name !== "AbortError" && !silent) {
934
- console.error("Task error:", error);
935
- ctx.reply(`${errorMessage}\nОшибка: ${error.message}`).catch(console.error);
936
- }
937
- }
938
- });
939
-
940
- return taskId;
941
- }
942
-
943
- /**
944
- * Get information about a running task
945
- * @param taskId The ID of the task to check
946
- */
947
- getTaskInfo(taskId: string) {
948
- return this.runningTasks.get(taskId);
949
- }
950
-
951
- /**
952
- * Cancel a running task
953
- * @param taskId The ID of the task to cancel
954
- * @returns true if the task was cancelled, false if it couldn't be cancelled
955
- */
956
- cancelTask(taskId: string): boolean {
957
- const taskInfo = this.runningTasks.get(taskId);
958
- if (taskInfo && taskInfo.cancel && taskInfo.status === "running") {
959
- taskInfo.cancel();
960
- return true;
961
- }
962
- return false;
963
- }
964
-
965
- /**
966
- * Send a message to a running task
967
- * @param taskId The ID of the task to send the message to
968
- * @param message The message to send
969
- * @returns true if the message was sent, false if the task wasn't found or isn't running
970
- */
971
- async sendMessageToTask(taskId: string, message: string): Promise<boolean> {
972
- const taskInfo = this.runningTasks.get(taskId);
973
- if (taskInfo && taskInfo.controller && taskInfo.status === "running") {
974
- await taskInfo.controller.receiveMessage(message);
975
- return true;
976
- }
977
- return false;
978
- }
979
-
980
- /**
981
- * Get all tasks for a specific user
982
- * @param userId Telegram user ID
983
- */
984
- getUserTasks(
985
- userId: number
986
- ): Array<{ taskId: string; status: string; startTime: number; endTime?: number }> {
987
- const tasks: Array<{ taskId: string; status: string; startTime: number; endTime?: number }> =
988
- [];
989
-
990
- for (const [taskId, taskInfo] of this.runningTasks) {
991
- if (taskInfo.ctx.from?.id === userId) {
992
- tasks.push({
993
- taskId,
994
- status: taskInfo.status,
995
- startTime: taskInfo.startTime,
996
- endTime: taskInfo.endTime,
997
- });
998
- }
999
- }
1000
-
1001
- return tasks;
1002
- }
1003
-
1004
- /**
1005
- * Clean up completed/failed/cancelled tasks older than the specified age
1006
- * @param maxAge Maximum age in milliseconds (default: 1 hour)
1007
- */
1008
- cleanupOldTasks(maxAge: number = 3600000): void {
1009
- const now = Date.now();
1010
- for (const [taskId, taskInfo] of this.runningTasks) {
1011
- if (taskInfo.status !== "running" && taskInfo.endTime && now - taskInfo.endTime > maxAge) {
1012
- this.runningTasks.delete(taskId);
1013
- }
1014
- }
1015
- }
1016
-
1017
- private getTgUsername(ctx: Telegraf2byteContext): string {
1018
- return ctx.from?.username || "";
1019
- }
1020
-
1021
- private getTgName(ctx: Telegraf2byteContext): string {
1022
- return ctx.from?.first_name || "";
1023
- }
1024
-
1025
- private getTgId(ctx: Telegraf2byteContext): number {
1026
- return ctx.from?.id || 0;
1027
- }
1028
-
1029
- debugLog(...args: any[]): void {
1030
- if (this.config.debug) {
1031
- console.log(...args);
1032
- }
1033
- }
1034
-
1035
- get sections(): SectionList {
1036
- return this.config.sections;
1037
- }
1038
-
1039
- get configApp(): AppConfig {
1040
- return this.config;
1041
- }
1042
- }
1
+ import { Telegraf, Markup } from "telegraf";
2
+ import path from "node:path";
3
+ import { access } from "fs/promises";
4
+ import {
5
+ Telegraf2byteContext,
6
+ Telegraf2byteContextExtraMethods,
7
+ } from "../illumination/Telegraf2byteContext";
8
+ import { Section } from "../illumination/Section";
9
+ import { RunSectionRoute } from "../illumination/RunSectionRoute";
10
+ import { UserModel } from "../user/UserModel";
11
+ import { UserStore } from "../user/UserStore";
12
+ import {
13
+ AppConfig,
14
+ EnvVars,
15
+ RunnedSection,
16
+ SectionEntityConfig,
17
+ SectionList,
18
+ SectionOptions,
19
+ UserRegistrationData,
20
+ } from "../types";
21
+ import { nameToCapitalize } from "./utils";
22
+ import { ApiServiceManager } from "./ApiServiceManager";
23
+
24
+ export class App {
25
+ private config: AppConfig = {
26
+ accessPublic: true,
27
+ apiUrl: null,
28
+ envConfig: {},
29
+ botToken: null,
30
+ telegrafConfigLaunch: null,
31
+ settings: null,
32
+ userStorage: null,
33
+ builderPromises: [],
34
+ sections: {},
35
+ components: {},
36
+ debug: false,
37
+ devHotReloadSections: false,
38
+ telegrafLog: false,
39
+ mainMenuKeyboard: [],
40
+ hears: {},
41
+ terminateSigInt: true,
42
+ terminateSigTerm: true,
43
+ keepSectionInstances: false,
44
+ botCwd: process.cwd(),
45
+ };
46
+
47
+ public bot!: Telegraf<Telegraf2byteContext>;
48
+ private sectionClasses: Map<string, typeof Section> = new Map();
49
+ private runnedSections: WeakMap<UserModel, RunnedSection | Map<string, RunnedSection>> =
50
+ new WeakMap();
51
+ private middlewares: CallableFunction[] = [];
52
+ private apiServiceManager!: ApiServiceManager;
53
+
54
+ // Система управления фоновыми задачами
55
+ private runningTasks: Map<
56
+ string,
57
+ {
58
+ task: Promise<any>;
59
+ cancel?: () => void;
60
+ status: "running" | "completed" | "failed" | "cancelled";
61
+ startTime: number;
62
+ endTime?: number;
63
+ error?: Error;
64
+ ctx: Telegraf2byteContext;
65
+ controller?: {
66
+ signal: AbortSignal;
67
+ sendMessage: (message: string) => Promise<void>;
68
+ onMessage: (handler: (message: string, source: "task" | "external") => void) => void;
69
+ receiveMessage: (message: string) => Promise<void>;
70
+ };
71
+ messageQueue?: Array<{ message: string; source: "task" | "external" }>;
72
+ }
73
+ > = new Map();
74
+
75
+ constructor() {
76
+ this.middlewares.push(this.mainMiddleware.bind(this));
77
+ }
78
+
79
+ static Builder = class {
80
+ public app: App;
81
+
82
+ constructor() {
83
+ this.app = new App();
84
+ }
85
+
86
+ accessPublic(isPublic: boolean = true): this {
87
+ this.app.config.accessPublic = isPublic;
88
+ return this;
89
+ }
90
+
91
+ accessPrivate(isPrivate: boolean = true): this {
92
+ this.app.config.accessPublic = !isPrivate;
93
+ return this;
94
+ }
95
+
96
+ apiUrl(url: string): this {
97
+ this.app.config.apiUrl = url;
98
+ return this;
99
+ }
100
+
101
+ botToken(token: string): this {
102
+ this.app.config.botToken = token;
103
+ return this;
104
+ }
105
+
106
+ telegrafConfigLaunch(config: Record<string, any>): this {
107
+ this.app.config.telegrafConfigLaunch = config;
108
+ return this;
109
+ }
110
+
111
+ settings(settings: Record<string, any>): this {
112
+ this.app.config.settings = settings;
113
+ return this;
114
+ }
115
+
116
+ userStorage(storage: UserStore): this {
117
+ this.app.config.userStorage = storage;
118
+ return this;
119
+ }
120
+
121
+ debug(isDebug: boolean = true): this {
122
+ this.app.config.debug = isDebug;
123
+ return this;
124
+ }
125
+
126
+ devHotReloadSections(isReload: boolean = true): this {
127
+ this.app.config.devHotReloadSections = isReload;
128
+ return this;
129
+ }
130
+
131
+ telegrafLog(isLog: boolean = true): this {
132
+ this.app.config.telegrafLog = isLog;
133
+ return this;
134
+ }
135
+
136
+ mainMenuKeyboard(keyboard: any[][]): this {
137
+ this.app.config.mainMenuKeyboard = keyboard;
138
+ return this;
139
+ }
140
+
141
+ hears(hearsMap: Record<string, string>): this {
142
+ this.app.config.hears = hearsMap;
143
+ return this;
144
+ }
145
+
146
+ terminateSigInt(isTerminate: boolean = true): this {
147
+ this.app.config.terminateSigInt = isTerminate;
148
+ return this;
149
+ }
150
+
151
+ terminateSigTerm(isTerminate: boolean = true): this {
152
+ this.app.config.terminateSigTerm = isTerminate;
153
+ return this;
154
+ }
155
+
156
+ sections(sectionsList: SectionList): this {
157
+ this.app.config.sections = sectionsList;
158
+ return this;
159
+ }
160
+
161
+ /**
162
+ *
163
+ * @param keep Whether to keep section instances in memory after they are run.
164
+ * If true, sections will not be reloaded on each request, improving performance for frequently accessed sections.
165
+ * If false, sections will be reloaded each time they are accessed, ensuring the latest version is used.
166
+ * Default is true.
167
+ * @returns
168
+ */
169
+ keepSectionInstances(keep: boolean = true): this {
170
+ this.app.config.keepSectionInstances = keep;
171
+ return this;
172
+ }
173
+
174
+ envConfig(config: EnvVars): this {
175
+ this.app.config.envConfig = config;
176
+ return this;
177
+ }
178
+
179
+ botCwd(cwdPath: string): this {
180
+ this.app.config.botCwd = cwdPath;
181
+ return this;
182
+ }
183
+
184
+ build(): App {
185
+ return this.app;
186
+ }
187
+ };
188
+
189
+ async init(): Promise<this> {
190
+ if (!this.config.botToken) {
191
+ throw new Error("Bot token is not set");
192
+ }
193
+
194
+ this.bot = new Telegraf<Telegraf2byteContext>(this.config.botToken);
195
+
196
+ if (this.config.telegrafLog) {
197
+ this.bot.use(Telegraf.log());
198
+ }
199
+
200
+ this.debugLog("AppConfig", this.config);
201
+
202
+ await this.registerSections();
203
+
204
+ this.middlewares.forEach((middleware: CallableFunction) => {
205
+ middleware();
206
+ });
207
+
208
+ this.registerActionForCallbackQuery();
209
+ this.registerHears();
210
+ this.registerCommands();
211
+ this.registerMessageHandlers();
212
+ await this.registerServices();
213
+
214
+
215
+ return this;
216
+ }
217
+
218
+ async launch(): Promise<this> {
219
+ if (!this.bot) {
220
+ throw new Error("Bot is not initialized");
221
+ }
222
+
223
+ this.bot.catch((err) => {
224
+ this.debugLog("Error in bot:", err);
225
+ if (this.config.debug && err instanceof Error) {
226
+ this.debugLog("Stack trace:", err.stack);
227
+ }
228
+ });
229
+
230
+ await this.bot.launch(this.config.telegrafConfigLaunch || {});
231
+
232
+ if (this.config.terminateSigInt) {
233
+ process.once("SIGINT", () => {
234
+ this.bot?.stop("SIGINT");
235
+ });
236
+ }
237
+
238
+ if (this.config.terminateSigTerm) {
239
+ process.once("SIGTERM", () => {
240
+ this.bot?.stop("SIGTERM");
241
+ });
242
+ }
243
+
244
+ return this;
245
+ }
246
+
247
+ async mainMiddleware() {
248
+ this.bot.use(async (ctx: Telegraf2byteContext, next: () => Promise<void>) => {
249
+ const tgUsername = this.getTgUsername(ctx);
250
+
251
+ if (!tgUsername) {
252
+ return ctx.reply("Username is not set");
253
+ }
254
+
255
+ if (!this.config.userStorage) {
256
+ throw new Error("User storage is not set");
257
+ }
258
+
259
+ if (!this.config.userStorage.exists(tgUsername)) {
260
+ if (!this.config.accessPublic) {
261
+ const requestUsername = this.getTgUsername(ctx);
262
+ this.debugLog("Private access mode. Checking username:", requestUsername);
263
+ const checkAccess =
264
+ this.config.envConfig.ACCESS_USERNAMES &&
265
+ this.config.envConfig.ACCESS_USERNAMES.split(",").map((name) => name.trim());
266
+ if (checkAccess && checkAccess.every((name) => name !== requestUsername)) {
267
+ return ctx.reply("Access denied. Your username is not in the access list.");
268
+ }
269
+ }
270
+
271
+ if (!ctx.from) {
272
+ return ctx.reply("User information is not available");
273
+ }
274
+
275
+ const userRefIdFromStart = ctx.startPayload ? parseInt(ctx.startPayload) : 0;
276
+
277
+ await this.registerUser({
278
+ user_refid: userRefIdFromStart,
279
+ tg_id: ctx.from.id,
280
+ tg_username: tgUsername,
281
+ tg_first_name: ctx.from.first_name || tgUsername,
282
+ tg_last_name: ctx.from.last_name || "",
283
+ role: "user",
284
+ language: ctx.from.language_code || "en",
285
+ });
286
+ }
287
+
288
+ ctx.user = this.config.userStorage.find(tgUsername);
289
+ ctx.userStorage = this.config.userStorage;
290
+ ctx.userSession = this.config.userStorage.findSession(ctx.user);
291
+ Object.assign(ctx, Telegraf2byteContextExtraMethods);
292
+
293
+ this.config.userStorage.upActive(tgUsername);
294
+
295
+ if (ctx.msgId) {
296
+ this.config.userStorage.storeMessageId(tgUsername, ctx.msgId, 10);
297
+ }
298
+
299
+ return next();
300
+ });
301
+ }
302
+
303
+ async registerActionForCallbackQuery() {
304
+ // Register actions
305
+ this.bot.action(/(.+)/, async (ctx: Telegraf2byteContext) => {
306
+ let actionPath = (ctx as any).match?.[1];
307
+ const actionParamsString = actionPath.match(/\[(.+)\]/);
308
+ let actionParams: URLSearchParams = new URLSearchParams();
309
+
310
+ if (actionParamsString && actionParamsString[1]) {
311
+ actionParams = new URLSearchParams(actionParamsString[1]);
312
+
313
+ actionPath = actionPath.split("[")[0];
314
+ }
315
+
316
+ this.debugLog(
317
+ `Run action ${actionPath} with params ${actionParams.toString()} for user ${
318
+ ctx.user.username
319
+ }`
320
+ );
321
+
322
+ if (!actionPath) return;
323
+
324
+ // Assuming SectionData is a class to parse actionPath, but it's missing, so we will parse manually here
325
+ const actionPathParts = actionPath.split(".");
326
+
327
+ if (actionPathParts.length >= 2) {
328
+ const sectionId = actionPathParts[0];
329
+
330
+ let sectionClass = this.sectionClasses.get(sectionId);
331
+
332
+ if (!sectionClass) {
333
+ throw new Error(`Section class not found for sectionId ${sectionId}`);
334
+ }
335
+
336
+ const method = sectionClass.actionRoutes[actionPath];
337
+
338
+ if (!method) {
339
+ throw new Error(
340
+ `Action ${actionPath} method ${method} not found in section ${sectionId}`
341
+ );
342
+ }
343
+
344
+ const sectionRoute = new RunSectionRoute()
345
+ .section(sectionId)
346
+ .method(method)
347
+ .actionPath(actionPath);
348
+
349
+ this.runSection(ctx, sectionRoute).catch((err) => {
350
+ this.debugLog("Error running section:", err);
351
+ });
352
+ }
353
+ });
354
+ }
355
+
356
+ registerHears() {
357
+ // Register hears
358
+ Object.entries(this.config.hears).forEach(([key, sectionMethod]) => {
359
+ this.bot.hears(key, async (ctx: Telegraf2byteContext) => {
360
+ const [sectionId, method] = sectionMethod.split(".");
361
+ const sectionRoute = new RunSectionRoute().section(sectionId).method(method).hearsKey(key);
362
+
363
+ this.debugLog(`Hears matched: ${key}, running section ${sectionId}, method ${method}`);
364
+
365
+ this.runSection(ctx, sectionRoute).catch((err) => {
366
+ this.debugLog("Error running section:", err);
367
+ });
368
+ });
369
+ });
370
+ }
371
+
372
+ registerMessageHandlers() {
373
+ // Register message handler for text messages
374
+ this.bot.on("text", async (ctx: Telegraf2byteContext) => {
375
+ this.debugLog("Received text message:", (ctx.update as any).message?.text);
376
+ const messageText = (ctx.update as any).message?.text;
377
+ if (!messageText) return;
378
+
379
+ await this.handleUserInput(ctx, messageText, "text");
380
+ });
381
+
382
+ // Register message handler for documents/files
383
+ this.bot.on("document", async (ctx: Telegraf2byteContext) => {
384
+ const document = (ctx.update as any).message?.document;
385
+ if (!document) return;
386
+
387
+ await this.handleUserInput(ctx, document, "file");
388
+ });
389
+
390
+ // Register message handler for photos
391
+ this.bot.on("photo", async (ctx: Telegraf2byteContext) => {
392
+ const photo = (ctx.update as any).message?.photo;
393
+ if (!photo || !photo.length) return;
394
+
395
+ // Берем фото с наибольшим разрешением
396
+ const largestPhoto = photo[photo.length - 1];
397
+ await this.handleUserInput(ctx, largestPhoto, "photo");
398
+ });
399
+ }
400
+
401
+ private async registerServices() {
402
+ this.apiServiceManager = ApiServiceManager.init(this);
403
+
404
+ const registerServices = async (pathDirectory: string) => {
405
+ try {
406
+ await this.apiServiceManager.loadServicesFromDirectory(
407
+ pathDirectory
408
+ );
409
+ } catch (error) {
410
+ this.debugLog("Error loading services:", error);
411
+ throw error;
412
+ }
413
+
414
+ this.debugLog("Registered API services:%s in dir: %s", Array.from(this.apiServiceManager.getAll().keys()), pathDirectory);
415
+
416
+ for (const [name, service] of this.apiServiceManager.getAll()) {
417
+ await service.setup();
418
+ this.debugLog(`Service ${name} setup completed`);
419
+ await service.run();
420
+ this.debugLog(`Service ${name} run completed`);
421
+ }
422
+ };
423
+
424
+ // Register services from bot directory
425
+ await registerServices(this.config.botCwd + "/workflow/services");
426
+ // Register services from framework directory
427
+ await registerServices(path.resolve(__dirname, "../workflow/services"));
428
+ }
429
+
430
+ private async unregisterServices() {
431
+ this.apiServiceManager = ApiServiceManager.init(this);
432
+
433
+ try {
434
+ this.apiServiceManager.unsetupAllServices();
435
+ } catch (error) {
436
+ this.debugLog("Error unsetting up services:", error);
437
+ throw error;
438
+ }
439
+ }
440
+
441
+ private async handleUserInput(
442
+ ctx: Telegraf2byteContext,
443
+ inputValue: any,
444
+ inputType: "text" | "file" | "photo"
445
+ ) {
446
+ // Обработка awaitingInputPromise (для requestInputWithAwait)
447
+ if (ctx.userSession.awaitingInputPromise) {
448
+ this.debugLog("Handling input for awaitingInputPromise");
449
+ const awaitingPromise = ctx.userSession.awaitingInputPromise;
450
+ const {
451
+ key,
452
+ validator,
453
+ errorMessage,
454
+ allowCancel,
455
+ retryCount = 0,
456
+ resolve,
457
+ reject,
458
+ } = awaitingPromise;
459
+
460
+ try {
461
+ const isValid = await this.validateUserInput(
462
+ inputValue,
463
+ validator,
464
+ inputType,
465
+ awaitingPromise.fileValidation
466
+ );
467
+
468
+ this.debugLog(`Input validation result for key ${key}:`, isValid);
469
+
470
+ if (isValid) {
471
+ // Сохраняем ответ в сессии
472
+ ctx.userSession[key] = inputValue;
473
+ // Очищаем состояние ожидания
474
+ delete ctx.userSession.awaitingInputPromise;
475
+ // Разрешаем Promise
476
+ resolve(inputValue);
477
+ ctx.deleteLastMessage();
478
+ } else {
479
+ // Увеличиваем счетчик попыток
480
+ awaitingPromise.retryCount = retryCount + 1;
481
+
482
+ // Отправляем сообщение об ошибке
483
+ let errorMsg = errorMessage;
484
+ if (awaitingPromise.retryCount > 1) {
485
+ errorMsg += ` (попытка ${awaitingPromise.retryCount})`;
486
+ }
487
+
488
+ if (allowCancel) {
489
+ errorMsg += '\n\nИспользуйте кнопку "Отмена" для отмены ввода.';
490
+ }
491
+
492
+ await ctx.reply(errorMsg, {
493
+ ...Markup.inlineKeyboard([
494
+ [
495
+ Markup.button.callback(
496
+ "Отмена",
497
+ ctx?.userSession?.previousSection?.route?.getActionPath() ?? "home.index"
498
+ ),
499
+ ],
500
+ ]),
501
+ });
502
+
503
+ // НЕ очищаем состояние ожидания - пользователь остается в режиме ввода
504
+ // Состояние будет очищено только при успешном вводе или отмене
505
+ }
506
+ } catch (error) {
507
+ await ctx.reply(`Ошибка валидации: ${error}`);
508
+ if (allowCancel) {
509
+ await ctx.reply('Используйте кнопку "Отмена" для отмены ввода.');
510
+ }
511
+ }
512
+ return;
513
+ }
514
+
515
+ // Обработка awaitingInput (для requestInput с callback)
516
+ if (ctx.userSession.awaitingInput) {
517
+ const awaitingInput = ctx.userSession.awaitingInput;
518
+ const {
519
+ key,
520
+ validator,
521
+ errorMessage,
522
+ allowCancel,
523
+ retryCount = 0,
524
+ runSection,
525
+ } = awaitingInput;
526
+
527
+ try {
528
+ const isValid = await this.validateUserInput(
529
+ inputValue,
530
+ validator,
531
+ inputType,
532
+ awaitingInput.fileValidation
533
+ );
534
+
535
+ if (isValid) {
536
+ // Сохраняем ответ в сессии
537
+ ctx.userSession[key] = inputValue;
538
+ // Очищаем состояние ожидания
539
+ delete ctx.userSession.awaitingInput;
540
+
541
+ // Если указан runSection, выполняем его
542
+ if (runSection) {
543
+ await this.runSection(ctx, runSection);
544
+ }
545
+ } else {
546
+ // Увеличиваем счетчик попыток
547
+ awaitingInput.retryCount = retryCount + 1;
548
+
549
+ // Отправляем сообщение об ошибке
550
+ let errorMsg = errorMessage;
551
+ if (awaitingInput.retryCount > 1) {
552
+ errorMsg += ` (попытка ${awaitingInput.retryCount})`;
553
+ }
554
+ if (allowCancel) {
555
+ errorMsg += '\n\nИспользуйте кнопку "Отмена" для отмены ввода.';
556
+ }
557
+
558
+ await ctx.reply(errorMsg, {
559
+ ...Markup.inlineKeyboard([
560
+ [
561
+ Markup.button.callback(
562
+ "Отмена",
563
+ ctx?.userSession?.previousSection?.route?.getActionPath() ?? "home.index"
564
+ ),
565
+ ],
566
+ ]),
567
+ });
568
+
569
+ // НЕ очищаем состояние ожидания - пользователь остается в режиме ввода
570
+ }
571
+ } catch (error) {
572
+ await ctx.reply(`Ошибка валидации: ${error}`);
573
+ if (allowCancel) {
574
+ await ctx.reply('Используйте кнопку "Отмена" для отмены ввода.');
575
+ }
576
+ }
577
+ return;
578
+ }
579
+ }
580
+
581
+ private async validateUserInput(
582
+ value: any,
583
+ validator?: "number" | "phone" | "code" | "file" | ((value: any) => boolean | Promise<boolean>),
584
+ inputType?: "text" | "file" | "photo",
585
+ fileValidation?: { allowedTypes?: string[]; maxSize?: number; minSize?: number }
586
+ ): Promise<boolean> {
587
+ if (!validator) return true;
588
+
589
+ if (typeof validator === "function") {
590
+ const result = validator(value);
591
+ return result instanceof Promise ? await result : result;
592
+ }
593
+
594
+ switch (validator) {
595
+ case "number":
596
+ if (inputType !== "text") return false;
597
+ return !isNaN(Number(value)) && value.trim() !== "";
598
+
599
+ case "phone":
600
+ if (inputType !== "text") return false;
601
+ // Remove all non-digit characters
602
+ const cleanNumber = value.replace(/\D/g, "");
603
+ // Check international phone number format:
604
+ // - Optional '+' at start
605
+ // - May start with country code (1-3 digits)
606
+ // - Followed by 6-12 digits
607
+ // This covers most international formats including:
608
+ // - Russian format (7xxxxxxxxxx)
609
+ // - US/Canada format (1xxxxxxxxxx)
610
+ // - European formats
611
+ // - Asian formats
612
+ const phoneRegex = /^(\+?\d{1,3})?[0-9]{6,12}$/;
613
+ return phoneRegex.test(cleanNumber);
614
+
615
+ case "code":
616
+ if (inputType !== "text") return false;
617
+ // Проверяем код подтверждения (обычно 5-6 цифр)
618
+ const codeRegex = /^[0-9]{5,6}$/;
619
+ return codeRegex.test(value);
620
+
621
+ case "file":
622
+ if (inputType !== "file" && inputType !== "photo") return false;
623
+
624
+ // Валидация файла
625
+ if (fileValidation) {
626
+ // Проверка типа файла
627
+ if (fileValidation.allowedTypes && fileValidation.allowedTypes.length > 0) {
628
+ const mimeType = value.mime_type || "";
629
+ if (!fileValidation.allowedTypes.includes(mimeType)) {
630
+ throw new Error(
631
+ `Неподдерживаемый тип файла. Разрешены: ${fileValidation.allowedTypes.join(", ")}`
632
+ );
633
+ }
634
+ }
635
+
636
+ // Проверка размера файла
637
+ const fileSize = value.file_size || 0;
638
+ if (fileValidation.maxSize && fileSize > fileValidation.maxSize) {
639
+ throw new Error(
640
+ `Файл слишком большой. Максимальный размер: ${Math.round(
641
+ fileValidation.maxSize / 1024 / 1024
642
+ )} МБ`
643
+ );
644
+ }
645
+
646
+ if (fileValidation.minSize && fileSize < fileValidation.minSize) {
647
+ throw new Error(
648
+ `Файл слишком маленький. Минимальный размер: ${Math.round(
649
+ fileValidation.minSize / 1024
650
+ )} КБ`
651
+ );
652
+ }
653
+ }
654
+
655
+ return true;
656
+
657
+ default:
658
+ return true;
659
+ }
660
+ }
661
+
662
+ registerCommands() {
663
+ // Register command handlers
664
+ // Register commands according to sections, each section class has static command method
665
+ Array.from(this.sectionClasses.entries()).forEach(([sectionId, sectionClass]) => {
666
+ const command = (sectionClass as any).command;
667
+ this.debugLog(`Register command ${command} for section ${sectionId}`);
668
+ if (command) {
669
+ this.bot.command(command, async (ctx: Telegraf2byteContext) => {
670
+ const sectionRoute = new RunSectionRoute().section(sectionId).method("index");
671
+ await this.runSection(ctx, sectionRoute);
672
+ });
673
+ }
674
+ });
675
+ }
676
+
677
+ async loadSection(sectionId: string, freshVersion: boolean = false): Promise<typeof Section> {
678
+ const sectionParams = Object.entries(this.config.sections).find(
679
+ ([sectionId]) => sectionId === sectionId
680
+ )?.[1] as SectionEntityConfig;
681
+
682
+ if (!sectionParams) {
683
+ throw new Error(`Section ${sectionId} not found`);
684
+ }
685
+
686
+ let pathSectionModule =
687
+ sectionParams.pathModule ??
688
+ path.join(process.cwd(), "./sections/" + nameToCapitalize(sectionId) + "Section");
689
+
690
+ this.debugLog("Path to section module: ", pathSectionModule);
691
+
692
+ // Check if file exists
693
+ try {
694
+ await access(pathSectionModule + ".ts");
695
+ } catch {
696
+ throw new Error(`Section ${sectionId} not found at path ${pathSectionModule}.ts`);
697
+ }
698
+
699
+ if (freshVersion) {
700
+ pathSectionModule += "?update=" + Date.now();
701
+ }
702
+
703
+ const sectionClass = (await import(pathSectionModule)).default;
704
+
705
+ this.debugLog("Loaded section", sectionId);
706
+
707
+ return sectionClass;
708
+ }
709
+
710
+ async registerSections() {
711
+ // Register sections routes
712
+ for (const sectionId of Object.keys(this.config.sections)) {
713
+ this.debugLog("Registration section: " + sectionId);
714
+
715
+ try {
716
+ this.sectionClasses.set(sectionId, await this.loadSection(sectionId));
717
+ } catch (err) {
718
+ this.debugLog("Error stack:", err instanceof Error ? err.stack : "No stack available");
719
+ throw new Error(
720
+ `Failed to load section ${sectionId}: ${err instanceof Error ? err.message : err}`
721
+ );
722
+ }
723
+ }
724
+ }
725
+
726
+ async runSection(ctx: Telegraf2byteContext, sectionRoute: RunSectionRoute): Promise<void> {
727
+ const sectionId = sectionRoute.getSection();
728
+ const method = sectionRoute.getMethod();
729
+
730
+ this.debugLog(`Run section ${sectionId} method ${method}`);
731
+
732
+ if (!sectionId || !method) {
733
+ throw new Error("Section or method is not set");
734
+ }
735
+
736
+ let sectionClass: typeof Section;
737
+
738
+ if (this.config.devHotReloadSections) {
739
+ sectionClass = await this.loadSection(sectionId, true);
740
+ } else {
741
+ if (!this.sectionClasses.has(sectionId)) {
742
+ throw new Error(`Section ${sectionId} not found`);
743
+ }
744
+ sectionClass = this.sectionClasses.get(sectionId) as typeof Section;
745
+ }
746
+
747
+ const sectionInstance: Section = new sectionClass({
748
+ ctx,
749
+ bot: this.bot,
750
+ app: this,
751
+ route: sectionRoute,
752
+ } as SectionOptions);
753
+
754
+ let runnedSection;
755
+ let userRunnedSections: Map<string, RunnedSection> | RunnedSection | undefined;
756
+ let sectionInstalled = false;
757
+
758
+ if (this.config.keepSectionInstances) {
759
+ userRunnedSections = this.runnedSections.get(ctx.user);
760
+ if (userRunnedSections instanceof Map) {
761
+ runnedSection &&= userRunnedSections.get(sectionId);
762
+ }
763
+ } else {
764
+ runnedSection &&= this.runnedSections.get(ctx.user);
765
+ }
766
+ if (runnedSection) {
767
+ this.debugLog(`Restored a runned section for user ${ctx.user.username}:`, runnedSection);
768
+ }
769
+
770
+ if (!runnedSection && this.config.keepSectionInstances) {
771
+ if (userRunnedSections instanceof Map) {
772
+ userRunnedSections.set(sectionId, {
773
+ instance: sectionInstance,
774
+ route: sectionRoute,
775
+ });
776
+ sectionInstalled = true;
777
+ } else if (userRunnedSections === undefined) {
778
+ userRunnedSections = new Map<string, RunnedSection>([
779
+ [
780
+ sectionId,
781
+ {
782
+ instance: sectionInstance,
783
+ route: sectionRoute,
784
+ },
785
+ ],
786
+ ]);
787
+ sectionInstalled = true;
788
+ }
789
+ }
790
+
791
+ if (!runnedSection && !this.config.keepSectionInstances) {
792
+ this.runnedSections.set(ctx.user, {
793
+ instance: sectionInstance,
794
+ route: sectionRoute,
795
+ });
796
+ sectionInstalled = true;
797
+ }
798
+
799
+ if (!(sectionInstance as any)[method]) {
800
+ throw new Error(`Method ${method} not found in section ${sectionId}`);
801
+ }
802
+
803
+ /**
804
+ * Run section methods in the following order:
805
+ * 1. setup (if section is installed)
806
+ * 2. up
807
+ * 3. method (action)
808
+ * 4. down (if section is installed)
809
+ * 5. unsetup (if section is installed and previous section is different)
810
+ */
811
+
812
+ const setupMethod = sectionInstance.setup;
813
+ const upMethod = sectionInstance.up;
814
+ const downMethod = sectionInstance.down;
815
+ const unsetupMethod = sectionInstance.unsetup;
816
+
817
+ // Run setup if section is installed
818
+ if (sectionInstalled && setupMethod && typeof setupMethod === "function") {
819
+ if (sectionInstalled) {
820
+ this.debugLog(`[Setup] Section ${sectionId} install for user ${ctx.user.username}`);
821
+ await sectionInstance.setup();
822
+ this.debugLog(
823
+ `[Setup finish] Section ${sectionId} installed for user ${ctx.user.username}`
824
+ );
825
+ }
826
+ }
827
+
828
+ // Run up method
829
+ if (upMethod && typeof upMethod === "function") {
830
+ this.debugLog(`[Up] Section ${sectionId} up for user ${ctx.user.username}`);
831
+ await sectionInstance.up();
832
+ this.debugLog(`[Up finish] Section ${sectionId} up for user ${ctx.user.username}`);
833
+ }
834
+
835
+ try {
836
+ await (sectionInstance as any)[method]();
837
+ } catch (error) {
838
+ this.debugLog(`[Error] Section ${sectionId} error for user ${ctx.user.username}:`, error);
839
+ }
840
+
841
+ // Run down method if section is installed
842
+ const previousSection = (ctx.userSession.previousSection = runnedSection as RunnedSection);
843
+
844
+ if (downMethod && typeof downMethod === "function") {
845
+ this.debugLog(`[Down] Section ${sectionId} down for user ${ctx.user.username}`);
846
+ await sectionInstance.down();
847
+ this.debugLog(`[Down finish] Section ${sectionId} down for user ${ctx.user.username}`);
848
+ }
849
+
850
+ // Run unsetup method if section is installed and previous section is different
851
+ if (previousSection && previousSection.constructor.name !== sectionInstance.constructor.name) {
852
+ this.debugLog(
853
+ `Previous section ${previousSection.constructor.name} is different from current section ${sectionInstance.constructor.name}`
854
+ );
855
+
856
+ if (unsetupMethod && typeof unsetupMethod === "function") {
857
+ this.debugLog(
858
+ `[Unsetup] Section ${previousSection.instance.constructor.name} unsetup for user ${ctx.user.username}`
859
+ );
860
+ await previousSection.instance.unsetup();
861
+ this.debugLog(
862
+ `[Unsetup finish] Section ${previousSection.instance.constructor.name} unsetup for user ${ctx.user.username}`
863
+ );
864
+ }
865
+ }
866
+ }
867
+
868
+ getRunnedSection(user: UserModel): RunnedSection | Map<string, RunnedSection> {
869
+ const section = this.runnedSections.get(user);
870
+
871
+ if (!section) {
872
+ throw new Error("Section not found");
873
+ }
874
+
875
+ return section;
876
+ }
877
+
878
+ async registerUser(data: UserRegistrationData): Promise<UserModel | null> {
879
+ try {
880
+ const user = await UserModel.register(data);
881
+
882
+ if (this.config.userStorage) {
883
+ this.config.userStorage.add(data.tg_username, user);
884
+ }
885
+
886
+ return user;
887
+ } catch (error) {
888
+ console.error("User registration error:", error);
889
+ return null;
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Runs a task with bidirectional communication support
895
+ * @param ctx Telegram context
896
+ * @param task Function that performs the task with message handlers
897
+ * @param options Configuration options for the task
898
+ * @returns Task controller object with methods for communication and control
899
+ */
900
+ runTask(
901
+ ctx: Telegraf2byteContext,
902
+ task: (controller: {
903
+ signal: AbortSignal;
904
+ sendMessage: (message: string) => Promise<void>;
905
+ onMessage: (handler: (message: string, source: "task" | "external") => void) => void;
906
+ }) => Promise<any>,
907
+ options: {
908
+ taskId?: string;
909
+ notifyStart?: boolean;
910
+ notifyComplete?: boolean;
911
+ startMessage?: string;
912
+ completeMessage?: string;
913
+ errorMessage?: string;
914
+ silent?: boolean;
915
+ } = {}
916
+ ) {
917
+ const {
918
+ taskId = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
919
+ notifyStart = true,
920
+ notifyComplete = true,
921
+ startMessage = "Задача запущена и будет выполняться в фоновом режиме.",
922
+ completeMessage = "Задача успешно завершена!",
923
+ errorMessage = "Произошла ошибка при выполнении задачи.",
924
+ silent = false,
925
+ } = options;
926
+
927
+ // Create abort controller for task cancellation
928
+ const abortController = new AbortController();
929
+
930
+ // Message handling setup
931
+ const messageHandlers: ((message: string, source: "task" | "external") => void)[] = [];
932
+ const messageQueue: Array<{ message: string; source: "task" | "external" }> = [];
933
+
934
+ // Create task controller interface
935
+ const taskController = {
936
+ signal: abortController.signal,
937
+ // Send message from task to handlers
938
+ sendMessage: async (message: string) => {
939
+ if (!silent) {
940
+ await ctx.reply(`[Задача ${taskId}]: ${message}`).catch(console.error);
941
+ }
942
+ messageQueue.push({ message, source: "task" });
943
+ messageHandlers.forEach((handler) => handler(message, "task"));
944
+ },
945
+ // Handle incoming messages to task
946
+ onMessage: (handler: (message: string, source: "task" | "external") => void) => {
947
+ messageHandlers.push(handler);
948
+ // Process any queued messages
949
+ messageQueue.forEach(({ message, source }) => handler(message, source));
950
+ },
951
+ // Receive message from external source
952
+ receiveMessage: async (message: string) => {
953
+ messageQueue.push({ message, source: "external" });
954
+ messageHandlers.forEach((handler) => handler(message, "external"));
955
+ if (!silent) {
956
+ await ctx
957
+ .reply(`[Внешнее сообщение для задачи ${taskId}]: ${message}`)
958
+ .catch(console.error);
959
+ }
960
+ },
961
+ };
962
+
963
+ // Send start notification if enabled
964
+ if (notifyStart && !silent) {
965
+ ctx.reply(startMessage).catch(console.error);
966
+ }
967
+
968
+ // Create and run task promise
969
+ const taskPromise = Promise.resolve().then(() => {
970
+ return task(taskController);
971
+ });
972
+
973
+ // Save task information
974
+ this.runningTasks.set(taskId, {
975
+ task: taskPromise,
976
+ cancel: () => abortController.abort(),
977
+ status: "running",
978
+ startTime: Date.now(),
979
+ ctx,
980
+ controller: taskController,
981
+ messageQueue,
982
+ });
983
+
984
+ // Handle task completion and errors
985
+ taskPromise
986
+ .then((result) => {
987
+ const taskInfo = this.runningTasks.get(taskId);
988
+ if (taskInfo) {
989
+ taskInfo.status = "completed";
990
+ taskInfo.endTime = Date.now();
991
+ if (notifyComplete && !silent) {
992
+ ctx.reply(completeMessage).catch(console.error);
993
+ }
994
+ }
995
+ return result;
996
+ })
997
+ .catch((error) => {
998
+ const taskInfo = this.runningTasks.get(taskId);
999
+ if (taskInfo) {
1000
+ taskInfo.status = error.name === "AbortError" ? "cancelled" : "failed";
1001
+ taskInfo.endTime = Date.now();
1002
+ taskInfo.error = error;
1003
+
1004
+ if (error.name !== "AbortError" && !silent) {
1005
+ console.error("Task error:", error);
1006
+ ctx.reply(`${errorMessage}\nОшибка: ${error.message}`).catch(console.error);
1007
+ }
1008
+ }
1009
+ });
1010
+
1011
+ return taskId;
1012
+ }
1013
+
1014
+ /**
1015
+ * Get information about a running task
1016
+ * @param taskId The ID of the task to check
1017
+ */
1018
+ getTaskInfo(taskId: string) {
1019
+ return this.runningTasks.get(taskId);
1020
+ }
1021
+
1022
+ /**
1023
+ * Cancel a running task
1024
+ * @param taskId The ID of the task to cancel
1025
+ * @returns true if the task was cancelled, false if it couldn't be cancelled
1026
+ */
1027
+ cancelTask(taskId: string): boolean {
1028
+ const taskInfo = this.runningTasks.get(taskId);
1029
+ if (taskInfo && taskInfo.cancel && taskInfo.status === "running") {
1030
+ taskInfo.cancel();
1031
+ return true;
1032
+ }
1033
+ return false;
1034
+ }
1035
+
1036
+ /**
1037
+ * Send a message to a running task
1038
+ * @param taskId The ID of the task to send the message to
1039
+ * @param message The message to send
1040
+ * @returns true if the message was sent, false if the task wasn't found or isn't running
1041
+ */
1042
+ async sendMessageToTask(taskId: string, message: string): Promise<boolean> {
1043
+ const taskInfo = this.runningTasks.get(taskId);
1044
+ if (taskInfo && taskInfo.controller && taskInfo.status === "running") {
1045
+ await taskInfo.controller.receiveMessage(message);
1046
+ return true;
1047
+ }
1048
+ return false;
1049
+ }
1050
+
1051
+ /**
1052
+ * Get all tasks for a specific user
1053
+ * @param userId Telegram user ID
1054
+ */
1055
+ getUserTasks(
1056
+ userId: number
1057
+ ): Array<{ taskId: string; status: string; startTime: number; endTime?: number }> {
1058
+ const tasks: Array<{ taskId: string; status: string; startTime: number; endTime?: number }> =
1059
+ [];
1060
+
1061
+ for (const [taskId, taskInfo] of this.runningTasks) {
1062
+ if (taskInfo.ctx.from?.id === userId) {
1063
+ tasks.push({
1064
+ taskId,
1065
+ status: taskInfo.status,
1066
+ startTime: taskInfo.startTime,
1067
+ endTime: taskInfo.endTime,
1068
+ });
1069
+ }
1070
+ }
1071
+
1072
+ return tasks;
1073
+ }
1074
+
1075
+ /**
1076
+ * Clean up completed/failed/cancelled tasks older than the specified age
1077
+ * @param maxAge Maximum age in milliseconds (default: 1 hour)
1078
+ */
1079
+ cleanupOldTasks(maxAge: number = 3600000): void {
1080
+ const now = Date.now();
1081
+ for (const [taskId, taskInfo] of this.runningTasks) {
1082
+ if (taskInfo.status !== "running" && taskInfo.endTime && now - taskInfo.endTime > maxAge) {
1083
+ this.runningTasks.delete(taskId);
1084
+ }
1085
+ }
1086
+ }
1087
+
1088
+ private getTgUsername(ctx: Telegraf2byteContext): string {
1089
+ return ctx.from?.username || "";
1090
+ }
1091
+
1092
+ private getTgName(ctx: Telegraf2byteContext): string {
1093
+ return ctx.from?.first_name || "";
1094
+ }
1095
+
1096
+ private getTgId(ctx: Telegraf2byteContext): number {
1097
+ return ctx.from?.id || 0;
1098
+ }
1099
+
1100
+ debugLog(...args: any[]): void {
1101
+ if (this.config.debug) {
1102
+ console.log(...args);
1103
+ }
1104
+ }
1105
+
1106
+ get sections(): SectionList {
1107
+ return this.config.sections;
1108
+ }
1109
+
1110
+ get configApp(): AppConfig {
1111
+ return this.config;
1112
+ }
1113
+ }