@sugansociety/gallagherrich 4.16.8

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 (180) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1024 -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 +102 -0
  10. package/lib/cli.mjs +105 -0
  11. package/lib/composer.js +583 -0
  12. package/lib/context.js +1280 -0
  13. package/lib/core/helpers/args.js +59 -0
  14. package/lib/core/helpers/check.js +57 -0
  15. package/lib/core/helpers/compact.js +18 -0
  16. package/lib/core/helpers/deunionize.js +14 -0
  17. package/lib/core/helpers/formatting.js +92 -0
  18. package/lib/core/helpers/util.js +51 -0
  19. package/lib/core/network/client.js +321 -0
  20. package/lib/core/network/error.js +22 -0
  21. package/lib/core/network/multipart-stream.js +62 -0
  22. package/lib/core/network/polling.js +88 -0
  23. package/lib/core/network/webhook.js +55 -0
  24. package/lib/core/types/rich-message.js +288 -0
  25. package/lib/core/types/typegram.js +29 -0
  26. package/lib/filters.js +70 -0
  27. package/lib/filters.js.map +1 -0
  28. package/lib/format.js +39 -0
  29. package/lib/format.js.map +1 -0
  30. package/lib/future.js +167 -0
  31. package/lib/future.js.map +1 -0
  32. package/lib/index.js +50 -0
  33. package/lib/input.js +62 -0
  34. package/lib/markup.js +112 -0
  35. package/lib/markup.js.map +1 -0
  36. package/lib/middleware.js +3 -0
  37. package/lib/reactions.js +85 -0
  38. package/lib/router.js +47 -0
  39. package/lib/scenes/base.js +40 -0
  40. package/lib/scenes/context.js +105 -0
  41. package/lib/scenes/index.js +22 -0
  42. package/lib/scenes/stage.js +50 -0
  43. package/lib/scenes/wizard/context.js +32 -0
  44. package/lib/scenes/wizard/index.js +46 -0
  45. package/lib/scenes.js +18 -0
  46. package/lib/scenes.js.map +1 -0
  47. package/lib/session.js +167 -0
  48. package/lib/session.js.map +1 -0
  49. package/lib/telegraf.js +273 -0
  50. package/lib/telegram-types.js +7 -0
  51. package/lib/telegram.js +1270 -0
  52. package/lib/types.js +3 -0
  53. package/lib/types.js.map +1 -0
  54. package/lib/utils.js +6 -0
  55. package/lib/utils.js.map +1 -0
  56. package/markup.d.ts +1 -0
  57. package/markup.js +1 -0
  58. package/package.json +136 -0
  59. package/scenes.d.ts +1 -0
  60. package/scenes.js +1 -0
  61. package/session.d.ts +1 -0
  62. package/session.js +1 -0
  63. package/src/button.ts +182 -0
  64. package/src/composer.ts +1008 -0
  65. package/src/context.ts +1747 -0
  66. package/src/core/helpers/args.ts +63 -0
  67. package/src/core/helpers/check.ts +71 -0
  68. package/src/core/helpers/compact.ts +18 -0
  69. package/src/core/helpers/deunionize.ts +26 -0
  70. package/src/core/helpers/formatting.ts +119 -0
  71. package/src/core/helpers/util.ts +96 -0
  72. package/src/core/network/client.ts +396 -0
  73. package/src/core/network/error.ts +29 -0
  74. package/src/core/network/multipart-stream.ts +45 -0
  75. package/src/core/network/polling.ts +94 -0
  76. package/src/core/network/webhook.ts +58 -0
  77. package/src/core/types/rich-message.ts +375 -0
  78. package/src/core/types/typegram.ts +55 -0
  79. package/src/filters.ts +109 -0
  80. package/src/format.ts +110 -0
  81. package/src/future.ts +231 -0
  82. package/src/index.ts +18 -0
  83. package/src/input.ts +59 -0
  84. package/src/markup.ts +142 -0
  85. package/src/middleware.ts +24 -0
  86. package/src/reactions.ts +118 -0
  87. package/src/router.ts +55 -0
  88. package/src/scenes/base.ts +52 -0
  89. package/src/scenes/context.ts +136 -0
  90. package/src/scenes/index.ts +21 -0
  91. package/src/scenes/stage.ts +71 -0
  92. package/src/scenes/wizard/context.ts +58 -0
  93. package/src/scenes/wizard/index.ts +63 -0
  94. package/src/scenes.ts +1 -0
  95. package/src/session.ts +204 -0
  96. package/src/telegraf.ts +380 -0
  97. package/src/telegram-types.ts +256 -0
  98. package/src/telegram.ts +1676 -0
  99. package/src/types.ts +2 -0
  100. package/src/utils.ts +1 -0
  101. package/types.d.ts +1 -0
  102. package/types.js +1 -0
  103. package/typings/button.d.ts +36 -0
  104. package/typings/button.d.ts.map +1 -0
  105. package/typings/composer.d.ts +227 -0
  106. package/typings/composer.d.ts.map +1 -0
  107. package/typings/context.d.ts +699 -0
  108. package/typings/context.d.ts.map +1 -0
  109. package/typings/core/helpers/args.d.ts +11 -0
  110. package/typings/core/helpers/args.d.ts.map +1 -0
  111. package/typings/core/helpers/check.d.ts +56 -0
  112. package/typings/core/helpers/check.d.ts.map +1 -0
  113. package/typings/core/helpers/compact.d.ts +4 -0
  114. package/typings/core/helpers/compact.d.ts.map +1 -0
  115. package/typings/core/helpers/deunionize.d.ts +18 -0
  116. package/typings/core/helpers/deunionize.d.ts.map +1 -0
  117. package/typings/core/helpers/formatting.d.ts +30 -0
  118. package/typings/core/helpers/formatting.d.ts.map +1 -0
  119. package/typings/core/helpers/util.d.ts +27 -0
  120. package/typings/core/helpers/util.d.ts.map +1 -0
  121. package/typings/core/network/client.d.ts +55 -0
  122. package/typings/core/network/client.d.ts.map +1 -0
  123. package/typings/core/network/error.d.ts +16 -0
  124. package/typings/core/network/error.d.ts.map +1 -0
  125. package/typings/core/network/multipart-stream.d.ts +20 -0
  126. package/typings/core/network/multipart-stream.d.ts.map +1 -0
  127. package/typings/core/network/polling.d.ts +16 -0
  128. package/typings/core/network/polling.d.ts.map +1 -0
  129. package/typings/core/network/webhook.d.ts +7 -0
  130. package/typings/core/network/webhook.d.ts.map +1 -0
  131. package/typings/core/types/rich-message.d.ts +144 -0
  132. package/typings/core/types/rich-message.d.ts.map +1 -0
  133. package/typings/core/types/typegram.d.ts +46 -0
  134. package/typings/core/types/typegram.d.ts.map +1 -0
  135. package/typings/filters.d.ts +18 -0
  136. package/typings/filters.d.ts.map +1 -0
  137. package/typings/format.d.ts +22 -0
  138. package/typings/format.d.ts.map +1 -0
  139. package/typings/future.d.ts +12 -0
  140. package/typings/future.d.ts.map +1 -0
  141. package/typings/index.d.ts +16 -0
  142. package/typings/index.d.ts.map +1 -0
  143. package/typings/input.d.ts +59 -0
  144. package/typings/input.d.ts.map +1 -0
  145. package/typings/markup.d.ts +27 -0
  146. package/typings/markup.d.ts.map +1 -0
  147. package/typings/middleware.d.ts +8 -0
  148. package/typings/middleware.d.ts.map +1 -0
  149. package/typings/reactions.d.ts +32 -0
  150. package/typings/reactions.d.ts.map +1 -0
  151. package/typings/router.d.ts +21 -0
  152. package/typings/router.d.ts.map +1 -0
  153. package/typings/scenes/base.d.ts +22 -0
  154. package/typings/scenes/base.d.ts.map +1 -0
  155. package/typings/scenes/context.d.ts +36 -0
  156. package/typings/scenes/context.d.ts.map +1 -0
  157. package/typings/scenes/index.d.ts +11 -0
  158. package/typings/scenes/index.d.ts.map +1 -0
  159. package/typings/scenes/stage.d.ts +24 -0
  160. package/typings/scenes/stage.d.ts.map +1 -0
  161. package/typings/scenes/wizard/context.d.ts +29 -0
  162. package/typings/scenes/wizard/context.d.ts.map +1 -0
  163. package/typings/scenes/wizard/index.d.ts +16 -0
  164. package/typings/scenes/wizard/index.d.ts.map +1 -0
  165. package/typings/scenes.d.ts +2 -0
  166. package/typings/scenes.d.ts.map +1 -0
  167. package/typings/session.d.ts +55 -0
  168. package/typings/session.d.ts.map +1 -0
  169. package/typings/telegraf.d.ts +119 -0
  170. package/typings/telegraf.d.ts.map +1 -0
  171. package/typings/telegram-types.d.ts +141 -0
  172. package/typings/telegram-types.d.ts.map +1 -0
  173. package/typings/telegram.d.ts +694 -0
  174. package/typings/telegram.d.ts.map +1 -0
  175. package/typings/types.d.ts +3 -0
  176. package/typings/types.d.ts.map +1 -0
  177. package/typings/utils.d.ts +2 -0
  178. package/typings/utils.d.ts.map +1 -0
  179. package/utils.d.ts +1 -0
  180. package/utils.js +1 -0
@@ -0,0 +1,380 @@
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
+ ${reset}
175
+ ${bold}${white} @sugansociety/gallagherrich${reset} ${dim}v4.16.8${reset}
176
+ ${reset}
177
+ ${dim} thanks for using my package${reset}
178
+ ${dim} ~SuganSocietyTech ${cyan}t.me/suganzi${reset}
179
+ `)
180
+ }
181
+
182
+ private get token() {
183
+ return this.telegram.token
184
+ }
185
+
186
+ /** @deprecated use `ctx.telegram.webhookReply` */
187
+ set webhookReply(webhookReply: boolean) {
188
+ this.telegram.webhookReply = webhookReply
189
+ }
190
+
191
+ /** @deprecated use `ctx.telegram.webhookReply` */
192
+ get webhookReply() {
193
+ return this.telegram.webhookReply
194
+ }
195
+
196
+ /**
197
+ * _Override_ error handling
198
+ */
199
+ catch(handler: (err: unknown, ctx: C) => MaybePromise<void>) {
200
+ this.handleError = handler
201
+ return this
202
+ }
203
+
204
+ /**
205
+ * You must call `bot.telegram.setWebhook` for this to work.
206
+ * You should probably use {@link Telegraf.createWebhook} instead.
207
+ */
208
+ webhookCallback(path = '/', opts: { secretToken?: string } = {}) {
209
+ const { secretToken } = opts
210
+ return generateCallback(
211
+ this.webhookFilter.bind({ hookPath: path, path, secretToken }),
212
+ (update: tg.Update, res: http.ServerResponse) =>
213
+ this.handleUpdate(update, res)
214
+ )
215
+ }
216
+
217
+ private getDomainOpts(opts: { domain: string; path?: string }) {
218
+ const protocol =
219
+ opts.domain.startsWith('https://') || opts.domain.startsWith('http://')
220
+
221
+ if (protocol)
222
+ debug(
223
+ 'Unexpected protocol in domain, telegraf will use https:',
224
+ opts.domain
225
+ )
226
+
227
+ const domain = protocol ? new URL(opts.domain).host : opts.domain
228
+ const path = opts.path ?? `/telegraf/${this.secretPathComponent()}`
229
+ const url = `https://${domain}${path}`
230
+
231
+ return { domain, path, url }
232
+ }
233
+
234
+ /**
235
+ * Specify a url to receive incoming updates via webhook.
236
+ * Returns an Express-style middleware you can pass to app.use()
237
+ */
238
+ async createWebhook(
239
+ opts: { domain: string; path?: string } & tt.ExtraSetWebhook
240
+ ) {
241
+ const { domain, path, ...extra } = opts
242
+
243
+ const domainOpts = this.getDomainOpts({ domain, path })
244
+
245
+ await this.telegram.setWebhook(domainOpts.url, extra)
246
+ debug(`Webhook set to ${domainOpts.url}`)
247
+
248
+ return this.webhookCallback(domainOpts.path, {
249
+ secretToken: extra.secret_token,
250
+ })
251
+ }
252
+
253
+ private startPolling(allowedUpdates: tt.UpdateType[] = []) {
254
+ this.polling = new Polling(this.telegram, allowedUpdates)
255
+ return this.polling.loop(async (update) => {
256
+ await this.handleUpdate(update)
257
+ })
258
+ }
259
+
260
+ private startWebhook(
261
+ path: string,
262
+ tlsOptions?: TlsOptions,
263
+ port?: number,
264
+ host?: string,
265
+ cb?: http.RequestListener,
266
+ secretToken?: string
267
+ ) {
268
+ const webhookCb = this.webhookCallback(path, { secretToken })
269
+ const callback: http.RequestListener =
270
+ typeof cb === 'function'
271
+ ? (req, res) => webhookCb(req, res, () => cb(req, res))
272
+ : webhookCb
273
+ this.webhookServer =
274
+ tlsOptions != null
275
+ ? https.createServer(tlsOptions, callback)
276
+ : http.createServer(callback)
277
+ this.webhookServer.listen(port, host, () => {
278
+ debug('Webhook listening on port: %s', port)
279
+ })
280
+ return this
281
+ }
282
+
283
+ secretPathComponent() {
284
+ return crypto
285
+ .createHash('sha3-256')
286
+ .update(this.token)
287
+ .update(process.version) // salt
288
+ .digest('hex')
289
+ }
290
+
291
+ async launch(onLaunch?: () => void): Promise<void>
292
+ async launch(
293
+ config: Telegraf.LaunchOptions,
294
+ onLaunch?: () => void
295
+ ): Promise<void>
296
+ /**
297
+ * @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
298
+ */
299
+ async launch(
300
+ config: Telegraf.LaunchOptions | (() => void) = {},
301
+ /** @experimental */
302
+ onLaunch?: () => void
303
+ ) {
304
+ const [cfg, onMe] =
305
+ typeof config === 'function' ? [{}, config] : [config, onLaunch]
306
+ const drop_pending_updates = cfg.dropPendingUpdates
307
+ const allowed_updates = cfg.allowedUpdates
308
+ const webhook = cfg.webhook
309
+
310
+ debug('Connecting to Telegram')
311
+ this.botInfo ??= await this.telegram.getMe()
312
+ onMe?.()
313
+ debug(`Launching @${this.botInfo.username}`)
314
+
315
+ if (webhook === undefined) {
316
+ await this.telegram.deleteWebhook({ drop_pending_updates })
317
+ debug('Bot started with long polling')
318
+ await this.startPolling(allowed_updates)
319
+ return
320
+ }
321
+
322
+ const domainOpts = this.getDomainOpts({
323
+ domain: webhook.domain,
324
+ path: webhook.path ?? webhook.hookPath,
325
+ })
326
+
327
+ const { tlsOptions, port, host, cb, secretToken } = webhook
328
+
329
+ this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken)
330
+
331
+ await this.telegram.setWebhook(domainOpts.url, {
332
+ drop_pending_updates: drop_pending_updates,
333
+ allowed_updates: allowed_updates,
334
+ ip_address: webhook.ipAddress,
335
+ max_connections: webhook.maxConnections,
336
+ secret_token: webhook.secretToken,
337
+ certificate: webhook.certificate,
338
+ })
339
+
340
+ debug(`Bot started with webhook @ ${domainOpts.url}`)
341
+ }
342
+
343
+ stop(reason = 'unspecified') {
344
+ debug('Stopping bot... Reason:', reason)
345
+ // https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
346
+ if (this.polling === undefined && this.webhookServer === undefined) {
347
+ throw new Error('Bot is not running!')
348
+ }
349
+ this.webhookServer?.close()
350
+ this.polling?.stop()
351
+ }
352
+
353
+ private botInfoCall?: Promise<tg.UserFromGetMe>
354
+ async handleUpdate(update: tg.Update, webhookResponse?: http.ServerResponse) {
355
+ this.botInfo ??=
356
+ (debug(
357
+ 'Update %d is waiting for `botInfo` to be initialized',
358
+ update.update_id
359
+ ),
360
+ await (this.botInfoCall ??= this.telegram.getMe()))
361
+ debug('Processing update', update.update_id)
362
+ const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
363
+ const TelegrafContext = this.options.contextType
364
+ const ctx = new TelegrafContext(update, tg, this.botInfo)
365
+ Object.assign(ctx, this.context)
366
+ try {
367
+ await pTimeout(
368
+ Promise.resolve(this.middleware()(ctx, anoop)),
369
+ this.options.handlerTimeout
370
+ )
371
+ } catch (err) {
372
+ return await this.handleError(err, ctx)
373
+ } finally {
374
+ if (webhookResponse?.writableEnded === false) {
375
+ webhookResponse.end()
376
+ }
377
+ debug('Finished processing update', update.update_id)
378
+ }
379
+ }
380
+ }
@@ -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
+ }