@tgify/tgify 0.1.0 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +358 -356
  3. package/lib/cli.mjs +9 -9
  4. package/package.json +1 -1
  5. package/src/button.ts +182 -182
  6. package/src/composer.ts +1008 -1008
  7. package/src/context.ts +1661 -1661
  8. package/src/core/helpers/args.ts +63 -63
  9. package/src/core/helpers/check.ts +71 -71
  10. package/src/core/helpers/compact.ts +18 -18
  11. package/src/core/helpers/deunionize.ts +26 -26
  12. package/src/core/helpers/formatting.ts +119 -119
  13. package/src/core/helpers/util.ts +96 -96
  14. package/src/core/network/client.ts +396 -396
  15. package/src/core/network/error.ts +29 -29
  16. package/src/core/network/multipart-stream.ts +45 -45
  17. package/src/core/network/polling.ts +94 -94
  18. package/src/core/network/webhook.ts +58 -58
  19. package/src/core/types/typegram.ts +54 -54
  20. package/src/filters.ts +109 -109
  21. package/src/format.ts +110 -110
  22. package/src/future.ts +213 -213
  23. package/src/index.ts +17 -17
  24. package/src/input.ts +59 -59
  25. package/src/markup.ts +142 -142
  26. package/src/middleware.ts +24 -24
  27. package/src/reactions.ts +118 -118
  28. package/src/router.ts +55 -55
  29. package/src/scenes/base.ts +52 -52
  30. package/src/scenes/context.ts +136 -136
  31. package/src/scenes/index.ts +21 -21
  32. package/src/scenes/stage.ts +71 -71
  33. package/src/scenes/wizard/context.ts +58 -58
  34. package/src/scenes/wizard/index.ts +63 -63
  35. package/src/scenes.ts +1 -1
  36. package/src/session.ts +204 -204
  37. package/src/telegraf.ts +354 -354
  38. package/src/telegram-types.ts +219 -219
  39. package/src/telegram.ts +1635 -1635
  40. package/src/types.ts +2 -2
  41. package/src/utils.ts +1 -1
  42. package/typings/telegraf.d.ts.map +1 -1
package/src/telegraf.ts CHANGED
@@ -1,354 +1,354 @@
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
- }
155
-
156
- private get token() {
157
- return this.telegram.token
158
- }
159
-
160
- /** @deprecated use `ctx.telegram.webhookReply` */
161
- set webhookReply(webhookReply: boolean) {
162
- this.telegram.webhookReply = webhookReply
163
- }
164
-
165
- /** @deprecated use `ctx.telegram.webhookReply` */
166
- get webhookReply() {
167
- return this.telegram.webhookReply
168
- }
169
-
170
- /**
171
- * _Override_ error handling
172
- */
173
- catch(handler: (err: unknown, ctx: C) => MaybePromise<void>) {
174
- this.handleError = handler
175
- return this
176
- }
177
-
178
- /**
179
- * You must call `bot.telegram.setWebhook` for this to work.
180
- * You should probably use {@link Telegraf.createWebhook} instead.
181
- */
182
- webhookCallback(path = '/', opts: { secretToken?: string } = {}) {
183
- const { secretToken } = opts
184
- return generateCallback(
185
- this.webhookFilter.bind({ hookPath: path, path, secretToken }),
186
- (update: tg.Update, res: http.ServerResponse) =>
187
- this.handleUpdate(update, res)
188
- )
189
- }
190
-
191
- private getDomainOpts(opts: { domain: string; path?: string }) {
192
- const protocol =
193
- opts.domain.startsWith('https://') || opts.domain.startsWith('http://')
194
-
195
- if (protocol)
196
- debug(
197
- 'Unexpected protocol in domain, telegraf will use https:',
198
- opts.domain
199
- )
200
-
201
- const domain = protocol ? new URL(opts.domain).host : opts.domain
202
- const path = opts.path ?? `/telegraf/${this.secretPathComponent()}`
203
- const url = `https://${domain}${path}`
204
-
205
- return { domain, path, url }
206
- }
207
-
208
- /**
209
- * Specify a url to receive incoming updates via webhook.
210
- * Returns an Express-style middleware you can pass to app.use()
211
- */
212
- async createWebhook(
213
- opts: { domain: string; path?: string } & tt.ExtraSetWebhook
214
- ) {
215
- const { domain, path, ...extra } = opts
216
-
217
- const domainOpts = this.getDomainOpts({ domain, path })
218
-
219
- await this.telegram.setWebhook(domainOpts.url, extra)
220
- debug(`Webhook set to ${domainOpts.url}`)
221
-
222
- return this.webhookCallback(domainOpts.path, {
223
- secretToken: extra.secret_token,
224
- })
225
- }
226
-
227
- private startPolling(allowedUpdates: tt.UpdateType[] = []) {
228
- this.polling = new Polling(this.telegram, allowedUpdates)
229
- return this.polling.loop(async (update) => {
230
- await this.handleUpdate(update)
231
- })
232
- }
233
-
234
- private startWebhook(
235
- path: string,
236
- tlsOptions?: TlsOptions,
237
- port?: number,
238
- host?: string,
239
- cb?: http.RequestListener,
240
- secretToken?: string
241
- ) {
242
- const webhookCb = this.webhookCallback(path, { secretToken })
243
- const callback: http.RequestListener =
244
- typeof cb === 'function'
245
- ? (req, res) => webhookCb(req, res, () => cb(req, res))
246
- : webhookCb
247
- this.webhookServer =
248
- tlsOptions != null
249
- ? https.createServer(tlsOptions, callback)
250
- : http.createServer(callback)
251
- this.webhookServer.listen(port, host, () => {
252
- debug('Webhook listening on port: %s', port)
253
- })
254
- return this
255
- }
256
-
257
- secretPathComponent() {
258
- return crypto
259
- .createHash('sha3-256')
260
- .update(this.token)
261
- .update(process.version) // salt
262
- .digest('hex')
263
- }
264
-
265
- async launch(onLaunch?: () => void): Promise<void>
266
- async launch(
267
- config: Telegraf.LaunchOptions,
268
- onLaunch?: () => void
269
- ): Promise<void>
270
- /**
271
- * @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
272
- */
273
- async launch(
274
- config: Telegraf.LaunchOptions | (() => void) = {},
275
- /** @experimental */
276
- onLaunch?: () => void
277
- ) {
278
- const [cfg, onMe] =
279
- typeof config === 'function' ? [{}, config] : [config, onLaunch]
280
- const drop_pending_updates = cfg.dropPendingUpdates
281
- const allowed_updates = cfg.allowedUpdates
282
- const webhook = cfg.webhook
283
-
284
- debug('Connecting to Telegram')
285
- this.botInfo ??= await this.telegram.getMe()
286
- onMe?.()
287
- debug(`Launching @${this.botInfo.username}`)
288
-
289
- if (webhook === undefined) {
290
- await this.telegram.deleteWebhook({ drop_pending_updates })
291
- debug('Bot started with long polling')
292
- await this.startPolling(allowed_updates)
293
- return
294
- }
295
-
296
- const domainOpts = this.getDomainOpts({
297
- domain: webhook.domain,
298
- path: webhook.path ?? webhook.hookPath,
299
- })
300
-
301
- const { tlsOptions, port, host, cb, secretToken } = webhook
302
-
303
- this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken)
304
-
305
- await this.telegram.setWebhook(domainOpts.url, {
306
- drop_pending_updates: drop_pending_updates,
307
- allowed_updates: allowed_updates,
308
- ip_address: webhook.ipAddress,
309
- max_connections: webhook.maxConnections,
310
- secret_token: webhook.secretToken,
311
- certificate: webhook.certificate,
312
- })
313
-
314
- debug(`Bot started with webhook @ ${domainOpts.url}`)
315
- }
316
-
317
- stop(reason = 'unspecified') {
318
- debug('Stopping bot... Reason:', reason)
319
- // https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
320
- if (this.polling === undefined && this.webhookServer === undefined) {
321
- throw new Error('Bot is not running!')
322
- }
323
- this.webhookServer?.close()
324
- this.polling?.stop()
325
- }
326
-
327
- private botInfoCall?: Promise<tg.UserFromGetMe>
328
- async handleUpdate(update: tg.Update, webhookResponse?: http.ServerResponse) {
329
- this.botInfo ??=
330
- (debug(
331
- 'Update %d is waiting for `botInfo` to be initialized',
332
- update.update_id
333
- ),
334
- await (this.botInfoCall ??= this.telegram.getMe()))
335
- debug('Processing update', update.update_id)
336
- const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
337
- const TelegrafContext = this.options.contextType
338
- const ctx = new TelegrafContext(update, tg, this.botInfo)
339
- Object.assign(ctx, this.context)
340
- try {
341
- await pTimeout(
342
- Promise.resolve(this.middleware()(ctx, anoop)),
343
- this.options.handlerTimeout
344
- )
345
- } catch (err) {
346
- return await this.handleError(err, ctx)
347
- } finally {
348
- if (webhookResponse?.writableEnded === false) {
349
- webhookResponse.end()
350
- }
351
- debug('Finished processing update', update.update_id)
352
- }
353
- }
354
- }
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
+ }
155
+
156
+ private get token() {
157
+ return this.telegram.token
158
+ }
159
+
160
+ /** @deprecated use `ctx.telegram.webhookReply` */
161
+ set webhookReply(webhookReply: boolean) {
162
+ this.telegram.webhookReply = webhookReply
163
+ }
164
+
165
+ /** @deprecated use `ctx.telegram.webhookReply` */
166
+ get webhookReply() {
167
+ return this.telegram.webhookReply
168
+ }
169
+
170
+ /**
171
+ * _Override_ error handling
172
+ */
173
+ catch(handler: (err: unknown, ctx: C) => MaybePromise<void>) {
174
+ this.handleError = handler
175
+ return this
176
+ }
177
+
178
+ /**
179
+ * You must call `bot.telegram.setWebhook` for this to work.
180
+ * You should probably use {@link Telegraf.createWebhook} instead.
181
+ */
182
+ webhookCallback(path = '/', opts: { secretToken?: string } = {}) {
183
+ const { secretToken } = opts
184
+ return generateCallback(
185
+ this.webhookFilter.bind({ hookPath: path, path, secretToken }),
186
+ (update: tg.Update, res: http.ServerResponse) =>
187
+ this.handleUpdate(update, res)
188
+ )
189
+ }
190
+
191
+ private getDomainOpts(opts: { domain: string; path?: string }) {
192
+ const protocol =
193
+ opts.domain.startsWith('https://') || opts.domain.startsWith('http://')
194
+
195
+ if (protocol)
196
+ debug(
197
+ 'Unexpected protocol in domain, telegraf will use https:',
198
+ opts.domain
199
+ )
200
+
201
+ const domain = protocol ? new URL(opts.domain).host : opts.domain
202
+ const path = opts.path ?? `/telegraf/${this.secretPathComponent()}`
203
+ const url = `https://${domain}${path}`
204
+
205
+ return { domain, path, url }
206
+ }
207
+
208
+ /**
209
+ * Specify a url to receive incoming updates via webhook.
210
+ * Returns an Express-style middleware you can pass to app.use()
211
+ */
212
+ async createWebhook(
213
+ opts: { domain: string; path?: string } & tt.ExtraSetWebhook
214
+ ) {
215
+ const { domain, path, ...extra } = opts
216
+
217
+ const domainOpts = this.getDomainOpts({ domain, path })
218
+
219
+ await this.telegram.setWebhook(domainOpts.url, extra)
220
+ debug(`Webhook set to ${domainOpts.url}`)
221
+
222
+ return this.webhookCallback(domainOpts.path, {
223
+ secretToken: extra.secret_token,
224
+ })
225
+ }
226
+
227
+ private startPolling(allowedUpdates: tt.UpdateType[] = []) {
228
+ this.polling = new Polling(this.telegram, allowedUpdates)
229
+ return this.polling.loop(async (update) => {
230
+ await this.handleUpdate(update)
231
+ })
232
+ }
233
+
234
+ private startWebhook(
235
+ path: string,
236
+ tlsOptions?: TlsOptions,
237
+ port?: number,
238
+ host?: string,
239
+ cb?: http.RequestListener,
240
+ secretToken?: string
241
+ ) {
242
+ const webhookCb = this.webhookCallback(path, { secretToken })
243
+ const callback: http.RequestListener =
244
+ typeof cb === 'function'
245
+ ? (req, res) => webhookCb(req, res, () => cb(req, res))
246
+ : webhookCb
247
+ this.webhookServer =
248
+ tlsOptions != null
249
+ ? https.createServer(tlsOptions, callback)
250
+ : http.createServer(callback)
251
+ this.webhookServer.listen(port, host, () => {
252
+ debug('Webhook listening on port: %s', port)
253
+ })
254
+ return this
255
+ }
256
+
257
+ secretPathComponent() {
258
+ return crypto
259
+ .createHash('sha3-256')
260
+ .update(this.token)
261
+ .update(process.version) // salt
262
+ .digest('hex')
263
+ }
264
+
265
+ async launch(onLaunch?: () => void): Promise<void>
266
+ async launch(
267
+ config: Telegraf.LaunchOptions,
268
+ onLaunch?: () => void
269
+ ): Promise<void>
270
+ /**
271
+ * @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
272
+ */
273
+ async launch(
274
+ config: Telegraf.LaunchOptions | (() => void) = {},
275
+ /** @experimental */
276
+ onLaunch?: () => void
277
+ ) {
278
+ const [cfg, onMe] =
279
+ typeof config === 'function' ? [{}, config] : [config, onLaunch]
280
+ const drop_pending_updates = cfg.dropPendingUpdates
281
+ const allowed_updates = cfg.allowedUpdates
282
+ const webhook = cfg.webhook
283
+
284
+ debug('Connecting to Telegram')
285
+ this.botInfo ??= await this.telegram.getMe()
286
+ onMe?.()
287
+ debug(`Launching @${this.botInfo.username}`)
288
+
289
+ if (webhook === undefined) {
290
+ await this.telegram.deleteWebhook({ drop_pending_updates })
291
+ debug('Bot started with long polling')
292
+ await this.startPolling(allowed_updates)
293
+ return
294
+ }
295
+
296
+ const domainOpts = this.getDomainOpts({
297
+ domain: webhook.domain,
298
+ path: webhook.path ?? webhook.hookPath,
299
+ })
300
+
301
+ const { tlsOptions, port, host, cb, secretToken } = webhook
302
+
303
+ this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken)
304
+
305
+ await this.telegram.setWebhook(domainOpts.url, {
306
+ drop_pending_updates: drop_pending_updates,
307
+ allowed_updates: allowed_updates,
308
+ ip_address: webhook.ipAddress,
309
+ max_connections: webhook.maxConnections,
310
+ secret_token: webhook.secretToken,
311
+ certificate: webhook.certificate,
312
+ })
313
+
314
+ debug(`Bot started with webhook @ ${domainOpts.url}`)
315
+ }
316
+
317
+ stop(reason = 'unspecified') {
318
+ debug('Stopping bot... Reason:', reason)
319
+ // https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
320
+ if (this.polling === undefined && this.webhookServer === undefined) {
321
+ throw new Error('Bot is not running!')
322
+ }
323
+ this.webhookServer?.close()
324
+ this.polling?.stop()
325
+ }
326
+
327
+ private botInfoCall?: Promise<tg.UserFromGetMe>
328
+ async handleUpdate(update: tg.Update, webhookResponse?: http.ServerResponse) {
329
+ this.botInfo ??=
330
+ (debug(
331
+ 'Update %d is waiting for `botInfo` to be initialized',
332
+ update.update_id
333
+ ),
334
+ await (this.botInfoCall ??= this.telegram.getMe()))
335
+ debug('Processing update', update.update_id)
336
+ const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
337
+ const TelegrafContext = this.options.contextType
338
+ const ctx = new TelegrafContext(update, tg, this.botInfo)
339
+ Object.assign(ctx, this.context)
340
+ try {
341
+ await pTimeout(
342
+ Promise.resolve(this.middleware()(ctx, anoop)),
343
+ this.options.handlerTimeout
344
+ )
345
+ } catch (err) {
346
+ return await this.handleError(err, ctx)
347
+ } finally {
348
+ if (webhookResponse?.writableEnded === false) {
349
+ webhookResponse.end()
350
+ }
351
+ debug('Finished processing update', update.update_id)
352
+ }
353
+ }
354
+ }