@xbibzlibrary/telebibz 0.4.4 → 3.0.1

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 (258) hide show
  1. package/CHANGELOG.md +35 -138
  2. package/LICENSE +1 -1
  3. package/NOTICE.md +9 -4
  4. package/README.md +173 -242
  5. package/examples/01-quickstart.js +13 -0
  6. package/examples/02-menu-tombol.js +22 -0
  7. package/examples/03-wizard.js +29 -0
  8. package/examples/04-broadcast.js +25 -0
  9. package/examples/05-kirim-file.js +19 -0
  10. package/examples/06-menu.js +35 -0
  11. package/examples/07-inline-query.js +18 -0
  12. package/index.d.ts +81 -0
  13. package/index.js +42 -0
  14. package/lib/api.js +154 -0
  15. package/lib/broadcast.js +35 -0
  16. package/lib/composer.js +174 -0
  17. package/lib/context.js +190 -0
  18. package/lib/errors.js +35 -0
  19. package/lib/file.js +41 -0
  20. package/lib/inline-query.js +28 -0
  21. package/lib/keyboard.js +83 -0
  22. package/lib/logger.js +38 -0
  23. package/lib/menus.js +90 -0
  24. package/lib/net.js +115 -0
  25. package/lib/ratelimit.js +61 -0
  26. package/lib/runner.js +45 -0
  27. package/lib/session.js +36 -0
  28. package/lib/telebibz.js +190 -0
  29. package/lib/wizard.js +81 -0
  30. package/package.json +35 -97
  31. package/test/all.test.js +334 -0
  32. package/CODE_OF_CONDUCT.md +0 -37
  33. package/CONTRIBUTING.md +0 -59
  34. package/CONTRIBUTION_RULES.md +0 -41
  35. package/GOVERNANCE.md +0 -47
  36. package/README.id.md +0 -292
  37. package/README.zh-CN.md +0 -292
  38. package/RELEASE_AUTOMATION.md +0 -78
  39. package/RELEASE_POLICY.md +0 -32
  40. package/SECURITY.md +0 -47
  41. package/SHOWCASE.md +0 -29
  42. package/SUPPORT.md +0 -30
  43. package/assets/readme-preview.html +0 -75
  44. package/assets/telebibz-logo.png +0 -0
  45. package/assets/telebibz-readme-preview.png +0 -0
  46. package/bin/telebibz.mjs +0 -3
  47. package/dist/generated/api.d.ts +0 -13
  48. package/dist/generated/api.d.ts.map +0 -1
  49. package/dist/generated/api.js +0 -192
  50. package/dist/generated/api.js.map +0 -1
  51. package/dist/src/api/client.d.ts +0 -62
  52. package/dist/src/api/client.d.ts.map +0 -1
  53. package/dist/src/api/client.js +0 -104
  54. package/dist/src/api/client.js.map +0 -1
  55. package/dist/src/api/errors.d.ts +0 -45
  56. package/dist/src/api/errors.d.ts.map +0 -1
  57. package/dist/src/api/errors.js +0 -65
  58. package/dist/src/api/errors.js.map +0 -1
  59. package/dist/src/api/index.d.ts +0 -6
  60. package/dist/src/api/index.d.ts.map +0 -1
  61. package/dist/src/api/index.js +0 -6
  62. package/dist/src/api/index.js.map +0 -1
  63. package/dist/src/api/telegram-types/LICENSE +0 -21
  64. package/dist/src/api/telegram-types/api.d.ts +0 -22
  65. package/dist/src/api/telegram-types/checklist.d.ts +0 -72
  66. package/dist/src/api/telegram-types/inline.d.ts +0 -692
  67. package/dist/src/api/telegram-types/langs.d.ts +0 -193
  68. package/dist/src/api/telegram-types/manage.d.ts +0 -1144
  69. package/dist/src/api/telegram-types/markup.d.ts +0 -268
  70. package/dist/src/api/telegram-types/message.d.ts +0 -1537
  71. package/dist/src/api/telegram-types/methods.d.ts +0 -2870
  72. package/dist/src/api/telegram-types/mod.d.ts +0 -14
  73. package/dist/src/api/telegram-types/passport.d.ts +0 -163
  74. package/dist/src/api/telegram-types/payment.d.ts +0 -570
  75. package/dist/src/api/telegram-types/rich.d.ts +0 -1010
  76. package/dist/src/api/telegram-types/settings.d.ts +0 -120
  77. package/dist/src/api/telegram-types/story.d.ts +0 -89
  78. package/dist/src/api/telegram-types/update.d.ts +0 -84
  79. package/dist/src/api/telegram.d.ts +0 -7
  80. package/dist/src/api/telegram.d.ts.map +0 -1
  81. package/dist/src/api/telegram.js +0 -2
  82. package/dist/src/api/telegram.js.map +0 -1
  83. package/dist/src/api/transport.d.ts +0 -68
  84. package/dist/src/api/transport.d.ts.map +0 -1
  85. package/dist/src/api/transport.js +0 -264
  86. package/dist/src/api/transport.js.map +0 -1
  87. package/dist/src/api/types.d.ts +0 -466
  88. package/dist/src/api/types.d.ts.map +0 -1
  89. package/dist/src/api/types.js +0 -2
  90. package/dist/src/api/types.js.map +0 -1
  91. package/dist/src/branding/terminal.d.ts +0 -77
  92. package/dist/src/branding/terminal.d.ts.map +0 -1
  93. package/dist/src/branding/terminal.js +0 -328
  94. package/dist/src/branding/terminal.js.map +0 -1
  95. package/dist/src/broadcast/broadcast.d.ts +0 -50
  96. package/dist/src/broadcast/broadcast.d.ts.map +0 -1
  97. package/dist/src/broadcast/broadcast.js +0 -56
  98. package/dist/src/broadcast/broadcast.js.map +0 -1
  99. package/dist/src/cache/cache.d.ts +0 -34
  100. package/dist/src/cache/cache.d.ts.map +0 -1
  101. package/dist/src/cache/cache.js +0 -41
  102. package/dist/src/cache/cache.js.map +0 -1
  103. package/dist/src/cli.d.ts +0 -2
  104. package/dist/src/cli.d.ts.map +0 -1
  105. package/dist/src/cli.js +0 -84
  106. package/dist/src/cli.js.map +0 -1
  107. package/dist/src/context/context.d.ts +0 -124
  108. package/dist/src/context/context.d.ts.map +0 -1
  109. package/dist/src/context/context.js +0 -302
  110. package/dist/src/context/context.js.map +0 -1
  111. package/dist/src/core/bot.d.ts +0 -204
  112. package/dist/src/core/bot.d.ts.map +0 -1
  113. package/dist/src/core/bot.js +0 -506
  114. package/dist/src/core/bot.js.map +0 -1
  115. package/dist/src/core/events.d.ts +0 -75
  116. package/dist/src/core/events.d.ts.map +0 -1
  117. package/dist/src/core/events.js +0 -35
  118. package/dist/src/core/events.js.map +0 -1
  119. package/dist/src/core/webhook-reply.d.ts +0 -34
  120. package/dist/src/core/webhook-reply.d.ts.map +0 -1
  121. package/dist/src/core/webhook-reply.js +0 -37
  122. package/dist/src/core/webhook-reply.js.map +0 -1
  123. package/dist/src/index.d.ts +0 -24
  124. package/dist/src/index.d.ts.map +0 -1
  125. package/dist/src/index.js +0 -24
  126. package/dist/src/index.js.map +0 -1
  127. package/dist/src/keyboard/index.d.ts +0 -46
  128. package/dist/src/keyboard/index.d.ts.map +0 -1
  129. package/dist/src/keyboard/index.js +0 -55
  130. package/dist/src/keyboard/index.js.map +0 -1
  131. package/dist/src/middleware/compose.d.ts +0 -5
  132. package/dist/src/middleware/compose.d.ts.map +0 -1
  133. package/dist/src/middleware/compose.js +0 -17
  134. package/dist/src/middleware/compose.js.map +0 -1
  135. package/dist/src/observability/logger.d.ts +0 -78
  136. package/dist/src/observability/logger.d.ts.map +0 -1
  137. package/dist/src/observability/logger.js +0 -285
  138. package/dist/src/observability/logger.js.map +0 -1
  139. package/dist/src/plugins/plugin.d.ts +0 -38
  140. package/dist/src/plugins/plugin.d.ts.map +0 -1
  141. package/dist/src/plugins/plugin.js +0 -59
  142. package/dist/src/plugins/plugin.js.map +0 -1
  143. package/dist/src/queue/queue.d.ts +0 -77
  144. package/dist/src/queue/queue.d.ts.map +0 -1
  145. package/dist/src/queue/queue.js +0 -213
  146. package/dist/src/queue/queue.js.map +0 -1
  147. package/dist/src/router/router.d.ts +0 -61
  148. package/dist/src/router/router.d.ts.map +0 -1
  149. package/dist/src/router/router.js +0 -183
  150. package/dist/src/router/router.js.map +0 -1
  151. package/dist/src/state/conversation.d.ts +0 -56
  152. package/dist/src/state/conversation.d.ts.map +0 -1
  153. package/dist/src/state/conversation.js +0 -133
  154. package/dist/src/state/conversation.js.map +0 -1
  155. package/dist/src/state/forms.d.ts +0 -34
  156. package/dist/src/state/forms.d.ts.map +0 -1
  157. package/dist/src/state/forms.js +0 -44
  158. package/dist/src/state/forms.js.map +0 -1
  159. package/dist/src/state/menu.d.ts +0 -78
  160. package/dist/src/state/menu.d.ts.map +0 -1
  161. package/dist/src/state/menu.js +0 -127
  162. package/dist/src/state/menu.js.map +0 -1
  163. package/dist/src/storage/storage.d.ts +0 -146
  164. package/dist/src/storage/storage.d.ts.map +0 -1
  165. package/dist/src/storage/storage.js +0 -195
  166. package/dist/src/storage/storage.js.map +0 -1
  167. package/dist/src/telegram-features.d.ts +0 -33
  168. package/dist/src/telegram-features.d.ts.map +0 -1
  169. package/dist/src/telegram-features.js +0 -71
  170. package/dist/src/telegram-features.js.map +0 -1
  171. package/dist/src/testing.d.ts +0 -24
  172. package/dist/src/testing.d.ts.map +0 -1
  173. package/dist/src/testing.js +0 -38
  174. package/dist/src/testing.js.map +0 -1
  175. package/dist/src/utils/concurrency.d.ts +0 -25
  176. package/dist/src/utils/concurrency.d.ts.map +0 -1
  177. package/dist/src/utils/concurrency.js +0 -52
  178. package/dist/src/utils/concurrency.js.map +0 -1
  179. package/dist/src/utils/files.d.ts +0 -45
  180. package/dist/src/utils/files.d.ts.map +0 -1
  181. package/dist/src/utils/files.js +0 -53
  182. package/dist/src/utils/files.js.map +0 -1
  183. package/dist/src/utils/text.d.ts +0 -39
  184. package/dist/src/utils/text.d.ts.map +0 -1
  185. package/dist/src/utils/text.js +0 -56
  186. package/dist/src/utils/text.js.map +0 -1
  187. package/dist/src/webhook/handler.d.ts +0 -19
  188. package/dist/src/webhook/handler.d.ts.map +0 -1
  189. package/dist/src/webhook/handler.js +0 -141
  190. package/dist/src/webhook/handler.js.map +0 -1
  191. package/dist-cjs/generated/api.js +0 -194
  192. package/dist-cjs/package.json +0 -3
  193. package/dist-cjs/src/api/client.js +0 -107
  194. package/dist-cjs/src/api/errors.js +0 -74
  195. package/dist-cjs/src/api/index.js +0 -21
  196. package/dist-cjs/src/api/telegram-types/LICENSE +0 -21
  197. package/dist-cjs/src/api/telegram-types/api.d.ts +0 -22
  198. package/dist-cjs/src/api/telegram-types/checklist.d.ts +0 -72
  199. package/dist-cjs/src/api/telegram-types/inline.d.ts +0 -692
  200. package/dist-cjs/src/api/telegram-types/langs.d.ts +0 -193
  201. package/dist-cjs/src/api/telegram-types/manage.d.ts +0 -1144
  202. package/dist-cjs/src/api/telegram-types/markup.d.ts +0 -268
  203. package/dist-cjs/src/api/telegram-types/message.d.ts +0 -1537
  204. package/dist-cjs/src/api/telegram-types/methods.d.ts +0 -2870
  205. package/dist-cjs/src/api/telegram-types/mod.d.ts +0 -14
  206. package/dist-cjs/src/api/telegram-types/passport.d.ts +0 -163
  207. package/dist-cjs/src/api/telegram-types/payment.d.ts +0 -570
  208. package/dist-cjs/src/api/telegram-types/rich.d.ts +0 -1010
  209. package/dist-cjs/src/api/telegram-types/settings.d.ts +0 -120
  210. package/dist-cjs/src/api/telegram-types/story.d.ts +0 -89
  211. package/dist-cjs/src/api/telegram-types/update.d.ts +0 -84
  212. package/dist-cjs/src/api/telegram.js +0 -2
  213. package/dist-cjs/src/api/transport.js +0 -267
  214. package/dist-cjs/src/api/types.js +0 -2
  215. package/dist-cjs/src/branding/terminal.js +0 -338
  216. package/dist-cjs/src/broadcast/broadcast.js +0 -58
  217. package/dist-cjs/src/cache/cache.js +0 -45
  218. package/dist-cjs/src/cli.js +0 -86
  219. package/dist-cjs/src/context/context.js +0 -305
  220. package/dist-cjs/src/core/bot.js +0 -510
  221. package/dist-cjs/src/core/events.js +0 -38
  222. package/dist-cjs/src/core/webhook-reply.js +0 -42
  223. package/dist-cjs/src/index.js +0 -47
  224. package/dist-cjs/src/keyboard/index.js +0 -61
  225. package/dist-cjs/src/middleware/compose.js +0 -20
  226. package/dist-cjs/src/observability/logger.js +0 -293
  227. package/dist-cjs/src/plugins/plugin.js +0 -63
  228. package/dist-cjs/src/queue/queue.js +0 -219
  229. package/dist-cjs/src/router/router.js +0 -186
  230. package/dist-cjs/src/state/conversation.js +0 -139
  231. package/dist-cjs/src/state/forms.js +0 -47
  232. package/dist-cjs/src/state/menu.js +0 -133
  233. package/dist-cjs/src/storage/storage.js +0 -202
  234. package/dist-cjs/src/telegram-features.js +0 -76
  235. package/dist-cjs/src/testing.js +0 -45
  236. package/dist-cjs/src/utils/concurrency.js +0 -57
  237. package/dist-cjs/src/utils/files.js +0 -58
  238. package/dist-cjs/src/utils/text.js +0 -63
  239. package/dist-cjs/src/webhook/handler.js +0 -144
  240. package/docs/API.id.md +0 -1935
  241. package/docs/API.md +0 -1969
  242. package/docs/API.zh-CN.md +0 -1929
  243. package/docs/GETTING_STARTED.id.md +0 -85
  244. package/docs/GETTING_STARTED.md +0 -85
  245. package/docs/GETTING_STARTED.zh-CN.md +0 -85
  246. package/docs/GITHUB_PACKAGES.id.md +0 -82
  247. package/docs/GITHUB_PACKAGES.md +0 -82
  248. package/docs/GITHUB_PACKAGES.zh-CN.md +0 -82
  249. package/docs/README.md +0 -48
  250. package/docs/STORAGE.id.md +0 -105
  251. package/docs/STORAGE.md +0 -105
  252. package/docs/STORAGE.zh-CN.md +0 -105
  253. package/examples/README.md +0 -37
  254. package/examples/files.ts +0 -35
  255. package/examples/minimal.ts +0 -12
  256. package/examples/tsconfig.json +0 -9
  257. package/examples/webhook.ts +0 -42
  258. package/examples/wizard-registration.ts +0 -42
@@ -1,510 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Bot = exports.UpdateTimeoutError = void 0;
4
- const client_js_1 = require("../api/client.js");
5
- const transport_js_1 = require("../api/transport.js");
6
- const context_js_1 = require("../context/context.js");
7
- const compose_js_1 = require("../middleware/compose.js");
8
- const router_js_1 = require("../router/router.js");
9
- const events_js_1 = require("./events.js");
10
- const storage_js_1 = require("../storage/storage.js");
11
- const plugin_js_1 = require("../plugins/plugin.js");
12
- const logger_js_1 = require("../observability/logger.js");
13
- const terminal_js_1 = require("../branding/terminal.js");
14
- const conversation_js_1 = require("../state/conversation.js");
15
- const broadcast_js_1 = require("../broadcast/broadcast.js");
16
- const concurrency_js_1 = require("../utils/concurrency.js");
17
- const webhook_reply_js_1 = require("./webhook-reply.js");
18
- const node_async_hooks_1 = require("node:async_hooks");
19
- const promises_1 = require("node:fs/promises");
20
- /** Thrown when a single update exceeds `handlerTimeout`; the handler keeps running in the background. */
21
- class UpdateTimeoutError extends Error {
22
- name = "UpdateTimeoutError";
23
- updateId;
24
- constructor(updateId, timeoutMs) {
25
- super(`Update ${updateId} handler timed out after ${timeoutMs}ms`);
26
- this.updateId = updateId;
27
- }
28
- }
29
- exports.UpdateTimeoutError = UpdateTimeoutError;
30
- class Bot {
31
- api;
32
- router;
33
- events = new events_js_1.EventBus();
34
- plugins;
35
- session;
36
- services;
37
- token;
38
- logger;
39
- middlewares = [];
40
- pollingOptions;
41
- statusValue = "created";
42
- pollingAbort;
43
- offset = 0;
44
- me;
45
- /** Caps how many updates run at once (default: unlimited). */
46
- updateLimiter;
47
- /** Per-update timeout in ms; `Infinity` disables. */
48
- handlerTimeoutMs;
49
- /** Context class instantiated per update (default `Context`). */
50
- contextType;
51
- /** Per-chat processing chains: parallel across chats, ordered within a chat. */
52
- chatChains = new Map();
53
- /**
54
- * Identifies the update chain executing in the current async context so
55
- * `stop()` called from inside a handler never deadlocks waiting on itself
56
- * (Telegraf allows `bot.stop()` from within a handler).
57
- */
58
- currentUpdateChain = new node_async_hooks_1.AsyncLocalStorage();
59
- /** Memoized init so a burst of updates triggers exactly one getMe call. */
60
- initOnce;
61
- brandingEnabled;
62
- /** Branding effects run only on an interactive TTY; structured logs stay untouched otherwise. */
63
- brandingActive;
64
- activeBanner;
65
- errorHandler;
66
- constructor(options) {
67
- const config = typeof options === "string" ? { token: options } : options;
68
- if (!config.token || !/^\d+:[\w-]+$/.test(config.token))
69
- throw new Error("A valid Telegram bot token is required.");
70
- this.token = config.token;
71
- this.brandingEnabled = config.branding ?? true;
72
- this.brandingActive = this.brandingEnabled && process.stdout.isTTY === true;
73
- this.logger = config.logger instanceof logger_js_1.Logger ? config.logger : (0, logger_js_1.createLogger)(config.logger);
74
- this.router = new router_js_1.Router(config.router);
75
- this.session = config.session ?? new storage_js_1.MemoryStorage();
76
- this.services = { ...(config.services ?? {}) };
77
- const transport = config.transport ?? new transport_js_1.FetchTransport({ baseUrl: `${config.apiBaseUrl ?? "https://api.telegram.org"}/bot${config.token}`, ...(config.transportOptions ?? {}) });
78
- this.api = new client_js_1.ApiClient({
79
- hooks: {
80
- onRequest: (context) => { this.logger.trace("api.request", { method: context.method, payload: context.payload }); return this.events.emit("api:request", { method: context.method, payload: context.payload }); },
81
- onResponse: (context) => { this.logger.debug("api.response", { method: context.method, durationMs: context.durationMs ?? 0, ok: context.response?.ok }); return this.events.emit("api:response", { method: context.method, durationMs: context.durationMs ?? 0, response: context.response }); },
82
- onError: (context) => { this.logger.error("api.error", { method: context.method, durationMs: context.durationMs ?? 0, error: context.error }); return this.events.emit("api:error", { method: context.method, durationMs: context.durationMs ?? 0, error: context.error }); },
83
- },
84
- transport,
85
- });
86
- this.plugins = new plugin_js_1.PluginManager(this);
87
- this.updateLimiter = new concurrency_js_1.Limiter(config.updates?.concurrency ?? Infinity);
88
- this.handlerTimeoutMs = config.handlerTimeout ?? 90_000;
89
- this.contextType = config.contextType ?? context_js_1.Context;
90
- this.pollingOptions = {
91
- allowedUpdates: config.polling?.allowedUpdates ?? [],
92
- limit: config.polling?.limit ?? 100,
93
- maxRetryDelayMs: config.polling?.maxRetryDelayMs ?? 30_000,
94
- retryDelayMs: config.polling?.retryDelayMs ?? 500,
95
- timeout: config.polling?.timeout ?? 30,
96
- };
97
- this.startupLog("bot.created", { status: this.statusValue });
98
- void this.events.emit("bot:created", { bot: this });
99
- }
100
- /** Startup info logs are demoted to debug while the branding sequence owns the terminal. */
101
- startupLog(event, context) {
102
- if (this.brandingActive)
103
- this.logger.debug(event, context);
104
- else
105
- this.logger.info(event, context);
106
- }
107
- get status() { return this.statusValue; }
108
- get botInfo() { return this.me; }
109
- use(...middleware) { this.middlewares.push(...middleware); return this; }
110
- command(name, handler) { this.router.command(name, handler); return this; }
111
- callback(pattern, handler) { this.router.callback(pattern, handler); return this; }
112
- /** Telegraf-style alias for `callback()`: registers a handler for callback-query button data. */
113
- action(pattern, handler) { this.router.callback(pattern, handler); return this; }
114
- onText(text, handler) { this.router.text(text, handler); return this; }
115
- onRegex(expression, handler) { this.router.regex(expression, handler); return this; }
116
- /** Registers a handler for update types: `bot.on("message:photo", handler)` or `bot.on(["message:text", "callback_query:data"], handler)`. */
117
- on(filter, handler) { this.router.on(filter, handler); return this; }
118
- /** Registers a handler for exact text or a regular expression, mirroring familiar frameworks. */
119
- hears(trigger, handler) {
120
- if (trigger instanceof RegExp)
121
- this.router.regex(trigger, handler);
122
- else
123
- this.router.text(trigger, handler);
124
- return this;
125
- }
126
- /**
127
- * Sets the error boundary for update handlers. When set, handler failures are
128
- * passed here instead of rejecting `handleUpdate()` (webhooks answer 200).
129
- */
130
- catch(handler) { this.errorHandler = handler; return this; }
131
- usePlugin(plugin) { this.plugins.use(plugin); return this; }
132
- /**
133
- * Routes subsequent messages to the active Wizard step for the same chat/user.
134
- * The application starts the wizard once with `wizard.run(ctx, key)`; this
135
- * middleware keeps routing replies until the wizard is completed or cancelled.
136
- */
137
- useWizard(wizard, options = {}) {
138
- const cancelCommand = options.cancelCommand ?? "/cancel";
139
- this.use(async (ctx, next) => {
140
- const message = ctx.message;
141
- const key = (0, conversation_js_1.conversationKeyFromContext)(ctx);
142
- const state = await wizard.manager.getAsync(key);
143
- if (!message?.text || state?.status !== "active") {
144
- await next();
145
- return;
146
- }
147
- if (message.text.trim() === cancelCommand) {
148
- wizard.manager.cancel(key);
149
- await ctx.reply("Conversation cancelled.");
150
- return;
151
- }
152
- await wizard.run(ctx, key);
153
- });
154
- return this;
155
- }
156
- async init() {
157
- if (this.statusValue === "initialized" || this.statusValue === "running")
158
- return this;
159
- this.startupLog("bot.initializing", {});
160
- const standaloneBanner = this.brandingActive && !this.activeBanner;
161
- const animation = this.brandingActive ? undefined : (0, terminal_js_1.startTerminalAnimation)("Connecting to Telegram and initializing bot");
162
- if (standaloneBanner)
163
- (0, terminal_js_1.printTeleBibzBanner)({ subtitle: "Connecting to Telegram..." });
164
- try {
165
- this.me = await this.api.methods.getMe();
166
- this.statusValue = "initialized";
167
- this.startupLog("bot.initialized", { botId: this.me.id, username: this.me.username });
168
- await this.events.emit("bot:initialized", { bot: this });
169
- await this.plugins.setup();
170
- await this.plugins.start();
171
- if (standaloneBanner)
172
- (0, terminal_js_1.printStatusLine)(`✓ Bot initialized as @${this.me.username ?? this.me.id}`);
173
- else
174
- animation?.stop("Bot initialized; ready to start");
175
- return this;
176
- }
177
- catch (error) {
178
- if (standaloneBanner)
179
- (0, terminal_js_1.printStatusLine)(`✗ Bot could not initialize: ${error instanceof Error ? error.message : String(error)}`);
180
- else
181
- animation?.stop("Error: bot could not initialize");
182
- throw error;
183
- }
184
- }
185
- async start(options = {}) { await this.launch({ mode: "polling", ...options }); }
186
- async launch(options = { mode: "polling" }) {
187
- if (options.mode !== "polling")
188
- throw new Error("Use createWebhookHandler() for webhook mode.");
189
- const runBrandingSequence = this.brandingActive && !this.activeBanner && (this.statusValue === "created" || this.statusValue === "stopped");
190
- if (runBrandingSequence) {
191
- await (0, terminal_js_1.runStartupSequence)();
192
- this.activeBanner = (0, terminal_js_1.startTeleBibzBanner)({ subtitle: "Connecting to Telegram..." });
193
- }
194
- try {
195
- await this.init();
196
- }
197
- catch (error) {
198
- if (this.activeBanner) {
199
- this.activeBanner.stop(`Connection failed: ${error instanceof Error ? error.message : String(error)}`, "error");
200
- this.activeBanner = undefined;
201
- }
202
- throw error;
203
- }
204
- if (this.activeBanner) {
205
- this.activeBanner.stop(`Connected as @${this.me?.username ?? this.me?.id}`);
206
- this.activeBanner = undefined;
207
- }
208
- if (this.statusValue === "running")
209
- return;
210
- if (options.dropPendingUpdates) {
211
- // Same mechanism Telegraf uses: drop everything Telegram is holding for
212
- // this bot before the first getUpdates call.
213
- await this.api.call("deleteWebhook", { drop_pending_updates: true });
214
- }
215
- this.statusValue = "starting";
216
- this.startupLog("bot.starting", { mode: options.mode });
217
- await this.events.emit("bot:starting", { bot: this });
218
- this.pollingAbort = new AbortController();
219
- this.statusValue = "running";
220
- await this.events.emit("bot:started", { bot: this });
221
- if (this.brandingActive)
222
- (0, terminal_js_1.printStatusLine)("Listening for updates...");
223
- await this.poll(options.timeout ?? this.pollingOptions.timeout, options.allowedUpdates ?? this.pollingOptions.allowedUpdates, this.pollingAbort.signal);
224
- }
225
- async stop() {
226
- if (this.statusValue === "stopped" || this.statusValue === "created")
227
- return;
228
- this.statusValue = "stopping";
229
- await this.events.emit("bot:stopping", { bot: this });
230
- this.pollingAbort?.abort();
231
- this.pollingAbort = undefined;
232
- // Graceful shutdown: wait for updates still being processed (bounded by
233
- // handlerTimeout) so sessions finish writing before plugins are disposed.
234
- await this.drainInFlightUpdates();
235
- await this.plugins.stop();
236
- await this.plugins.dispose();
237
- this.statusValue = "stopped";
238
- if (this.brandingActive)
239
- (0, terminal_js_1.printStatusLine)("Bot stopped.");
240
- else
241
- this.logger.info("bot.stopped");
242
- await this.events.emit("bot:stopped", { bot: this });
243
- }
244
- /** Waits (bounded by `handlerTimeout`) for updates that are still processing. */
245
- async drainInFlightUpdates() {
246
- // A handler calling stop() must not wait on its own chain (deadlock); it
247
- // keeps running in the background, exactly like Telegraf.
248
- const current = this.currentUpdateChain.getStore();
249
- const inFlight = [...this.chatChains.values()].filter((chain) => chain !== current);
250
- if (inFlight.length === 0)
251
- return;
252
- this.logger.info("bot.draining_updates", { inFlight: inFlight.length });
253
- await this.withTimeout(Promise.allSettled(inFlight), this.handlerTimeoutMs, -1);
254
- }
255
- async restart() { await this.stop(); await this.start(); }
256
- async health() {
257
- try {
258
- const bot = await this.api.methods.getMe();
259
- return { status: this.statusValue, apiReachable: true, bot, checkedAt: new Date().toISOString() };
260
- }
261
- catch (error) {
262
- return { status: this.statusValue, apiReachable: false, checkedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error) };
263
- }
264
- }
265
- async getMe() { const me = await this.api.methods.getMe(); this.me = me; return me; }
266
- async setCommands(commands, scope, languageCode) { return this.api.call("setMyCommands", { commands, scope, language_code: languageCode }); }
267
- async deleteCommands(scope, languageCode) { return this.api.call("deleteMyCommands", { scope, language_code: languageCode }); }
268
- /**
269
- * Downloads a Telegram file by `file_id`: resolves it with `getFile`, then
270
- * fetches the raw bytes via the transport's download endpoint. Pass
271
- * `destination` to also persist the bytes to a local file path. The
272
- * returned `url` is valid for at least one hour; Telegram caps downloads
273
- * at 20 MB.
274
- */
275
- async downloadFile(fileId, options = {}) {
276
- const downloaded = await this.api.downloadFile(fileId, options.signal !== undefined ? { signal: options.signal } : {});
277
- if (options.destination !== undefined) {
278
- await (0, promises_1.writeFile)(options.destination, downloaded.bytes);
279
- return { ...downloaded, savedTo: options.destination };
280
- }
281
- return downloaded;
282
- }
283
- /**
284
- * Handles a single update. Updates for different chats run in parallel;
285
- * updates for the same chat are processed strictly in arrival order so
286
- * sessions, wizards, and conversations never interleave. Rejects for this
287
- * update's failure (as before) without affecting other updates.
288
- *
289
- * `options.webhookReply` installs a Telegraf-style responder: the first
290
- * outgoing API call during this update is answered through the webhook HTTP
291
- * response instead of a separate request, and resolves with `true` because
292
- * Telegram never sends the method result back to a webhook response.
293
- */
294
- async handleUpdate(update, options = {}) {
295
- const key = this.conversationKey(update);
296
- const previous = this.chatChains.get(key);
297
- const execute = options.webhookReply === undefined
298
- ? () => this.processUpdate(update)
299
- : () => (0, webhook_reply_js_1.runWithWebhookReply)(options.webhookReply, () => this.processUpdate(update));
300
- // The chain waits for the real completion so same-chat ordering holds
301
- // even when the caller-facing await below is released by a timeout. The
302
- // chain is installed as the current AsyncLocalStorage value so a handler
303
- // calling bot.stop() is excluded from the drain set.
304
- const run = (previous ?? Promise.resolve()).catch(() => undefined).then(() => this.currentUpdateChain.run(tail, execute));
305
- const tail = run.then(() => undefined, () => undefined);
306
- this.chatChains.set(key, tail);
307
- void tail.then(() => {
308
- if (this.chatChains.get(key) === tail)
309
- this.chatChains.delete(key);
310
- });
311
- try {
312
- await this.withTimeout(run, this.handlerTimeoutMs, update.update_id);
313
- }
314
- catch (error) {
315
- if (!(error instanceof UpdateTimeoutError))
316
- throw error;
317
- // A timed-out update follows the same error flow as a failed handler;
318
- // the handler itself keeps running to completion in the background.
319
- this.logger.error("update.handler_timeout", { updateId: update.update_id, timeoutMs: this.handlerTimeoutMs });
320
- await this.events.emit("update:error", { update, error });
321
- await this.events.emit("bot:error", { bot: this, error });
322
- if (this.errorHandler) {
323
- await this.errorHandler(error, new context_js_1.Context({ update, api: this.api, session: {}, services: this.services, me: this.me }));
324
- return;
325
- }
326
- throw error;
327
- }
328
- }
329
- /** Rejects with `UpdateTimeoutError` after `timeoutMs` unless `promise` settles first; `timeoutMs <= 0` or a non-finite value disables the guard. */
330
- async withTimeout(promise, timeoutMs, updateId) {
331
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
332
- return promise;
333
- let timer;
334
- const timeout = new Promise((_, reject) => {
335
- timer = setTimeout(() => reject(new UpdateTimeoutError(updateId, timeoutMs)), timeoutMs);
336
- });
337
- try {
338
- return await Promise.race([promise, timeout]);
339
- }
340
- finally {
341
- if (timer !== undefined)
342
- clearTimeout(timer);
343
- }
344
- }
345
- /**
346
- * Handles a whole batch of updates at once: every chat in the batch is
347
- * processed immediately (parallel across chats, ordered per chat), so a
348
- * burst of 1000 messages is not stuck behind one slow handler. Individual
349
- * handler failures are logged, emitted as `update:error`, and passed to the
350
- * `catch()` error boundary; they never reject this promise.
351
- */
352
- async handleUpdates(updates) {
353
- await Promise.all(updates.map(async (update) => {
354
- try {
355
- await this.handleUpdate(update);
356
- }
357
- catch {
358
- // Already logged and emitted by processUpdate; the polling loop must
359
- // keep flowing no matter how many handlers failed.
360
- }
361
- }));
362
- }
363
- /**
364
- * Sends to many chats in parallel — built for broadcasts to 1000+ users.
365
- * There is no proactive cooldown: every chat is attempted at once (up to
366
- * `concurrency`). When Telegram answers 429, the send is retried
367
- * automatically after exactly the `retry_after` delay Telegram ordered, so
368
- * bursts deliver completely instead of failing.
369
- */
370
- async broadcast(chatIds, send, options) {
371
- return (0, broadcast_js_1.runBroadcast)(chatIds, send, options);
372
- }
373
- /** Runs init() once even when many updates arrive concurrently; never claims a webhook reply slot. */
374
- ensureInitialized() {
375
- if (this.me)
376
- return Promise.resolve();
377
- if (!this.initOnce) {
378
- this.initOnce = (0, webhook_reply_js_1.runWithoutWebhookReply)(() => this.init()).then(() => { this.initOnce = undefined; }, (error) => {
379
- this.initOnce = undefined;
380
- throw error;
381
- });
382
- }
383
- return this.initOnce;
384
- }
385
- async processUpdate(update) {
386
- await this.updateLimiter.run(() => this.runUpdate(update));
387
- }
388
- async runUpdate(update) {
389
- this.logger.incoming((0, logger_js_1.describeIncomingUpdate)(update));
390
- const message = update.message
391
- ?? update.edited_message
392
- ?? update.channel_post
393
- ?? update.edited_channel_post
394
- ?? update.business_message
395
- ?? update.edited_business_message
396
- ?? update.guest_message
397
- ?? update.callback_query?.message;
398
- const key = this.conversationKey(update);
399
- const session = await this.session.get(key) ?? {};
400
- if (!this.me)
401
- await this.ensureInitialized();
402
- if (!this.me)
403
- return;
404
- const ctx = new this.contextType({ update, api: this.api, session, services: this.services, me: this.me });
405
- await this.events.emit("update", { update });
406
- if (message) {
407
- await this.events.emit("message", { message });
408
- if (message.text?.startsWith("/")) {
409
- const command = message.text.slice(1).split(/[\s@]/, 1)[0] ?? "";
410
- await this.events.emit("command", { name: command, update });
411
- }
412
- }
413
- if (update.callback_query)
414
- await this.events.emit("callback", { data: update.callback_query.data ?? "", update });
415
- const pipeline = (0, compose_js_1.compose)([...this.middlewares, async (context) => this.router.handle(context)]);
416
- try {
417
- await this.plugins.update(ctx);
418
- await pipeline(ctx);
419
- await this.session.set(key, ctx.session);
420
- }
421
- catch (error) {
422
- // A handler failure belongs to this update. It must remain observable and reject
423
- // direct handleUpdate() callers, but it must not poison the polling lifecycle.
424
- this.logger.error("update.handler_error", { update: (0, logger_js_1.summarizeUpdate)(update, this.logger.includeUpdateContent), error });
425
- await this.events.emit("update:error", { update, error });
426
- await this.events.emit("bot:error", { bot: this, error });
427
- if (this.errorHandler) {
428
- // With an error boundary registered, the failure is considered handled:
429
- // webhooks answer 200 and polling continues without rethrowing.
430
- await this.errorHandler(error, ctx);
431
- return;
432
- }
433
- throw error;
434
- }
435
- }
436
- conversationKey(update) {
437
- if (update.callback_query) {
438
- const chat = update.callback_query.message?.chat;
439
- const userId = update.callback_query.from.id;
440
- if (chat?.id !== undefined)
441
- return `${chat.id}:${userId}`;
442
- return `user:${userId}`;
443
- }
444
- if (update.inline_query?.from?.id !== undefined)
445
- return `user:${update.inline_query.from.id}`;
446
- if (update.chosen_inline_result?.from?.id !== undefined)
447
- return `user:${update.chosen_inline_result.from.id}`;
448
- const message = update.message
449
- ?? update.edited_message
450
- ?? update.channel_post
451
- ?? update.edited_channel_post
452
- ?? update.business_message
453
- ?? update.edited_business_message
454
- ?? update.guest_message;
455
- if (message?.chat?.id !== undefined)
456
- return `${message.chat.id}:${message.from?.id ?? "anonymous"}`;
457
- if (update.chat_member?.chat?.id !== undefined)
458
- return `${update.chat_member.chat.id}:${update.chat_member.from.id}`;
459
- if (update.my_chat_member?.chat?.id !== undefined)
460
- return `${update.my_chat_member.chat.id}:${update.my_chat_member.from.id}`;
461
- if (update.chat_join_request?.chat?.id !== undefined)
462
- return `${update.chat_join_request.chat.id}:${update.chat_join_request.from.id}`;
463
- return `update:${update.update_id}`;
464
- }
465
- async waitForRetry(delayMs, signal) {
466
- if (signal.aborted)
467
- return false;
468
- return new Promise((resolve) => {
469
- const timer = setTimeout(() => {
470
- signal.removeEventListener("abort", onAbort);
471
- resolve(true);
472
- }, delayMs);
473
- const onAbort = () => {
474
- clearTimeout(timer);
475
- signal.removeEventListener("abort", onAbort);
476
- resolve(false);
477
- };
478
- signal.addEventListener("abort", onAbort, { once: true });
479
- });
480
- }
481
- async poll(timeout, allowedUpdates, signal) {
482
- let delay = this.pollingOptions.retryDelayMs;
483
- // Telegram holds a long-poll connection open for `timeout` seconds, so the
484
- // request timeout must exceed it to avoid aborting a healthy connection.
485
- const requestTimeoutMs = timeout * 1_000 + 10_000;
486
- while (!signal.aborted) {
487
- try {
488
- const updates = await this.api.request("getUpdates", { offset: this.offset, limit: this.pollingOptions.limit, timeout, allowed_updates: allowedUpdates }, signal, { timeoutMs: requestTimeoutMs });
489
- delay = this.pollingOptions.retryDelayMs;
490
- // Confirm the whole batch first, then process it: updates run in
491
- // parallel across chats (ordered per chat) instead of one by one.
492
- for (const update of updates) {
493
- this.offset = Math.max(this.offset, update.update_id + 1);
494
- }
495
- await this.handleUpdates(updates);
496
- }
497
- catch (error) {
498
- if (signal.aborted)
499
- break;
500
- const attempt = Math.max(1, Math.round(Math.log2(delay / this.pollingOptions.retryDelayMs) + 1));
501
- this.logger.warn("polling.reconnect", { attempt, delayMs: delay, error });
502
- await this.events.emit("polling:reconnect", { error, attempt });
503
- if (!(await this.waitForRetry(delay, signal)))
504
- break;
505
- delay = Math.min(this.pollingOptions.maxRetryDelayMs, delay * 2);
506
- }
507
- }
508
- }
509
- }
510
- exports.Bot = Bot;
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EventBus = void 0;
4
- class EventBus {
5
- listeners = new Map();
6
- on(event, listener) {
7
- const bucket = this.listeners.get(event) ?? new Set();
8
- bucket.add(listener);
9
- this.listeners.set(event, bucket);
10
- return () => this.off(event, listener);
11
- }
12
- once(event, listener) {
13
- const dispose = this.on(event, async (payload) => { dispose(); await listener(payload); });
14
- return dispose;
15
- }
16
- off(event, listener) {
17
- this.listeners.get(event)?.delete(listener);
18
- }
19
- async emit(event, payload) {
20
- const listeners = [...(this.listeners.get(event) ?? [])];
21
- const errors = [];
22
- for (const listener of listeners) {
23
- try {
24
- await listener(payload);
25
- }
26
- catch (error) {
27
- errors.push(error);
28
- }
29
- }
30
- if (errors.length === 1)
31
- throw errors[0];
32
- if (errors.length > 1)
33
- throw new AggregateError(errors, `One or more listeners failed for event ${String(event)}`);
34
- }
35
- removeAllListeners() { this.listeners.clear(); }
36
- listenerCount(event) { return this.listeners.get(event)?.size ?? 0; }
37
- }
38
- exports.EventBus = EventBus;
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runWithWebhookReply = runWithWebhookReply;
4
- exports.runWithoutWebhookReply = runWithoutWebhookReply;
5
- exports.claimWebhookReply = claimWebhookReply;
6
- exports.hasWebhookReply = hasWebhookReply;
7
- const node_async_hooks_1 = require("node:async_hooks");
8
- const storage = new node_async_hooks_1.AsyncLocalStorage();
9
- /** Runs `fn` with a webhook reply sink active for every API call inside it. */
10
- function runWithWebhookReply(sink, fn) {
11
- return storage.run({ sink, claimed: false, suppressed: false }, fn);
12
- }
13
- /**
14
- * Runs `fn` with webhook replies suppressed (library-internal calls such as
15
- * the lazy `getMe` initialization must never claim the response slot).
16
- */
17
- function runWithoutWebhookReply(fn) {
18
- const state = storage.getStore();
19
- if (!state)
20
- return fn();
21
- return storage.run({ ...state, suppressed: true }, fn);
22
- }
23
- /**
24
- * Claims the webhook reply for `method`/`payload` if a sink is active and not
25
- * yet used. Returns the synthesized transport response the caller should
26
- * resolve with, or `undefined` when the call must go through the transport.
27
- */
28
- function claimWebhookReply(method, payload) {
29
- const state = storage.getStore();
30
- if (!state || state.claimed || state.suppressed)
31
- return undefined;
32
- state.claimed = true;
33
- state.sink({ method, ...(payload ?? {}) });
34
- // Telegram never sends the method result back to the webhook response, so
35
- // the caller resolves with a synthetic success (same as Telegraf).
36
- return { status: 200, data: { ok: true, result: true } };
37
- }
38
- /** True while an unclaimed webhook reply is available (diagnostics/testing). */
39
- function hasWebhookReply() {
40
- const state = storage.getStore();
41
- return state !== undefined && !state.claimed;
42
- }
@@ -1,47 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.startTeleBibzBanner = exports.runStartupSequence = exports.printStatusLine = exports.paintRainbow = exports.printTeleBibzBanner = exports.printTerminalBranding = exports.buildTerminalBranding = void 0;
18
- __exportStar(require("./core/bot.js"), exports);
19
- __exportStar(require("./core/webhook-reply.js"), exports);
20
- __exportStar(require("./core/events.js"), exports);
21
- __exportStar(require("./api/index.js"), exports);
22
- __exportStar(require("./context/context.js"), exports);
23
- __exportStar(require("./middleware/compose.js"), exports);
24
- __exportStar(require("./router/router.js"), exports);
25
- __exportStar(require("./keyboard/index.js"), exports);
26
- __exportStar(require("./storage/storage.js"), exports);
27
- __exportStar(require("./cache/cache.js"), exports);
28
- __exportStar(require("./queue/queue.js"), exports);
29
- __exportStar(require("./plugins/plugin.js"), exports);
30
- __exportStar(require("./webhook/handler.js"), exports);
31
- __exportStar(require("./utils/text.js"), exports);
32
- __exportStar(require("./utils/files.js"), exports);
33
- __exportStar(require("./utils/concurrency.js"), exports);
34
- __exportStar(require("./broadcast/broadcast.js"), exports);
35
- __exportStar(require("./state/conversation.js"), exports);
36
- __exportStar(require("./state/forms.js"), exports);
37
- __exportStar(require("./state/menu.js"), exports);
38
- __exportStar(require("./telegram-features.js"), exports);
39
- var terminal_js_1 = require("./branding/terminal.js");
40
- Object.defineProperty(exports, "buildTerminalBranding", { enumerable: true, get: function () { return terminal_js_1.buildTerminalBranding; } });
41
- Object.defineProperty(exports, "printTerminalBranding", { enumerable: true, get: function () { return terminal_js_1.printTerminalBranding; } });
42
- Object.defineProperty(exports, "printTeleBibzBanner", { enumerable: true, get: function () { return terminal_js_1.printTeleBibzBanner; } });
43
- Object.defineProperty(exports, "paintRainbow", { enumerable: true, get: function () { return terminal_js_1.paintRainbow; } });
44
- Object.defineProperty(exports, "printStatusLine", { enumerable: true, get: function () { return terminal_js_1.printStatusLine; } });
45
- Object.defineProperty(exports, "runStartupSequence", { enumerable: true, get: function () { return terminal_js_1.runStartupSequence; } });
46
- Object.defineProperty(exports, "startTeleBibzBanner", { enumerable: true, get: function () { return terminal_js_1.startTeleBibzBanner; } });
47
- __exportStar(require("./observability/logger.js"), exports);