teledzik 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1126 -0
  3. package/filters.d.ts +1 -0
  4. package/filters.js +1 -0
  5. package/format.d.ts +1 -0
  6. package/format.js +1 -0
  7. package/future.d.ts +1 -0
  8. package/future.js +1 -0
  9. package/lib/button.js +101 -0
  10. package/lib/cli.mjs +105 -0
  11. package/lib/composer.js +581 -0
  12. package/lib/context.js +1300 -0
  13. package/lib/core/helpers/ai-stream.js +69 -0
  14. package/lib/core/helpers/args.js +58 -0
  15. package/lib/core/helpers/check.js +56 -0
  16. package/lib/core/helpers/compact.js +17 -0
  17. package/lib/core/helpers/deunionize.js +13 -0
  18. package/lib/core/helpers/formatting.js +89 -0
  19. package/lib/core/helpers/input-box.js +87 -0
  20. package/lib/core/helpers/rich-sanitizer.js +31 -0
  21. package/lib/core/helpers/smart-queue.js +70 -0
  22. package/lib/core/helpers/util.js +50 -0
  23. package/lib/core/network/client.js +318 -0
  24. package/lib/core/network/error.js +21 -0
  25. package/lib/core/network/multipart-stream.js +61 -0
  26. package/lib/core/network/polling.js +86 -0
  27. package/lib/core/network/webhook.js +54 -0
  28. package/lib/core/types/rich-message.js +287 -0
  29. package/lib/core/types/typegram.js +18 -0
  30. package/lib/filters.js +69 -0
  31. package/lib/format.js +38 -0
  32. package/lib/future.js +166 -0
  33. package/lib/index.js +61 -0
  34. package/lib/input.js +61 -0
  35. package/lib/markup.js +111 -0
  36. package/lib/middleware.js +2 -0
  37. package/lib/paginated.js +76 -0
  38. package/lib/reactions.js +81 -0
  39. package/lib/router.js +45 -0
  40. package/lib/scenes/base.js +39 -0
  41. package/lib/scenes/context.js +99 -0
  42. package/lib/scenes/form-scene.js +23 -0
  43. package/lib/scenes/index.js +21 -0
  44. package/lib/scenes/stage.js +49 -0
  45. package/lib/scenes/wizard/context.js +30 -0
  46. package/lib/scenes/wizard/index.js +45 -0
  47. package/lib/scenes.js +17 -0
  48. package/lib/session.js +163 -0
  49. package/lib/telegraf.js +274 -0
  50. package/lib/telegram-types.js +6 -0
  51. package/lib/telegram.js +1286 -0
  52. package/lib/types.js +2 -0
  53. package/lib/utils.js +5 -0
  54. package/markup.d.ts +1 -0
  55. package/markup.js +1 -0
  56. package/package.json +141 -0
  57. package/scenes.d.ts +1 -0
  58. package/scenes.js +1 -0
  59. package/session.d.ts +1 -0
  60. package/session.js +1 -0
  61. package/src/button.ts +182 -0
  62. package/src/composer.ts +1008 -0
  63. package/src/context.ts +1778 -0
  64. package/src/core/helpers/ai-stream.ts +96 -0
  65. package/src/core/helpers/args.ts +63 -0
  66. package/src/core/helpers/check.ts +71 -0
  67. package/src/core/helpers/compact.ts +18 -0
  68. package/src/core/helpers/deunionize.ts +26 -0
  69. package/src/core/helpers/formatting.ts +119 -0
  70. package/src/core/helpers/input-box.ts +86 -0
  71. package/src/core/helpers/rich-sanitizer.ts +36 -0
  72. package/src/core/helpers/smart-queue.ts +89 -0
  73. package/src/core/helpers/util.ts +96 -0
  74. package/src/core/network/client.ts +396 -0
  75. package/src/core/network/error.ts +29 -0
  76. package/src/core/network/multipart-stream.ts +45 -0
  77. package/src/core/network/polling.ts +94 -0
  78. package/src/core/network/webhook.ts +58 -0
  79. package/src/core/types/rich-message.ts +375 -0
  80. package/src/core/types/typegram.ts +44 -0
  81. package/src/filters.js +69 -0
  82. package/src/filters.ts +109 -0
  83. package/src/format.js +38 -0
  84. package/src/format.ts +110 -0
  85. package/src/future.js +147 -0
  86. package/src/future.ts +231 -0
  87. package/src/index.ts +27 -0
  88. package/src/input.ts +59 -0
  89. package/src/markup.js +93 -0
  90. package/src/markup.ts +142 -0
  91. package/src/middleware.ts +24 -0
  92. package/src/paginated.ts +75 -0
  93. package/src/reactions.ts +118 -0
  94. package/src/router.ts +55 -0
  95. package/src/scenes/base.ts +52 -0
  96. package/src/scenes/context.ts +136 -0
  97. package/src/scenes/form-scene.ts +34 -0
  98. package/src/scenes/index.ts +21 -0
  99. package/src/scenes/stage.ts +71 -0
  100. package/src/scenes/wizard/context.ts +58 -0
  101. package/src/scenes/wizard/index.ts +63 -0
  102. package/src/scenes.js +17 -0
  103. package/src/scenes.ts +1 -0
  104. package/src/session.js +175 -0
  105. package/src/session.ts +204 -0
  106. package/src/telegraf.ts +385 -0
  107. package/src/telegram-types.ts +256 -0
  108. package/src/telegram.ts +1700 -0
  109. package/src/types.js +2 -0
  110. package/src/types.ts +2 -0
  111. package/src/utils.js +5 -0
  112. package/src/utils.ts +1 -0
  113. package/types.d.ts +1 -0
  114. package/types.js +1 -0
  115. package/typings/button.d.ts +35 -0
  116. package/typings/button.d.ts.map +1 -0
  117. package/typings/composer.d.ts +226 -0
  118. package/typings/composer.d.ts.map +1 -0
  119. package/typings/context.d.ts +711 -0
  120. package/typings/context.d.ts.map +1 -0
  121. package/typings/core/helpers/ai-stream.d.ts +33 -0
  122. package/typings/core/helpers/args.d.ts +10 -0
  123. package/typings/core/helpers/args.d.ts.map +1 -0
  124. package/typings/core/helpers/check.d.ts +55 -0
  125. package/typings/core/helpers/check.d.ts.map +1 -0
  126. package/typings/core/helpers/compact.d.ts +3 -0
  127. package/typings/core/helpers/compact.d.ts.map +1 -0
  128. package/typings/core/helpers/deunionize.d.ts +17 -0
  129. package/typings/core/helpers/deunionize.d.ts.map +1 -0
  130. package/typings/core/helpers/formatting.d.ts +29 -0
  131. package/typings/core/helpers/formatting.d.ts.map +1 -0
  132. package/typings/core/helpers/input-box.d.ts +32 -0
  133. package/typings/core/helpers/rich-sanitizer.d.ts +5 -0
  134. package/typings/core/helpers/smart-queue.d.ts +18 -0
  135. package/typings/core/helpers/util.d.ts +26 -0
  136. package/typings/core/helpers/util.d.ts.map +1 -0
  137. package/typings/core/network/client.d.ts +54 -0
  138. package/typings/core/network/client.d.ts.map +1 -0
  139. package/typings/core/network/error.d.ts +15 -0
  140. package/typings/core/network/error.d.ts.map +1 -0
  141. package/typings/core/network/multipart-stream.d.ts +19 -0
  142. package/typings/core/network/multipart-stream.d.ts.map +1 -0
  143. package/typings/core/network/polling.d.ts +15 -0
  144. package/typings/core/network/polling.d.ts.map +1 -0
  145. package/typings/core/network/webhook.d.ts +6 -0
  146. package/typings/core/network/webhook.d.ts.map +1 -0
  147. package/typings/core/types/rich-message.d.ts +143 -0
  148. package/typings/core/types/rich-message.d.ts.map +1 -0
  149. package/typings/core/types/typegram.d.ts +36 -0
  150. package/typings/core/types/typegram.d.ts.map +1 -0
  151. package/typings/filters.d.ts +17 -0
  152. package/typings/filters.d.ts.map +1 -0
  153. package/typings/format.d.ts +21 -0
  154. package/typings/format.d.ts.map +1 -0
  155. package/typings/future.d.ts +11 -0
  156. package/typings/future.d.ts.map +1 -0
  157. package/typings/index.d.ts +21 -0
  158. package/typings/index.d.ts.map +1 -0
  159. package/typings/input.d.ts +58 -0
  160. package/typings/input.d.ts.map +1 -0
  161. package/typings/markup.d.ts +26 -0
  162. package/typings/markup.d.ts.map +1 -0
  163. package/typings/middleware.d.ts +7 -0
  164. package/typings/middleware.d.ts.map +1 -0
  165. package/typings/paginated.d.ts +20 -0
  166. package/typings/reactions.d.ts +31 -0
  167. package/typings/reactions.d.ts.map +1 -0
  168. package/typings/router.d.ts +20 -0
  169. package/typings/router.d.ts.map +1 -0
  170. package/typings/scenes/base.d.ts +21 -0
  171. package/typings/scenes/base.d.ts.map +1 -0
  172. package/typings/scenes/context.d.ts +35 -0
  173. package/typings/scenes/context.d.ts.map +1 -0
  174. package/typings/scenes/form-scene.d.ts +17 -0
  175. package/typings/scenes/index.d.ts +10 -0
  176. package/typings/scenes/index.d.ts.map +1 -0
  177. package/typings/scenes/stage.d.ts +23 -0
  178. package/typings/scenes/stage.d.ts.map +1 -0
  179. package/typings/scenes/wizard/context.d.ts +28 -0
  180. package/typings/scenes/wizard/context.d.ts.map +1 -0
  181. package/typings/scenes/wizard/index.d.ts +15 -0
  182. package/typings/scenes/wizard/index.d.ts.map +1 -0
  183. package/typings/scenes.d.ts +1 -0
  184. package/typings/scenes.d.ts.map +1 -0
  185. package/typings/session.d.ts +54 -0
  186. package/typings/session.d.ts.map +1 -0
  187. package/typings/telegraf.d.ts +118 -0
  188. package/typings/telegraf.d.ts.map +1 -0
  189. package/typings/telegram-types.d.ts +140 -0
  190. package/typings/telegram-types.d.ts.map +1 -0
  191. package/typings/telegram.d.ts +697 -0
  192. package/typings/telegram.d.ts.map +1 -0
  193. package/typings/types.d.ts +2 -0
  194. package/typings/types.d.ts.map +1 -0
  195. package/typings/utils.d.ts +1 -0
  196. package/typings/utils.d.ts.map +1 -0
  197. package/utils.d.ts +1 -0
  198. package/utils.js +1 -0
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WizardScene = void 0;
7
+ const base_1 = __importDefault(require("../base"));
8
+ const context_1 = __importDefault(require("./context"));
9
+ const composer_1 = __importDefault(require("../../composer"));
10
+ class WizardScene extends base_1.default {
11
+ constructor(id, options, ...steps) {
12
+ let opts;
13
+ let s;
14
+ if (typeof options === 'function' || 'middleware' in options) {
15
+ opts = undefined;
16
+ s = [options, ...steps];
17
+ }
18
+ else {
19
+ opts = options;
20
+ s = steps;
21
+ }
22
+ super(id, opts);
23
+ this.steps = s;
24
+ }
25
+ middleware() {
26
+ return composer_1.default.compose([
27
+ (ctx, next) => {
28
+ ctx.wizard = new context_1.default(ctx, this.steps);
29
+ return next();
30
+ },
31
+ super.middleware(),
32
+ (ctx, next) => {
33
+ if (ctx.wizard.step === undefined) {
34
+ ctx.wizard.selectStep(0);
35
+ return ctx.scene.leave();
36
+ }
37
+ return composer_1.default.unwrap(ctx.wizard.step)(ctx, next);
38
+ },
39
+ ]);
40
+ }
41
+ enterMiddleware() {
42
+ return composer_1.default.compose([this.enterHandler, this.middleware()]);
43
+ }
44
+ }
45
+ exports.WizardScene = WizardScene;
package/lib/scenes.js ADDED
@@ -0,0 +1,17 @@
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
+ __exportStar(require("./scenes/index.js"), exports);
package/lib/session.js ADDED
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isSessionContext = exports.MemorySessionStore = exports.session = void 0;
7
+ const debug_1 = __importDefault(require("debug"));
8
+ const debug = (0, debug_1.default)('telegraf:session');
9
+ /**
10
+ * Returns middleware that adds `ctx.session` for storing arbitrary state per session key.
11
+ *
12
+ * The default `getSessionKey` is `${ctx.from.id}:${ctx.chat.id}`.
13
+ * If either `ctx.from` or `ctx.chat` is `undefined`, default session key and thus `ctx.session` are also `undefined`.
14
+ *
15
+ * > ⚠️ Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
16
+ * >
17
+ * > If you want to persist data across process restarts, or share it among multiple instances, you should use
18
+ * [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.
19
+ *
20
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/b694bcc36b4f71fb1cd650a345c2009ab4d2a2a5/guide/session.md Telegraf Docs | Session}
21
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/master/examples/session-bot.ts Example}
22
+ */
23
+ function session(options) {
24
+ const prop = options?.property ?? 'session';
25
+ const getSessionKey = options?.getSessionKey ?? defaultGetSessionKey;
26
+ const store = options?.store ?? new MemorySessionStore();
27
+ // caches value from store in-memory while simultaneous updates share it
28
+ // when counter reaches 0, the cached ref will be freed from memory
29
+ const cache = new Map();
30
+ // temporarily stores concurrent requests
31
+ const concurrents = new Map();
32
+ // this function must be handled with care
33
+ // read full description on the original PR: https://github.com/telegraf/telegraf/pull/1713
34
+ // make sure to update the tests in test/session.js if you make any changes or fix bugs here
35
+ return async (ctx, next) => {
36
+ const updId = ctx.update.update_id;
37
+ let released = false;
38
+ function releaseChecks() {
39
+ if (released && process.env.EXPERIMENTAL_SESSION_CHECKS)
40
+ throw new Error("Session was accessed or assigned to after the middleware chain exhausted. This is a bug in your code. You're probably accessing session asynchronously and missing awaits.");
41
+ }
42
+ // because this is async, requests may still race here, but it will get autocorrected at (1)
43
+ // v5 getSessionKey should probably be synchronous to avoid that
44
+ const key = await getSessionKey(ctx);
45
+ if (!key) {
46
+ // Leaving this here could be useful to check for `prop in ctx` in future middleware
47
+ ctx[prop] = undefined;
48
+ return await next();
49
+ }
50
+ let cached = cache.get(key);
51
+ if (cached) {
52
+ debug(`(${updId}) found cached session, reusing from cache`);
53
+ ++cached.counter;
54
+ }
55
+ else {
56
+ debug(`(${updId}) did not find cached session`);
57
+ // if another concurrent request has already sent a store request, fetch that instead
58
+ let promise = concurrents.get(key);
59
+ if (promise)
60
+ debug(`(${updId}) found a concurrent request, reusing promise`);
61
+ else {
62
+ debug(`(${updId}) fetching from upstream store`);
63
+ promise = store.get(key);
64
+ }
65
+ // synchronously store promise so concurrent requests can share response
66
+ concurrents.set(key, promise);
67
+ const upstream = await promise;
68
+ // all concurrent awaits will have promise in their closure, safe to remove now
69
+ concurrents.delete(key);
70
+ debug(`(${updId}) updating cache`);
71
+ // another request may have beaten us to the punch
72
+ const c = cache.get(key);
73
+ if (c) {
74
+ // another request did beat us to the punch
75
+ c.counter++;
76
+ // (1) preserve cached reference; in-memory reference is always newer than from store
77
+ cached = c;
78
+ }
79
+ else {
80
+ // we're the first, so we must cache the reference
81
+ cached = { ref: upstream ?? options?.defaultSession?.(ctx), counter: 1 };
82
+ cache.set(key, cached);
83
+ }
84
+ }
85
+ // TS already knows cached is always defined by this point, but does not guard cached.
86
+ // It will, however, guard `c` here.
87
+ const c = cached;
88
+ let touched = false;
89
+ Object.defineProperty(ctx, prop, {
90
+ get() {
91
+ releaseChecks();
92
+ touched = true;
93
+ return c.ref;
94
+ },
95
+ set(value) {
96
+ releaseChecks();
97
+ touched = true;
98
+ c.ref = value;
99
+ },
100
+ });
101
+ try {
102
+ await next();
103
+ released = true;
104
+ }
105
+ finally {
106
+ if (--c.counter === 0) {
107
+ // decrement to avoid memory leak
108
+ debug(`(${updId}) refcounter reached 0, removing cached`);
109
+ cache.delete(key);
110
+ }
111
+ debug(`(${updId}) middlewares completed, checking session`);
112
+ // only update store if ctx.session was touched
113
+ if (touched)
114
+ if (c.ref == null) {
115
+ debug(`(${updId}) ctx.${prop} missing, removing from store`);
116
+ await store.delete(key);
117
+ }
118
+ else {
119
+ debug(`(${updId}) ctx.${prop} found, updating store`);
120
+ await store.set(key, c.ref);
121
+ }
122
+ }
123
+ };
124
+ }
125
+ exports.session = session;
126
+ function defaultGetSessionKey(ctx) {
127
+ const fromId = ctx.from?.id;
128
+ const chatId = ctx.chat?.id;
129
+ if (fromId == null || chatId == null)
130
+ return undefined;
131
+ return `${fromId}:${chatId}`;
132
+ }
133
+ /** @deprecated Use `Map` */
134
+ class MemorySessionStore {
135
+ constructor(ttl = Infinity) {
136
+ this.ttl = ttl;
137
+ this.store = new Map();
138
+ }
139
+ get(name) {
140
+ const entry = this.store.get(name);
141
+ if (entry == null) {
142
+ return undefined;
143
+ }
144
+ else if (entry.expires < Date.now()) {
145
+ this.delete(name);
146
+ return undefined;
147
+ }
148
+ return entry.session;
149
+ }
150
+ set(name, value) {
151
+ const now = Date.now();
152
+ this.store.set(name, { session: value, expires: now + this.ttl });
153
+ }
154
+ delete(name) {
155
+ this.store.delete(name);
156
+ }
157
+ }
158
+ exports.MemorySessionStore = MemorySessionStore;
159
+ /** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
160
+ function isSessionContext(ctx) {
161
+ return 'session' in ctx;
162
+ }
163
+ exports.isSessionContext = isSessionContext;
@@ -0,0 +1,274 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.Telegraf = void 0;
30
+ const crypto = __importStar(require("crypto"));
31
+ const http = __importStar(require("http"));
32
+ const https = __importStar(require("https"));
33
+ const composer_1 = require("./composer");
34
+ const compact_1 = require("./core/helpers/compact");
35
+ const context_1 = __importDefault(require("./context"));
36
+ const debug_1 = __importDefault(require("debug"));
37
+ const webhook_1 = __importDefault(require("./core/network/webhook"));
38
+ const polling_1 = require("./core/network/polling");
39
+ const p_timeout_1 = __importDefault(require("p-timeout"));
40
+ const telegram_1 = __importDefault(require("./telegram"));
41
+ const url_1 = require("url");
42
+ const safeCompare = require("safe-compare");
43
+ const debug = (0, debug_1.default)('telegraf:main');
44
+ const DEFAULT_OPTIONS = {
45
+ telegram: {},
46
+ handlerTimeout: 90_000, // 90s in ms
47
+ contextType: context_1.default,
48
+ };
49
+ function always(x) {
50
+ return () => x;
51
+ }
52
+ const anoop = always(Promise.resolve());
53
+ const TOKEN_HEADER = 'x-telegram-bot-api-secret-token';
54
+ class Telegraf extends composer_1.Composer {
55
+ constructor(token, options) {
56
+ super();
57
+ this.context = {};
58
+ /** Assign to this to customise the webhook filter middleware.
59
+ * `{ path, secretToken }` will be bound to this rather than the Telegraf instance.
60
+ * Remember to assign a regular function and not an arrow function so it's bindable.
61
+ */
62
+ this.webhookFilter = function (req) {
63
+ const debug = (0, debug_1.default)('telegraf:webhook');
64
+ if (req.method === 'POST') {
65
+ if (safeCompare(this.path, req.url)) {
66
+ // no need to check if secret_token was not set
67
+ if (!this.secretToken)
68
+ return true;
69
+ else {
70
+ const token = req.headers[TOKEN_HEADER];
71
+ if (safeCompare(this.secretToken, token))
72
+ return true;
73
+ else
74
+ debug('Secret token does not match:', token, this.secretToken);
75
+ }
76
+ }
77
+ else
78
+ debug('Path does not match:', req.url, this.path);
79
+ }
80
+ else
81
+ debug('Unexpected request method, not POST. Received:', req.method);
82
+ return false;
83
+ };
84
+ this.handleError = (err, ctx) => {
85
+ // set exit code to emulate `warn-with-error-code` behavior of
86
+ // https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode
87
+ // to prevent a clean exit despite an error being thrown
88
+ process.exitCode = 1;
89
+ console.error('Unhandled error while processing', ctx.update);
90
+ throw err;
91
+ };
92
+ // @ts-expect-error Trust me, TS
93
+ this.options = {
94
+ ...DEFAULT_OPTIONS,
95
+ ...(0, compact_1.compactOptions)(options),
96
+ };
97
+ this.telegram = new telegram_1.default(token, this.options.telegram);
98
+ debug('Created a `Telegraf` instance');
99
+ Telegraf.printBanner();
100
+ }
101
+ static printBanner() {
102
+ if (Telegraf._bannerPrinted)
103
+ return;
104
+ Telegraf._bannerPrinted = true;
105
+ const reset = '\x1b[0m';
106
+ const bold = '\x1b[1m';
107
+ const dim = '\x1b[2m';
108
+ const cyan = '\x1b[36m';
109
+ const white = '\x1b[37m';
110
+ console.log(`
111
+ ${cyan}${bold} ╭─╮${reset}
112
+ ${cyan}${bold} │ │${reset}
113
+ ${cyan}${bold} ╰┬╯${reset}
114
+ ${cyan}${bold} │ ╭─╮${reset}
115
+ ${cyan}${bold} ╭┴╮ ╭────┤ │${reset}
116
+ ${cyan}${bold} │ ├───╯ ╰─╯${reset}
117
+ ${cyan}${bold} │ ├───╮${reset}
118
+ ${cyan}${bold} ╰┬╯ │ ╭─╮${reset}
119
+ ${cyan}${bold} │ ╰────┤ │${reset}
120
+ ${cyan}${bold} ╭┴╮ ╰─╯${reset}
121
+ ${cyan}${bold} │ │${reset}
122
+ ${cyan}${bold} ╰─╯${reset}
123
+ ${reset}
124
+ ${bold}${white} @icanseeuanywhere/telekaf${reset} ${dim}v4.16.8${reset}
125
+ ${reset}
126
+ ${dim} thanks for using my package${reset}
127
+ ${dim} ~kafk6 ${cyan}t.me/kafk6${reset}
128
+ `);
129
+ }
130
+ get token() {
131
+ return this.telegram.token;
132
+ }
133
+ /** @deprecated use `ctx.telegram.webhookReply` */
134
+ set webhookReply(webhookReply) {
135
+ this.telegram.webhookReply = webhookReply;
136
+ }
137
+ /** @deprecated use `ctx.telegram.webhookReply` */
138
+ get webhookReply() {
139
+ return this.telegram.webhookReply;
140
+ }
141
+ /**
142
+ * _Override_ error handling
143
+ */
144
+ catch(handler) {
145
+ this.handleError = handler;
146
+ return this;
147
+ }
148
+ /**
149
+ * You must call `bot.telegram.setWebhook` for this to work.
150
+ * You should probably use {@link Telegraf.createWebhook} instead.
151
+ */
152
+ webhookCallback(path = '/', opts = {}) {
153
+ const { secretToken } = opts;
154
+ return (0, webhook_1.default)(this.webhookFilter.bind({ hookPath: path, path, secretToken }), (update, res) => this.handleUpdate(update, res));
155
+ }
156
+ getDomainOpts(opts) {
157
+ const protocol = opts.domain.startsWith('https://') || opts.domain.startsWith('http://');
158
+ if (protocol)
159
+ debug('Unexpected protocol in domain, telegraf will use https:', opts.domain);
160
+ const domain = protocol ? new url_1.URL(opts.domain).host : opts.domain;
161
+ const path = opts.path ?? `/telegraf/${this.secretPathComponent()}`;
162
+ const url = `https://${domain}${path}`;
163
+ return { domain, path, url };
164
+ }
165
+ /**
166
+ * Specify a url to receive incoming updates via webhook.
167
+ * Returns an Express-style middleware you can pass to app.use()
168
+ */
169
+ async createWebhook(opts) {
170
+ const { domain, path, ...extra } = opts;
171
+ const domainOpts = this.getDomainOpts({ domain, path });
172
+ await this.telegram.setWebhook(domainOpts.url, extra);
173
+ debug(`Webhook set to ${domainOpts.url}`);
174
+ return this.webhookCallback(domainOpts.path, {
175
+ secretToken: extra.secret_token,
176
+ });
177
+ }
178
+ startPolling(allowedUpdates = []) {
179
+ this.polling = new polling_1.Polling(this.telegram, allowedUpdates);
180
+ return this.polling.loop(async (update) => {
181
+ await this.handleUpdate(update);
182
+ });
183
+ }
184
+ startWebhook(path, tlsOptions, port, host, cb, secretToken) {
185
+ const webhookCb = this.webhookCallback(path, { secretToken });
186
+ const callback = typeof cb === 'function'
187
+ ? (req, res) => webhookCb(req, res, () => cb(req, res))
188
+ : webhookCb;
189
+ this.webhookServer =
190
+ tlsOptions != null
191
+ ? https.createServer(tlsOptions, callback)
192
+ : http.createServer(callback);
193
+ this.webhookServer.listen(port, host, () => {
194
+ debug('Webhook listening on port: %s', port);
195
+ });
196
+ return this;
197
+ }
198
+ secretPathComponent() {
199
+ return crypto
200
+ .createHash('sha3-256')
201
+ .update(this.token)
202
+ .update(process.version) // salt
203
+ .digest('hex');
204
+ }
205
+ /**
206
+ * @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
207
+ */
208
+ async launch(config = {},
209
+ /** @experimental */
210
+ onLaunch) {
211
+ const [cfg, onMe] = typeof config === 'function' ? [{}, config] : [config, onLaunch];
212
+ const drop_pending_updates = cfg.dropPendingUpdates;
213
+ const allowed_updates = cfg.allowedUpdates;
214
+ const webhook = cfg.webhook;
215
+ debug('Connecting to Telegram');
216
+ this.botInfo ??= await this.telegram.getMe();
217
+ onMe?.();
218
+ debug(`Launching @${this.botInfo.username}`);
219
+ if (webhook === undefined) {
220
+ await this.telegram.deleteWebhook({ drop_pending_updates });
221
+ debug('Bot started with long polling');
222
+ await this.startPolling(allowed_updates);
223
+ return;
224
+ }
225
+ const domainOpts = this.getDomainOpts({
226
+ domain: webhook.domain,
227
+ path: webhook.path ?? webhook.hookPath,
228
+ });
229
+ const { tlsOptions, port, host, cb, secretToken } = webhook;
230
+ this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken);
231
+ await this.telegram.setWebhook(domainOpts.url, {
232
+ drop_pending_updates: drop_pending_updates,
233
+ allowed_updates: allowed_updates,
234
+ ip_address: webhook.ipAddress,
235
+ max_connections: webhook.maxConnections,
236
+ secret_token: webhook.secretToken,
237
+ certificate: webhook.certificate,
238
+ });
239
+ debug(`Bot started with webhook @ ${domainOpts.url}`);
240
+ }
241
+ stop(reason = 'unspecified') {
242
+ debug('Stopping bot... Reason:', reason);
243
+ // https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
244
+ if (this.polling === undefined && this.webhookServer === undefined) {
245
+ throw new Error('Bot is not running!');
246
+ }
247
+ this.webhookServer?.close();
248
+ this.polling?.stop();
249
+ }
250
+ async handleUpdate(update, webhookResponse) {
251
+ this.botInfo ??=
252
+ (debug('Update %d is waiting for `botInfo` to be initialized', update.update_id),
253
+ await (this.botInfoCall ??= this.telegram.getMe()));
254
+ debug('Processing update', update.update_id);
255
+ const tg = new telegram_1.default(this.token, this.telegram.options, webhookResponse);
256
+ const TelegrafContext = this.options.contextType;
257
+ const ctx = new TelegrafContext(update, tg, this.botInfo);
258
+ Object.assign(ctx, this.context);
259
+ try {
260
+ await (0, p_timeout_1.default)(Promise.resolve(this.middleware()(ctx, anoop)), this.options.handlerTimeout);
261
+ }
262
+ catch (err) {
263
+ return await this.handleError(err, ctx);
264
+ }
265
+ finally {
266
+ if (webhookResponse?.writableEnded === false) {
267
+ webhookResponse.end();
268
+ }
269
+ debug('Finished processing update', update.update_id);
270
+ }
271
+ }
272
+ }
273
+ exports.Telegraf = Telegraf;
274
+ Telegraf._bannerPrinted = false;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /** @format */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.Markup = void 0;
5
+ var markup_1 = require("./markup");
6
+ Object.defineProperty(exports, "Markup", { enumerable: true, get: function () { return markup_1.Markup; } });