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,385 @@
1
+ import * as crypto from 'crypto'
2
+ import * as http from 'http'
3
+ import * as https from 'https'
4
+ import * as tg from './core/types/typegram'
5
+ import * as tt from './telegram-types'
6
+ import { Composer } from './composer'
7
+ import { MaybePromise } from './core/helpers/util'
8
+ import ApiClient from './core/network/client'
9
+ import { compactOptions } from './core/helpers/compact'
10
+ import Context from './context'
11
+ import d from 'debug'
12
+ import generateCallback from './core/network/webhook'
13
+ import { Polling } from './core/network/polling'
14
+ import pTimeout from 'p-timeout'
15
+ import Telegram from './telegram'
16
+ import { TlsOptions } from 'tls'
17
+ import { URL } from 'url'
18
+ import safeCompare = require('safe-compare')
19
+ const debug = d('telegraf:main')
20
+
21
+ const DEFAULT_OPTIONS: Telegraf.Options<Context> = {
22
+ telegram: {},
23
+ handlerTimeout: 90_000, // 90s in ms
24
+ contextType: Context,
25
+ }
26
+
27
+ function always<T>(x: T) {
28
+ return () => x
29
+ }
30
+
31
+ const anoop = always(Promise.resolve())
32
+
33
+ export namespace Telegraf {
34
+ export interface Options<TContext extends Context> {
35
+ contextType: new (
36
+ ...args: ConstructorParameters<typeof Context>
37
+ ) => TContext
38
+ handlerTimeout: number
39
+ telegram?: Partial<ApiClient.Options>
40
+ }
41
+
42
+ export interface LaunchOptions {
43
+ dropPendingUpdates?: boolean
44
+ /** List the types of updates you want your bot to receive */
45
+ allowedUpdates?: tt.UpdateType[]
46
+ /** Configuration options for when the bot is run via webhooks */
47
+ webhook?: {
48
+ /** Public domain for webhook. */
49
+ domain: string
50
+
51
+ /**
52
+ * Webhook url path; will be automatically generated if not specified
53
+ * @deprecated Pass `path` instead
54
+ * */
55
+ hookPath?: string
56
+
57
+ /** Webhook url path; will be automatically generated if not specified */
58
+ path?: string
59
+
60
+ host?: string
61
+ port?: number
62
+
63
+ /** The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS */
64
+ ipAddress?: string
65
+
66
+ /**
67
+ * Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40.
68
+ * Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.
69
+ */
70
+ maxConnections?: number
71
+
72
+ /** TLS server options. Omit to use http. */
73
+ tlsOptions?: TlsOptions
74
+
75
+ /**
76
+ * A secret token to be sent in a header `“X-Telegram-Bot-Api-Secret-Token”` in every webhook request.
77
+ * 1-256 characters. Only characters `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed.
78
+ * The header is useful to ensure that the request comes from a webhook set by you.
79
+ */
80
+ secretToken?: string
81
+
82
+ /**
83
+ * Upload your public key certificate so that the root certificate in use can be checked.
84
+ * See [self-signed guide](https://core.telegram.org/bots/self-signed) for details.
85
+ */
86
+ certificate?: tg.InputFile
87
+
88
+ cb?: http.RequestListener
89
+ }
90
+ }
91
+ }
92
+
93
+ const TOKEN_HEADER = 'x-telegram-bot-api-secret-token'
94
+
95
+ export class Telegraf<C extends Context = Context> extends Composer<C> {
96
+ private readonly options: Telegraf.Options<C>
97
+ private webhookServer?: http.Server | https.Server
98
+ private polling?: Polling
99
+ /** Set manually to avoid implicit `getMe` call in `launch` or `webhookCallback` */
100
+ public botInfo?: tg.UserFromGetMe
101
+ public telegram: Telegram
102
+ readonly context: Partial<C> = {}
103
+
104
+ /** Assign to this to customise the webhook filter middleware.
105
+ * `{ path, secretToken }` will be bound to this rather than the Telegraf instance.
106
+ * Remember to assign a regular function and not an arrow function so it's bindable.
107
+ */
108
+ public webhookFilter = function (
109
+ // NOTE: this function is assigned to a variable instead of being a method to signify that it's assignable
110
+ // NOTE: the `this` binding is so custom impls don't need to double wrap
111
+ this: {
112
+ /** @deprecated Use path instead */
113
+ hookPath: string
114
+ path: string
115
+ secretToken?: string
116
+ },
117
+ req: http.IncomingMessage
118
+ ) {
119
+ const debug = d('telegraf:webhook')
120
+
121
+ if (req.method === 'POST') {
122
+ if (safeCompare(this.path, req.url as string)) {
123
+ // no need to check if secret_token was not set
124
+ if (!this.secretToken) return true
125
+ else {
126
+ const token = req.headers[TOKEN_HEADER] as string
127
+ if (safeCompare(this.secretToken, token)) return true
128
+ else debug('Secret token does not match:', token, this.secretToken)
129
+ }
130
+ } else debug('Path does not match:', req.url, this.path)
131
+ } else debug('Unexpected request method, not POST. Received:', req.method)
132
+
133
+ return false
134
+ }
135
+
136
+ private handleError = (err: unknown, ctx: C): MaybePromise<void> => {
137
+ // set exit code to emulate `warn-with-error-code` behavior of
138
+ // https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode
139
+ // to prevent a clean exit despite an error being thrown
140
+ process.exitCode = 1
141
+ console.error('Unhandled error while processing', ctx.update)
142
+ throw err
143
+ }
144
+
145
+ constructor(token: string, options?: Partial<Telegraf.Options<C>>) {
146
+ super()
147
+ // @ts-expect-error Trust me, TS
148
+ this.options = {
149
+ ...DEFAULT_OPTIONS,
150
+ ...compactOptions(options),
151
+ }
152
+ this.telegram = new Telegram(token, this.options.telegram)
153
+ debug('Created a `Telegraf` instance')
154
+ Telegraf.printBanner()
155
+ }
156
+
157
+ private static _bannerPrinted = false
158
+ private static printBanner() {
159
+ if (Telegraf._bannerPrinted) return
160
+ Telegraf._bannerPrinted = true
161
+ const reset = '\x1b[0m'
162
+ const bold = '\x1b[1m'
163
+ const dim = '\x1b[2m'
164
+ const cyan = '\x1b[36m'
165
+ const white = '\x1b[37m'
166
+ console.log(`
167
+ ${cyan}${bold} ╭─╮${reset}
168
+ ${cyan}${bold} │ │${reset}
169
+ ${cyan}${bold} ╰┬╯${reset}
170
+ ${cyan}${bold} │ ╭─╮${reset}
171
+ ${cyan}${bold} ╭┴╮ ╭────┤ │${reset}
172
+ ${cyan}${bold} │ ├───╯ ╰─╯${reset}
173
+ ${cyan}${bold} │ ├───╮${reset}
174
+ ${cyan}${bold} ╰┬╯ │ ╭─╮${reset}
175
+ ${cyan}${bold} │ ╰────┤ │${reset}
176
+ ${cyan}${bold} ╭┴╮ ╰─╯${reset}
177
+ ${cyan}${bold} │ │${reset}
178
+ ${cyan}${bold} ╰─╯${reset}
179
+ ${reset}
180
+ ${bold}${white} @icanseeuanywhere/telekaf${reset} ${dim}v4.16.8${reset}
181
+ ${reset}
182
+ ${dim} thanks for using my package${reset}
183
+ ${dim} ~kafk6 ${cyan}t.me/kafk6${reset}
184
+ `)
185
+ }
186
+
187
+ private get token() {
188
+ return this.telegram.token
189
+ }
190
+
191
+ /** @deprecated use `ctx.telegram.webhookReply` */
192
+ set webhookReply(webhookReply: boolean) {
193
+ this.telegram.webhookReply = webhookReply
194
+ }
195
+
196
+ /** @deprecated use `ctx.telegram.webhookReply` */
197
+ get webhookReply() {
198
+ return this.telegram.webhookReply
199
+ }
200
+
201
+ /**
202
+ * _Override_ error handling
203
+ */
204
+ catch(handler: (err: unknown, ctx: C) => MaybePromise<void>) {
205
+ this.handleError = handler
206
+ return this
207
+ }
208
+
209
+ /**
210
+ * You must call `bot.telegram.setWebhook` for this to work.
211
+ * You should probably use {@link Telegraf.createWebhook} instead.
212
+ */
213
+ webhookCallback(path = '/', opts: { secretToken?: string } = {}) {
214
+ const { secretToken } = opts
215
+ return generateCallback(
216
+ this.webhookFilter.bind({ hookPath: path, path, secretToken }),
217
+ (update: tg.Update, res: http.ServerResponse) =>
218
+ this.handleUpdate(update, res)
219
+ )
220
+ }
221
+
222
+ private getDomainOpts(opts: { domain: string; path?: string }) {
223
+ const protocol =
224
+ opts.domain.startsWith('https://') || opts.domain.startsWith('http://')
225
+
226
+ if (protocol)
227
+ debug(
228
+ 'Unexpected protocol in domain, telegraf will use https:',
229
+ opts.domain
230
+ )
231
+
232
+ const domain = protocol ? new URL(opts.domain).host : opts.domain
233
+ const path = opts.path ?? `/telegraf/${this.secretPathComponent()}`
234
+ const url = `https://${domain}${path}`
235
+
236
+ return { domain, path, url }
237
+ }
238
+
239
+ /**
240
+ * Specify a url to receive incoming updates via webhook.
241
+ * Returns an Express-style middleware you can pass to app.use()
242
+ */
243
+ async createWebhook(
244
+ opts: { domain: string; path?: string } & tt.ExtraSetWebhook
245
+ ) {
246
+ const { domain, path, ...extra } = opts
247
+
248
+ const domainOpts = this.getDomainOpts({ domain, path })
249
+
250
+ await this.telegram.setWebhook(domainOpts.url, extra)
251
+ debug(`Webhook set to ${domainOpts.url}`)
252
+
253
+ return this.webhookCallback(domainOpts.path, {
254
+ secretToken: extra.secret_token,
255
+ })
256
+ }
257
+
258
+ private startPolling(allowedUpdates: tt.UpdateType[] = []) {
259
+ this.polling = new Polling(this.telegram, allowedUpdates)
260
+ return this.polling.loop(async (update) => {
261
+ await this.handleUpdate(update)
262
+ })
263
+ }
264
+
265
+ private startWebhook(
266
+ path: string,
267
+ tlsOptions?: TlsOptions,
268
+ port?: number,
269
+ host?: string,
270
+ cb?: http.RequestListener,
271
+ secretToken?: string
272
+ ) {
273
+ const webhookCb = this.webhookCallback(path, { secretToken })
274
+ const callback: http.RequestListener =
275
+ typeof cb === 'function'
276
+ ? (req, res) => webhookCb(req, res, () => cb(req, res))
277
+ : webhookCb
278
+ this.webhookServer =
279
+ tlsOptions != null
280
+ ? https.createServer(tlsOptions, callback)
281
+ : http.createServer(callback)
282
+ this.webhookServer.listen(port, host, () => {
283
+ debug('Webhook listening on port: %s', port)
284
+ })
285
+ return this
286
+ }
287
+
288
+ secretPathComponent() {
289
+ return crypto
290
+ .createHash('sha3-256')
291
+ .update(this.token)
292
+ .update(process.version) // salt
293
+ .digest('hex')
294
+ }
295
+
296
+ async launch(onLaunch?: () => void): Promise<void>
297
+ async launch(
298
+ config: Telegraf.LaunchOptions,
299
+ onLaunch?: () => void
300
+ ): Promise<void>
301
+ /**
302
+ * @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
303
+ */
304
+ async launch(
305
+ config: Telegraf.LaunchOptions | (() => void) = {},
306
+ /** @experimental */
307
+ onLaunch?: () => void
308
+ ) {
309
+ const [cfg, onMe] =
310
+ typeof config === 'function' ? [{}, config] : [config, onLaunch]
311
+ const drop_pending_updates = cfg.dropPendingUpdates
312
+ const allowed_updates = cfg.allowedUpdates
313
+ const webhook = cfg.webhook
314
+
315
+ debug('Connecting to Telegram')
316
+ this.botInfo ??= await this.telegram.getMe()
317
+ onMe?.()
318
+ debug(`Launching @${this.botInfo.username}`)
319
+
320
+ if (webhook === undefined) {
321
+ await this.telegram.deleteWebhook({ drop_pending_updates })
322
+ debug('Bot started with long polling')
323
+ await this.startPolling(allowed_updates)
324
+ return
325
+ }
326
+
327
+ const domainOpts = this.getDomainOpts({
328
+ domain: webhook.domain,
329
+ path: webhook.path ?? webhook.hookPath,
330
+ })
331
+
332
+ const { tlsOptions, port, host, cb, secretToken } = webhook
333
+
334
+ this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken)
335
+
336
+ await this.telegram.setWebhook(domainOpts.url, {
337
+ drop_pending_updates: drop_pending_updates,
338
+ allowed_updates: allowed_updates,
339
+ ip_address: webhook.ipAddress,
340
+ max_connections: webhook.maxConnections,
341
+ secret_token: webhook.secretToken,
342
+ certificate: webhook.certificate,
343
+ })
344
+
345
+ debug(`Bot started with webhook @ ${domainOpts.url}`)
346
+ }
347
+
348
+ stop(reason = 'unspecified') {
349
+ debug('Stopping bot... Reason:', reason)
350
+ // https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
351
+ if (this.polling === undefined && this.webhookServer === undefined) {
352
+ throw new Error('Bot is not running!')
353
+ }
354
+ this.webhookServer?.close()
355
+ this.polling?.stop()
356
+ }
357
+
358
+ private botInfoCall?: Promise<tg.UserFromGetMe>
359
+ async handleUpdate(update: tg.Update, webhookResponse?: http.ServerResponse) {
360
+ this.botInfo ??=
361
+ (debug(
362
+ 'Update %d is waiting for `botInfo` to be initialized',
363
+ update.update_id
364
+ ),
365
+ await (this.botInfoCall ??= this.telegram.getMe()))
366
+ debug('Processing update', update.update_id)
367
+ const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
368
+ const TelegrafContext = this.options.contextType
369
+ const ctx = new TelegrafContext(update, tg, this.botInfo)
370
+ Object.assign(ctx, this.context)
371
+ try {
372
+ await pTimeout(
373
+ Promise.resolve(this.middleware()(ctx, anoop)),
374
+ this.options.handlerTimeout
375
+ )
376
+ } catch (err) {
377
+ return await this.handleError(err, ctx)
378
+ } finally {
379
+ if (webhookResponse?.writableEnded === false) {
380
+ webhookResponse.end()
381
+ }
382
+ debug('Finished processing update', update.update_id)
383
+ }
384
+ }
385
+ }
@@ -0,0 +1,256 @@
1
+ /** @format */
2
+
3
+ import { Expand } from './core/helpers/util'
4
+ import {
5
+ Message,
6
+ Opts,
7
+ Telegram,
8
+ Update,
9
+ InputMediaAudio,
10
+ InputMediaDocument,
11
+ InputMediaPhoto,
12
+ InputMediaVideo,
13
+ InlineKeyboardMarkup,
14
+ ReplyKeyboardMarkup,
15
+ ReplyKeyboardRemove,
16
+ ForceReply,
17
+ ReplyParameters,
18
+ ParseMode,
19
+ } from './core/types/typegram'
20
+ import type { InputRichMessage } from './core/types/rich-message'
21
+
22
+ import { UnionKeys } from './core/helpers/deunionize'
23
+ import { FmtString } from './format'
24
+
25
+ export { Markup } from './markup'
26
+
27
+ // tiny helper types
28
+ export type ChatAction = Opts<'sendChatAction'>['action']
29
+
30
+ // Modify type so caption, if exists, can be FmtString
31
+ export type WrapCaption<T> = T extends { caption?: string }
32
+ ? Expand<Omit<T, 'caption'> & { caption?: string | FmtString }>
33
+ : T
34
+
35
+ // extra types
36
+ /**
37
+ * Create an `Extra*` type from the arguments of a given method `M extends keyof Telegram` but `Omit`ting fields with key `K` from it.
38
+ *
39
+ * Note that `chat_id` may not be specified in `K` because it is `Omit`ted by default.
40
+ */
41
+ type MakeExtra<
42
+ M extends keyof Telegram,
43
+ K extends keyof Omit<Opts<M>, 'chat_id'> = never,
44
+ > = WrapCaption<Omit<Opts<M>, 'chat_id' | K>>
45
+
46
+ export type ExtraAddStickerToSet = MakeExtra<
47
+ 'addStickerToSet',
48
+ 'name' | 'user_id'
49
+ >
50
+ export type ExtraAnimation = MakeExtra<'sendAnimation', 'animation'>
51
+ export type ExtraAnswerCbQuery = MakeExtra<
52
+ 'answerCallbackQuery',
53
+ 'text' | 'callback_query_id'
54
+ >
55
+ export type ExtraAnswerInlineQuery = MakeExtra<
56
+ 'answerInlineQuery',
57
+ 'inline_query_id' | 'results'
58
+ >
59
+ export type ExtraSetChatPermissions = MakeExtra<
60
+ 'setChatPermissions',
61
+ 'permissions'
62
+ >
63
+ export type ExtraAudio = MakeExtra<'sendAudio', 'audio'>
64
+ export type ExtraContact = MakeExtra<
65
+ 'sendContact',
66
+ 'phone_number' | 'first_name'
67
+ >
68
+ export type ExtraCopyMessage = MakeExtra<
69
+ 'copyMessage',
70
+ 'from_chat_id' | 'message_id'
71
+ >
72
+ export type ExtraCopyMessages = MakeExtra<
73
+ 'copyMessages',
74
+ 'from_chat_id' | 'message_ids'
75
+ >
76
+ export type ExtraCreateChatInviteLink = MakeExtra<'createChatInviteLink'>
77
+ export type NewInvoiceLinkParameters = MakeExtra<'createInvoiceLink'>
78
+ export type ExtraCreateNewStickerSet = MakeExtra<
79
+ 'createNewStickerSet',
80
+ 'name' | 'title' | 'user_id'
81
+ >
82
+ export type ExtraDice = MakeExtra<'sendDice'>
83
+ export type ExtraDocument = MakeExtra<'sendDocument', 'document'>
84
+ export type ExtraEditChatInviteLink = MakeExtra<
85
+ 'editChatInviteLink',
86
+ 'invite_link'
87
+ >
88
+ export type ExtraEditMessageCaption = MakeExtra<
89
+ 'editMessageCaption',
90
+ 'message_id' | 'inline_message_id' | 'caption'
91
+ >
92
+ export type ExtraEditMessageLiveLocation = MakeExtra<
93
+ 'editMessageLiveLocation',
94
+ 'message_id' | 'inline_message_id' | 'latitude' | 'longitude'
95
+ >
96
+ export type ExtraEditMessageMedia = MakeExtra<
97
+ 'editMessageMedia',
98
+ 'message_id' | 'inline_message_id' | 'media'
99
+ >
100
+ export type ExtraEditMessageText = MakeExtra<
101
+ 'editMessageText',
102
+ 'message_id' | 'inline_message_id' | 'text'
103
+ >
104
+ export type ExtraGame = MakeExtra<'sendGame', 'game_short_name'>
105
+ export type NewInvoiceParameters = MakeExtra<
106
+ 'sendInvoice',
107
+ | 'disable_notification'
108
+ | 'reply_parameters'
109
+ | 'reply_markup'
110
+ | 'message_thread_id'
111
+ >
112
+ export type ExtraInvoice = MakeExtra<'sendInvoice', keyof NewInvoiceParameters>
113
+ export type ExtraBanChatMember = MakeExtra<
114
+ 'banChatMember',
115
+ 'user_id' | 'until_date'
116
+ >
117
+ export type ExtraKickChatMember = ExtraBanChatMember
118
+ export type ExtraLocation = MakeExtra<'sendLocation', 'latitude' | 'longitude'>
119
+ export type ExtraMediaGroup = MakeExtra<'sendMediaGroup', 'media'>
120
+ export type ExtraPhoto = MakeExtra<'sendPhoto', 'photo'>
121
+ export type ExtraPoll = MakeExtra<'sendPoll', 'question' | 'options' | 'type'>
122
+ export type ExtraPromoteChatMember = MakeExtra<'promoteChatMember', 'user_id'>
123
+ export type ExtraReplyMessage = MakeExtra<'sendMessage', 'text'>
124
+ export type ExtraForwardMessage = MakeExtra<
125
+ 'forwardMessage',
126
+ 'from_chat_id' | 'message_id'
127
+ >
128
+ export type ExtraForwardMessages = MakeExtra<
129
+ 'forwardMessages',
130
+ 'from_chat_id' | 'message_ids'
131
+ >
132
+ export type ExtraSendChatAction = MakeExtra<'sendChatAction', 'action'>
133
+ export type ExtraRestrictChatMember = MakeExtra<'restrictChatMember', 'user_id'>
134
+ export type ExtraSetMyCommands = MakeExtra<'setMyCommands', 'commands'>
135
+ export type ExtraSetWebhook = MakeExtra<'setWebhook', 'url'>
136
+ export type ExtraSticker = MakeExtra<'sendSticker', 'sticker'>
137
+ export type ExtraStopPoll = MakeExtra<'stopPoll', 'message_id'>
138
+ export type ExtraVenue = MakeExtra<
139
+ 'sendVenue',
140
+ 'latitude' | 'longitude' | 'title' | 'address'
141
+ >
142
+ export type ExtraVideo = MakeExtra<'sendVideo', 'video'>
143
+ export type ExtraVideoNote = MakeExtra<'sendVideoNote', 'video_note'>
144
+ export type ExtraVoice = MakeExtra<'sendVoice', 'voice'>
145
+ export type ExtraBanChatSenderChat = MakeExtra<
146
+ 'banChatSenderChat',
147
+ 'sender_chat_id'
148
+ >
149
+ export type ExtraCreateForumTopic = MakeExtra<'createForumTopic', 'name'>
150
+ export type ExtraEditForumTopic = MakeExtra<
151
+ 'editForumTopic',
152
+ 'message_thread_id'
153
+ >
154
+
155
+ export type MediaGroup =
156
+ | readonly (InputMediaPhoto | InputMediaVideo)[]
157
+ | readonly InputMediaAudio[]
158
+ | readonly InputMediaDocument[]
159
+
160
+ // types used for inference of ctx object
161
+
162
+ /** Possible update types */
163
+ export type UpdateType = Exclude<UnionKeys<Update>, keyof Update>
164
+
165
+ /** Possible message subtypes. Same as the properties on a message object */
166
+ export type MessageSubType =
167
+ | 'forward_date'
168
+ | Exclude<
169
+ UnionKeys<Message>,
170
+ keyof Message.CaptionableMessage | 'entities' | 'media_group_id'
171
+ >
172
+
173
+ type ExtractPartial<T extends object, U extends object> = T extends unknown
174
+ ? Required<T> extends U
175
+ ? T
176
+ : never
177
+ : never
178
+
179
+ /**
180
+ * Maps [[`Composer.on`]]'s `updateType` or `messageSubType` to a `tt.Update` subtype.
181
+ * @deprecated
182
+ */
183
+ export type MountMap = {
184
+ [T in UpdateType]: Extract<Update, Record<T, object>>
185
+ } & {
186
+ [T in MessageSubType]: {
187
+ message: ExtractPartial<Update.MessageUpdate['message'], Record<T, unknown>>
188
+ update_id: number
189
+ }
190
+ }
191
+
192
+ export interface CommandContextExtn {
193
+ match: RegExpExecArray
194
+ /**
195
+ * Matched command. This will always be the actual command, excluding preceeding slash and `@botname`
196
+ *
197
+ * Examples:
198
+ * ```
199
+ * /command abc -> command
200
+ * /command@xyzbot abc -> command
201
+ * ```
202
+ */
203
+ command: string
204
+ /**
205
+ * The unparsed payload part of the command
206
+ *
207
+ * Examples:
208
+ * ```
209
+ * /command abc def -> "abc def"
210
+ * /command "token1 token2" -> "\"token1 token2\""
211
+ * ```
212
+ */
213
+ payload: string
214
+ /**
215
+ * Command args parsed into an array.
216
+ *
217
+ * Examples:
218
+ * ```
219
+ * /command token1 token2 -> [ "token1", "token2" ]
220
+ * /command "token1 token2" -> [ "token1 token2" ]
221
+ * /command token1 "token2 token3" -> [ "token1" "token2 token3" ]
222
+ * ```
223
+ * @unstable Parser implementation might vary until considered stable
224
+ * */
225
+ args: string[]
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Bot API 10.1 — Rich Messages extra types
230
+ // ---------------------------------------------------------------------------
231
+
232
+ export type ExtraSendRichMessage = {
233
+ business_connection_id?: string
234
+ message_thread_id?: number
235
+ direct_messages_topic_id?: number
236
+ disable_notification?: boolean
237
+ protect_content?: boolean
238
+ allow_paid_broadcast?: boolean
239
+ message_effect_id?: string
240
+ reply_parameters?: ReplyParameters
241
+ reply_markup?: InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply
242
+ }
243
+
244
+ /** sendRichMessageDraft only works in private chats; chat_id must be a number. */
245
+ export type ExtraSendRichMessageDraft = {
246
+ message_thread_id?: number
247
+ }
248
+
249
+ export type ExtraEditMessageRichText = {
250
+ chat_id?: number | string
251
+ message_id?: number
252
+ inline_message_id?: string
253
+ rich_message?: InputRichMessage
254
+ parse_mode?: ParseMode
255
+ reply_markup?: InlineKeyboardMarkup
256
+ }