@2byte/tgbot-framework 1.0.6 → 1.0.8
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.
- package/README.md +300 -300
- package/bin/2byte-cli.ts +97 -97
- package/package.json +55 -55
- package/src/cli/CreateBotCommand.ts +181 -181
- package/src/cli/GenerateCommand.ts +195 -195
- package/src/cli/InitCommand.ts +107 -107
- package/src/cli/TgAccountManager.ts +50 -50
- package/src/console/migrate.ts +82 -82
- package/src/core/ApiService.ts +20 -20
- package/src/core/ApiServiceManager.ts +63 -63
- package/src/core/App.ts +1157 -1143
- package/src/core/BotArtisan.ts +79 -79
- package/src/core/BotMigration.ts +30 -30
- package/src/core/BotSeeder.ts +66 -66
- package/src/core/Model.ts +84 -84
- package/src/core/utils.ts +2 -2
- package/src/illumination/Artisan.ts +149 -149
- package/src/illumination/InlineKeyboard.ts +61 -61
- package/src/illumination/Message2Byte.ts +255 -255
- package/src/illumination/Message2ByteLiveProgressive.ts +278 -278
- package/src/illumination/Message2bytePool.ts +107 -107
- package/src/illumination/Migration.ts +186 -186
- package/src/illumination/RunSectionRoute.ts +85 -85
- package/src/illumination/Section.ts +410 -410
- package/src/illumination/SectionComponent.ts +64 -64
- package/src/illumination/Telegraf2byteContext.ts +32 -32
- package/src/index.ts +42 -42
- package/src/libs/TelegramAccountControl.ts +1140 -1140
- package/src/libs/TgSender.ts +53 -53
- package/src/models/Model.ts +67 -67
- package/src/models/Proxy.ts +217 -217
- package/src/models/TgAccount.ts +362 -362
- package/src/models/index.ts +2 -2
- package/src/types.ts +191 -191
- package/src/user/UserModel.ts +297 -297
- package/src/user/UserStore.ts +119 -119
- package/src/workflow/services/MassSendApiService.ts +83 -80
- package/templates/bot/.env.example +33 -33
- package/templates/bot/artisan.ts +8 -8
- package/templates/bot/bot.ts +82 -82
- package/templates/bot/database/dbConnector.ts +4 -4
- package/templates/bot/database/migrate.ts +9 -9
- package/templates/bot/database/migrations/001_create_users.sql +18 -18
- package/templates/bot/database/migrations/007_proxy.sql +27 -27
- package/templates/bot/database/migrations/008_tg_accounts.sql +32 -32
- package/templates/bot/database/seed.ts +14 -14
- package/templates/bot/docs/CLI_SERVICES.md +536 -536
- package/templates/bot/docs/INPUT_SYSTEM.md +211 -211
- package/templates/bot/docs/MASS_SEND_SERVICE.md +327 -0
- package/templates/bot/docs/SERVICE_EXAMPLES.md +384 -384
- package/templates/bot/docs/TASK_SYSTEM.md +156 -156
- package/templates/bot/models/Model.ts +7 -7
- package/templates/bot/models/index.ts +1 -1
- package/templates/bot/package.json +30 -30
- package/templates/bot/sectionList.ts +9 -9
- package/templates/bot/sections/ExampleInputSection.ts +85 -85
- package/templates/bot/sections/ExampleLiveTaskerSection.ts +60 -60
- package/templates/bot/sections/HomeSection.ts +63 -63
- 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 =
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
if (!
|
|
366
|
-
throw new Error(
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
this.
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
this.
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
//
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
//
|
|
637
|
-
|
|
638
|
-
//
|
|
639
|
-
// -
|
|
640
|
-
// -
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
//
|
|
647
|
-
const
|
|
648
|
-
return
|
|
649
|
-
|
|
650
|
-
case "
|
|
651
|
-
if (inputType !== "
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
)
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
pathSectionModule
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
this.debugLog(
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
const
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
//
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
ctx
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
ctx.reply(
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
return
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
/**
|
|
1067
|
-
*
|
|
1068
|
-
* @param taskId The ID of the task to
|
|
1069
|
-
* @
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
*
|
|
1083
|
-
* @param
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
}
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
return
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
return
|
|
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
|
+
// For bypassing cache in Node.js/Bun, we use file:// protocol with a query parameter
|
|
739
|
+
let importPath = pathSectionModule;
|
|
740
|
+
if (freshVersion) {
|
|
741
|
+
// We convert the path to a file:// URL with a query parameter
|
|
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
|
+
}
|