@2byte/tgbot-framework 1.0.6 → 1.0.7

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