telegram-botbuilder 1.6.6 → 2.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 (165) hide show
  1. package/Changelog.md +81 -0
  2. package/MIGRATION.md +453 -0
  3. package/README.md +403 -0
  4. package/lib/actions/callback_action.d.ts +14 -0
  5. package/lib/actions/callback_action.d.ts.map +1 -0
  6. package/lib/actions/callback_action.js +25 -0
  7. package/lib/actions/callback_action.js.map +1 -0
  8. package/lib/actions/change_dialog.d.ts +10 -0
  9. package/lib/actions/change_dialog.d.ts.map +1 -0
  10. package/lib/actions/change_dialog.js +17 -0
  11. package/lib/actions/change_dialog.js.map +1 -0
  12. package/lib/actions/control_flow.d.ts +26 -0
  13. package/lib/actions/control_flow.d.ts.map +1 -0
  14. package/lib/actions/control_flow.js +61 -0
  15. package/lib/actions/control_flow.js.map +1 -0
  16. package/lib/actions/index.d.ts +6 -0
  17. package/lib/actions/index.d.ts.map +1 -0
  18. package/lib/actions/index.js +11 -0
  19. package/lib/actions/index.js.map +1 -0
  20. package/lib/actions/send_message.d.ts +16 -0
  21. package/lib/actions/send_message.d.ts.map +1 -0
  22. package/lib/actions/send_message.js +32 -0
  23. package/lib/actions/send_message.js.map +1 -0
  24. package/lib/actions/wait_for_input.d.ts +14 -0
  25. package/lib/actions/wait_for_input.d.ts.map +1 -0
  26. package/lib/actions/wait_for_input.js +54 -0
  27. package/lib/actions/wait_for_input.js.map +1 -0
  28. package/lib/core/bot_builder.d.ts +145 -0
  29. package/lib/core/bot_builder.d.ts.map +1 -0
  30. package/lib/core/bot_builder.js +678 -0
  31. package/lib/core/bot_builder.js.map +1 -0
  32. package/lib/core/button_registry.d.ts +39 -0
  33. package/lib/core/button_registry.d.ts.map +1 -0
  34. package/lib/core/button_registry.js +84 -0
  35. package/lib/core/button_registry.js.map +1 -0
  36. package/lib/core/dialog_manager.d.ts +71 -0
  37. package/lib/core/dialog_manager.d.ts.map +1 -0
  38. package/lib/core/dialog_manager.js +146 -0
  39. package/lib/core/dialog_manager.js.map +1 -0
  40. package/lib/core/index.d.ts +8 -0
  41. package/lib/core/index.d.ts.map +1 -0
  42. package/lib/core/index.js +8 -0
  43. package/lib/core/index.js.map +1 -0
  44. package/lib/core/input_manager.d.ts +49 -0
  45. package/lib/core/input_manager.d.ts.map +1 -0
  46. package/lib/core/input_manager.js +129 -0
  47. package/lib/core/input_manager.js.map +1 -0
  48. package/lib/core/keyboard_builder.d.ts +35 -0
  49. package/lib/core/keyboard_builder.d.ts.map +1 -0
  50. package/lib/core/keyboard_builder.js +87 -0
  51. package/lib/core/keyboard_builder.js.map +1 -0
  52. package/lib/core/middleware_chain.d.ts +25 -0
  53. package/lib/core/middleware_chain.d.ts.map +1 -0
  54. package/lib/core/middleware_chain.js +54 -0
  55. package/lib/core/middleware_chain.js.map +1 -0
  56. package/lib/core/schema_compiler.d.ts +25 -0
  57. package/lib/core/schema_compiler.d.ts.map +1 -0
  58. package/lib/core/schema_compiler.js +65 -0
  59. package/lib/core/schema_compiler.js.map +1 -0
  60. package/lib/errors/bot_error.d.ts +7 -0
  61. package/lib/errors/bot_error.d.ts.map +1 -0
  62. package/lib/errors/bot_error.js +17 -0
  63. package/lib/errors/bot_error.js.map +1 -0
  64. package/lib/errors/dialog_error.d.ts +12 -0
  65. package/lib/errors/dialog_error.d.ts.map +1 -0
  66. package/lib/errors/dialog_error.js +22 -0
  67. package/lib/errors/dialog_error.js.map +1 -0
  68. package/lib/errors/index.d.ts +5 -0
  69. package/lib/errors/index.d.ts.map +1 -0
  70. package/lib/errors/index.js +5 -0
  71. package/lib/errors/index.js.map +1 -0
  72. package/lib/errors/telegram_error.d.ts +12 -0
  73. package/lib/errors/telegram_error.d.ts.map +1 -0
  74. package/lib/errors/telegram_error.js +39 -0
  75. package/lib/errors/telegram_error.js.map +1 -0
  76. package/lib/errors/validation_error.d.ts +19 -0
  77. package/lib/errors/validation_error.d.ts.map +1 -0
  78. package/lib/errors/validation_error.js +35 -0
  79. package/lib/errors/validation_error.js.map +1 -0
  80. package/lib/index.d.ts +6 -2
  81. package/lib/index.d.ts.map +1 -1
  82. package/lib/index.js +9 -18
  83. package/lib/index.js.map +1 -1
  84. package/lib/types/action.d.ts +58 -0
  85. package/lib/types/action.d.ts.map +1 -0
  86. package/lib/types/action.js +2 -0
  87. package/lib/types/action.js.map +1 -0
  88. package/lib/types/config.d.ts +36 -0
  89. package/lib/types/config.d.ts.map +1 -0
  90. package/lib/types/config.js +12 -0
  91. package/lib/types/config.js.map +1 -0
  92. package/lib/types/dialog.d.ts +39 -0
  93. package/lib/types/dialog.d.ts.map +1 -0
  94. package/lib/types/dialog.js +2 -0
  95. package/lib/types/dialog.js.map +1 -0
  96. package/lib/types/index.d.ts +10 -0
  97. package/lib/types/index.d.ts.map +1 -0
  98. package/lib/types/index.js +3 -0
  99. package/lib/types/index.js.map +1 -0
  100. package/lib/types/internal.d.ts +58 -0
  101. package/lib/types/internal.d.ts.map +1 -0
  102. package/lib/types/internal.js +11 -0
  103. package/lib/types/internal.js.map +1 -0
  104. package/lib/types/keyboard.d.ts +41 -0
  105. package/lib/types/keyboard.d.ts.map +1 -0
  106. package/lib/types/keyboard.js +2 -0
  107. package/lib/types/keyboard.js.map +1 -0
  108. package/lib/types/middleware.d.ts +24 -0
  109. package/lib/types/middleware.d.ts.map +1 -0
  110. package/lib/types/middleware.js +2 -0
  111. package/lib/types/middleware.js.map +1 -0
  112. package/lib/types/schema.d.ts +17 -0
  113. package/lib/types/schema.d.ts.map +1 -0
  114. package/lib/types/schema.js +2 -0
  115. package/lib/types/schema.js.map +1 -0
  116. package/lib/utils/constants.d.ts +33 -0
  117. package/lib/utils/constants.d.ts.map +1 -0
  118. package/lib/utils/constants.js +33 -0
  119. package/lib/utils/constants.js.map +1 -0
  120. package/lib/utils/deep_copy.d.ts +6 -0
  121. package/lib/utils/deep_copy.d.ts.map +1 -0
  122. package/lib/utils/deep_copy.js +45 -0
  123. package/lib/utils/deep_copy.js.map +1 -0
  124. package/lib/utils/hash.d.ts +17 -0
  125. package/lib/utils/hash.d.ts.map +1 -0
  126. package/lib/utils/hash.js +50 -0
  127. package/lib/utils/hash.js.map +1 -0
  128. package/lib/utils/index.d.ts +7 -0
  129. package/lib/utils/index.d.ts.map +1 -0
  130. package/lib/utils/index.js +7 -0
  131. package/lib/utils/index.js.map +1 -0
  132. package/lib/utils/logger.d.ts +17 -0
  133. package/lib/utils/logger.d.ts.map +1 -0
  134. package/lib/utils/logger.js +91 -0
  135. package/lib/utils/logger.js.map +1 -0
  136. package/lib/utils/resolvers.d.ts +29 -0
  137. package/lib/utils/resolvers.d.ts.map +1 -0
  138. package/lib/utils/resolvers.js +60 -0
  139. package/lib/utils/resolvers.js.map +1 -0
  140. package/lib/utils/type_guards.d.ts +22 -0
  141. package/lib/utils/type_guards.d.ts.map +1 -0
  142. package/lib/utils/type_guards.js +38 -0
  143. package/lib/utils/type_guards.js.map +1 -0
  144. package/lib/validation/index.d.ts +2 -0
  145. package/lib/validation/index.d.ts.map +1 -0
  146. package/lib/validation/index.js +2 -0
  147. package/lib/validation/index.js.map +1 -0
  148. package/lib/validation/schema_validator.d.ts +11 -0
  149. package/lib/validation/schema_validator.d.ts.map +1 -0
  150. package/lib/validation/schema_validator.js +156 -0
  151. package/lib/validation/schema_validator.js.map +1 -0
  152. package/package.json +59 -15
  153. package/lib/bot-service.d.ts +0 -27
  154. package/lib/bot-service.d.ts.map +0 -1
  155. package/lib/bot-service.js +0 -326
  156. package/lib/bot-service.js.map +0 -1
  157. package/lib/bot-struct.d.ts +0 -58
  158. package/lib/bot-struct.d.ts.map +0 -1
  159. package/lib/bot-struct.js +0 -3
  160. package/lib/bot-struct.js.map +0 -1
  161. package/readme.md +0 -54
  162. package/src/bot-service.ts +0 -289
  163. package/src/bot-struct.ts +0 -59
  164. package/src/index.ts +0 -2
  165. package/tsconfig.json +0 -108
@@ -1,289 +0,0 @@
1
- import TelegramBot, { InlineKeyboardButton, InputMediaPhoto } from 'node-telegram-bot-api';
2
- import { Schema, Action, BotSchema, Button, BotButton, BotDialog, UserDialog, BotBuilderMiddleware, MWBreakDown, CallbackActionFunc, Dialog } from './bot-struct';
3
- import EventEmitter from 'events';
4
- import { readFileSync, rmSync } from 'fs';
5
- import * as deepcopy from 'rfdc';
6
- var hash = require('object-hash');
7
-
8
- const bypass_str = 'ETELEGRAM: 400 Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message';
9
-
10
- export class BotBuilder {
11
- public _bot: TelegramBot;
12
- private _schema: BotSchema;
13
- public ActionSystem: EventEmitter;
14
- private _userdialogs: UserDialog;
15
- private _middleware: BotBuilderMiddleware[] = [];
16
- private _mwbreak: MWBreakDown = {};
17
-
18
- // Adds a middleware function to the bot
19
- public use(func: BotBuilderMiddleware) {
20
- this._middleware.push(func);
21
- }
22
-
23
- // Waits for the middleware break-down event to be emitted
24
- private _mwba(desc: string): Promise<boolean> {
25
- return new Promise(r => {
26
- this.ActionSystem.once(`mwb_${desc}`, r)
27
- });
28
- }
29
-
30
- // Runs all middleware functions and waits for the result
31
- private async _runmw(chat: number, msg: TelegramBot.Message | TelegramBot.CallbackQuery) {
32
- let desc = `${chat}_${(msg as TelegramBot.Message).message_id || (msg as TelegramBot.CallbackQuery).id}`;
33
- let mwb = this._mwbreak[desc];
34
- if (typeof mwb === 'boolean') return mwb;
35
- if (mwb === null) return await this._mwba(desc);
36
- this._mwbreak[desc] = null;
37
-
38
- let res = false;
39
- for (let mw of this._middleware) {
40
- res = res || await mw(chat, msg);
41
- }
42
-
43
- this._mwbreak[desc] = res;
44
- this.ActionSystem.emit(`mwb_${desc}`, res);
45
- return res;
46
- }
47
-
48
- // Generates a hash for a button based on the dialog and button properties
49
- private _hashbtn(dia: BotDialog, btn: Button) {
50
- return hash([dia.id, {a: btn.action, b: btn.text, c: btn.url, d: btn.mini_app }]);
51
- }
52
-
53
- constructor (schema: Schema, token: string, options?: TelegramBot.ConstructorOptions) {
54
- this._bot = new TelegramBot(token, options);
55
- this._schema = schema as BotSchema;
56
- this._schema.buttons = [];
57
-
58
- this.ActionSystem = new EventEmitter();
59
- this._userdialogs = {};
60
-
61
- // buttons first pass | fp disable var | fp for funcs | TODO
62
- try {
63
- for (let fp_di = 0; fp_di < this._schema.content.length; fp_di++) {
64
- let fp_db = this._schema.content[fp_di].buttons
65
- if (typeof fp_db == 'function') continue;
66
-
67
- for (let fp_by = 0; fp_db.length; fp_by++) {
68
- let fp_ln = fp_db[fp_by];
69
- for (let fp_bx = 0; fp_bx < fp_ln.length; fp_bx++) {
70
- let fp_b = fp_db[fp_by][fp_bx];
71
- fp_b._callback = this._hashbtn(this._schema.content[fp_di], fp_b);
72
- this._schema.buttons.push(fp_b);
73
- }
74
- }
75
- }
76
- } catch {}
77
-
78
-
79
- this._bot.onText(/.+/gms, async (msg) => {
80
- if (!this._userdialogs[msg.chat.id]) this._userdialogs[msg.chat.id] = {dialog: this._schema.start, lastid: msg.message_id, waiter: { statewait: false, descriptor: '' }}
81
- if (await this._runmw(msg.chat.id, msg)) return;
82
-
83
- let chat = msg.chat.id;
84
- if (this._userdialogs[chat]!.waiter!.statewait) {
85
- this._userdialogs[chat].waiter.statewait = false;
86
- await this._bot.deleteMessage(chat, msg.message_id).catch(() => undefined);
87
- this.ActionSystem.emit(this._userdialogs[chat].waiter.descriptor, chat, msg.text, msg.entities, msg.caption_entities);
88
- return;
89
- }
90
-
91
- // test commands
92
- let text = msg.text || '';
93
- if (this._schema.commands != undefined) {
94
- for (let cmd of this._schema.commands) {
95
- let r_exec = new RegExp(`^\\/(${cmd.text.trim().toLowerCase()})\\b(?:\\s+(.+))?$`, 'gms').exec(text.trim());
96
- if (r_exec != null) {
97
- if (typeof cmd.action == 'function') await cmd.action(msg.chat.id, this, (r_exec[2] as string | undefined));
98
- else if (Array.isArray(cmd.action)) for (let r_act of cmd.action) await r_act(msg.chat.id, this, (r_exec[2] as string | undefined));
99
- }
100
- }
101
- }
102
- });
103
-
104
- this._bot.on('callback_query', async (query) => {
105
- if (!this._userdialogs[query.message!.chat.id]) {
106
- this._userdialogs[query.message!.chat.id] = {dialog: this._schema.start, lastid: query.message?.message_id || this._userdialogs[query.message!.chat.id].lastid || -1, waiter: { statewait: false, descriptor: '' }}
107
- } else {
108
- this._userdialogs[query.message!.chat.id].lastid = query.message?.message_id || this._userdialogs[query.message!.chat.id].lastid || -1;
109
- }
110
-
111
- if (await this._runmw(query.message!.chat.id, query)) return;
112
-
113
- await this._activateButton(query.message!.chat.id, query.data!, query.message?.message_id)
114
- });
115
-
116
- this._bot.on('document', async (msg) => {
117
- if (!this._userdialogs[msg.chat.id]) this._userdialogs[msg.chat.id] = {dialog: this._schema.start, lastid: msg.message_id, waiter: { statewait: false, descriptor: '' }}
118
- if (await this._runmw(msg.chat.id, msg)) return;
119
-
120
- if (!msg.document) return;
121
- let chat = msg.chat.id;
122
- if (!this._userdialogs[chat].waiter.statewait) return;
123
- await this._bot.downloadFile(msg.document.file_id, './').then((x) => {
124
- this._userdialogs[chat].waiter.statewait = false;
125
- this._bot.deleteMessage(chat, msg.message_id).catch(() => undefined);
126
- let content = readFileSync(x, 'utf8');
127
- rmSync(x);
128
- this.ActionSystem.emit(this._userdialogs[chat].waiter.descriptor, chat, content);
129
- });
130
- });
131
-
132
- this._bot.onText(/^\/start/, async (msg) => {
133
- if (this._schema.enable_start === false) return;
134
- if (await this._runmw(msg.chat.id, msg)) return;
135
-
136
- if (this._userdialogs[msg.chat.id] != undefined) this._bot.deleteMessage(msg.chat.id, this._userdialogs[msg.chat.id].lastid).catch(() => undefined);
137
- this._userdialogs[msg.chat.id] = {dialog: this._schema.start, lastid: -1, waiter: { statewait: false, descriptor: '' }}
138
- this._bot.deleteMessage(msg.chat.id, msg.message_id).catch(() => undefined);
139
- this.ChangeDialog(msg.chat.id, this._schema.start);
140
- });
141
- }
142
-
143
- // Returns the dialog with the specified ID
144
- private _getDialog(id: string) {
145
- return this._schema.content.find(x => x.id === id);
146
- }
147
-
148
- // Returns the button with the specified callback hash
149
- private _getButton(callback: string) {
150
- return this._schema.buttons?.find(x => x._callback === callback);
151
- }
152
-
153
- // Returns the index of the button with the specified callback hash
154
- private _getButtonID(callback: string) {
155
- return this._schema.buttons?.findIndex(x => x._callback === callback);
156
- }
157
-
158
- private async _activateButton(chat: number, btn: string | BotButton, message_id?: number) {
159
- let _btn: BotButton | undefined;
160
- if (typeof btn === 'string') { _btn = this._getButton(btn); }
161
- else { _btn = btn; }
162
-
163
- if (_btn == undefined) {
164
- return (this.ChangeDialog(chat, this._schema.start, message_id), void 0);
165
- }
166
-
167
- if (Array.isArray(_btn?.action)) {
168
- for (let act of (_btn?.action as Action[])) {
169
- await act(chat, this);
170
- }
171
- } else if (_btn?.action as Action) {
172
- await (_btn?.action as Action)(chat, this);
173
- }
174
- }
175
-
176
- public async ChangeDialog(chat: number, id: string | Dialog, message_id?: number) {
177
- if (this._userdialogs[chat] == undefined) this._userdialogs[chat] = {dialog: this._schema.start, lastid: -1, waiter: { statewait: false, descriptor: '' }}
178
-
179
- if (typeof id != 'string') {
180
- this._userdialogs[chat].dialog = id.id;
181
- } else {
182
- this._userdialogs[chat].dialog = id;
183
- }
184
-
185
- if (message_id != undefined) {
186
- this._userdialogs[chat].lastid = message_id;
187
- }
188
-
189
- if (this._userdialogs[chat].waiter.statewait) {
190
- this._userdialogs[chat].waiter.statewait = false;
191
- this.ActionSystem.emit(`cancel_${this._userdialogs[chat].waiter.descriptor}`, chat)
192
- }
193
-
194
- let dialog: BotDialog | undefined;
195
- if (typeof id == 'string') { dialog = this._getDialog(id); }
196
- else { dialog = id as BotDialog; }
197
-
198
- let btns: BotButton[][] = deepcopy.default()((typeof dialog?.buttons === 'function' ? await dialog?.buttons(chat) : dialog?.buttons)) || [];
199
-
200
- let markup: InlineKeyboardButton[][] | undefined = undefined;
201
- if (btns.length > 0) {
202
- markup = [];
203
- for (let b = 0; b < btns.length; b++) {
204
- markup[b] = [];
205
- for (let btn of btns[b]) {
206
- btn.text = typeof btn.text === 'function' ? await btn.text(chat) : btn.text;
207
- if (btn.url != undefined) btn.url = typeof btn.url == 'function' ? await btn.url(chat) : btn.url;
208
- if (btn.mini_app != undefined) btn.mini_app = typeof btn.mini_app == 'function' ? await btn.mini_app(chat) : btn.mini_app;
209
- btn._callback = this._hashbtn(dialog!, btn);
210
- let psid = this._getButtonID(btn._callback);
211
- if (psid == -1) this._schema.buttons?.push(btn);
212
- markup[b].push({ text: (btn.text || ''), callback_data: (btn.mini_app ? undefined : btn._callback), url: btn.url, web_app: (btn.mini_app != undefined ? { url: btn.mini_app } : undefined) });
213
- }
214
- }
215
- }
216
-
217
- if (dialog == undefined) markup = [[{ text: "Reload", callback_data: this._schema.start }]]; // FIX RAND BTN
218
- let text = typeof dialog?.text === 'function' ? await dialog?.text(chat) : dialog?.text;
219
-
220
- try {
221
- let imgs = (dialog != undefined && dialog.images != undefined) ? (typeof dialog.images == 'function' ? await dialog.images(chat) : dialog.images) : undefined;
222
- if (dialog != undefined && imgs != undefined) {
223
- if (Array.isArray(imgs) && imgs.length > 1) {
224
- if (this._userdialogs[chat].last_type == 'default' && this._userdialogs[chat].lastid != -1) await this._bot.deleteMessage(chat, this._userdialogs[chat].lastid).catch(() => {});
225
- let res_msg = await this._bot.sendMediaGroup(chat, imgs.map(x => { return { media: x } as InputMediaPhoto })); // * WARN currently not support image group with text
226
- this._userdialogs[chat].lastid = res_msg.pop()?.message_id || this._userdialogs[chat].lastid;
227
- this._userdialogs[chat].last_type = 'image';
228
- } else {
229
- if (this._userdialogs[chat].last_type == 'default' && this._userdialogs[chat].lastid != -1) await this._bot.deleteMessage(chat, this._userdialogs[chat].lastid).catch(() => {});
230
- let img = Array.isArray(imgs) ? imgs[0]: imgs;
231
- let res_msg = await this._bot.sendPhoto(chat, img, { caption: text || "", parse_mode: 'HTML', reply_markup: markup ? { inline_keyboard: markup} : undefined });
232
- this._userdialogs[chat].lastid = res_msg.message_id || this._userdialogs[chat].lastid;
233
- this._userdialogs[chat].last_type = 'image';
234
- }
235
- } else {
236
- if (this._userdialogs[chat].last_type == 'default') await this._bot.editMessageText(text || "404", { chat_id: chat, message_id: this._userdialogs[chat].lastid, parse_mode: 'HTML', reply_markup: markup ? { inline_keyboard: markup } : undefined });
237
- else {
238
- if (this._userdialogs[chat].lastid != -1) await this._bot.deleteMessage(chat, this._userdialogs[chat].lastid).catch(() => {});
239
- let res_msg = await this._bot.sendMessage(chat, text || "404", {parse_mode: 'HTML', reply_markup: markup ? { inline_keyboard: markup} : undefined });
240
- this._userdialogs[chat].lastid = res_msg.message_id || this._userdialogs[chat].lastid;
241
- this._userdialogs[chat].last_type = 'default';
242
- }
243
- }
244
- } catch (e) {
245
- if ((e as Error).message == bypass_str) return;
246
- if (this._userdialogs[chat].lastid != -1) await this._bot.deleteMessage(chat, this._userdialogs[chat].lastid).catch(() => {});
247
- let res_msg = await this._bot.sendMessage(chat, text || "404", {parse_mode: 'HTML', reply_markup: markup ? { inline_keyboard: markup} : undefined });
248
- this._userdialogs[chat].lastid = res_msg.message_id || this._userdialogs[chat].lastid;
249
- this._userdialogs[chat].last_type = 'default';
250
- }
251
- }
252
- public AttachDataWait(chat: number, descriptor: string) {
253
- this._userdialogs[chat].waiter.descriptor = descriptor;
254
- this._userdialogs[chat].waiter.statewait = true;
255
- }
256
- public Message(chat: number, content: string) {
257
- return this._bot.sendMessage(chat, content, {parse_mode: 'HTML'});
258
- }
259
- }
260
-
261
- export function ChangeDialog(id: string): Action {
262
- return (chat: number, _bot: BotBuilder) => { return _bot.ChangeDialog(chat, id); };
263
- }
264
- export function CallbackAction(descriptor: string | CallbackActionFunc, ...args: any[]): Action {
265
- return async (chat: number, _bot: BotBuilder, ..._args: any[]) => {
266
- return typeof descriptor == 'function' ? await descriptor(chat, ...args, ..._args) : _bot.ActionSystem.emit(descriptor, chat, ...args, ..._args);
267
- };
268
- }
269
- export function WaitForData(descriptor: string | CallbackActionFunc): Action {
270
- return async (chat: number, _bot: BotBuilder) => {
271
- if (typeof descriptor == 'string') {
272
- let _tmpds = crypto.randomUUID();
273
- _bot.AttachDataWait(chat, _tmpds);
274
- return new Promise(r => {
275
- _bot.ActionSystem.once(_tmpds, (...args: any[]) => {_bot.ActionSystem.emit(descriptor, ...args); return r(undefined)});
276
- _bot.ActionSystem.once(`cancel_${_tmpds}`, (...args: any[]) => {_bot.ActionSystem.emit(`cancel_${descriptor}`, ...args); return r(undefined)});
277
- });
278
- } else {
279
- let desc = crypto.randomUUID();
280
- _bot.AttachDataWait(chat, desc);
281
- return new Promise(r => {
282
- _bot.ActionSystem.once(desc, descriptor);
283
- _bot.ActionSystem.once(`cancel_${desc}`, descriptor);
284
- _bot.ActionSystem.once(desc, r);
285
- _bot.ActionSystem.once(`cancel_${desc}`, r);
286
- });
287
- }
288
- };
289
- }
package/src/bot-struct.ts DELETED
@@ -1,59 +0,0 @@
1
- import TelegramBot from "node-telegram-bot-api";
2
- import { BotBuilder } from "./bot-service";
3
-
4
-
5
- export type Action = (chat: number, _bot: BotBuilder, ...args: any[]) => (Promise<any> | any);
6
- export type ImageFunc = string | string[] | ((chat: number) => (Promise<string | string[] | undefined> | (string | string[] | undefined)));
7
- export type TextFunc = string | ((chat: number) => (Promise<string | undefined> | (string | undefined)));
8
-
9
-
10
- export interface Dialog {
11
- id: string;
12
- text?: TextFunc;
13
- buttons: Button[][] | ((chat: number) => Promise<Button[][]>) | ((chat: number) => Button[][]);
14
- disable_btn_fp?: boolean;
15
- images?: ImageFunc;
16
- }
17
- export interface BotDialog extends Dialog {
18
- buttons: BotButton[][] | ((chat: number) => Promise<BotButton[][]>) | ((chat: number) => BotButton[][]);
19
- }
20
-
21
- export interface Button {
22
- text?: TextFunc;
23
- action?: Action[] | Action;
24
- url?: TextFunc;
25
- mini_app?: TextFunc;
26
- }
27
- export interface BotButton extends Button {
28
- _callback: string;
29
- }
30
-
31
- export interface Schema {
32
- start: string;
33
- content: Dialog[];
34
- commands?: Command[];
35
- enable_start?: boolean;
36
- }
37
- export interface BotSchema extends Schema {
38
- content: BotDialog[];
39
- buttons?: BotButton[];
40
- }
41
-
42
- export interface Command {
43
- text: string;
44
- action?: Action[] | Action;
45
- }
46
-
47
- export interface UserDialog {
48
- [key: number]: {dialog: string, lastid: number, waiter: { statewait: boolean, descriptor: string }, last_type?: 'default' | 'image' };
49
- }
50
- export interface MWBreakDown {
51
- [key: string]: boolean | undefined | null;
52
- }
53
- export type BotBuilderMiddleware = (chat: number, msg: TelegramBot.Message | TelegramBot.CallbackQuery) => Promise<boolean> | boolean;
54
-
55
- export interface ActionCallback {
56
- chatid: number;
57
- }
58
-
59
- export type CallbackActionFunc = ((chatid: number, ...args: any[]) => void) | ((chatid: number, ...args: any[]) => Promise<void>)
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './bot-service';
2
- export * from './bot-struct';
package/tsconfig.json DELETED
@@ -1,108 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
-
27
- /* Modules */
28
- "module": "commonjs", /* Specify what module code is generated. */
29
- "rootDir": "./src/", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
- // "resolveJsonModule": true, /* Enable importing .json files. */
43
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
-
46
- /* JavaScript Support */
47
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
-
51
- /* Emit */
52
- "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
- "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
- "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
- "outDir": "./lib/", /* Specify an output folder for all emitted files. */
59
- // "removeComments": true, /* Disable emitting comments. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
63
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
64
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
65
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
66
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
67
- // "newLine": "crlf", /* Set the newline character for emitting files. */
68
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
69
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
70
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
71
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
72
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
73
-
74
- /* Interop Constraints */
75
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
76
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
77
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
78
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
79
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
80
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
81
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
82
-
83
- /* Type Checking */
84
- "strict": true, /* Enable all strict type-checking options. */
85
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
86
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
87
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
88
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
89
- "strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */
90
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
91
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
92
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
93
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
94
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
95
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
96
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
97
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
98
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
99
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
100
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
101
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
102
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
103
-
104
- /* Completeness */
105
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
106
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
107
- }
108
- }