@im-more/dsh-telegram 0.0.0-stage → 0.1.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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +10 -0
  3. package/lib/index.js +2067 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +70 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +231 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +34 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +41 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +39 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +382 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +33 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +89 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +19 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +34 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +10 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +8 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/media.d.ts +38 -0
  30. package/lib/types/media.d.ts.map +1 -0
  31. package/lib/types/media.js +65 -0
  32. package/lib/types/media.js.map +1 -0
  33. package/lib/types/modes/html.d.ts +16 -0
  34. package/lib/types/modes/html.d.ts.map +1 -0
  35. package/lib/types/modes/html.js +155 -0
  36. package/lib/types/modes/html.js.map +1 -0
  37. package/lib/types/modes/plain.d.ts +14 -0
  38. package/lib/types/modes/plain.d.ts.map +1 -0
  39. package/lib/types/modes/plain.js +56 -0
  40. package/lib/types/modes/plain.js.map +1 -0
  41. package/lib/types/modes/shared.d.ts +140 -0
  42. package/lib/types/modes/shared.d.ts.map +1 -0
  43. package/lib/types/modes/shared.js +405 -0
  44. package/lib/types/modes/shared.js.map +1 -0
  45. package/lib/types/polling.d.ts +26 -0
  46. package/lib/types/polling.d.ts.map +1 -0
  47. package/lib/types/polling.js +149 -0
  48. package/lib/types/polling.js.map +1 -0
  49. package/lib/types/request.d.ts +67 -0
  50. package/lib/types/request.d.ts.map +1 -0
  51. package/lib/types/request.js +158 -0
  52. package/lib/types/request.js.map +1 -0
  53. package/lib/types/secret.d.ts +27 -0
  54. package/lib/types/secret.d.ts.map +1 -0
  55. package/lib/types/secret.js +39 -0
  56. package/lib/types/secret.js.map +1 -0
  57. package/lib/types/send.d.ts +48 -0
  58. package/lib/types/send.d.ts.map +1 -0
  59. package/lib/types/send.js +326 -0
  60. package/lib/types/send.js.map +1 -0
  61. package/lib/types/types/game.d.ts +102 -0
  62. package/lib/types/types/game.d.ts.map +1 -0
  63. package/lib/types/types/game.js +5 -0
  64. package/lib/types/types/game.js.map +1 -0
  65. package/lib/types/types/index.d.ts +2751 -0
  66. package/lib/types/types/index.d.ts.map +1 -0
  67. package/lib/types/types/index.js +88 -0
  68. package/lib/types/types/index.js.map +1 -0
  69. package/lib/types/types/inline.d.ts +796 -0
  70. package/lib/types/types/inline.d.ts.map +1 -0
  71. package/lib/types/types/inline.js +4 -0
  72. package/lib/types/types/inline.js.map +1 -0
  73. package/lib/types/types/internal.d.ts +32 -0
  74. package/lib/types/types/internal.d.ts.map +1 -0
  75. package/lib/types/types/internal.js +30 -0
  76. package/lib/types/types/internal.js.map +1 -0
  77. package/lib/types/types/passport.d.ts +229 -0
  78. package/lib/types/types/passport.d.ts.map +1 -0
  79. package/lib/types/types/passport.js +3 -0
  80. package/lib/types/types/passport.js.map +1 -0
  81. package/lib/types/types/payment.d.ts +285 -0
  82. package/lib/types/types/payment.d.ts.map +1 -0
  83. package/lib/types/types/payment.js +6 -0
  84. package/lib/types/types/payment.js.map +1 -0
  85. package/lib/types/types/sticker.d.ts +221 -0
  86. package/lib/types/types/sticker.d.ts.map +1 -0
  87. package/lib/types/types/sticker.js +11 -0
  88. package/lib/types/types/sticker.js.map +1 -0
  89. package/lib/types/types/update.d.ts +97 -0
  90. package/lib/types/types/update.d.ts.map +1 -0
  91. package/lib/types/types/update.js +6 -0
  92. package/lib/types/types/update.js.map +1 -0
  93. package/lib/types/webhook.d.ts +29 -0
  94. package/lib/types/webhook.d.ts.map +1 -0
  95. package/lib/types/webhook.js +129 -0
  96. package/lib/types/webhook.js.map +1 -0
  97. package/package.json +61 -3
  98. package/src/bot.ts +349 -0
  99. package/src/config.ts +73 -0
  100. package/src/decode.ts +472 -0
  101. package/src/errors.ts +103 -0
  102. package/src/identity.ts +41 -0
  103. package/src/index.ts +14 -0
  104. package/src/media.ts +79 -0
  105. package/src/modes/html.ts +193 -0
  106. package/src/modes/plain.ts +75 -0
  107. package/src/modes/shared.ts +505 -0
  108. package/src/polling.ts +176 -0
  109. package/src/request.ts +224 -0
  110. package/src/secret.ts +46 -0
  111. package/src/send.ts +454 -0
  112. package/src/types/.eslintrc.yml +2 -0
  113. package/src/types/game.ts +112 -0
  114. package/src/types/index.ts +3028 -0
  115. package/src/types/inline.ts +857 -0
  116. package/src/types/internal.ts +64 -0
  117. package/src/types/passport.ts +256 -0
  118. package/src/types/payment.ts +304 -0
  119. package/src/types/sticker.ts +244 -0
  120. package/src/types/update.ts +107 -0
  121. package/src/webhook.ts +168 -0
  122. package/README.md +0 -3
@@ -0,0 +1,244 @@
1
+ import { File, Float, ForceReply, InlineKeyboardMarkup, InputFile, Integer, Internal, Message, PhotoSize, ReplyKeyboardMarkup, ReplyKeyboardRemove } from './index.ts'
2
+
3
+ /**
4
+ * This object represents a sticker.
5
+ * @see https://core.telegram.org/bots/api#sticker
6
+ */
7
+ export interface Sticker {
8
+ /** Identifier for this file, which can be used to download or reuse the file */
9
+ file_id?: string
10
+ /** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
11
+ file_unique_id?: string
12
+ /** Sticker width */
13
+ width?: Integer
14
+ /** Sticker height */
15
+ height?: Integer
16
+ /** True, if the sticker is animated */
17
+ is_animated?: boolean
18
+ /** True, if the sticker is a video sticker */
19
+ is_video?: boolean
20
+ /** Optional. Sticker thumbnail in the .WEBP or .JPG format */
21
+ thumb?: PhotoSize
22
+ /** Optional. Sticker thumbnail in the .WEBP or .JPG format (renamed from `thumb`) */
23
+ thumbnail?: PhotoSize
24
+ /** Optional. Emoji associated with the sticker */
25
+ emoji?: string
26
+ /** Optional. Name of the sticker set to which the sticker belongs */
27
+ set_name?: string
28
+ /** Optional. For premium regular stickers, premium animation for the sticker */
29
+ premium_animation?: File
30
+ /** Optional. For mask stickers, the position where the mask should be placed */
31
+ mask_position?: MaskPosition
32
+ /** Optional. For custom emoji stickers, unique identifier of the custom emoji */
33
+ custom_emoji_id?: string
34
+ /** Optional. File size in bytes */
35
+ file_size?: Integer
36
+ }
37
+
38
+ /**
39
+ * This object represents a sticker set.
40
+ * @see https://core.telegram.org/bots/api#stickerset
41
+ */
42
+ export interface StickerSet {
43
+ /** Sticker set name */
44
+ name?: string
45
+ /** Sticker set title */
46
+ title?: string
47
+ /** Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” */
48
+ sticker_type: string
49
+ /** True, if the sticker set contains animated stickers */
50
+ is_animated?: boolean
51
+ /** True, if the sticker set contains video stickers */
52
+ is_video?: boolean
53
+ /**
54
+ * True, if the sticker set contains masks
55
+ * @deprecated
56
+ */
57
+ contains_masks?: boolean
58
+ /** List of all set stickers */
59
+ stickers?: Sticker[]
60
+ /** Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format */
61
+ thumb?: PhotoSize
62
+ }
63
+
64
+ /**
65
+ * This object describes the position on faces where a mask should be placed by default.
66
+ * @see https://core.telegram.org/bots/api#maskposition
67
+ */
68
+ export interface MaskPosition {
69
+ /** The part of the face relative to which the mask should be placed. One of "forehead", "eyes", "mouth", or "chin". */
70
+ point?: string
71
+ /** Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. */
72
+ x_shift?: Float
73
+ /** Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. */
74
+ y_shift?: Float
75
+ /** Mask scaling coefficient. For example, 2.0 means double size. */
76
+ scale?: Float
77
+ }
78
+
79
+ export interface SendStickerPayload {
80
+ /** Unique identifier for the target chat or username of the target channel (in the format @channelusername) */
81
+ chat_id?: Integer | string
82
+ /** Unique identifier for the target message thread (topic) of the forum; for forum supergroups only */
83
+ message_thread_id?: number
84
+ /** Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
85
+ sticker?: InputFile | string
86
+ /** Sends the message silently. Users will receive a notification with no sound. */
87
+ disable_notification?: boolean
88
+ /** Protects the contents of the sent message from forwarding and saving */
89
+ protect_content?: boolean
90
+ /** If the message is a reply, ID of the original message */
91
+ reply_to_message_id?: Integer
92
+ /** Pass True, if the message should be sent even if the specified replied-to message is not found */
93
+ allow_sending_without_reply?: boolean
94
+ /** Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. */
95
+ reply_markup?: InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply
96
+ }
97
+
98
+ export interface GetStickerSetPayload {
99
+ /** Name of the sticker set */
100
+ name?: string
101
+ }
102
+
103
+ export interface GetCustomEmojiStickersPayload {
104
+ /** List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. */
105
+ custom_emoji_ids: string[]
106
+ }
107
+
108
+ export interface UploadStickerFilePayload {
109
+ /** User identifier of sticker file owner */
110
+ user_id?: Integer
111
+ /** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files » */
112
+ png_sticker?: InputFile
113
+ }
114
+
115
+ export interface CreateNewStickerSetPayload {
116
+ /** User identifier of created sticker set owner */
117
+ user_id?: Integer
118
+ /** Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "by<bot username>". <bot_username> is case insensitive. 1-64 characters. */
119
+ name?: string
120
+ /** Sticker set title, 1-64 characters */
121
+ title?: string
122
+ /** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
123
+ png_sticker?: InputFile | string
124
+ /** TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#animated-sticker-requirements for technical requirements */
125
+ tgs_sticker?: InputFile
126
+ /** WEBM video with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#video-sticker-requirements for technical requirements */
127
+ webm_sticker?: InputFile
128
+ /** Type of stickers in the set, pass “regular” or “mask”. Custom emoji sticker sets can't be created via the Bot API at the moment. By default, a regular sticker set is created. */
129
+ sticker_type?: string
130
+ /** One or more emoji corresponding to the sticker */
131
+ emojis?: string
132
+ /**
133
+ * Pass True, if a set of mask stickers should be created
134
+ * @deprecated
135
+ */
136
+ contains_masks?: boolean
137
+ /** A JSON-serialized object for position where the mask should be placed on faces */
138
+ mask_position?: MaskPosition
139
+ }
140
+
141
+ export interface AddStickerToSetPayload {
142
+ /** User identifier of sticker set owner */
143
+ user_id?: Integer
144
+ /** Sticker set name */
145
+ name?: string
146
+ /** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
147
+ png_sticker?: InputFile | string
148
+ /** TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#animated-sticker-requirements for technical requirements */
149
+ tgs_sticker?: InputFile
150
+ /** WEBM video with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#video-sticker-requirements for technical requirements */
151
+ webm_sticker?: InputFile
152
+ /** One or more emoji corresponding to the sticker */
153
+ emojis?: string
154
+ /** A JSON-serialized object for position where the mask should be placed on faces */
155
+ mask_position?: MaskPosition
156
+ }
157
+
158
+ export interface SetStickerPositionInSetPayload {
159
+ /** File identifier of the sticker */
160
+ sticker?: string
161
+ /** New sticker position in the set, zero-based */
162
+ position?: Integer
163
+ }
164
+
165
+ export interface DeleteStickerFromSetPayload {
166
+ /** File identifier of the sticker */
167
+ sticker?: string
168
+ }
169
+
170
+ export interface SetStickerSetThumbPayload {
171
+ /** Sticker set name */
172
+ name?: string
173
+ /** User identifier of the sticker set owner */
174
+ user_id?: Integer
175
+ /** A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements, or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files ». Animated sticker set thumbnails can't be uploaded via HTTP URL. */
176
+ thumb?: InputFile | string
177
+ }
178
+
179
+ declare module './index.ts' {
180
+ interface Message {
181
+ /** Optional. Message is a sticker, information about the sticker */
182
+ sticker?: Sticker
183
+ }
184
+ }
185
+
186
+ declare module './internal.ts' {
187
+ interface Internal {
188
+ /**
189
+ * Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
190
+ * @see https://core.telegram.org/bots/api#sendsticker
191
+ */
192
+ sendSticker(payload: SendStickerPayload): Promise<Message>
193
+ /**
194
+ * Use this method to get a sticker set. On success, a StickerSet object is returned.
195
+ * @see https://core.telegram.org/bots/api#getstickerset
196
+ */
197
+ getStickerSet(payload: GetStickerSetPayload): Promise<StickerSet>
198
+ /**
199
+ * Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
200
+ * @see https://core.telegram.org/bots/api#getcustomemojistickers
201
+ */
202
+ getCustomEmojiStickers(payload: GetCustomEmojiStickersPayload): Promise<Sticker[]>
203
+ /**
204
+ * Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
205
+ * @see https://core.telegram.org/bots/api#uploadstickerfile
206
+ */
207
+ uploadStickerFile(payload: UploadStickerFilePayload): Promise<File>
208
+ /**
209
+ * Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.
210
+ * @see https://core.telegram.org/bots/api#createnewstickerset
211
+ */
212
+ createNewStickerSet(payload: CreateNewStickerSetPayload): Promise<boolean>
213
+ /**
214
+ * Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
215
+ * @see https://core.telegram.org/bots/api#addstickertoset
216
+ */
217
+ addStickerToSet(payload: AddStickerToSetPayload): Promise<boolean>
218
+ /**
219
+ * Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
220
+ * @see https://core.telegram.org/bots/api#setstickerpositioninset
221
+ */
222
+ setStickerPositionInSet(payload: SetStickerPositionInSetPayload): Promise<boolean>
223
+ /**
224
+ * Use this method to delete a sticker from a set created by the bot. Returns True on success.
225
+ * @see https://core.telegram.org/bots/api#deletestickerfromset
226
+ */
227
+ deleteStickerFromSet(payload: DeleteStickerFromSetPayload): Promise<boolean>
228
+ /**
229
+ * Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only. Returns True on success.
230
+ * @see https://core.telegram.org/bots/api#setstickersetthumb
231
+ */
232
+ setStickerSetThumb(payload: SetStickerSetThumbPayload): Promise<boolean>
233
+ }
234
+ }
235
+
236
+ Internal.define('sendSticker')
237
+ Internal.define('getStickerSet')
238
+ Internal.define('getCustomEmojiStickers')
239
+ Internal.define('uploadStickerFile')
240
+ Internal.define('createNewStickerSet')
241
+ Internal.define('addStickerToSet')
242
+ Internal.define('setStickerPositionInSet')
243
+ Internal.define('deleteStickerFromSet')
244
+ Internal.define('setStickerSetThumb')
@@ -0,0 +1,107 @@
1
+ import { InputFile, Integer, Internal } from './index.ts'
2
+
3
+ /**
4
+ * This object represents an incoming update. At most one of the optional parameters can be present in any given update.
5
+ * @see https://core.telegram.org/bots/api#update
6
+ */
7
+ export interface Update {
8
+ /** The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. */
9
+ update_id?: Integer
10
+ }
11
+
12
+ export interface GetUpdatesPayload {
13
+ /** Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten. */
14
+ offset?: Integer
15
+ /** Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. */
16
+ limit?: Integer
17
+ /** Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. */
18
+ timeout?: Integer
19
+ /**
20
+ * A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
21
+ * Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.
22
+ */
23
+ allowed_updates?: string[]
24
+ }
25
+
26
+ export interface SetWebhookPayload {
27
+ /** HTTPS url to send updates to. Use an empty string to remove webhook integration */
28
+ url?: string
29
+ /** Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. */
30
+ certificate?: InputFile
31
+ /** The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS */
32
+ ip_address?: string
33
+ /** Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. */
34
+ max_connections?: Integer
35
+ /**
36
+ * A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
37
+ *
38
+ * Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.
39
+ */
40
+ allowed_updates?: string[]
41
+ /** Pass True to drop all pending updates */
42
+ drop_pending_updates?: boolean
43
+ /** A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. */
44
+ secret_token?: string
45
+ }
46
+
47
+ export interface DeleteWebhookPayload {
48
+ /** Pass True to drop all pending updates */
49
+ drop_pending_updates?: boolean
50
+ }
51
+
52
+ /**
53
+ * Contains information about the current status of a webhook.
54
+ * @see https://core.telegram.org/bots/api#webhookinfo
55
+ */
56
+ export interface WebhookInfo {
57
+ /** Webhook URL, may be empty if webhook is not set up */
58
+ url?: string
59
+ /** True, if a custom certificate was provided for webhook certificate checks */
60
+ has_custom_certificate?: boolean
61
+ /** Number of updates awaiting delivery */
62
+ pending_update_count?: Integer
63
+ /** Optional. Currently used webhook IP address */
64
+ ip_address?: string
65
+ /** Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook */
66
+ last_error_date?: Integer
67
+ /** Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook */
68
+ last_error_message?: string
69
+ /** Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters */
70
+ last_synchronization_error_date?: number
71
+ /** Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery */
72
+ max_connections?: Integer
73
+ /** Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member */
74
+ allowed_updates?: string[]
75
+ }
76
+
77
+ declare module './internal.ts' {
78
+ interface Internal {
79
+ /**
80
+ * Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
81
+ * @see https://core.telegram.org/bots/api#getupdates
82
+ */
83
+ getUpdates(payload: GetUpdatesPayload): Promise<Update[]>
84
+ /**
85
+ * Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
86
+ *
87
+ * If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot's token, you can be pretty sure it's us.
88
+ * @see https://core.telegram.org/bots/api#setwebhook
89
+ */
90
+ setWebhook(payload: SetWebhookPayload): Promise<boolean>
91
+ /**
92
+ * Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
93
+ * @see https://core.telegram.org/bots/api#deletewebhook
94
+ */
95
+ deleteWebhook(payload: DeleteWebhookPayload): Promise<boolean>
96
+ /**
97
+ * Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
98
+ * @see https://core.telegram.org/bots/api#getwebhookinfo
99
+ */
100
+ getWebhookInfo(): Promise<WebhookInfo>
101
+ }
102
+ }
103
+
104
+ Internal.define('getUpdates')
105
+ Internal.define('setWebhook')
106
+ Internal.define('deleteWebhook')
107
+ Internal.define('getWebhookInfo')
package/src/webhook.ts ADDED
@@ -0,0 +1,168 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http'
2
+ import type { TelegramBot } from './bot.ts'
3
+ import { decodeUpdate } from './decode.ts'
4
+ import { ALLOWED_UPDATES } from './polling.ts'
5
+ import { deriveWebhookSecret, matchesWebhookSecret } from './secret.ts'
6
+ import type { Update } from './types/index.ts'
7
+
8
+ /** The part of `ctx.webServer` this adapter uses. */
9
+ interface WebServerLike {
10
+ register(route: {
11
+ kind: 'exact'
12
+ path: string
13
+ auth: 'anonymous'
14
+ handler: (
15
+ request: IncomingMessage,
16
+ response: ServerResponse,
17
+ ) => void | Promise<void>
18
+ }): () => void
19
+ }
20
+
21
+ /** Header Telegram echoes the configured secret token in. */
22
+ const SECRET_HEADER = 'x-telegram-bot-api-secret-token'
23
+
24
+ /** Route path Telegram posts to: leading slash, no trailing slash. */
25
+ function routePath(path: string): string {
26
+ const withSlash = path.startsWith('/') ? path : `/${path}`
27
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash
28
+ }
29
+
30
+ /** One request's bounded body. */
31
+ async function readBody(
32
+ request: IncomingMessage,
33
+ limit: number,
34
+ ): Promise<string | undefined> {
35
+ const chunks: Buffer[] = []
36
+ let size = 0
37
+ for await (const chunk of request) {
38
+ const buffer = Buffer.isBuffer(chunk)
39
+ ? chunk
40
+ : Buffer.from(chunk as Uint8Array)
41
+ size += buffer.byteLength
42
+ if (size > limit) return undefined
43
+ chunks.push(buffer)
44
+ }
45
+ return Buffer.concat(chunks).toString('utf8')
46
+ }
47
+
48
+ /**
49
+ * Webhook transport over the profile's `ctx.webServer`.
50
+ *
51
+ * The route is anonymous at the Web server layer and authenticated by
52
+ * Telegram's secret-token header, whose value the adapter derives from the
53
+ * Bot API token. `connect` registers the route and calls `setWebhook`, so a
54
+ * profile without `webServer` fails with an actionable message instead of
55
+ * silently receiving nothing.
56
+ */
57
+ export class TelegramWebhook {
58
+ private dispose: (() => void) | undefined
59
+
60
+ constructor(private readonly bot: TelegramBot) {}
61
+
62
+ /** Register the route and point Telegram at it. */
63
+ async start(): Promise<void> {
64
+ const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
65
+ if (webServer === undefined) {
66
+ throw this.failStart(
67
+ 'telegram: the webhook transport needs a profile-provided webServer; use transport "polling" instead',
68
+ )
69
+ }
70
+ const publicUrl = this.bot.config.webhook.publicUrl
71
+ if (publicUrl === undefined || publicUrl === null || publicUrl === '') {
72
+ throw this.failStart(
73
+ 'telegram: webhook.publicUrl is required for the webhook transport',
74
+ )
75
+ }
76
+ const url = new URL(publicUrl)
77
+ if (url.protocol !== 'https:') {
78
+ throw this.failStart(
79
+ 'telegram: webhook.publicUrl must be an https URL (Telegram refuses plain HTTP webhooks)',
80
+ )
81
+ }
82
+ const path = routePath(this.bot.config.webhook.path)
83
+ this.dispose = webServer.register({
84
+ kind: 'exact',
85
+ path,
86
+ auth: 'anonymous',
87
+ handler: (request, response) => this.handle(request, response),
88
+ })
89
+ try {
90
+ await this.bot.internal.setWebhook({
91
+ url: `${publicUrl.replace(/\/+$/, '')}${path}`,
92
+ secret_token: deriveWebhookSecret(this.bot.config.token),
93
+ drop_pending_updates: this.bot.config.dropPendingUpdates,
94
+ allowed_updates: [...ALLOWED_UPDATES],
95
+ })
96
+ } catch (error) {
97
+ this.dispose()
98
+ this.dispose = undefined
99
+ this.bot.ctx.logger.error(
100
+ 'telegram: setWebhook failed: %s',
101
+ error instanceof Error ? error.message : String(error),
102
+ )
103
+ throw error
104
+ }
105
+ this.bot.online()
106
+ }
107
+
108
+ /** Release the route. The webhook itself stays registered so Telegram keeps retrying. */
109
+ async stop(): Promise<void> {
110
+ this.dispose?.()
111
+ this.dispose = undefined
112
+ }
113
+
114
+ /**
115
+ * Log a fatal start failure before the caller throws it, because `Bot.start`
116
+ * only stores a connect failure on `bot.error`.
117
+ *
118
+ * @param message - error text that also names the corrective action.
119
+ * @returns the error for the caller to throw.
120
+ */
121
+ private failStart(message: string): Error {
122
+ this.bot.ctx.logger.error(message)
123
+ return new Error(message)
124
+ }
125
+
126
+ private async handle(
127
+ request: IncomingMessage,
128
+ response: ServerResponse,
129
+ ): Promise<void> {
130
+ try {
131
+ if (request.method !== 'POST') {
132
+ response.writeHead(405, { allow: 'POST' })
133
+ response.end()
134
+ return
135
+ }
136
+ const expected = deriveWebhookSecret(this.bot.config.token)
137
+ const received = request.headers[SECRET_HEADER]
138
+ if (
139
+ !matchesWebhookSecret(
140
+ expected,
141
+ typeof received === 'string' ? received : undefined,
142
+ )
143
+ ) {
144
+ response.writeHead(401)
145
+ response.end()
146
+ return
147
+ }
148
+ const body = await readBody(request, this.bot.config.webhook.maxBodyBytes)
149
+ if (body === undefined) {
150
+ response.writeHead(413)
151
+ response.end()
152
+ return
153
+ }
154
+ const update = JSON.parse(body) as Update
155
+ const session = decodeUpdate(this.bot, update)
156
+ if (session !== undefined) await this.bot.receive(session)
157
+ response.writeHead(200, { 'content-type': 'text/plain' })
158
+ response.end('OK')
159
+ } catch (error) {
160
+ this.bot.ctx.logger.warn(
161
+ 'telegram: webhook delivery failed: %s',
162
+ error instanceof Error ? error.message : String(error),
163
+ )
164
+ if (!response.headersSent) response.writeHead(500)
165
+ response.end()
166
+ }
167
+ }
168
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.