@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
@@ -1,29 +1,29 @@
1
- import { ResponseParameters } from '../types/typegram'
2
-
3
- interface ErrorPayload {
4
- error_code: number
5
- description: string
6
- parameters?: ResponseParameters
7
- }
8
- export class TelegramError extends Error {
9
- constructor(
10
- readonly response: ErrorPayload,
11
- readonly on = {}
12
- ) {
13
- super(`${response.error_code}: ${response.description}`)
14
- }
15
-
16
- get code() {
17
- return this.response.error_code
18
- }
19
-
20
- get description() {
21
- return this.response.description
22
- }
23
-
24
- get parameters() {
25
- return this.response.parameters
26
- }
27
- }
28
-
29
- export default TelegramError
1
+ import { ResponseParameters } from '../types/typegram'
2
+
3
+ interface ErrorPayload {
4
+ error_code: number
5
+ description: string
6
+ parameters?: ResponseParameters
7
+ }
8
+ export class TelegramError extends Error {
9
+ constructor(
10
+ readonly response: ErrorPayload,
11
+ readonly on = {}
12
+ ) {
13
+ super(`${response.error_code}: ${response.description}`)
14
+ }
15
+
16
+ get code() {
17
+ return this.response.error_code
18
+ }
19
+
20
+ get description() {
21
+ return this.response.description
22
+ }
23
+
24
+ get parameters() {
25
+ return this.response.parameters
26
+ }
27
+ }
28
+
29
+ export default TelegramError
@@ -1,45 +1,45 @@
1
- import * as stream from 'stream'
2
- import { hasPropType } from '../helpers/check'
3
- import SandwichStream from 'sandwich-stream'
4
- const CRNL = '\r\n'
5
-
6
- interface Part {
7
- headers: { [key: string]: string }
8
- body: NodeJS.ReadStream | NodeJS.ReadableStream | Buffer | string
9
- }
10
-
11
- class MultipartStream extends SandwichStream {
12
- constructor(boundary: string) {
13
- super({
14
- head: `--${boundary}${CRNL}`,
15
- tail: `${CRNL}--${boundary}--`,
16
- separator: `${CRNL}--${boundary}${CRNL}`,
17
- })
18
- }
19
-
20
- addPart(part: Part) {
21
- const partStream = new stream.PassThrough()
22
- for (const [key, header] of Object.entries(part.headers)) {
23
- partStream.write(`${key}:${header}${CRNL}`)
24
- }
25
- partStream.write(CRNL)
26
- if (MultipartStream.isStream(part.body)) {
27
- part.body.pipe(partStream)
28
- } else {
29
- partStream.end(part.body)
30
- }
31
- this.add(partStream)
32
- }
33
-
34
- static isStream(
35
- stream: unknown
36
- ): stream is { pipe: MultipartStream['pipe'] } {
37
- return (
38
- typeof stream === 'object' &&
39
- stream !== null &&
40
- hasPropType(stream, 'pipe', 'function')
41
- )
42
- }
43
- }
44
-
45
- export default MultipartStream
1
+ import * as stream from 'stream'
2
+ import { hasPropType } from '../helpers/check'
3
+ import SandwichStream from 'sandwich-stream'
4
+ const CRNL = '\r\n'
5
+
6
+ interface Part {
7
+ headers: { [key: string]: string }
8
+ body: NodeJS.ReadStream | NodeJS.ReadableStream | Buffer | string
9
+ }
10
+
11
+ class MultipartStream extends SandwichStream {
12
+ constructor(boundary: string) {
13
+ super({
14
+ head: `--${boundary}${CRNL}`,
15
+ tail: `${CRNL}--${boundary}--`,
16
+ separator: `${CRNL}--${boundary}${CRNL}`,
17
+ })
18
+ }
19
+
20
+ addPart(part: Part) {
21
+ const partStream = new stream.PassThrough()
22
+ for (const [key, header] of Object.entries(part.headers)) {
23
+ partStream.write(`${key}:${header}${CRNL}`)
24
+ }
25
+ partStream.write(CRNL)
26
+ if (MultipartStream.isStream(part.body)) {
27
+ part.body.pipe(partStream)
28
+ } else {
29
+ partStream.end(part.body)
30
+ }
31
+ this.add(partStream)
32
+ }
33
+
34
+ static isStream(
35
+ stream: unknown
36
+ ): stream is { pipe: MultipartStream['pipe'] } {
37
+ return (
38
+ typeof stream === 'object' &&
39
+ stream !== null &&
40
+ hasPropType(stream, 'pipe', 'function')
41
+ )
42
+ }
43
+ }
44
+
45
+ export default MultipartStream
@@ -1,94 +1,94 @@
1
- import * as tg from '../types/typegram'
2
- import * as tt from '../../telegram-types'
3
- import AbortController from 'abort-controller'
4
- import ApiClient from './client'
5
- import d from 'debug'
6
- import { promisify } from 'util'
7
- import { TelegramError } from './error'
8
- const debug = d('telegraf:polling')
9
- const wait = promisify(setTimeout)
10
- function always<T>(x: T) {
11
- return () => x
12
- }
13
- const noop = always(Promise.resolve())
14
-
15
- export class Polling {
16
- private readonly abortController = new AbortController()
17
- private skipOffsetSync = false
18
- private offset = 0
19
- constructor(
20
- private readonly telegram: ApiClient,
21
- private readonly allowedUpdates: readonly tt.UpdateType[]
22
- ) {}
23
-
24
- private async *[Symbol.asyncIterator]() {
25
- debug('Starting long polling')
26
- do {
27
- try {
28
- const updates = await this.telegram.callApi(
29
- 'getUpdates',
30
- {
31
- timeout: 50,
32
- offset: this.offset,
33
- allowed_updates: this.allowedUpdates,
34
- },
35
- this.abortController
36
- )
37
- const last = updates[updates.length - 1]
38
- if (last !== undefined) {
39
- this.offset = last.update_id + 1
40
- }
41
- yield updates
42
- } catch (error) {
43
- const err = error as Error & {
44
- parameters?: { retry_after: number }
45
- }
46
-
47
- if (err.name === 'AbortError') return
48
- if (
49
- err.name === 'FetchError' ||
50
- (err instanceof TelegramError && err.code === 429) ||
51
- (err instanceof TelegramError && err.code >= 500)
52
- ) {
53
- const retryAfter: number = err.parameters?.retry_after ?? 5
54
- debug('Failed to fetch updates, retrying after %ds.', retryAfter, err)
55
- await wait(retryAfter * 1000)
56
- continue
57
- }
58
- if (
59
- err instanceof TelegramError &&
60
- // Unauthorized Conflict
61
- (err.code === 401 || err.code === 409)
62
- ) {
63
- this.skipOffsetSync = true
64
- throw err
65
- }
66
- throw err
67
- }
68
- } while (!this.abortController.signal.aborted)
69
- }
70
-
71
- private async syncUpdateOffset() {
72
- if (this.skipOffsetSync) return
73
- debug('Syncing update offset...')
74
- await this.telegram.callApi('getUpdates', { offset: this.offset, limit: 1 })
75
- }
76
-
77
- async loop(handleUpdate: (updates: tg.Update) => Promise<void>) {
78
- if (this.abortController.signal.aborted)
79
- throw new Error('Polling instances must not be reused!')
80
- try {
81
- for await (const updates of this)
82
- await Promise.all(updates.map(handleUpdate))
83
- } finally {
84
- debug('Long polling stopped')
85
- // prevent instance reuse
86
- this.stop()
87
- await this.syncUpdateOffset().catch(noop)
88
- }
89
- }
90
-
91
- stop() {
92
- this.abortController.abort()
93
- }
94
- }
1
+ import * as tg from '../types/typegram'
2
+ import * as tt from '../../telegram-types'
3
+ import AbortController from 'abort-controller'
4
+ import ApiClient from './client'
5
+ import d from 'debug'
6
+ import { promisify } from 'util'
7
+ import { TelegramError } from './error'
8
+ const debug = d('telegraf:polling')
9
+ const wait = promisify(setTimeout)
10
+ function always<T>(x: T) {
11
+ return () => x
12
+ }
13
+ const noop = always(Promise.resolve())
14
+
15
+ export class Polling {
16
+ private readonly abortController = new AbortController()
17
+ private skipOffsetSync = false
18
+ private offset = 0
19
+ constructor(
20
+ private readonly telegram: ApiClient,
21
+ private readonly allowedUpdates: readonly tt.UpdateType[]
22
+ ) {}
23
+
24
+ private async *[Symbol.asyncIterator]() {
25
+ debug('Starting long polling')
26
+ do {
27
+ try {
28
+ const updates = await this.telegram.callApi(
29
+ 'getUpdates',
30
+ {
31
+ timeout: 50,
32
+ offset: this.offset,
33
+ allowed_updates: this.allowedUpdates,
34
+ },
35
+ this.abortController
36
+ )
37
+ const last = updates[updates.length - 1]
38
+ if (last !== undefined) {
39
+ this.offset = last.update_id + 1
40
+ }
41
+ yield updates
42
+ } catch (error) {
43
+ const err = error as Error & {
44
+ parameters?: { retry_after: number }
45
+ }
46
+
47
+ if (err.name === 'AbortError') return
48
+ if (
49
+ err.name === 'FetchError' ||
50
+ (err instanceof TelegramError && err.code === 429) ||
51
+ (err instanceof TelegramError && err.code >= 500)
52
+ ) {
53
+ const retryAfter: number = err.parameters?.retry_after ?? 5
54
+ debug('Failed to fetch updates, retrying after %ds.', retryAfter, err)
55
+ await wait(retryAfter * 1000)
56
+ continue
57
+ }
58
+ if (
59
+ err instanceof TelegramError &&
60
+ // Unauthorized Conflict
61
+ (err.code === 401 || err.code === 409)
62
+ ) {
63
+ this.skipOffsetSync = true
64
+ throw err
65
+ }
66
+ throw err
67
+ }
68
+ } while (!this.abortController.signal.aborted)
69
+ }
70
+
71
+ private async syncUpdateOffset() {
72
+ if (this.skipOffsetSync) return
73
+ debug('Syncing update offset...')
74
+ await this.telegram.callApi('getUpdates', { offset: this.offset, limit: 1 })
75
+ }
76
+
77
+ async loop(handleUpdate: (updates: tg.Update) => Promise<void>) {
78
+ if (this.abortController.signal.aborted)
79
+ throw new Error('Polling instances must not be reused!')
80
+ try {
81
+ for await (const updates of this)
82
+ await Promise.all(updates.map(handleUpdate))
83
+ } finally {
84
+ debug('Long polling stopped')
85
+ // prevent instance reuse
86
+ this.stop()
87
+ await this.syncUpdateOffset().catch(noop)
88
+ }
89
+ }
90
+
91
+ stop() {
92
+ this.abortController.abort()
93
+ }
94
+ }
@@ -1,58 +1,58 @@
1
- import * as http from 'http'
2
- import d from 'debug'
3
- import { type Update } from '../types/typegram'
4
- const debug = d('telegraf:webhook')
5
-
6
- export default function generateWebhook(
7
- filter: (req: http.IncomingMessage) => boolean,
8
- updateHandler: (update: Update, res: http.ServerResponse) => Promise<void>
9
- ) {
10
- return async (
11
- req: http.IncomingMessage & { body?: Update },
12
- res: http.ServerResponse,
13
- next = (): void => {
14
- res.statusCode = 403
15
- debug('Replying with status code', res.statusCode)
16
- res.end()
17
- }
18
- ): Promise<void> => {
19
- debug('Incoming request', req.method, req.url)
20
-
21
- if (!filter(req)) {
22
- debug('Webhook filter failed', req.method, req.url)
23
- return next()
24
- }
25
-
26
- let update: Update
27
-
28
- try {
29
- if (req.body != null) {
30
- /* If req.body is already set, we expect it to be the parsed
31
- request body (update object) received from Telegram
32
- However, some libraries such as `serverless-http` set req.body to the
33
- raw buffer, so we'll handle that additionally */
34
-
35
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
- let body: any = req.body
37
- // if body is Buffer, parse it into string
38
- if (body instanceof Buffer) body = String(req.body)
39
- // if body is string, parse it into object
40
- if (typeof body === 'string') body = JSON.parse(body)
41
- update = body
42
- } else {
43
- let body = ''
44
- // parse each buffer to string and append to body
45
- for await (const chunk of req) body += String(chunk)
46
- // parse body to object
47
- update = JSON.parse(body)
48
- }
49
- } catch (error: unknown) {
50
- // if any of the parsing steps fails, give up and respond with error
51
- res.writeHead(415).end()
52
- debug('Failed to parse request body:', error)
53
- return
54
- }
55
-
56
- return await updateHandler(update, res)
57
- }
58
- }
1
+ import * as http from 'http'
2
+ import d from 'debug'
3
+ import { type Update } from '../types/typegram'
4
+ const debug = d('telegraf:webhook')
5
+
6
+ export default function generateWebhook(
7
+ filter: (req: http.IncomingMessage) => boolean,
8
+ updateHandler: (update: Update, res: http.ServerResponse) => Promise<void>
9
+ ) {
10
+ return async (
11
+ req: http.IncomingMessage & { body?: Update },
12
+ res: http.ServerResponse,
13
+ next = (): void => {
14
+ res.statusCode = 403
15
+ debug('Replying with status code', res.statusCode)
16
+ res.end()
17
+ }
18
+ ): Promise<void> => {
19
+ debug('Incoming request', req.method, req.url)
20
+
21
+ if (!filter(req)) {
22
+ debug('Webhook filter failed', req.method, req.url)
23
+ return next()
24
+ }
25
+
26
+ let update: Update
27
+
28
+ try {
29
+ if (req.body != null) {
30
+ /* If req.body is already set, we expect it to be the parsed
31
+ request body (update object) received from Telegram
32
+ However, some libraries such as `serverless-http` set req.body to the
33
+ raw buffer, so we'll handle that additionally */
34
+
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ let body: any = req.body
37
+ // if body is Buffer, parse it into string
38
+ if (body instanceof Buffer) body = String(req.body)
39
+ // if body is string, parse it into object
40
+ if (typeof body === 'string') body = JSON.parse(body)
41
+ update = body
42
+ } else {
43
+ let body = ''
44
+ // parse each buffer to string and append to body
45
+ for await (const chunk of req) body += String(chunk)
46
+ // parse body to object
47
+ update = JSON.parse(body)
48
+ }
49
+ } catch (error: unknown) {
50
+ // if any of the parsing steps fails, give up and respond with error
51
+ res.writeHead(415).end()
52
+ debug('Failed to parse request body:', error)
53
+ return
54
+ }
55
+
56
+ return await updateHandler(update, res)
57
+ }
58
+ }
@@ -1,54 +1,54 @@
1
- import * as Typegram from '@telegraf/types'
2
-
3
- // internal type provisions
4
- export * from '@telegraf/types/api'
5
- export * from '@telegraf/types/inline'
6
- export * from '@telegraf/types/manage'
7
- export * from '@telegraf/types/markup'
8
- export * from '@telegraf/types/message'
9
- export * from '@telegraf/types/methods'
10
- export * from '@telegraf/types/passport'
11
- export * from '@telegraf/types/payment'
12
- export * from '@telegraf/types/settings'
13
- export * from '@telegraf/types/update'
14
-
15
- // telegraf input file definition
16
- interface InputFileByPath {
17
- source: string
18
- filename?: string
19
- }
20
- interface InputFileByReadableStream {
21
- source: NodeJS.ReadableStream
22
- filename?: string
23
- }
24
- interface InputFileByBuffer {
25
- source: Buffer
26
- filename?: string
27
- }
28
- interface InputFileByURL {
29
- url: string
30
- filename?: string
31
- }
32
- export type InputFile =
33
- | InputFileByPath
34
- | InputFileByReadableStream
35
- | InputFileByBuffer
36
- | InputFileByURL
37
-
38
- export type Telegram = Typegram.ApiMethods<InputFile>
39
-
40
- export type Opts<M extends keyof Telegram> = Typegram.Opts<InputFile>[M]
41
- export type InputMedia = Typegram.InputMedia<InputFile>
42
- export type InputMediaPhoto = Typegram.InputMediaPhoto<InputFile>
43
- export type InputMediaVideo = Typegram.InputMediaVideo<InputFile>
44
- export type InputMediaAnimation = Typegram.InputMediaAnimation<InputFile>
45
- export type InputMediaAudio = Typegram.InputMediaAudio<InputFile>
46
- export type InputMediaDocument = Typegram.InputMediaDocument<InputFile>
47
-
48
- // tiny helper types
49
- export type ChatAction = Opts<'sendChatAction'>['action']
50
-
51
- /**
52
- * Sending video notes by a URL is currently unsupported
53
- */
54
- export type InputFileVideoNote = Exclude<InputFile, InputFileByURL>
1
+ import * as Typegram from '@telegraf/types'
2
+
3
+ // internal type provisions
4
+ export * from '@telegraf/types/api'
5
+ export * from '@telegraf/types/inline'
6
+ export * from '@telegraf/types/manage'
7
+ export * from '@telegraf/types/markup'
8
+ export * from '@telegraf/types/message'
9
+ export * from '@telegraf/types/methods'
10
+ export * from '@telegraf/types/passport'
11
+ export * from '@telegraf/types/payment'
12
+ export * from '@telegraf/types/settings'
13
+ export * from '@telegraf/types/update'
14
+
15
+ // telegraf input file definition
16
+ interface InputFileByPath {
17
+ source: string
18
+ filename?: string
19
+ }
20
+ interface InputFileByReadableStream {
21
+ source: NodeJS.ReadableStream
22
+ filename?: string
23
+ }
24
+ interface InputFileByBuffer {
25
+ source: Buffer
26
+ filename?: string
27
+ }
28
+ interface InputFileByURL {
29
+ url: string
30
+ filename?: string
31
+ }
32
+ export type InputFile =
33
+ | InputFileByPath
34
+ | InputFileByReadableStream
35
+ | InputFileByBuffer
36
+ | InputFileByURL
37
+
38
+ export type Telegram = Typegram.ApiMethods<InputFile>
39
+
40
+ export type Opts<M extends keyof Telegram> = Typegram.Opts<InputFile>[M]
41
+ export type InputMedia = Typegram.InputMedia<InputFile>
42
+ export type InputMediaPhoto = Typegram.InputMediaPhoto<InputFile>
43
+ export type InputMediaVideo = Typegram.InputMediaVideo<InputFile>
44
+ export type InputMediaAnimation = Typegram.InputMediaAnimation<InputFile>
45
+ export type InputMediaAudio = Typegram.InputMediaAudio<InputFile>
46
+ export type InputMediaDocument = Typegram.InputMediaDocument<InputFile>
47
+
48
+ // tiny helper types
49
+ export type ChatAction = Opts<'sendChatAction'>['action']
50
+
51
+ /**
52
+ * Sending video notes by a URL is currently unsupported
53
+ */
54
+ export type InputFileVideoNote = Exclude<InputFile, InputFileByURL>