@2byte/tgbot-framework 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +300 -300
  2. package/bin/2byte-cli.ts +97 -97
  3. package/package.json +6 -5
  4. package/src/cli/CreateBotCommand.ts +181 -181
  5. package/src/cli/GenerateCommand.ts +195 -195
  6. package/src/cli/InitCommand.ts +107 -107
  7. package/src/cli/TgAccountManager.ts +50 -0
  8. package/src/console/migrate.ts +82 -82
  9. package/src/core/ApiService.ts +20 -20
  10. package/src/core/ApiServiceManager.ts +63 -63
  11. package/src/core/App.ts +1143 -1113
  12. package/src/core/BotArtisan.ts +79 -79
  13. package/src/core/BotMigration.ts +30 -30
  14. package/src/core/BotSeeder.ts +66 -66
  15. package/src/core/Model.ts +84 -84
  16. package/src/core/utils.ts +2 -2
  17. package/src/illumination/Artisan.ts +149 -149
  18. package/src/illumination/InlineKeyboard.ts +61 -61
  19. package/src/illumination/Message2Byte.ts +255 -255
  20. package/src/illumination/Message2ByteLiveProgressive.ts +278 -278
  21. package/src/illumination/Message2bytePool.ts +107 -107
  22. package/src/illumination/Migration.ts +186 -186
  23. package/src/illumination/RunSectionRoute.ts +85 -85
  24. package/src/illumination/Section.ts +410 -410
  25. package/src/illumination/SectionComponent.ts +64 -64
  26. package/src/illumination/Telegraf2byteContext.ts +32 -32
  27. package/src/index.ts +42 -35
  28. package/src/libs/TelegramAccountControl.ts +1140 -738
  29. package/src/libs/TgSender.ts +53 -0
  30. package/src/models/Model.ts +67 -0
  31. package/src/models/Proxy.ts +218 -0
  32. package/src/models/TgAccount.ts +362 -0
  33. package/src/models/index.ts +3 -0
  34. package/src/types.ts +191 -188
  35. package/src/user/UserModel.ts +297 -297
  36. package/src/user/UserStore.ts +119 -119
  37. package/src/workflow/services/MassSendApiService.ts +80 -80
  38. package/templates/bot/.env.example +23 -19
  39. package/templates/bot/artisan.ts +8 -8
  40. package/templates/bot/bot.ts +82 -79
  41. package/templates/bot/database/dbConnector.ts +4 -4
  42. package/templates/bot/database/migrate.ts +9 -9
  43. package/templates/bot/database/migrations/001_create_users.sql +18 -18
  44. package/templates/bot/database/migrations/007_proxy.sql +27 -0
  45. package/templates/bot/database/migrations/008_tg_accounts.sql +32 -0
  46. package/templates/bot/database/seed.ts +14 -14
  47. package/templates/bot/docs/CLI_SERVICES.md +536 -0
  48. package/templates/bot/docs/INPUT_SYSTEM.md +211 -0
  49. package/templates/bot/docs/SERVICE_EXAMPLES.md +384 -0
  50. package/templates/bot/docs/TASK_SYSTEM.md +156 -0
  51. package/templates/bot/models/Model.ts +7 -0
  52. package/templates/bot/models/index.ts +2 -0
  53. package/templates/bot/package.json +30 -30
  54. package/templates/bot/sectionList.ts +9 -9
  55. package/templates/bot/sections/ExampleInputSection.ts +85 -85
  56. package/templates/bot/sections/ExampleLiveTaskerSection.ts +60 -60
  57. package/templates/bot/sections/HomeSection.ts +63 -63
  58. package/templates/bot/workflow/services/{ExampleServise.ts → ExampleService.ts} +23 -23
@@ -0,0 +1,156 @@
1
+ # Система управления задачами в 2byte Telegram Bot
2
+
3
+ ## Описание
4
+
5
+ Система управления задачами позволяет запускать длительные операции в фоновом режиме с возможностью двусторонней коммуникации между задачей и основным кодом бота.
6
+
7
+ ## Основные возможности
8
+
9
+ - Запуск фоновых задач без блокировки основного потока
10
+ - Двусторонняя коммуникация с задачами
11
+ - Отслеживание статуса задач
12
+ - Возможность отмены задач
13
+ - Автоматическая очистка завершенных задач
14
+ - Поддержка "тихого" режима (без уведомлений в чат)
15
+
16
+ ## Примеры использования
17
+
18
+ ### 1. Простой запуск задачи
19
+
20
+ ```typescript
21
+ const taskId = this.app.runTask(ctx, async ({ signal, sendMessage }) => {
22
+ await sendMessage("Начинаю обработку...");
23
+
24
+ for (let i = 0; i < 100 && !signal.aborted; i++) {
25
+ await sendMessage(`Прогресс: ${i}%`);
26
+ await new Promise(resolve => setTimeout(resolve, 1000));
27
+ }
28
+
29
+ await sendMessage("Обработка завершена!");
30
+ });
31
+ ```
32
+
33
+ ### 2. Задача с обработкой входящих сообщений
34
+
35
+ ```typescript
36
+ const taskId = this.app.runTask(ctx, async ({ signal, sendMessage, onMessage }) => {
37
+ // Подписываемся на входящие сообщения
38
+ onMessage((message, source) => {
39
+ if (source === 'external') {
40
+ switch (message) {
41
+ case 'status':
42
+ sendMessage("Задача активна и обрабатывает данные...");
43
+ break;
44
+ case 'speed_up':
45
+ sendMessage("Ускоряю обработку!");
46
+ break;
47
+ case 'pause':
48
+ sendMessage("Приостанавливаю обработку...");
49
+ break;
50
+ }
51
+ }
52
+ });
53
+
54
+ // Основной код задачи
55
+ while (!signal.aborted) {
56
+ await sendMessage("Обработка данных...");
57
+ await new Promise(resolve => setTimeout(resolve, 1000));
58
+ }
59
+ }, {
60
+ startMessage: "Запуск интерактивной задачи",
61
+ completeMessage: "Задача завершена",
62
+ silent: false
63
+ });
64
+ ```
65
+
66
+ ### 3. Отправка сообщений в задачу
67
+
68
+ ```typescript
69
+ // Отправка команды в задачу
70
+ await this.app.sendMessageToTask(taskId, "status");
71
+
72
+ // Отправка данных для обработки
73
+ await this.app.sendMessageToTask(taskId, JSON.stringify({
74
+ action: "process",
75
+ data: { /* ... */ }
76
+ }));
77
+ ```
78
+
79
+ ### 4. Задача в тихом режиме
80
+
81
+ ```typescript
82
+ const taskId = this.app.runTask(ctx, async ({ signal, sendMessage }) => {
83
+ await sendMessage("Начало тихой обработки");
84
+ // ... код задачи ...
85
+ }, {
86
+ silent: true // Отключаем уведомления в чат
87
+ });
88
+ ```
89
+
90
+ ### 5. Отмена задачи
91
+
92
+ ```typescript
93
+ // Отмена задачи по ID
94
+ const cancelled = this.app.cancelTask(taskId);
95
+ if (cancelled) {
96
+ console.log("Задача успешно отменена");
97
+ } else {
98
+ console.log("Не удалось отменить задачу");
99
+ }
100
+ ```
101
+
102
+ ### 6. Получение информации о задаче
103
+
104
+ ```typescript
105
+ const taskInfo = this.app.getTaskInfo(taskId);
106
+ if (taskInfo) {
107
+ console.log(`Статус задачи: ${taskInfo.status}`);
108
+ console.log(`Время запуска: ${new Date(taskInfo.startTime)}`);
109
+ if (taskInfo.endTime) {
110
+ console.log(`Время завершения: ${new Date(taskInfo.endTime)}`);
111
+ }
112
+ }
113
+ ```
114
+
115
+ ### 7. Получение списка задач пользователя
116
+
117
+ ```typescript
118
+ const userTasks = this.app.getUserTasks(ctx.from.id);
119
+ console.log(`Активные задачи пользователя:`, userTasks);
120
+ ```
121
+
122
+ ## Параметры конфигурации
123
+
124
+ При запуске задачи можно указать следующие параметры:
125
+
126
+ ```typescript
127
+ interface TaskOptions {
128
+ taskId?: string; // Пользовательский ID задачи
129
+ notifyStart?: boolean; // Уведомлять о запуске
130
+ notifyComplete?: boolean; // Уведомлять о завершении
131
+ startMessage?: string; // Сообщение при запуске
132
+ completeMessage?: string; // Сообщение при завершении
133
+ errorMessage?: string; // Сообщение при ошибке
134
+ silent?: boolean; // Тихий режим (без сообщений в чат)
135
+ }
136
+ ```
137
+
138
+ ## Очистка старых задач
139
+
140
+ Система автоматически не очищает завершенные задачи. Для очистки старых задач используйте метод:
141
+
142
+ ```typescript
143
+ // Очистка задач старше 1 часа
144
+ this.app.cleanupOldTasks(3600000);
145
+
146
+ // Очистка задач старше 24 часов
147
+ this.app.cleanupOldTasks(24 * 3600000);
148
+ ```
149
+
150
+ ## Рекомендации по использованию
151
+
152
+ 1. Всегда проверяйте `signal.aborted` в длительных операциях для корректной отмены задачи
153
+ 2. Используйте `try/catch` внутри задач для обработки ошибок
154
+ 3. В тихом режиме (`silent: true`) сообщения не отправляются в чат, но всё ещё доступны через обработчики
155
+ 4. Регулярно очищайте старые завершенные задачи
156
+ 5. Используйте структурированные сообщения (например, JSON) для передачи сложных команд в задачу
@@ -0,0 +1,7 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { MakeManualPaginateButtonsParams, ModelPaginateParams, PaginateResult } from "@2byte/tgbot-framework";
3
+ import { Section } from "@2byte/tgbot-framework";
4
+
5
+ export abstract class Model {
6
+
7
+ }
@@ -0,0 +1,2 @@
1
+ export * from './Model';
2
+ export { Proxy, ProxyData, ProxyStatus, ProxySocksType } from './Proxy';
@@ -1,31 +1,31 @@
1
- {
2
- "name": "{{kebabName}}",
3
- "version": "1.0.0",
4
- "description": "{{description}}",
5
- "main": "bot.ts",
6
- "scripts": {
7
- "dev": "bun --watch bot.ts",
8
- "start": "bun bot.ts",
9
- "build": "bun build bot.ts --outdir ./dist",
10
- "migrate": "bun database/migrate.ts",
11
- "artisan": "bun artisan.ts",
12
- "seed": "bun database/seed.ts",
13
- "seed:clear": "bun database/seed.ts --clear",
14
- "seed:clean": "bun database/seed.ts --clean-only"
15
- },
16
- "keywords": [
17
- "telegram",
18
- "bot",
19
- "2byte"
20
- ],
21
- "author": "{{author}}",
22
- "license": "MIT",
23
- "dependencies": {
24
- "@2byte/tgbot-framework": "^1.0.0"
25
- },
26
- "devDependencies": {
27
- "@types/node": "^20.19.8",
28
- "bun-types": "^1.2.18",
29
- "typescript": "^5.8.3"
30
- }
1
+ {
2
+ "name": "{{kebabName}}",
3
+ "version": "1.0.0",
4
+ "description": "{{description}}",
5
+ "main": "bot.ts",
6
+ "scripts": {
7
+ "dev": "bun --watch bot.ts",
8
+ "start": "bun bot.ts",
9
+ "build": "bun build bot.ts --outdir ./dist",
10
+ "migrate": "bun database/migrate.ts",
11
+ "artisan": "bun artisan.ts",
12
+ "seed": "bun database/seed.ts",
13
+ "seed:clear": "bun database/seed.ts --clear",
14
+ "seed:clean": "bun database/seed.ts --clean-only"
15
+ },
16
+ "keywords": [
17
+ "telegram",
18
+ "bot",
19
+ "2byte"
20
+ ],
21
+ "author": "{{author}}",
22
+ "license": "MIT",
23
+ "dependencies": {
24
+ "@2byte/tgbot-framework": "^1.0.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^20.19.8",
28
+ "bun-types": "^1.2.18",
29
+ "typescript": "^5.8.3"
30
+ }
31
31
  }
@@ -1,9 +1,9 @@
1
- import { SectionEnabledList, SectionList } from "@2byte/tgbot-framework";
2
-
3
- export const sectionList: SectionList = {
4
- home: {},
5
- exampleInput: {},
6
- exampleLiveTasker: {},
7
- }
8
-
9
- export const enabledList: SectionEnabledList = Object.keys(sectionList);
1
+ import { SectionEnabledList, SectionList } from "@2byte/tgbot-framework";
2
+
3
+ export const sectionList: SectionList = {
4
+ home: {},
5
+ exampleInput: {},
6
+ exampleLiveTasker: {},
7
+ }
8
+
9
+ export const enabledList: SectionEnabledList = Object.keys(sectionList);
@@ -1,85 +1,85 @@
1
- import { RunSectionRoute, Section } from "@2byte/tgbot-framework";
2
- import { SectionOptions } from "@2byte/tgbot-framework";
3
- import { InlineKeyboard } from "@2byte/tgbot-framework";
4
-
5
- export default class ExampleInputSection extends Section {
6
- static command = "exampleInput";
7
- static description = "ExampleInput section";
8
- static actionRoutes = {
9
- "exampleInput.index": "index",
10
- "exampleInput.input": "input",
11
- "exampleInput.inputAwaiting": "inputAwaiting",
12
- };
13
-
14
- public sectionId = "exampleInput";
15
- private mainInlineKeyboard: InlineKeyboard;
16
-
17
- constructor(options: SectionOptions) {
18
- super(options);
19
-
20
- this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
21
- }
22
-
23
- public async up(): Promise<void> {}
24
- public async down(): Promise<void> {}
25
- public async setup(): Promise<void> {}
26
- public async unsetup(): Promise<void> {}
27
-
28
- async index() {
29
- const message = `
30
- 👋 Welcome to Exampleinput Section
31
- `;
32
-
33
- await this.message(message)
34
- .inlineKeyboard(
35
- this.mainInlineKeyboard.append(
36
- this.makeInlineButton('➕ Example input', 'exampleInput.input')
37
- ).append(
38
- this.makeInlineButton('➕ Example input with awaiting', 'exampleInput.inputAwaiting')
39
- ).append(
40
- this.btnHome
41
- )
42
- )
43
- .send();
44
- }
45
-
46
- async input() {
47
- await this.message("Please enter some text:")
48
- .inlineKeyboard(this.mainInlineKeyboard)
49
- .requestInput("userText", {
50
- runSection: new RunSectionRoute().section("exampleInput").method("exampleInputHandler"),
51
- }).send();
52
- }
53
-
54
- async exampleInputHandler() {
55
- const userText = this.getAnswerInput("userText");
56
-
57
- await this.message(`You entered: ${userText}`)
58
- .inlineKeyboard(this.mainInlineKeyboard.append(
59
- this.makeInlineButton('➕ Example input', 'exampleInput.input')
60
- ))
61
- .send();
62
- }
63
-
64
- async inputAwaiting() {
65
- try {
66
- const userText = await this.message("Please enter some text (with awaiting):")
67
- .inlineKeyboard(this.mainInlineKeyboard)
68
- .requestInputWithAwait("userTextAwaiting", {
69
- allowCancel: true,
70
- cancelButtonText: "Cancel",
71
- });
72
-
73
- await this.message(`You entered (awaiting): ${userText}`)
74
- .inlineKeyboard(this.mainInlineKeyboard.append(
75
- this.makeInlineButton('➕ Example input with awaiting', 'exampleInput.inputAwaiting')
76
- ))
77
- .send();
78
- } catch (error) {
79
- await this.message("Input was cancelled.")
80
- .inlineKeyboard(this.mainInlineKeyboard)
81
- .send();
82
- }
83
- }
84
-
85
- }
1
+ import { RunSectionRoute, Section } from "@2byte/tgbot-framework";
2
+ import { SectionOptions } from "@2byte/tgbot-framework";
3
+ import { InlineKeyboard } from "@2byte/tgbot-framework";
4
+
5
+ export default class ExampleInputSection extends Section {
6
+ static command = "exampleInput";
7
+ static description = "ExampleInput section";
8
+ static actionRoutes = {
9
+ "exampleInput.index": "index",
10
+ "exampleInput.input": "input",
11
+ "exampleInput.inputAwaiting": "inputAwaiting",
12
+ };
13
+
14
+ public sectionId = "exampleInput";
15
+ private mainInlineKeyboard: InlineKeyboard;
16
+
17
+ constructor(options: SectionOptions) {
18
+ super(options);
19
+
20
+ this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
21
+ }
22
+
23
+ public async up(): Promise<void> {}
24
+ public async down(): Promise<void> {}
25
+ public async setup(): Promise<void> {}
26
+ public async unsetup(): Promise<void> {}
27
+
28
+ async index() {
29
+ const message = `
30
+ 👋 Welcome to Exampleinput Section
31
+ `;
32
+
33
+ await this.message(message)
34
+ .inlineKeyboard(
35
+ this.mainInlineKeyboard.append(
36
+ this.makeInlineButton('➕ Example input', 'exampleInput.input')
37
+ ).append(
38
+ this.makeInlineButton('➕ Example input with awaiting', 'exampleInput.inputAwaiting')
39
+ ).append(
40
+ this.btnHome
41
+ )
42
+ )
43
+ .send();
44
+ }
45
+
46
+ async input() {
47
+ await this.message("Please enter some text:")
48
+ .inlineKeyboard(this.mainInlineKeyboard)
49
+ .requestInput("userText", {
50
+ runSection: new RunSectionRoute().section("exampleInput").method("exampleInputHandler"),
51
+ }).send();
52
+ }
53
+
54
+ async exampleInputHandler() {
55
+ const userText = this.getAnswerInput("userText");
56
+
57
+ await this.message(`You entered: ${userText}`)
58
+ .inlineKeyboard(this.mainInlineKeyboard.append(
59
+ this.makeInlineButton('➕ Example input', 'exampleInput.input')
60
+ ))
61
+ .send();
62
+ }
63
+
64
+ async inputAwaiting() {
65
+ try {
66
+ const userText = await this.message("Please enter some text (with awaiting):")
67
+ .inlineKeyboard(this.mainInlineKeyboard)
68
+ .requestInputWithAwait("userTextAwaiting", {
69
+ allowCancel: true,
70
+ cancelButtonText: "Cancel",
71
+ });
72
+
73
+ await this.message(`You entered (awaiting): ${userText}`)
74
+ .inlineKeyboard(this.mainInlineKeyboard.append(
75
+ this.makeInlineButton('➕ Example input with awaiting', 'exampleInput.inputAwaiting')
76
+ ))
77
+ .send();
78
+ } catch (error) {
79
+ await this.message("Input was cancelled.")
80
+ .inlineKeyboard(this.mainInlineKeyboard)
81
+ .send();
82
+ }
83
+ }
84
+
85
+ }
@@ -1,60 +1,60 @@
1
- import { Section } from "@2byte/tgbot-framework";
2
- import { SectionOptions } from "@2byte/tgbot-framework";
3
- import { InlineKeyboard } from "@2byte/tgbot-framework";
4
-
5
- export default class ExampleLiveTaskerSection extends Section {
6
- static command = "examplelivetasker";
7
- static description = "ExampleLiveTasker section";
8
- static actionRoutes = {
9
- "exampleLiveTasker.index": "index",
10
- "exampleLiveTasker.runTasker": "runTasker",
11
- };
12
-
13
- public sectionId = "ExampleLiveTasker";
14
- private mainInlineKeyboard: InlineKeyboard;
15
-
16
- constructor(options: SectionOptions) {
17
- super(options);
18
-
19
- this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
20
- }
21
-
22
- public async up(): Promise<void> {}
23
- public async down(): Promise<void> {}
24
- public async setup(): Promise<void> {}
25
- public async unsetup(): Promise<void> {}
26
-
27
- async index() {
28
- const message = `
29
- 👋 Welcome to ExampleLiveTasker Section
30
- `;
31
-
32
- await this.message(message)
33
- .inlineKeyboard(this.mainInlineKeyboard.append(
34
- this.makeInlineButton('➕ Example Live Tasker', 'exampleLiveTasker.runTasker')
35
- ))
36
- .send();
37
- }
38
-
39
- async runTasker() {
40
- const msgPool = this.createUpdatePoolMessage("Starting tasker...");
41
-
42
- await msgPool.send();
43
-
44
- const msgProgressive = msgPool.liveProgressive();
45
-
46
- await msgProgressive.setBaseMessage("Tasker in progress:").send();
47
-
48
- for (let i = 1; i <= 5; i++) {
49
- await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate a task taking time
50
- await msgProgressive.appendItem(i, `Task ${i} running`).send();
51
- await msgProgressive.sleepProgressBar(2000).send();
52
- await msgProgressive.changeItem(i, `Task ${i} changed`).send();
53
- await msgProgressive.setItemStatusCompleted(i).send();
54
- }
55
-
56
- await msgProgressive.stopSleepProgress();
57
- const res = await msgPool.append("\n\nAll tasks completed!").send();
58
- console.log("Final message sent:", res);
59
- }
60
- }
1
+ import { Section } from "@2byte/tgbot-framework";
2
+ import { SectionOptions } from "@2byte/tgbot-framework";
3
+ import { InlineKeyboard } from "@2byte/tgbot-framework";
4
+
5
+ export default class ExampleLiveTaskerSection extends Section {
6
+ static command = "examplelivetasker";
7
+ static description = "ExampleLiveTasker section";
8
+ static actionRoutes = {
9
+ "exampleLiveTasker.index": "index",
10
+ "exampleLiveTasker.runTasker": "runTasker",
11
+ };
12
+
13
+ public sectionId = "ExampleLiveTasker";
14
+ private mainInlineKeyboard: InlineKeyboard;
15
+
16
+ constructor(options: SectionOptions) {
17
+ super(options);
18
+
19
+ this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
20
+ }
21
+
22
+ public async up(): Promise<void> {}
23
+ public async down(): Promise<void> {}
24
+ public async setup(): Promise<void> {}
25
+ public async unsetup(): Promise<void> {}
26
+
27
+ async index() {
28
+ const message = `
29
+ 👋 Welcome to ExampleLiveTasker Section
30
+ `;
31
+
32
+ await this.message(message)
33
+ .inlineKeyboard(this.mainInlineKeyboard.append(
34
+ this.makeInlineButton('➕ Example Live Tasker', 'exampleLiveTasker.runTasker')
35
+ ))
36
+ .send();
37
+ }
38
+
39
+ async runTasker() {
40
+ const msgPool = this.createUpdatePoolMessage("Starting tasker...");
41
+
42
+ await msgPool.send();
43
+
44
+ const msgProgressive = msgPool.liveProgressive();
45
+
46
+ await msgProgressive.setBaseMessage("Tasker in progress:").send();
47
+
48
+ for (let i = 1; i <= 5; i++) {
49
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate a task taking time
50
+ await msgProgressive.appendItem(i, `Task ${i} running`).send();
51
+ await msgProgressive.sleepProgressBar(2000).send();
52
+ await msgProgressive.changeItem(i, `Task ${i} changed`).send();
53
+ await msgProgressive.setItemStatusCompleted(i).send();
54
+ }
55
+
56
+ await msgProgressive.stopSleepProgress();
57
+ const res = await msgPool.append("\n\nAll tasks completed!").send();
58
+ console.log("Final message sent:", res);
59
+ }
60
+ }
@@ -1,63 +1,63 @@
1
- import { Section, SectionOptions, InlineKeyboard } from "@2byte/tgbot-framework";
2
-
3
- export default class HomeSection extends Section {
4
- static command = "start";
5
- static description = "Example Bot Home section";
6
- static actionRoutes = {
7
- "home.index": "index",
8
- "home.help": "help",
9
- };
10
-
11
- public sectionId = "home";
12
- private mainInlineKeyboard: InlineKeyboard;
13
-
14
- constructor(options: SectionOptions) {
15
- super(options);
16
-
17
- this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
18
- }
19
-
20
- public async up(): Promise<void> {}
21
- public async down(): Promise<void> {}
22
- public async setup(): Promise<void> {}
23
- public async unsetup(): Promise<void> {}
24
-
25
- async index() {
26
- const message = `
27
- 🏠 **Example Bot**
28
-
29
- Добро пожаловать в Example бот!
30
- Это стартовая секция, созданная с помощью 2byte framework.
31
-
32
- Выберите действие:
33
- `;
34
-
35
- await this.message(message)
36
- .markdown()
37
- .inlineKeyboard(
38
- this.mainInlineKeyboard
39
- .append(this.makeInlineButton("ℹ️ Помощь", "home.help"))
40
- .append(this.makeInlineButton("➕ Example Input", "exampleInput.index"))
41
- .append(this.makeInlineButton("🚀 Example Live Tasker", "exampleLiveTasker.index"))
42
- )
43
- .send();
44
- }
45
-
46
- async help() {
47
- const message = `
48
- ℹ️ **Помощь**
49
-
50
- Это бот, созданный с помощью 2byte Telegram Bot Framework.
51
-
52
- Доступные команды:
53
- • /start - Главное меню
54
-
55
- Для разработчиков:
56
- • bun run artisan make:section <name> - Создать секцию
57
- • bun run migrate - Выполнить миграции
58
- • bun run seed - Заполнить данными
59
- `;
60
-
61
- await this.message(message).inlineKeyboard(this.mainInlineKeyboard).markdown().send();
62
- }
63
- }
1
+ import { Section, SectionOptions, InlineKeyboard } from "@2byte/tgbot-framework";
2
+
3
+ export default class HomeSection extends Section {
4
+ static command = "start";
5
+ static description = "Example Bot Home section";
6
+ static actionRoutes = {
7
+ "home.index": "index",
8
+ "home.help": "help",
9
+ };
10
+
11
+ public sectionId = "home";
12
+ private mainInlineKeyboard: InlineKeyboard;
13
+
14
+ constructor(options: SectionOptions) {
15
+ super(options);
16
+
17
+ this.mainInlineKeyboard = this.makeInlineKeyboard().addFootFixedButtons(this.btnHome);
18
+ }
19
+
20
+ public async up(): Promise<void> {}
21
+ public async down(): Promise<void> {}
22
+ public async setup(): Promise<void> {}
23
+ public async unsetup(): Promise<void> {}
24
+
25
+ async index() {
26
+ const message = `
27
+ 🏠 **Example Bot**
28
+
29
+ Добро пожаловать в Example бот!
30
+ Это стартовая секция, созданная с помощью 2byte framework.
31
+
32
+ Выберите действие:
33
+ `;
34
+
35
+ await this.message(message)
36
+ .markdown()
37
+ .inlineKeyboard(
38
+ this.mainInlineKeyboard
39
+ .append(this.makeInlineButton("ℹ️ Помощь", "home.help"))
40
+ .append(this.makeInlineButton("➕ Example Input", "exampleInput.index"))
41
+ .append(this.makeInlineButton("🚀 Example Live Tasker", "exampleLiveTasker.index"))
42
+ )
43
+ .send();
44
+ }
45
+
46
+ async help() {
47
+ const message = `
48
+ ℹ️ **Помощь**
49
+
50
+ Это бот, созданный с помощью 2byte Telegram Bot Framework.
51
+
52
+ Доступные команды:
53
+ • /start - Главное меню
54
+
55
+ Для разработчиков:
56
+ • bun run artisan make:section <name> - Создать секцию
57
+ • bun run migrate - Выполнить миграции
58
+ • bun run seed - Заполнить данными
59
+ `;
60
+
61
+ await this.message(message).inlineKeyboard(this.mainInlineKeyboard).markdown().send();
62
+ }
63
+ }