@2byte/tgbot-framework 1.0.0

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