@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
package/src/decode.ts ADDED
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Inbound decoding: one Telegram update becomes either an intake `Session`
3
+ * (`message`) or a button interaction session.
4
+ *
5
+ * Text runs through `entities` into the element vocabulary (bold, italic,
6
+ * links, mentions, code, spoilers, quotes), media becomes resource elements
7
+ * whose `src` is the bot's `satori:` file route, and everything the vocabulary
8
+ * cannot express degrades to readable text. Only `message` and `callback_query`
9
+ * updates are decoded; other update families are ignored.
10
+ */
11
+
12
+ import {
13
+ type ChatRef,
14
+ type InboundMessage,
15
+ type Session,
16
+ type UserRef,
17
+ } from '@deepseek-ai/cordis-plugin-im-core'
18
+ import { h, normalize, type Child } from '@deepseek-ai/satori-element'
19
+ import type { TelegramBot } from './bot.ts'
20
+ import type {
21
+ Chat,
22
+ Message,
23
+ MessageEntity,
24
+ Update,
25
+ User,
26
+ } from './types/index.ts'
27
+
28
+ /** Adapter-private context carried through `Target.referrer`. */
29
+ export interface TelegramReferrer {
30
+ chatId: string
31
+ messageId: string
32
+ threadId?: string
33
+ date: number
34
+ }
35
+
36
+ /** Callback context carried on a button interaction. */
37
+ export interface TelegramCallbackReferrer extends TelegramReferrer {
38
+ callbackQueryId: string
39
+ }
40
+
41
+ /** Display name of a Telegram user. */
42
+ function userName(user: User): string {
43
+ const name = [user.first_name, user.last_name]
44
+ .filter((part) => part !== undefined && part !== '')
45
+ .join(' ')
46
+ return name !== '' ? name : (user.username ?? String(user.id!))
47
+ }
48
+
49
+ /** Platform user reference. */
50
+ function userRef(user: User): UserRef {
51
+ return {
52
+ id: String(user.id!),
53
+ name: userName(user),
54
+ isBot: user.is_bot!,
55
+ }
56
+ }
57
+
58
+ /** Chat reference; forum messages are `topic`, everything else is `group`. */
59
+ function chatRef(
60
+ chat: Chat,
61
+ message: Pick<Message, 'is_topic_message'>,
62
+ ): ChatRef {
63
+ const name =
64
+ chat.title ??
65
+ [chat.first_name, chat.last_name]
66
+ .filter((part) => part !== undefined)
67
+ .join(' ')
68
+ if (chat.type === 'private') {
69
+ return {
70
+ id: String(chat.id!),
71
+ type: 'direct',
72
+ ...(name === '' ? {} : { name }),
73
+ }
74
+ }
75
+ return {
76
+ id: String(chat.id!),
77
+ type: message.is_topic_message === true ? 'topic' : 'group',
78
+ ...(name === '' ? {} : { name }),
79
+ }
80
+ }
81
+
82
+ interface TextInput {
83
+ text: string
84
+ entities?: MessageEntity[] | undefined
85
+ }
86
+
87
+ /** Whether an entity type is one the vocabulary renders. */
88
+ function entityTag(type: MessageEntity['type']): string | undefined {
89
+ switch (type) {
90
+ case 'bold':
91
+ return 'b'
92
+ case 'italic':
93
+ return 'i'
94
+ case 'underline':
95
+ return 'u'
96
+ case 'strikethrough':
97
+ return 's'
98
+ case 'spoiler':
99
+ return 'spoiler'
100
+ case 'blockquote':
101
+ case 'expandable_blockquote':
102
+ return 'blockquote'
103
+ case 'code':
104
+ return 'code'
105
+ case 'pre':
106
+ return 'pre'
107
+ default:
108
+ return undefined
109
+ }
110
+ }
111
+
112
+ /** Render a text range with its nested entities. */
113
+ function renderRange(
114
+ input: TextInput,
115
+ entities: readonly MessageEntity[],
116
+ from: number,
117
+ to: number,
118
+ ): Child[] {
119
+ const nodes: Child[] = []
120
+ let cursor = from
121
+ for (const entity of entities) {
122
+ const start = entity.offset!
123
+ const end = start + entity.length!
124
+ if (start < cursor || end > to) continue
125
+ if (start > cursor) nodes.push(input.text.slice(cursor, start))
126
+ const inner = renderRange(
127
+ input,
128
+ entities.filter((other) => other !== entity),
129
+ start,
130
+ end,
131
+ )
132
+ const tag = entityTag(entity.type)
133
+ if (tag !== undefined) {
134
+ switch (tag) {
135
+ case 'b':
136
+ nodes.push(h('b', {}, ...inner))
137
+ break
138
+ case 'i':
139
+ nodes.push(h('i', {}, ...inner))
140
+ break
141
+ case 'u':
142
+ nodes.push(h('u', {}, ...inner))
143
+ break
144
+ case 's':
145
+ nodes.push(h('s', {}, ...inner))
146
+ break
147
+ case 'spoiler':
148
+ nodes.push(h('spoiler', {}, ...inner))
149
+ break
150
+ case 'blockquote':
151
+ nodes.push(h('blockquote', {}, ...inner))
152
+ break
153
+ case 'code':
154
+ nodes.push(h('code', {}, ...inner))
155
+ break
156
+ case 'pre':
157
+ nodes.push(
158
+ h(
159
+ 'pre',
160
+ entity.language === undefined ? {} : { lang: entity.language },
161
+ ...inner,
162
+ ),
163
+ )
164
+ break
165
+ }
166
+ } else if (entity.type === 'text_link' && entity.url !== undefined) {
167
+ nodes.push(h('a', { href: entity.url }, ...inner))
168
+ } else if (entity.type === 'text_mention' && entity.user !== undefined) {
169
+ nodes.push(
170
+ h('at', {
171
+ type: 'user',
172
+ id: String(entity.user.id!),
173
+ name: userName(entity.user),
174
+ }),
175
+ )
176
+ } else {
177
+ nodes.push(...inner)
178
+ }
179
+ cursor = end
180
+ }
181
+ if (cursor < to) nodes.push(input.text.slice(cursor, to))
182
+ return nodes
183
+ }
184
+
185
+ /** Element tree of one text body. */
186
+ function textNodes(input: TextInput): Child[] {
187
+ if (input.text === '') return []
188
+ const entities = [...(input.entities ?? [])]
189
+ .filter(
190
+ (entity) =>
191
+ entity.offset! >= 0 &&
192
+ entity.length! > 0 &&
193
+ entity.offset! + entity.length! <= input.text.length,
194
+ )
195
+ .sort((a, b) => a.offset! - b.offset! || b.length! - a.length!)
196
+ return renderRange(input, entities, 0, input.text.length)
197
+ }
198
+
199
+ /** The best photo size of a message (the last one is the largest). */
200
+ function photoSize(message: Message) {
201
+ return message.photo?.[message.photo.length - 1]
202
+ }
203
+
204
+ /** One `satori:` URL for a Telegram file id. */
205
+ function fileUrl(bot: TelegramBot, fileId: string): string {
206
+ return bot.getInternalUrl(`/files/${encodeURIComponent(fileId)}`)
207
+ }
208
+
209
+ /** Media elements of one message. */
210
+ function mediaNodes(bot: TelegramBot, message: Message): Child[] {
211
+ const nodes: Child[] = []
212
+ const photo = photoSize(message)
213
+ if (photo !== undefined)
214
+ nodes.push(h('img', { src: fileUrl(bot, photo.file_id!) }))
215
+ if (message.sticker !== undefined) {
216
+ if (
217
+ message.sticker.is_animated &&
218
+ message.sticker.thumbnail === undefined
219
+ ) {
220
+ nodes.push('[动画表情]')
221
+ } else {
222
+ const fileId =
223
+ message.sticker.thumbnail?.file_id ?? message.sticker.file_id!
224
+ nodes.push(h('img', { src: fileUrl(bot, fileId) }))
225
+ }
226
+ }
227
+ if (message.animation !== undefined) {
228
+ nodes.push(
229
+ h('video', {
230
+ src: fileUrl(bot, message.animation.file_id!),
231
+ ...(message.animation.file_name === undefined
232
+ ? {}
233
+ : { name: message.animation.file_name }),
234
+ duration: message.animation.duration!,
235
+ }),
236
+ )
237
+ }
238
+ if (message.video !== undefined) {
239
+ nodes.push(
240
+ h('video', {
241
+ src: fileUrl(bot, message.video.file_id!),
242
+ ...(message.video.file_name === undefined
243
+ ? {}
244
+ : { name: message.video.file_name }),
245
+ duration: message.video.duration!,
246
+ }),
247
+ )
248
+ }
249
+ if (message.voice !== undefined) {
250
+ nodes.push(
251
+ h('audio', {
252
+ src: fileUrl(bot, message.voice.file_id!),
253
+ name: 'voice',
254
+ duration: message.voice.duration!,
255
+ }),
256
+ )
257
+ }
258
+ if (message.audio !== undefined) {
259
+ nodes.push(
260
+ h('audio', {
261
+ src: fileUrl(bot, message.audio.file_id!),
262
+ ...(message.audio.file_name === undefined
263
+ ? {}
264
+ : { name: message.audio.file_name }),
265
+ duration: message.audio.duration!,
266
+ }),
267
+ )
268
+ }
269
+ if (message.document !== undefined) {
270
+ nodes.push(
271
+ h('file', {
272
+ src: fileUrl(bot, message.document.file_id!),
273
+ ...(message.document.file_name === undefined
274
+ ? {}
275
+ : { name: message.document.file_name }),
276
+ }),
277
+ )
278
+ }
279
+ if (message.venue !== undefined) {
280
+ nodes.push(`[位置: ${message.venue.title} — ${message.venue.address}]`)
281
+ } else if (message.location !== undefined) {
282
+ nodes.push(
283
+ `[位置: ${message.location.latitude}, ${message.location.longitude}]`,
284
+ )
285
+ }
286
+ if (message.contact !== undefined) {
287
+ const name = [message.contact.first_name, message.contact.last_name]
288
+ .filter((part) => part !== undefined)
289
+ .join(' ')
290
+ nodes.push(`[联系人: ${name} ${message.contact.phone_number}]`)
291
+ }
292
+ return nodes
293
+ }
294
+
295
+ /** Message body: caption/text entities plus media. */
296
+ function contentNodes(bot: TelegramBot, message: Message): Child[] {
297
+ const text: TextInput = {
298
+ text: message.text ?? message.caption ?? '',
299
+ entities: message.entities ?? message.caption_entities,
300
+ }
301
+ const nodes = [...textNodes(text), ...mediaNodes(bot, message)]
302
+ return nodes.length > 0
303
+ ? nodes
304
+ : [
305
+ h('raw', {
306
+ platform: 'telegram',
307
+ type: 'message',
308
+ data: message,
309
+ }),
310
+ ]
311
+ }
312
+
313
+ /** Mention flags and mentioned users of a message. */
314
+ function mentionsOf(
315
+ bot: TelegramBot,
316
+ message: Message,
317
+ ): InboundMessage['mentions'] {
318
+ const users: UserRef[] = []
319
+ let self = false
320
+ const username = bot.username?.toLowerCase()
321
+ for (const entity of [
322
+ ...(message.entities ?? []),
323
+ ...(message.caption_entities ?? []),
324
+ ]) {
325
+ if (entity.type === 'text_mention' && entity.user !== undefined) {
326
+ const ref = userRef(entity.user)
327
+ users.push(ref)
328
+ if (ref.id === bot.selfId) self = true
329
+ } else if (entity.type === 'mention') {
330
+ const text = (message.text ?? message.caption ?? '').slice(
331
+ entity.offset!,
332
+ entity.offset! + entity.length!,
333
+ )
334
+ const name = text.replace(/^@/, '')
335
+ if (name === '') continue
336
+ users.push({ id: name, name: `@${name}` })
337
+ if (username !== undefined && name.toLowerCase() === username) self = true
338
+ }
339
+ }
340
+ if (!self && username !== undefined) {
341
+ const body = message.text ?? message.caption ?? ''
342
+ if (new RegExp(`(^|\\s)@${username}(\\s|$)`, 'i').test(body)) self = true
343
+ }
344
+ return { self, all: false, users }
345
+ }
346
+
347
+ /**
348
+ * Decode one message into `InboundMessage`.
349
+ * @param bot - the receiving adapter.
350
+ * @param messages - one message, or every message of a merged media group (in order).
351
+ * @returns the normalized inbound message.
352
+ */
353
+ export function decodeMessage(
354
+ bot: TelegramBot,
355
+ messages: readonly Message[],
356
+ ): InboundMessage {
357
+ const [primary] = messages
358
+ if (primary === undefined)
359
+ throw new Error('telegram: decodeMessage requires at least one message')
360
+ const senderUser = primary.from ?? primary.sender_chat
361
+ const sender: UserRef =
362
+ senderUser === undefined
363
+ ? { id: 'unknown', name: 'unknown' }
364
+ : 'is_bot' in senderUser
365
+ ? userRef(senderUser)
366
+ : {
367
+ id: String(senderUser.id!),
368
+ name:
369
+ ('title' in senderUser ? senderUser.title : undefined) ??
370
+ String(senderUser.id!),
371
+ }
372
+ const content = normalize(
373
+ messages.flatMap((message) => contentNodes(bot, message)),
374
+ )
375
+ const threadId = primary.message_thread_id
376
+ const date = primary.date! * 1000
377
+ const referrer: TelegramReferrer = {
378
+ chatId: String(primary.chat!.id!),
379
+ messageId: String(primary.message_id!),
380
+ date,
381
+ ...(threadId === undefined ? {} : { threadId: String(threadId) }),
382
+ }
383
+ const ids = messages.map((message) => String(message.message_id!))
384
+ return {
385
+ id: String(Math.min(...messages.map((message) => message.message_id!))),
386
+ ...(ids.length < 2 ? {} : { aliases: ids.slice(1) }),
387
+ chat: chatRef(primary.chat!, primary),
388
+ ...(threadId === undefined || primary.is_topic_message !== true
389
+ ? {}
390
+ : { thread: { id: String(threadId) } }),
391
+ sender,
392
+ content,
393
+ ...(primary.reply_to_message === undefined ||
394
+ 'forum_topic_created' in primary.reply_to_message
395
+ ? {}
396
+ : { quote: { id: String(primary.reply_to_message.message_id!) } }),
397
+ mentions: mentionsOf(bot, primary),
398
+ time: date,
399
+ referrer,
400
+ raw: messages.length === 1 ? primary : messages,
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Decode one Telegram update.
406
+ * @param bot - the receiving adapter.
407
+ * @param update - the update envelope.
408
+ * @returns the session to publish, or undefined for an ignored update.
409
+ */
410
+ export function decodeUpdate(
411
+ bot: TelegramBot,
412
+ update: Update,
413
+ ): Session | undefined {
414
+ if (update.message !== undefined) {
415
+ const message = decodeMessage(bot, [update.message])
416
+ return bot.session({
417
+ type: 'message',
418
+ id: message.id,
419
+ timestamp: message.time,
420
+ message,
421
+ raw: update,
422
+ })
423
+ }
424
+ if (update.callback_query !== undefined) {
425
+ return decodeCallback(bot, update.callback_query)
426
+ }
427
+ return undefined
428
+ }
429
+
430
+ /** Decode one button click. */
431
+ function decodeCallback(
432
+ bot: TelegramBot,
433
+ query: Update['callback_query'],
434
+ ): Session | undefined {
435
+ if (query === undefined || query.message === undefined) return undefined
436
+ const message = query.message
437
+ const chat = chatRef(message.chat!, message)
438
+ const referrer: TelegramCallbackReferrer = {
439
+ chatId: String(message.chat!.id!),
440
+ messageId: String(message.message_id!),
441
+ date: message.date! * 1000,
442
+ ...(message.message_thread_id === undefined
443
+ ? {}
444
+ : { threadId: String(message.message_thread_id) }),
445
+ callbackQueryId: query.id!,
446
+ }
447
+ const button = {
448
+ id: query.data ?? '',
449
+ ...(query.data === undefined ? {} : { data: query.data }),
450
+ referrer,
451
+ time: Date.now(),
452
+ bot,
453
+ user: userRef(query.from!),
454
+ chat,
455
+ message: { id: String(message.message_id!), chat },
456
+ respond: async (answer: { toast?: { content: string } | undefined }) => {
457
+ await bot.internal.answerCallbackQuery({
458
+ callback_query_id: query.id!,
459
+ ...(answer.toast === undefined
460
+ ? {}
461
+ : { text: answer.toast.content, show_alert: false }),
462
+ })
463
+ },
464
+ }
465
+ return bot.session({
466
+ type: 'interaction/button',
467
+ id: query.id!,
468
+ timestamp: Date.now(),
469
+ button,
470
+ raw: query,
471
+ })
472
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
2
+
3
+ /** Fields a failed Bot API call carries for classification. */
4
+ export interface TelegramApiErrorInit {
5
+ method: string
6
+ status?: number
7
+ errorCode?: number
8
+ description?: string
9
+ retryAfterMs?: number
10
+ cause?: unknown
11
+ }
12
+
13
+ /** One failed Telegram Bot API call, with the fields `classify` needs. */
14
+ export class TelegramApiError extends Error {
15
+ readonly method: string
16
+ readonly status: number | undefined
17
+ readonly errorCode: number | undefined
18
+ readonly description: string | undefined
19
+ readonly retryAfterMs: number | undefined
20
+
21
+ constructor(message: string, init: TelegramApiErrorInit) {
22
+ super(message, init.cause === undefined ? undefined : { cause: init.cause })
23
+ this.name = 'TelegramApiError'
24
+ this.method = init.method
25
+ this.status = init.status
26
+ this.errorCode = init.errorCode
27
+ this.description = init.description
28
+ this.retryAfterMs = init.retryAfterMs
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Map any failure onto the core platform taxonomy.
34
+ *
35
+ * Telegram answers content and permission refusals with a JSON error code, so
36
+ * those are certainly unpublished; transport failures and 5xx answers leave
37
+ * the outcome unknown.
38
+ *
39
+ * @param error - the caught failure.
40
+ * @returns the classified platform error.
41
+ */
42
+ export function classifyTelegramError(error: unknown): PlatformError {
43
+ if (error instanceof PlatformError) return error
44
+ if (error instanceof TelegramApiError) {
45
+ const code = error.errorCode ?? error.status
46
+ const init = {
47
+ ...(code === undefined ? {} : { code }),
48
+ ...(error.retryAfterMs === undefined
49
+ ? {}
50
+ : { retryAfterMs: error.retryAfterMs }),
51
+ cause: error,
52
+ }
53
+ if (code === 429)
54
+ return new PlatformError('rate-limit', error.message, {
55
+ ...init,
56
+ published: 'no',
57
+ })
58
+ if (code === 401 || code === 403)
59
+ return new PlatformError('permission', error.message, {
60
+ ...init,
61
+ published: 'no',
62
+ })
63
+ if (code === 404)
64
+ return new PlatformError('not-found', error.message, {
65
+ ...init,
66
+ published: 'no',
67
+ })
68
+ if (code !== undefined && code >= 500)
69
+ return new PlatformError('retryable', error.message, {
70
+ ...init,
71
+ published: 'unknown',
72
+ })
73
+ if (code !== undefined && code >= 400)
74
+ return new PlatformError('invalid', error.message, {
75
+ ...init,
76
+ published: 'no',
77
+ })
78
+ return new PlatformError('retryable', error.message, {
79
+ ...init,
80
+ published: 'unknown',
81
+ })
82
+ }
83
+ if (error instanceof Error && error.name === 'AbortError') {
84
+ return new PlatformError('fatal', error.message, {
85
+ published: 'unknown',
86
+ cause: error,
87
+ })
88
+ }
89
+ const message = error instanceof Error ? error.message : String(error)
90
+ return new PlatformError('retryable', `telegram request failed: ${message}`, {
91
+ published: 'unknown',
92
+ cause: error,
93
+ })
94
+ }
95
+
96
+ /** Whether an API failure means the requested edit changed nothing. */
97
+ export function isNotModified(error: unknown): boolean {
98
+ return (
99
+ error instanceof TelegramApiError &&
100
+ error.errorCode === 400 &&
101
+ (error.description ?? '').includes('message is not modified')
102
+ )
103
+ }
@@ -0,0 +1,41 @@
1
+ import type { User } from './types/index.ts'
2
+
3
+ /** Failure to derive the bot identity from the configured token. */
4
+ export class TelegramIdentityError extends Error {
5
+ constructor(message: string) {
6
+ super(message)
7
+ this.name = 'TelegramIdentityError'
8
+ }
9
+ }
10
+
11
+ /**
12
+ * The bot id encoded in a Bot API token.
13
+ * @param token - `<bot id>:<secret>`.
14
+ * @returns the numeric bot id as text.
15
+ */
16
+ export function botIdFromToken(token: string): string {
17
+ const [id] = token.split(':')
18
+ if (id === undefined || !/^\d+$/.test(id)) {
19
+ throw new TelegramIdentityError(
20
+ 'telegram: token must look like "<bot id>:<secret>"',
21
+ )
22
+ }
23
+ return id
24
+ }
25
+
26
+ /**
27
+ * Verify a `getMe` answer against the token prefix.
28
+ * @param token - the configured Bot API token.
29
+ * @param user - the `getMe` result.
30
+ * @returns the bot's numeric id.
31
+ */
32
+ export function verifyIdentity(token: string, user: User): string {
33
+ const expected = botIdFromToken(token)
34
+ const actual = String(user.id)
35
+ if (actual !== expected) {
36
+ throw new TelegramIdentityError(
37
+ `telegram: token belongs to bot ${expected} but getMe returned bot ${actual}`,
38
+ )
39
+ }
40
+ return actual
41
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ import * as Telegram from './types/index.ts'
2
+
3
+ export {
4
+ TelegramBot,
5
+ TelegramBot as default,
6
+ type TelegramModes,
7
+ } from './bot.ts'
8
+ export { Config, type Config as TelegramConfig } from './config.ts'
9
+ export { TelegramApiError, classifyTelegramError } from './errors.ts'
10
+ export type { TelegramModeTypes } from './modes/shared.ts'
11
+ export type { TelegramRequestBody } from './request.ts'
12
+ export { deriveWebhookSecret, matchesWebhookSecret } from './secret.ts'
13
+ export { Internal } from './types/internal.ts'
14
+ export { Telegram }
package/src/media.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { ResolvedResource } from '@deepseek-ai/cordis-plugin-im-core'
2
+ import { randomUUID } from 'node:crypto'
3
+
4
+ /** Bytes staged for one outbound media part. */
5
+ export interface StagedMedia {
6
+ data: Uint8Array
7
+ name: string
8
+ mime?: string | undefined
9
+ }
10
+
11
+ interface Entry {
12
+ media: StagedMedia
13
+ bytes: number
14
+ expiresAt: number
15
+ }
16
+
17
+ /**
18
+ * Bounded in-memory staging for outbound media.
19
+ *
20
+ * Telegram has no standalone upload endpoint: bytes must ride the `sendPhoto`
21
+ * / `sendMediaGroup` multipart request. `upload` fetches and stages them, and
22
+ * `sendPayload` reads them back by key. Entries expire and the whole store is
23
+ * bounded, so a long-lived bot cannot grow without limit; a retried send still
24
+ * finds its bytes until the TTL elapses.
25
+ */
26
+ export class MediaStaging {
27
+ private readonly entries = new Map<string, Entry>()
28
+ private bytes = 0
29
+
30
+ constructor(
31
+ private readonly ttlMs: number,
32
+ private readonly maxBytes: number,
33
+ ) {}
34
+
35
+ /**
36
+ * Stage bytes under a fresh opaque key.
37
+ * @param media - the bytes and their display name.
38
+ * @returns the resource key `prepare` hands to `serialize`.
39
+ */
40
+ stage(media: StagedMedia): ResolvedResource {
41
+ const now = Date.now()
42
+ this.prune(now)
43
+ const key = `tg-media:${randomUUID()}`
44
+ const bytes = media.data.byteLength
45
+ this.entries.set(key, { media, bytes, expiresAt: now + this.ttlMs })
46
+ this.bytes += bytes
47
+ this.evict(now)
48
+ return { key, expiresAt: now + this.ttlMs }
49
+ }
50
+
51
+ /**
52
+ * Read staged bytes back.
53
+ * @param key - a key returned by {@link stage}.
54
+ * @returns the staged media, or undefined once expired or evicted.
55
+ */
56
+ get(key: string): StagedMedia | undefined {
57
+ this.prune(Date.now())
58
+ return this.entries.get(key)?.media
59
+ }
60
+
61
+ private prune(now: number): void {
62
+ for (const [key, entry] of this.entries) {
63
+ if (entry.expiresAt > now) continue
64
+ this.entries.delete(key)
65
+ this.bytes -= entry.bytes
66
+ }
67
+ }
68
+
69
+ private evict(now: number): void {
70
+ while (this.bytes > this.maxBytes) {
71
+ const oldest = this.entries.keys().next()
72
+ if (oldest.done === true) return
73
+ const entry = this.entries.get(oldest.value)
74
+ this.entries.delete(oldest.value)
75
+ if (entry !== undefined) this.bytes -= entry.bytes
76
+ }
77
+ this.prune(now)
78
+ }
79
+ }