@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.
- package/LICENSE +21 -0
- package/cordis.patch.yml +10 -0
- package/lib/index.js +2067 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +70 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +231 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +34 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +41 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +39 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +382 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +33 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +89 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +19 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +34 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +10 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +8 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/media.d.ts +38 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +65 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/html.d.ts +16 -0
- package/lib/types/modes/html.d.ts.map +1 -0
- package/lib/types/modes/html.js +155 -0
- package/lib/types/modes/html.js.map +1 -0
- package/lib/types/modes/plain.d.ts +14 -0
- package/lib/types/modes/plain.d.ts.map +1 -0
- package/lib/types/modes/plain.js +56 -0
- package/lib/types/modes/plain.js.map +1 -0
- package/lib/types/modes/shared.d.ts +140 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +405 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/polling.d.ts +26 -0
- package/lib/types/polling.d.ts.map +1 -0
- package/lib/types/polling.js +149 -0
- package/lib/types/polling.js.map +1 -0
- package/lib/types/request.d.ts +67 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +158 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/secret.d.ts +27 -0
- package/lib/types/secret.d.ts.map +1 -0
- package/lib/types/secret.js +39 -0
- package/lib/types/secret.js.map +1 -0
- package/lib/types/send.d.ts +48 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +326 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types/game.d.ts +102 -0
- package/lib/types/types/game.d.ts.map +1 -0
- package/lib/types/types/game.js +5 -0
- package/lib/types/types/game.js.map +1 -0
- package/lib/types/types/index.d.ts +2751 -0
- package/lib/types/types/index.d.ts.map +1 -0
- package/lib/types/types/index.js +88 -0
- package/lib/types/types/index.js.map +1 -0
- package/lib/types/types/inline.d.ts +796 -0
- package/lib/types/types/inline.d.ts.map +1 -0
- package/lib/types/types/inline.js +4 -0
- package/lib/types/types/inline.js.map +1 -0
- package/lib/types/types/internal.d.ts +32 -0
- package/lib/types/types/internal.d.ts.map +1 -0
- package/lib/types/types/internal.js +30 -0
- package/lib/types/types/internal.js.map +1 -0
- package/lib/types/types/passport.d.ts +229 -0
- package/lib/types/types/passport.d.ts.map +1 -0
- package/lib/types/types/passport.js +3 -0
- package/lib/types/types/passport.js.map +1 -0
- package/lib/types/types/payment.d.ts +285 -0
- package/lib/types/types/payment.d.ts.map +1 -0
- package/lib/types/types/payment.js +6 -0
- package/lib/types/types/payment.js.map +1 -0
- package/lib/types/types/sticker.d.ts +221 -0
- package/lib/types/types/sticker.d.ts.map +1 -0
- package/lib/types/types/sticker.js +11 -0
- package/lib/types/types/sticker.js.map +1 -0
- package/lib/types/types/update.d.ts +97 -0
- package/lib/types/types/update.d.ts.map +1 -0
- package/lib/types/types/update.js +6 -0
- package/lib/types/types/update.js.map +1 -0
- package/lib/types/webhook.d.ts +29 -0
- package/lib/types/webhook.d.ts.map +1 -0
- package/lib/types/webhook.js +129 -0
- package/lib/types/webhook.js.map +1 -0
- package/package.json +61 -3
- package/src/bot.ts +349 -0
- package/src/config.ts +73 -0
- package/src/decode.ts +472 -0
- package/src/errors.ts +103 -0
- package/src/identity.ts +41 -0
- package/src/index.ts +14 -0
- package/src/media.ts +79 -0
- package/src/modes/html.ts +193 -0
- package/src/modes/plain.ts +75 -0
- package/src/modes/shared.ts +505 -0
- package/src/polling.ts +176 -0
- package/src/request.ts +224 -0
- package/src/secret.ts +46 -0
- package/src/send.ts +454 -0
- package/src/types/.eslintrc.yml +2 -0
- package/src/types/game.ts +112 -0
- package/src/types/index.ts +3028 -0
- package/src/types/inline.ts +857 -0
- package/src/types/internal.ts +64 -0
- package/src/types/passport.ts +256 -0
- package/src/types/payment.ts +304 -0
- package/src/types/sticker.ts +244 -0
- package/src/types/update.ts +107 -0
- package/src/webhook.ts +168 -0
- package/README.md +0 -3
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type LimitViolation,
|
|
3
|
+
type ModeTypes,
|
|
4
|
+
type Prepared,
|
|
5
|
+
type RenderContext,
|
|
6
|
+
type ResourceKind,
|
|
7
|
+
type ResourceRef,
|
|
8
|
+
type SerializeContext,
|
|
9
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
10
|
+
import { type Element, isPhrasingContainer } from '@deepseek-ai/satori-element'
|
|
11
|
+
import type { InlineKeyboardButton } from '../types/index.ts'
|
|
12
|
+
|
|
13
|
+
/** Media kinds Telegram's send methods distinguish. */
|
|
14
|
+
export type MediaKind = 'photo' | 'video' | 'audio' | 'animation' | 'document'
|
|
15
|
+
|
|
16
|
+
/** One inline-keyboard button collected from `<button>`. */
|
|
17
|
+
export interface ButtonNode {
|
|
18
|
+
kind: 'link' | 'callback'
|
|
19
|
+
text: string
|
|
20
|
+
url?: string
|
|
21
|
+
data?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One node a mode handler produces. */
|
|
25
|
+
export type TelegramNode =
|
|
26
|
+
| { type: 'text'; html: string }
|
|
27
|
+
| { type: 'media'; ref: ResourceRef; kind: MediaKind }
|
|
28
|
+
| { type: 'button'; button: ButtonNode }
|
|
29
|
+
|
|
30
|
+
/** One platform message before resource resolution. */
|
|
31
|
+
export interface TelegramDraft {
|
|
32
|
+
/** Body of a text message, or the caption of a media message. */
|
|
33
|
+
text: string
|
|
34
|
+
media: { ref: ResourceRef; kind: MediaKind }[]
|
|
35
|
+
buttons: ButtonNode[][]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Exact request data for one platform message. */
|
|
39
|
+
export interface TelegramPayload {
|
|
40
|
+
kind: 'text' | 'media' | 'album'
|
|
41
|
+
chatId: string
|
|
42
|
+
threadId?: number
|
|
43
|
+
replyTo?: number
|
|
44
|
+
parseMode?: 'HTML'
|
|
45
|
+
text?: string
|
|
46
|
+
caption?: string
|
|
47
|
+
media?: { kind: MediaKind; key: string; name: string }[]
|
|
48
|
+
buttons?: InlineKeyboardButton[][]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Mode types of the Telegram html/plain modes. */
|
|
52
|
+
export interface TelegramModeTypes extends ModeTypes {
|
|
53
|
+
node: TelegramNode
|
|
54
|
+
draft: TelegramDraft
|
|
55
|
+
payload: TelegramPayload
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Telegram's documented bounds, shared by both modes. */
|
|
59
|
+
export const TELEGRAM_LIMITS = {
|
|
60
|
+
text: 4_096,
|
|
61
|
+
caption: 1_024,
|
|
62
|
+
parts: 10,
|
|
63
|
+
buttonsPerRow: 5,
|
|
64
|
+
streamIntervalMs: 1_000,
|
|
65
|
+
deleteWindowMs: 48 * 60 * 60 * 1_000,
|
|
66
|
+
} as const
|
|
67
|
+
|
|
68
|
+
/** Map a core resource kind onto the Telegram method family. */
|
|
69
|
+
export function mediaKindOf(kind: ResourceKind): MediaKind {
|
|
70
|
+
switch (kind) {
|
|
71
|
+
case 'image':
|
|
72
|
+
return 'photo'
|
|
73
|
+
case 'audio':
|
|
74
|
+
return 'audio'
|
|
75
|
+
case 'video':
|
|
76
|
+
return 'video'
|
|
77
|
+
case 'file':
|
|
78
|
+
return 'document'
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Elements both modes publish as a platform message of their own. */
|
|
83
|
+
export type MediaTag = 'img' | 'audio' | 'video' | 'file'
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Media element → the node of its own platform message.
|
|
87
|
+
*
|
|
88
|
+
* Telegram has no inline media, and a `parse_mode` message carries no attachment, so media never stays inside a
|
|
89
|
+
* text run. Media that stood in phrasing content (`<p>`, a heading, a link, an inline wrapper) is reported as
|
|
90
|
+
* `moved`: the caller sees the message as text plus an extra media message instead of one block.
|
|
91
|
+
*
|
|
92
|
+
* @param el - one of `img`/`audio`/`video`/`file`.
|
|
93
|
+
* @param ctx - render context of the mode.
|
|
94
|
+
* @returns the media node, to be published after the text run it was found in.
|
|
95
|
+
*/
|
|
96
|
+
export function mediaNode(
|
|
97
|
+
el: Element<MediaTag>,
|
|
98
|
+
ctx: RenderContext<TelegramModeTypes>,
|
|
99
|
+
): TelegramNode {
|
|
100
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1]
|
|
101
|
+
if (parent !== undefined && isPhrasingContainer(parent.type)) {
|
|
102
|
+
ctx.report.moved.push({
|
|
103
|
+
tag: el.type,
|
|
104
|
+
reason: 'telegram-media-split',
|
|
105
|
+
path: ctx.stableId(el),
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
switch (el.type) {
|
|
109
|
+
case 'img':
|
|
110
|
+
return {
|
|
111
|
+
type: 'media',
|
|
112
|
+
ref: ctx.resource('image', el.attrs.src, {}),
|
|
113
|
+
kind: 'photo',
|
|
114
|
+
}
|
|
115
|
+
case 'video':
|
|
116
|
+
return {
|
|
117
|
+
type: 'media',
|
|
118
|
+
ref: ctx.resource('video', el.attrs.src, {}),
|
|
119
|
+
kind: 'video',
|
|
120
|
+
}
|
|
121
|
+
case 'audio':
|
|
122
|
+
return {
|
|
123
|
+
type: 'media',
|
|
124
|
+
ref: ctx.resource('audio', el.attrs.src, {}),
|
|
125
|
+
kind: 'audio',
|
|
126
|
+
}
|
|
127
|
+
case 'file':
|
|
128
|
+
return {
|
|
129
|
+
type: 'media',
|
|
130
|
+
ref: ctx.resource(
|
|
131
|
+
'file',
|
|
132
|
+
el.attrs.src,
|
|
133
|
+
el.attrs.name === undefined ? {} : { name: el.attrs.name },
|
|
134
|
+
),
|
|
135
|
+
kind: 'document',
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Escape character data for `parse_mode: HTML`. */
|
|
141
|
+
export function escapeHtml(text: string): string {
|
|
142
|
+
return text
|
|
143
|
+
.replaceAll('&', '&')
|
|
144
|
+
.replaceAll('<', '<')
|
|
145
|
+
.replaceAll('>', '>')
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Escape one HTML attribute value. */
|
|
149
|
+
export function escapeAttribute(text: string): string {
|
|
150
|
+
return escapeHtml(text).replaceAll('"', '"')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Concatenate the text nodes of a subtree, dropping non-text nodes.
|
|
155
|
+
*
|
|
156
|
+
* Only for a context that holds a label and nothing else (a button caption); content handlers go through
|
|
157
|
+
* {@link textRun} so that a media element reaches `assemble` instead of disappearing.
|
|
158
|
+
*/
|
|
159
|
+
export function inlineText(nodes: readonly TelegramNode[]): string {
|
|
160
|
+
let html = ''
|
|
161
|
+
for (const node of nodes) {
|
|
162
|
+
if (node.type === 'text') html += node.html
|
|
163
|
+
else if (node.type === 'button') html += escapeHtml(node.button.text)
|
|
164
|
+
}
|
|
165
|
+
return html
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** One text run of a platform message and the nodes that cannot ride inside it. */
|
|
169
|
+
export interface TextRun {
|
|
170
|
+
/** Concatenated text HTML, in source order. */
|
|
171
|
+
html: string
|
|
172
|
+
/** Media and buttons, in source order. */
|
|
173
|
+
nodes: TelegramNode[]
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Split rendered children into the text run of one platform message and the nodes Telegram posts on their own.
|
|
178
|
+
*
|
|
179
|
+
* Inline wrappers (`p`, `b`, `a`, `li`, …) use this instead of concatenating text: a media element of the subtree
|
|
180
|
+
* has to reach `assemble`, which turns it into a media message, rather than being dropped from the run.
|
|
181
|
+
*
|
|
182
|
+
* @param nodes - rendered children.
|
|
183
|
+
* @returns the text HTML of the run and the non-text nodes, both in source order.
|
|
184
|
+
*/
|
|
185
|
+
export function textRun(nodes: readonly TelegramNode[]): TextRun {
|
|
186
|
+
let html = ''
|
|
187
|
+
const rest: TelegramNode[] = []
|
|
188
|
+
for (const node of nodes) {
|
|
189
|
+
if (node.type === 'text') html += node.html
|
|
190
|
+
else rest.push(node)
|
|
191
|
+
}
|
|
192
|
+
return { html, nodes: rest }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
interface Token {
|
|
196
|
+
raw: string
|
|
197
|
+
visible: number
|
|
198
|
+
newline: boolean
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Split markup into tags, entities and code points so cuts never break a tag. */
|
|
202
|
+
function tokenize(html: string): Token[] {
|
|
203
|
+
const tokens: Token[] = []
|
|
204
|
+
let i = 0
|
|
205
|
+
while (i < html.length) {
|
|
206
|
+
const char = html[i]!
|
|
207
|
+
if (char === '<') {
|
|
208
|
+
const end = html.indexOf('>', i)
|
|
209
|
+
if (end === -1) {
|
|
210
|
+
tokens.push({ raw: html.slice(i), visible: 0, newline: false })
|
|
211
|
+
break
|
|
212
|
+
}
|
|
213
|
+
tokens.push({ raw: html.slice(i, end + 1), visible: 0, newline: false })
|
|
214
|
+
i = end + 1
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
if (char === '&') {
|
|
218
|
+
const end = html.indexOf(';', i)
|
|
219
|
+
if (end !== -1 && end - i <= 10) {
|
|
220
|
+
tokens.push({ raw: html.slice(i, end + 1), visible: 1, newline: false })
|
|
221
|
+
i = end + 1
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const codePoint = html.codePointAt(i)!
|
|
226
|
+
const raw = String.fromCodePoint(codePoint)
|
|
227
|
+
tokens.push({ raw, visible: 1, newline: raw === '\n' })
|
|
228
|
+
i += raw.length
|
|
229
|
+
}
|
|
230
|
+
return tokens
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Visible (after entity parsing) length of rendered HTML. */
|
|
234
|
+
export function visibleLength(html: string): number {
|
|
235
|
+
let length = 0
|
|
236
|
+
for (const token of tokenize(html)) length += token.visible
|
|
237
|
+
return length
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Tag name of an opening tag, or undefined for a closing/self-closing tag. */
|
|
241
|
+
function openTagName(raw: string): string | undefined {
|
|
242
|
+
if (!raw.startsWith('<') || raw.startsWith('</') || raw.startsWith('<!'))
|
|
243
|
+
return undefined
|
|
244
|
+
const name = /^<([a-zA-Z][\w-]*)/.exec(raw)?.[1]
|
|
245
|
+
return name?.toLowerCase()
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Split rendered HTML into chunks no longer than `limit` visible characters,
|
|
250
|
+
* closing and reopening inline tags at every cut so each message parses alone.
|
|
251
|
+
*/
|
|
252
|
+
export function splitHtml(html: string, limit: number): string[] {
|
|
253
|
+
if (visibleLength(html) <= limit) return [html]
|
|
254
|
+
const chunks: string[] = []
|
|
255
|
+
let current = ''
|
|
256
|
+
let visible = 0
|
|
257
|
+
const stack: { name: string; open: string }[] = []
|
|
258
|
+
const closeAll = (): string =>
|
|
259
|
+
stack
|
|
260
|
+
.map((tag) => `</${tag.name}>`)
|
|
261
|
+
.reverse()
|
|
262
|
+
.join('')
|
|
263
|
+
const reopenAll = (): string => stack.map((tag) => tag.open).join('')
|
|
264
|
+
|
|
265
|
+
const flush = (): void => {
|
|
266
|
+
if (current === '') return
|
|
267
|
+
chunks.push(current + closeAll())
|
|
268
|
+
current = reopenAll()
|
|
269
|
+
visible = 0
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
for (const token of tokenize(html)) {
|
|
273
|
+
if (token.visible > 0 && visible + token.visible > limit) flush()
|
|
274
|
+
current += token.raw
|
|
275
|
+
visible += token.visible
|
|
276
|
+
const name = openTagName(token.raw)
|
|
277
|
+
if (name !== undefined && !token.raw.endsWith('/>')) {
|
|
278
|
+
stack.push({ name, open: token.raw })
|
|
279
|
+
} else if (token.raw.startsWith('</')) {
|
|
280
|
+
stack.pop()
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (current !== '') chunks.push(current + closeAll())
|
|
284
|
+
return chunks
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Group consecutive media into albums Telegram accepts. */
|
|
288
|
+
function groupMedia(
|
|
289
|
+
items: { ref: ResourceRef; kind: MediaKind }[],
|
|
290
|
+
): { ref: ResourceRef; kind: MediaKind }[][] {
|
|
291
|
+
const groups: { ref: ResourceRef; kind: MediaKind }[][] = []
|
|
292
|
+
for (const item of items) {
|
|
293
|
+
const current = groups[groups.length - 1]
|
|
294
|
+
const mixable = (a: MediaKind, b: MediaKind): boolean => {
|
|
295
|
+
const visual = (kind: MediaKind): boolean =>
|
|
296
|
+
kind === 'photo' || kind === 'video' || kind === 'animation'
|
|
297
|
+
return (visual(a) && visual(b)) || a === b
|
|
298
|
+
}
|
|
299
|
+
if (
|
|
300
|
+
current === undefined ||
|
|
301
|
+
current.length >= TELEGRAM_LIMITS.parts ||
|
|
302
|
+
!current.every((other) => mixable(other.kind, item.kind))
|
|
303
|
+
) {
|
|
304
|
+
groups.push([item])
|
|
305
|
+
} else {
|
|
306
|
+
current.push(item)
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return groups
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Lay buttons into rows of at most five. */
|
|
313
|
+
function layoutButtons(buttons: ButtonNode[]): ButtonNode[][] {
|
|
314
|
+
const rows: ButtonNode[][] = []
|
|
315
|
+
let row: ButtonNode[] = []
|
|
316
|
+
for (const button of buttons) {
|
|
317
|
+
if (row.length >= TELEGRAM_LIMITS.buttonsPerRow) {
|
|
318
|
+
rows.push(row)
|
|
319
|
+
row = []
|
|
320
|
+
}
|
|
321
|
+
row.push(button)
|
|
322
|
+
}
|
|
323
|
+
if (row.length > 0) rows.push(row)
|
|
324
|
+
return rows
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Fold a node stream into platform messages.
|
|
329
|
+
*
|
|
330
|
+
* Text before a media element becomes its caption when it fits; otherwise it
|
|
331
|
+
* stays a text message. Consecutive media are grouped into albums, and all
|
|
332
|
+
* buttons are attached to the last message.
|
|
333
|
+
*/
|
|
334
|
+
export function assembleDraft(nodes: TelegramNode[]): TelegramDraft[] {
|
|
335
|
+
const drafts: TelegramDraft[] = []
|
|
336
|
+
let text = ''
|
|
337
|
+
let media: { ref: ResourceRef; kind: MediaKind }[] = []
|
|
338
|
+
let caption: string | undefined
|
|
339
|
+
let buttons: ButtonNode[] = []
|
|
340
|
+
|
|
341
|
+
const flushText = (): void => {
|
|
342
|
+
const trimmed = text.trim()
|
|
343
|
+
if (trimmed === '') {
|
|
344
|
+
text = ''
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
for (const chunk of splitHtml(trimmed, TELEGRAM_LIMITS.text)) {
|
|
348
|
+
drafts.push({ text: chunk, media: [], buttons: [] })
|
|
349
|
+
}
|
|
350
|
+
text = ''
|
|
351
|
+
}
|
|
352
|
+
const flushMedia = (): void => {
|
|
353
|
+
if (media.length === 0) return
|
|
354
|
+
const groups = groupMedia(media)
|
|
355
|
+
for (const [index, group] of groups.entries()) {
|
|
356
|
+
drafts.push({
|
|
357
|
+
text: index === 0 ? (caption ?? '') : '',
|
|
358
|
+
media: group,
|
|
359
|
+
buttons: [],
|
|
360
|
+
})
|
|
361
|
+
}
|
|
362
|
+
media = []
|
|
363
|
+
caption = undefined
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
for (const node of nodes) {
|
|
367
|
+
switch (node.type) {
|
|
368
|
+
case 'text':
|
|
369
|
+
if (media.length > 0) {
|
|
370
|
+
if (text.trim() !== '') flushText()
|
|
371
|
+
flushMedia()
|
|
372
|
+
}
|
|
373
|
+
text += node.html
|
|
374
|
+
break
|
|
375
|
+
case 'media':
|
|
376
|
+
if (media.length === 0) {
|
|
377
|
+
if (text.trim() !== '') {
|
|
378
|
+
const visible = visibleLength(text.trim())
|
|
379
|
+
if (visible <= TELEGRAM_LIMITS.caption) {
|
|
380
|
+
caption = text.trim()
|
|
381
|
+
text = ''
|
|
382
|
+
} else {
|
|
383
|
+
flushText()
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
media.push({ ref: node.ref, kind: node.kind })
|
|
388
|
+
break
|
|
389
|
+
case 'button':
|
|
390
|
+
buttons.push(node.button)
|
|
391
|
+
break
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
flushMedia()
|
|
395
|
+
flushText()
|
|
396
|
+
|
|
397
|
+
const rows = layoutButtons(buttons)
|
|
398
|
+
if (rows.length > 0) {
|
|
399
|
+
const last = drafts[drafts.length - 1]
|
|
400
|
+
if (last !== undefined) last.buttons = rows
|
|
401
|
+
else drafts.push({ text: '\u2060', media: [], buttons: rows })
|
|
402
|
+
}
|
|
403
|
+
return drafts
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Resolve one media key from `prepared.resolved`. */
|
|
407
|
+
function resolvedKey(
|
|
408
|
+
prepared: Prepared<TelegramDraft>,
|
|
409
|
+
ref: ResourceRef,
|
|
410
|
+
): string {
|
|
411
|
+
const resolved = prepared.resolved.get(ref)
|
|
412
|
+
if (resolved === undefined) {
|
|
413
|
+
throw new Error('telegram: media was not prepared before serialize')
|
|
414
|
+
}
|
|
415
|
+
return resolved.key
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Build the request payload of one draft. */
|
|
419
|
+
export function serializeDraft(
|
|
420
|
+
prepared: Prepared<TelegramDraft>,
|
|
421
|
+
ctx: SerializeContext,
|
|
422
|
+
parseMode: 'HTML' | undefined,
|
|
423
|
+
): TelegramPayload {
|
|
424
|
+
const { draft } = prepared
|
|
425
|
+
const threadId =
|
|
426
|
+
typeof ctx.target.thread === 'string' && /^\d+$/.test(ctx.target.thread)
|
|
427
|
+
? Number(ctx.target.thread)
|
|
428
|
+
: undefined
|
|
429
|
+
// Only the first platform message answers the quoted one: a split message would otherwise repeat the quote on
|
|
430
|
+
// every part. `SerializeContext.quote` reaches every part, so the adapter picks the one that carries it.
|
|
431
|
+
const replyTo =
|
|
432
|
+
ctx.index === 0 && ctx.quote !== undefined && /^\d+$/.test(ctx.quote)
|
|
433
|
+
? Number(ctx.quote)
|
|
434
|
+
: undefined
|
|
435
|
+
const buttons =
|
|
436
|
+
draft.buttons.length === 0
|
|
437
|
+
? undefined
|
|
438
|
+
: draft.buttons.map((row) => row.map(toWireButton))
|
|
439
|
+
|
|
440
|
+
if (draft.media.length === 0) {
|
|
441
|
+
return {
|
|
442
|
+
kind: 'text',
|
|
443
|
+
chatId: ctx.target.chat.id,
|
|
444
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
445
|
+
...(replyTo === undefined ? {} : { replyTo }),
|
|
446
|
+
...(parseMode === undefined ? {} : { parseMode }),
|
|
447
|
+
text: draft.text,
|
|
448
|
+
...(buttons === undefined ? {} : { buttons }),
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const media = draft.media.map((item) => ({
|
|
453
|
+
kind: item.kind,
|
|
454
|
+
key: resolvedKey(prepared, item.ref),
|
|
455
|
+
name: item.ref.meta.name ?? '',
|
|
456
|
+
}))
|
|
457
|
+
return {
|
|
458
|
+
kind: media.length > 1 ? 'album' : 'media',
|
|
459
|
+
chatId: ctx.target.chat.id,
|
|
460
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
461
|
+
...(replyTo === undefined ? {} : { replyTo }),
|
|
462
|
+
...(parseMode === undefined ? {} : { parseMode }),
|
|
463
|
+
...(draft.text.trim() === '' ? {} : { caption: draft.text.trim() }),
|
|
464
|
+
media,
|
|
465
|
+
...(buttons === undefined ? {} : { buttons }),
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Hard platform limits of one draft, checked before any request.
|
|
471
|
+
*
|
|
472
|
+
* Only `callback_data` can fail here. The three other bounds the platform
|
|
473
|
+
* documents are unreachable by construction: `splitHtml` cuts text at
|
|
474
|
+
* `TELEGRAM_LIMITS.text`, `assembleDraft` keeps a caption only when it fits
|
|
475
|
+
* `TELEGRAM_LIMITS.caption` (longer text stays a text message), and
|
|
476
|
+
* `groupMedia` caps an album at `TELEGRAM_LIMITS.parts`.
|
|
477
|
+
*
|
|
478
|
+
* @param draft - the assembled draft.
|
|
479
|
+
* @returns every violation the platform would refuse.
|
|
480
|
+
*/
|
|
481
|
+
export function checkDraft(draft: TelegramDraft): LimitViolation[] {
|
|
482
|
+
const violations: LimitViolation[] = []
|
|
483
|
+
for (const row of draft.buttons) {
|
|
484
|
+
for (const button of row) {
|
|
485
|
+
if (button.kind !== 'callback') continue
|
|
486
|
+
const bytes = Buffer.byteLength(button.data ?? '', 'utf8')
|
|
487
|
+
if (bytes <= 64) continue
|
|
488
|
+
violations.push({
|
|
489
|
+
kind: 'size',
|
|
490
|
+
key: 'limit.payload.bytes',
|
|
491
|
+
limit: 64,
|
|
492
|
+
actual: bytes,
|
|
493
|
+
message: `Telegram callback_data accepts 64 bytes, got ${bytes}`,
|
|
494
|
+
})
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return violations
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Convert one collected button into Telegram's wire shape. */
|
|
501
|
+
function toWireButton(button: ButtonNode): InlineKeyboardButton {
|
|
502
|
+
return button.kind === 'link'
|
|
503
|
+
? { text: button.text, url: button.url ?? '' }
|
|
504
|
+
: { text: button.text, callback_data: button.data ?? '' }
|
|
505
|
+
}
|
package/src/polling.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { Status } from '@deepseek-ai/cordis-plugin-im-core'
|
|
2
|
+
import type { TelegramBot } from './bot.ts'
|
|
3
|
+
import { decodeMessage, decodeUpdate } from './decode.ts'
|
|
4
|
+
import { classifyTelegramError } from './errors.ts'
|
|
5
|
+
import type { Message, Update } from './types/index.ts'
|
|
6
|
+
|
|
7
|
+
/** Update families the adapter consumes */
|
|
8
|
+
export const ALLOWED_UPDATES = ['message', 'callback_query']
|
|
9
|
+
|
|
10
|
+
/** Waitable sleep that resolves early on abort. */
|
|
11
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
if (signal.aborted) {
|
|
14
|
+
resolve()
|
|
15
|
+
return
|
|
16
|
+
}
|
|
17
|
+
const timer = setTimeout(() => {
|
|
18
|
+
signal.removeEventListener('abort', onAbort)
|
|
19
|
+
resolve()
|
|
20
|
+
}, ms)
|
|
21
|
+
const onAbort = (): void => {
|
|
22
|
+
clearTimeout(timer)
|
|
23
|
+
resolve()
|
|
24
|
+
}
|
|
25
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* `getUpdates` long polling.
|
|
31
|
+
*
|
|
32
|
+
* The offset is the next update to fetch. It advances only after
|
|
33
|
+
* `bot.receive` accepted an update, so a crash or a failed intake leaves the
|
|
34
|
+
* update unacknowledged and Telegram redelivers it; the host's event dedupe
|
|
35
|
+
* covers the frames already stored.
|
|
36
|
+
*/
|
|
37
|
+
export class TelegramPolling {
|
|
38
|
+
private controller: AbortController | undefined
|
|
39
|
+
private running: Promise<void> | undefined
|
|
40
|
+
private offset = 0
|
|
41
|
+
|
|
42
|
+
constructor(private readonly bot: TelegramBot) {}
|
|
43
|
+
|
|
44
|
+
/** Register nothing; establish the offset and start the loop. */
|
|
45
|
+
async start(): Promise<void> {
|
|
46
|
+
const { internal, config } = this.bot
|
|
47
|
+
try {
|
|
48
|
+
const info = await internal.getWebhookInfo()
|
|
49
|
+
if (info.url !== '') {
|
|
50
|
+
this.bot.ctx.logger.warn(
|
|
51
|
+
'telegram: removing the existing webhook so polling can receive updates',
|
|
52
|
+
)
|
|
53
|
+
await internal.setWebhook({ url: '' })
|
|
54
|
+
}
|
|
55
|
+
if (config.dropPendingUpdates) {
|
|
56
|
+
const pending = await internal.getUpdates({
|
|
57
|
+
offset: -1,
|
|
58
|
+
limit: 1,
|
|
59
|
+
timeout: 0,
|
|
60
|
+
})
|
|
61
|
+
const highest = pending.reduce(
|
|
62
|
+
(max, update) => Math.max(max, update.update_id!),
|
|
63
|
+
-1,
|
|
64
|
+
)
|
|
65
|
+
this.offset = highest + 1
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
// `Bot.start` only stores a connect failure on `bot.error`, so log it here.
|
|
69
|
+
this.bot.ctx.logger.error(
|
|
70
|
+
'telegram: long polling could not start: %s',
|
|
71
|
+
error instanceof Error ? error.message : String(error),
|
|
72
|
+
)
|
|
73
|
+
throw error
|
|
74
|
+
}
|
|
75
|
+
this.controller = new AbortController()
|
|
76
|
+
this.running = this.loop(this.controller.signal)
|
|
77
|
+
this.bot.online()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Stop polling and wait for the loop to unwind. */
|
|
81
|
+
async stop(): Promise<void> {
|
|
82
|
+
this.controller?.abort()
|
|
83
|
+
this.controller = undefined
|
|
84
|
+
await this.running?.catch(() => undefined)
|
|
85
|
+
this.running = undefined
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private async loop(signal: AbortSignal): Promise<void> {
|
|
89
|
+
const { internal, config } = this.bot
|
|
90
|
+
let failures = 0
|
|
91
|
+
while (!signal.aborted) {
|
|
92
|
+
try {
|
|
93
|
+
const updates = await internal.getUpdates(
|
|
94
|
+
{
|
|
95
|
+
offset: this.offset,
|
|
96
|
+
limit: 100,
|
|
97
|
+
timeout: Math.max(1, Math.ceil(config.polling.timeoutMs / 1_000)),
|
|
98
|
+
allowed_updates: ALLOWED_UPDATES,
|
|
99
|
+
},
|
|
100
|
+
signal,
|
|
101
|
+
)
|
|
102
|
+
failures = 0
|
|
103
|
+
this.bot.online()
|
|
104
|
+
await this.process(updates, signal)
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (signal.aborted) return
|
|
107
|
+
const classified = classifyTelegramError(error)
|
|
108
|
+
this.bot.ctx.logger.warn(
|
|
109
|
+
'telegram: long polling failed: %s',
|
|
110
|
+
classified.message,
|
|
111
|
+
)
|
|
112
|
+
this.bot.status = Status.RECONNECT
|
|
113
|
+
// `retryTimes` is a fast-retry budget, not a give-up limit: after that
|
|
114
|
+
// many consecutive failures the loop keeps retrying at the lazy
|
|
115
|
+
// interval, and a rate-limit answer overrides both intervals.
|
|
116
|
+
const base =
|
|
117
|
+
failures < config.polling.retryTimes
|
|
118
|
+
? config.polling.retryIntervalMs
|
|
119
|
+
: config.polling.retryLazyMs
|
|
120
|
+
await sleep(classified.retryAfterMs ?? base, signal)
|
|
121
|
+
failures += 1
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private async process(
|
|
127
|
+
updates: readonly Update[],
|
|
128
|
+
signal: AbortSignal,
|
|
129
|
+
): Promise<void> {
|
|
130
|
+
let index = 0
|
|
131
|
+
while (index < updates.length) {
|
|
132
|
+
const update = updates[index]!
|
|
133
|
+
const groupId = update.message?.media_group_id
|
|
134
|
+
if (groupId === undefined) {
|
|
135
|
+
await this.publish(update)
|
|
136
|
+
this.offset = update.update_id! + 1
|
|
137
|
+
index += 1
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
const entries: { updateId: number; message: Message }[] = []
|
|
141
|
+
while (index < updates.length) {
|
|
142
|
+
const candidate = updates[index]!
|
|
143
|
+
const message = candidate.message
|
|
144
|
+
if (message === undefined || message.media_group_id !== groupId) break
|
|
145
|
+
entries.push({ updateId: candidate.update_id!, message })
|
|
146
|
+
index += 1
|
|
147
|
+
}
|
|
148
|
+
// One album arrives as several updates in a burst; wait out the window so
|
|
149
|
+
// the parts are published as one message, then confirm them together.
|
|
150
|
+
await sleep(this.bot.config.polling.mediaGroupWindowMs, signal)
|
|
151
|
+
if (signal.aborted) return
|
|
152
|
+
entries.sort((a, b) => a.message.message_id! - b.message.message_id!)
|
|
153
|
+
const inbound = decodeMessage(
|
|
154
|
+
this.bot,
|
|
155
|
+
entries.map((entry) => entry.message),
|
|
156
|
+
)
|
|
157
|
+
await this.bot.receive(
|
|
158
|
+
this.bot.session({
|
|
159
|
+
type: 'message',
|
|
160
|
+
id: inbound.id,
|
|
161
|
+
timestamp: inbound.time,
|
|
162
|
+
message: inbound,
|
|
163
|
+
}),
|
|
164
|
+
)
|
|
165
|
+
this.offset = Math.max(
|
|
166
|
+
this.offset,
|
|
167
|
+
...entries.map((entry) => entry.updateId + 1),
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private async publish(update: Update): Promise<void> {
|
|
173
|
+
const session = decodeUpdate(this.bot, update)
|
|
174
|
+
if (session !== undefined) await this.bot.receive(session)
|
|
175
|
+
}
|
|
176
|
+
}
|