@operad-io/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/README.md +75 -2
- package/package.json +26 -4
- package/src/api.ts +359 -0
- package/src/format.ts +169 -0
- package/src/index.ts +56 -0
- package/src/pending.ts +483 -0
- package/src/replies.ts +250 -0
- package/src/settings.ts +56 -0
- package/src/source.ts +275 -0
- package/src/state.ts +205 -0
- package/telegram.schema.json +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yinghai Zhao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @operad-io/telegram
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Telegram plugin: the first channel and the first outside source.
|
|
4
|
+
|
|
5
|
+
It is an optional plugin. `operad plugin enable telegram` adds it to the home's
|
|
6
|
+
`config.json`, and `operad serve` starts it.
|
|
7
|
+
|
|
8
|
+
```json
|
|
9
|
+
{
|
|
10
|
+
"plugins": {
|
|
11
|
+
"telegram": {
|
|
12
|
+
"settings": {
|
|
13
|
+
"users": [123456789],
|
|
14
|
+
"bot": "default",
|
|
15
|
+
"pending": []
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
| key | default | meaning |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `users` | `[]` | The Telegram user ids whose private messages become chat messages. A message from anyone else, and every group message, is recorded and starts nothing. |
|
|
25
|
+
| `bot` | `"default"` | The bot a chat is opened on when a listed user writes first. |
|
|
26
|
+
| `pending` | `[]` | The plugins whose pending items are also sent to Telegram. Items of a chat bound to Telegram are always sent. |
|
|
27
|
+
|
|
28
|
+
The Bot API token is the plugin's secret:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
operad secret set telegram token
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The token never reaches a fact, a log line or an error.
|
|
35
|
+
|
|
36
|
+
A listed user's first private message opens a chat on the configured bot and
|
|
37
|
+
binds it through the chat's `channels` (`telegram:<Telegram chat id>`); later
|
|
38
|
+
messages go to the same chat. A closed chat is replaced on the next message. One
|
|
39
|
+
user's messages never land in another user's chat.
|
|
40
|
+
|
|
41
|
+
The long-poll offset lives in `<home>/telegram/state.json`. Dedupe does not rely
|
|
42
|
+
on it: each update is recorded once as a `telegram` event keyed by its
|
|
43
|
+
`update_id`, and a message is written only when the bound chat holds no message
|
|
44
|
+
whose source ref is that update id. A killed `operad serve` that starts again
|
|
45
|
+
reads the same update without writing a second message or starting a second
|
|
46
|
+
reply.
|
|
47
|
+
|
|
48
|
+
Each new assistant reply of a chat bound to Telegram is sent to that Telegram
|
|
49
|
+
chat once. Markdown is reduced to what Telegram accepts (bold, italic, code,
|
|
50
|
+
links; headings and lists become plain lines) and a long reply goes out as
|
|
51
|
+
several messages. A failed send is retried with growing waits; when it gives up,
|
|
52
|
+
the plugin records a `telegram/send_failed` event for the chat (in the run log's
|
|
53
|
+
inputs) and writes a line in its own log; the chat's messages are not touched.
|
|
54
|
+
The event does **not** show in `operad history` of the chat or in the chat's History
|
|
55
|
+
section: those list only the chat's runs and the actions people ran on it, and read
|
|
56
|
+
no source event. Showing it there needs a kernel change. What was sent is kept in `<home>/telegram/sent.json`,
|
|
57
|
+
so a restart neither resends a reply nor skips one written while it was down.
|
|
58
|
+
Replies from before the plugin first ran are not sent. Tool calls are not sent.
|
|
59
|
+
|
|
60
|
+
## What waits for a person
|
|
61
|
+
|
|
62
|
+
An item waiting in a chat bound to Telegram goes to that Telegram chat. An item
|
|
63
|
+
of a plugin listed in the `pending` setting goes to every user in `users`.
|
|
64
|
+
Nothing else is sent, so `dev`'s items stay out until `pending` lists `dev`.
|
|
65
|
+
Each item is one message with one button per option. An action that needs a
|
|
66
|
+
note (such as reject) has no button: reply to the item's message and the reply
|
|
67
|
+
is the note (with several such actions, begin the reply with `reject:`). A
|
|
68
|
+
question with no choices is answered the same way, by replying; text that is not
|
|
69
|
+
a reply stays an ordinary chat message. Only a listed user's tap or reply
|
|
70
|
+
counts, and it is given through the client API with the actor
|
|
71
|
+
`{ via: "telegram", id }`. A tap on a button whose action asks to confirm counts
|
|
72
|
+
as the confirmation. After an answer from anywhere the buttons go and the
|
|
73
|
+
message ends "answered: X", X being the action or choice; a tap on an item
|
|
74
|
+
already answered says so and changes nothing. Where an item was answered
|
|
75
|
+
somewhere else and no action shows what it was, the message ends "answered".
|
|
76
|
+
What was sent is kept in `<home>/telegram/pending.json`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/telegram",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/chat": "0.1.0",
|
|
10
|
+
"@operad-io/engine": "0.1.0"
|
|
11
|
+
},
|
|
12
|
+
"description": "operad: the Telegram plugin, a channel and an outside source",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/operad-io/operad.git",
|
|
16
|
+
"directory": "packages/telegram"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"telegram.schema.json",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@operad-io/dev": "0.1.0"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Bot API calls the source makes, behind a small interface so a test gives
|
|
3
|
+
* it a fake. Only `getUpdates` is needed here; the token reaches no log, fact
|
|
4
|
+
* or error.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { isRecord, messageOf, type Secret } from "@operad-io/engine";
|
|
8
|
+
|
|
9
|
+
/** Who sent a Telegram message. */
|
|
10
|
+
export interface TelegramUser {
|
|
11
|
+
readonly id: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The chat a Telegram message is in. */
|
|
15
|
+
export interface TelegramChat {
|
|
16
|
+
readonly id: number;
|
|
17
|
+
/** `private`, `group`, `supergroup` or `channel`. */
|
|
18
|
+
readonly type: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One Telegram message, as far as the source reads it. */
|
|
22
|
+
export interface TelegramMessage {
|
|
23
|
+
readonly message_id: number;
|
|
24
|
+
readonly date: number;
|
|
25
|
+
readonly chat: TelegramChat;
|
|
26
|
+
readonly from?: TelegramUser | undefined;
|
|
27
|
+
readonly text?: string | undefined;
|
|
28
|
+
readonly caption?: string | undefined;
|
|
29
|
+
/** The message this one replies to, when it is a reply. */
|
|
30
|
+
readonly reply_to_message?: { readonly message_id: number } | undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A tap on an inline-keyboard button. */
|
|
34
|
+
export interface TelegramCallback {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly from: TelegramUser;
|
|
37
|
+
/** The message the button was on; absent for a message too old to carry it. */
|
|
38
|
+
readonly message?: { readonly message_id: number; readonly chat: TelegramChat } | undefined;
|
|
39
|
+
readonly data?: string | undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One update from `getUpdates`. */
|
|
43
|
+
export interface TelegramUpdate {
|
|
44
|
+
readonly update_id: number;
|
|
45
|
+
readonly message?: TelegramMessage | undefined;
|
|
46
|
+
readonly callback_query?: TelegramCallback | undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One long-poll request. */
|
|
50
|
+
export interface GetUpdatesRequest {
|
|
51
|
+
/** The first update id to ask for. */
|
|
52
|
+
readonly offset: number;
|
|
53
|
+
/** How long Telegram may hold the request open. */
|
|
54
|
+
readonly timeoutSecs: number;
|
|
55
|
+
readonly signal?: AbortSignal | undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One message to send. */
|
|
59
|
+
export interface SendMessageRequest {
|
|
60
|
+
readonly chatId: number;
|
|
61
|
+
readonly text: string;
|
|
62
|
+
/** `HTML` when the text is already Telegram HTML; absent for plain text. */
|
|
63
|
+
readonly parseMode?: "HTML" | undefined;
|
|
64
|
+
/** An inline keyboard: rows of buttons, each carrying the data a tap returns. */
|
|
65
|
+
readonly keyboard?: readonly (readonly InlineButton[])[] | undefined;
|
|
66
|
+
readonly signal?: AbortSignal | undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One inline-keyboard button. */
|
|
70
|
+
export interface InlineButton {
|
|
71
|
+
readonly text: string;
|
|
72
|
+
/** What `callback_query.data` carries when the button is tapped; at most 64 bytes. */
|
|
73
|
+
readonly data: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A message's new text; its inline keyboard goes. */
|
|
77
|
+
export interface EditMessageRequest {
|
|
78
|
+
readonly chatId: number;
|
|
79
|
+
readonly messageId: number;
|
|
80
|
+
readonly text: string;
|
|
81
|
+
readonly signal?: AbortSignal | undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The answer to a button tap, shown to the person who tapped. */
|
|
85
|
+
export interface AnswerCallbackRequest {
|
|
86
|
+
readonly callbackId: string;
|
|
87
|
+
readonly text?: string | undefined;
|
|
88
|
+
readonly signal?: AbortSignal | undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Why a Bot API call failed, and whether trying again can help. */
|
|
92
|
+
export class BotApiError extends Error {
|
|
93
|
+
/** False for a refusal that will not change (a bad request, a blocked bot). */
|
|
94
|
+
readonly retryable: boolean;
|
|
95
|
+
/** How long Telegram asked to wait, in seconds, when it said. */
|
|
96
|
+
readonly retryAfterSecs?: number | undefined;
|
|
97
|
+
/** Telegram could not read the markup of the text. */
|
|
98
|
+
readonly badMarkup: boolean;
|
|
99
|
+
|
|
100
|
+
constructor(
|
|
101
|
+
message: string,
|
|
102
|
+
options: { retryable: boolean; retryAfterSecs?: number | undefined; badMarkup?: boolean },
|
|
103
|
+
) {
|
|
104
|
+
super(message);
|
|
105
|
+
this.name = "BotApiError";
|
|
106
|
+
this.retryable = options.retryable;
|
|
107
|
+
this.retryAfterSecs = options.retryAfterSecs;
|
|
108
|
+
this.badMarkup = options.badMarkup === true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** What the plugin needs of Telegram. */
|
|
113
|
+
export interface BotApi {
|
|
114
|
+
getUpdates(request: GetUpdatesRequest): Promise<readonly TelegramUpdate[]>;
|
|
115
|
+
/** Sends one text message; returns its Telegram `message_id`. */
|
|
116
|
+
sendMessage(request: SendMessageRequest): Promise<number>;
|
|
117
|
+
/** Replaces a message's text and removes its inline keyboard. */
|
|
118
|
+
editMessage(request: EditMessageRequest): Promise<void>;
|
|
119
|
+
/** Tells Telegram the tap was seen, with a short note for the person. */
|
|
120
|
+
answerCallback(request: AnswerCallbackRequest): Promise<void>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface BotApiOptions {
|
|
124
|
+
readonly token: Secret<string>;
|
|
125
|
+
/** The API origin; a test may point it at a local fake. */
|
|
126
|
+
readonly baseUrl?: string | undefined;
|
|
127
|
+
/** The request function; a test gives a fake that never reaches the network. */
|
|
128
|
+
readonly fetch?: ((url: string, init?: RequestInit) => Promise<Response>) | undefined;
|
|
129
|
+
/** How long a send, edit or answer may take before it counts as failed; 30 seconds by default. */
|
|
130
|
+
readonly sendTimeoutMs?: number | undefined;
|
|
131
|
+
/** Makes the signal that ends a send after its time; a test gives one it aborts itself. */
|
|
132
|
+
readonly timeoutSignal?: ((ms: number) => AbortSignal) | undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Hides the token from anything a caller may log or throw. */
|
|
136
|
+
export function redactToken(text: string, token: string): string {
|
|
137
|
+
return token.length === 0 ? text : text.split(token).join("[redacted]");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function failure(detail: string | undefined, token: string): Error {
|
|
141
|
+
const suffix = detail === undefined || detail.length === 0 ? "" : `: ${redactToken(detail, token)}`;
|
|
142
|
+
return new Error(`the Telegram Bot API did not answer the update request${suffix}`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function sendFailure(
|
|
146
|
+
detail: string,
|
|
147
|
+
token: string,
|
|
148
|
+
options: { retryable: boolean; retryAfterSecs?: number | undefined; badMarkup?: boolean },
|
|
149
|
+
): BotApiError {
|
|
150
|
+
return new BotApiError(
|
|
151
|
+
`the Telegram Bot API did not send the message: ${redactToken(detail, token)}`,
|
|
152
|
+
options,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function callbackOf(value: unknown): TelegramCallback | undefined {
|
|
157
|
+
if (!isRecord(value) || typeof value.id !== "string" || !isRecord(value.from) || typeof value.from.id !== "number") {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
const message = value.message;
|
|
161
|
+
const chat = isRecord(message) ? message.chat : undefined;
|
|
162
|
+
return {
|
|
163
|
+
id: value.id,
|
|
164
|
+
from: { id: value.from.id },
|
|
165
|
+
...(isRecord(message) &&
|
|
166
|
+
typeof message.message_id === "number" &&
|
|
167
|
+
isRecord(chat) &&
|
|
168
|
+
typeof chat.id === "number" &&
|
|
169
|
+
typeof chat.type === "string"
|
|
170
|
+
? { message: { message_id: message.message_id, chat: { id: chat.id, type: chat.type } } }
|
|
171
|
+
: {}),
|
|
172
|
+
...(typeof value.data === "string" ? { data: value.data } : {}),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function updateOf(value: unknown): TelegramUpdate | undefined {
|
|
177
|
+
if (!isRecord(value) || typeof value.update_id !== "number" || !Number.isInteger(value.update_id)) {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
const callback = callbackOf(value.callback_query);
|
|
181
|
+
if (callback !== undefined) return { update_id: value.update_id, callback_query: callback };
|
|
182
|
+
const message = value.message;
|
|
183
|
+
if (!isRecord(message)) return { update_id: value.update_id };
|
|
184
|
+
const chat = message.chat;
|
|
185
|
+
if (
|
|
186
|
+
typeof message.message_id !== "number" ||
|
|
187
|
+
typeof message.date !== "number" ||
|
|
188
|
+
!isRecord(chat) ||
|
|
189
|
+
typeof chat.id !== "number" ||
|
|
190
|
+
typeof chat.type !== "string"
|
|
191
|
+
) {
|
|
192
|
+
return { update_id: value.update_id };
|
|
193
|
+
}
|
|
194
|
+
const from = message.from;
|
|
195
|
+
return {
|
|
196
|
+
update_id: value.update_id,
|
|
197
|
+
message: {
|
|
198
|
+
message_id: message.message_id,
|
|
199
|
+
date: message.date,
|
|
200
|
+
chat: { id: chat.id, type: chat.type },
|
|
201
|
+
...(isRecord(from) && typeof from.id === "number" ? { from: { id: from.id } } : {}),
|
|
202
|
+
...(typeof message.text === "string" ? { text: message.text } : {}),
|
|
203
|
+
...(typeof message.caption === "string" ? { caption: message.caption } : {}),
|
|
204
|
+
...(isRecord(message.reply_to_message) && typeof message.reply_to_message.message_id === "number"
|
|
205
|
+
? { reply_to_message: { message_id: message.reply_to_message.message_id } }
|
|
206
|
+
: {}),
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The Bot API over `fetch`; no runtime package is needed. */
|
|
212
|
+
export function createBotApi(options: BotApiOptions): BotApi {
|
|
213
|
+
const token = options.token.reveal();
|
|
214
|
+
const origin = options.baseUrl ?? "https://api.telegram.org";
|
|
215
|
+
const request = options.fetch ?? fetch;
|
|
216
|
+
const sendTimeoutMs = options.sendTimeoutMs ?? 30_000;
|
|
217
|
+
/** The caller's signal joined with the send's own time limit. */
|
|
218
|
+
const limited = (signal: AbortSignal | undefined): AbortSignal => {
|
|
219
|
+
const timeout = (options.timeoutSignal ?? AbortSignal.timeout.bind(AbortSignal))(sendTimeoutMs);
|
|
220
|
+
return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
|
|
221
|
+
};
|
|
222
|
+
/** One Bot API call whose result nobody reads. */
|
|
223
|
+
const post = async (method: string, payload: Record<string, unknown>, signal?: AbortSignal): Promise<void> => {
|
|
224
|
+
let response: Response;
|
|
225
|
+
try {
|
|
226
|
+
response = await request(`${origin}/bot${token}/${method}`, {
|
|
227
|
+
method: "POST",
|
|
228
|
+
headers: { "content-type": "application/json" },
|
|
229
|
+
body: JSON.stringify(payload),
|
|
230
|
+
signal: limited(signal),
|
|
231
|
+
});
|
|
232
|
+
} catch (error) {
|
|
233
|
+
throw sendFailure(messageOf(error), token, { retryable: true });
|
|
234
|
+
}
|
|
235
|
+
let body: unknown;
|
|
236
|
+
try {
|
|
237
|
+
body = await response.json();
|
|
238
|
+
} catch {
|
|
239
|
+
throw sendFailure(`HTTP ${response.status} with no JSON`, token, {
|
|
240
|
+
retryable: response.status >= 500 || response.status === 429,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
if (isRecord(body) && body.ok === true) return;
|
|
244
|
+
const description =
|
|
245
|
+
isRecord(body) && typeof body.description === "string" ? body.description : `HTTP ${response.status}`;
|
|
246
|
+
throw sendFailure(description, token, { retryable: response.status === 429 || response.status >= 500 });
|
|
247
|
+
};
|
|
248
|
+
return {
|
|
249
|
+
async editMessage(input) {
|
|
250
|
+
await post(
|
|
251
|
+
"editMessageText",
|
|
252
|
+
{
|
|
253
|
+
chat_id: input.chatId,
|
|
254
|
+
message_id: input.messageId,
|
|
255
|
+
text: input.text,
|
|
256
|
+
reply_markup: { inline_keyboard: [] },
|
|
257
|
+
link_preview_options: { is_disabled: true },
|
|
258
|
+
},
|
|
259
|
+
input.signal,
|
|
260
|
+
);
|
|
261
|
+
},
|
|
262
|
+
async answerCallback(input) {
|
|
263
|
+
await post(
|
|
264
|
+
"answerCallbackQuery",
|
|
265
|
+
{
|
|
266
|
+
callback_query_id: input.callbackId,
|
|
267
|
+
...(input.text === undefined ? {} : { text: input.text }),
|
|
268
|
+
},
|
|
269
|
+
input.signal,
|
|
270
|
+
);
|
|
271
|
+
},
|
|
272
|
+
async getUpdates(input) {
|
|
273
|
+
const query = new URLSearchParams({
|
|
274
|
+
offset: String(input.offset),
|
|
275
|
+
timeout: String(input.timeoutSecs),
|
|
276
|
+
allowed_updates: JSON.stringify(["message", "callback_query"]),
|
|
277
|
+
});
|
|
278
|
+
const url = `${origin}/bot${token}/getUpdates?${query.toString()}`;
|
|
279
|
+
let response: Response;
|
|
280
|
+
try {
|
|
281
|
+
response = await request(url, {
|
|
282
|
+
method: "GET",
|
|
283
|
+
...(input.signal === undefined ? {} : { signal: input.signal }),
|
|
284
|
+
});
|
|
285
|
+
} catch (error) {
|
|
286
|
+
throw failure(messageOf(error), token);
|
|
287
|
+
}
|
|
288
|
+
let body: unknown;
|
|
289
|
+
try {
|
|
290
|
+
body = await response.json();
|
|
291
|
+
} catch {
|
|
292
|
+
throw failure(`HTTP ${response.status} with no JSON`, token);
|
|
293
|
+
}
|
|
294
|
+
if (!isRecord(body) || body.ok !== true) {
|
|
295
|
+
const description = isRecord(body) && typeof body.description === "string" ? body.description : undefined;
|
|
296
|
+
throw failure(description ?? `HTTP ${response.status}`, token);
|
|
297
|
+
}
|
|
298
|
+
if (!Array.isArray(body.result)) {
|
|
299
|
+
throw failure("the result is not an array of updates", token);
|
|
300
|
+
}
|
|
301
|
+
const updates: TelegramUpdate[] = [];
|
|
302
|
+
for (const value of body.result) {
|
|
303
|
+
const update = updateOf(value);
|
|
304
|
+
if (update !== undefined) updates.push(update);
|
|
305
|
+
}
|
|
306
|
+
return updates;
|
|
307
|
+
},
|
|
308
|
+
async sendMessage(input) {
|
|
309
|
+
const url = `${origin}/bot${token}/sendMessage`;
|
|
310
|
+
const payload = {
|
|
311
|
+
chat_id: input.chatId,
|
|
312
|
+
text: input.text,
|
|
313
|
+
...(input.parseMode === undefined ? {} : { parse_mode: input.parseMode }),
|
|
314
|
+
...(input.keyboard === undefined
|
|
315
|
+
? {}
|
|
316
|
+
: {
|
|
317
|
+
reply_markup: {
|
|
318
|
+
inline_keyboard: input.keyboard.map((row) =>
|
|
319
|
+
row.map((button) => ({ text: button.text, callback_data: button.data })),
|
|
320
|
+
),
|
|
321
|
+
},
|
|
322
|
+
}),
|
|
323
|
+
link_preview_options: { is_disabled: true },
|
|
324
|
+
};
|
|
325
|
+
let response: Response;
|
|
326
|
+
try {
|
|
327
|
+
response = await request(url, {
|
|
328
|
+
method: "POST",
|
|
329
|
+
headers: { "content-type": "application/json" },
|
|
330
|
+
body: JSON.stringify(payload),
|
|
331
|
+
signal: limited(input.signal),
|
|
332
|
+
});
|
|
333
|
+
} catch (error) {
|
|
334
|
+
throw sendFailure(messageOf(error), token, { retryable: true });
|
|
335
|
+
}
|
|
336
|
+
let body: unknown;
|
|
337
|
+
try {
|
|
338
|
+
body = await response.json();
|
|
339
|
+
} catch {
|
|
340
|
+
throw sendFailure(`HTTP ${response.status} with no JSON`, token, {
|
|
341
|
+
retryable: response.status >= 500 || response.status === 429,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
if (isRecord(body) && body.ok === true && isRecord(body.result) && typeof body.result.message_id === "number") {
|
|
345
|
+
return body.result.message_id;
|
|
346
|
+
}
|
|
347
|
+
const description =
|
|
348
|
+
isRecord(body) && typeof body.description === "string" ? body.description : `HTTP ${response.status}`;
|
|
349
|
+
const parameters = isRecord(body) && isRecord(body.parameters) ? body.parameters : undefined;
|
|
350
|
+
const retryAfter =
|
|
351
|
+
parameters !== undefined && typeof parameters.retry_after === "number" ? parameters.retry_after : undefined;
|
|
352
|
+
throw sendFailure(description, token, {
|
|
353
|
+
retryable: response.status === 429 || response.status >= 500,
|
|
354
|
+
retryAfterSecs: retryAfter,
|
|
355
|
+
badMarkup: response.status === 400 && /can't parse entities/i.test(description),
|
|
356
|
+
});
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reduces an assistant reply's Markdown to what Telegram accepts, and splits a
|
|
3
|
+
* long reply. Telegram's HTML subset is used because escaping it is mechanical:
|
|
4
|
+
* `b`, `i`, `code`, `pre`, `a`, `blockquote`. Everything else (headings, lists,
|
|
5
|
+
* tables, images, HTML) becomes plain text or one of those.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** The longest text Telegram takes in one message. */
|
|
9
|
+
export const TELEGRAM_MAX_CHARS = 4096;
|
|
10
|
+
|
|
11
|
+
/** The source length a chunk aims at, below the limit so markup has room. */
|
|
12
|
+
const CHUNK_TARGET = 3500;
|
|
13
|
+
|
|
14
|
+
function escapeHtml(text: string): string {
|
|
15
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function escapeAttribute(text: string): string {
|
|
19
|
+
return escapeHtml(text).replace(/"/g, """);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Inline Markdown of one line as Telegram HTML. */
|
|
23
|
+
function inline(text: string): string {
|
|
24
|
+
const parts: string[] = [];
|
|
25
|
+
const hold = (html: string): string => {
|
|
26
|
+
parts.push(html);
|
|
27
|
+
return `\u0000${parts.length - 1}\u0000`;
|
|
28
|
+
};
|
|
29
|
+
let work = text.replace(/`([^`\n]+)`/g, (_m, code: string) => hold(`<code>${escapeHtml(code)}</code>`));
|
|
30
|
+
work = work.replace(/!?\[([^\]\n]*)\]\(([^)\s]+)\)/g, (_m, label: string, url: string) =>
|
|
31
|
+
/^(https?:|tg:|mailto:)/i.test(url)
|
|
32
|
+
? hold(`<a href="${escapeAttribute(url)}">${escapeHtml(label.length === 0 ? url : label)}</a>`)
|
|
33
|
+
: hold(escapeHtml(label.length === 0 ? url : label)),
|
|
34
|
+
);
|
|
35
|
+
work = escapeHtml(work);
|
|
36
|
+
// `__x__` is bold only as a whole word, so `__init__` and `a__b__c` keep their underscores.
|
|
37
|
+
work = work.replace(/\*\*([^*\n]+)\*\*/g, (_m, body: string) => `<b>${body}</b>`);
|
|
38
|
+
work = work.replace(/(^|[^\w])__([^_\n]+)__(?!\w|\.\w)/g, (_m, lead: string, body: string) => `${lead}<b>${body}</b>`);
|
|
39
|
+
work = work.replace(/(^|[\s(])\*([^*\s][^*\n]*)\*(?=$|[\s).,;:!?])/g, (_m, lead: string, body: string) => `${lead}<i>${body}</i>`);
|
|
40
|
+
work = work.replace(/(^|[\s(])_([^_\s][^_\n]*)_(?=$|[\s).,;:!?])/g, (_m, lead: string, body: string) => `${lead}<i>${body}</i>`);
|
|
41
|
+
work = work.replace(/~~([^~\n]+)~~/g, "$1");
|
|
42
|
+
return work.replace(/\u0000(\d+)\u0000/g, (_m, index: string) => parts[Number(index)] ?? "");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const FENCE = /^\s{0,3}(```+|~~~+)\s*([^`\s]*)\s*$/;
|
|
46
|
+
|
|
47
|
+
function isHighSurrogate(code: number): boolean {
|
|
48
|
+
return code >= 0xd800 && code <= 0xdbff;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether a fence line closes the fence opened with `marker`. */
|
|
52
|
+
function closesFence(match: RegExpExecArray, marker: string | undefined): boolean {
|
|
53
|
+
const open = marker ?? "```";
|
|
54
|
+
return match[1]?.[0] === open[0] && (match[1]?.length ?? 0) >= open.length && (match[2] ?? "") === "";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Telegram HTML for one chunk of Markdown. */
|
|
58
|
+
export function markdownToTelegramHtml(markdown: string): string {
|
|
59
|
+
const out: string[] = [];
|
|
60
|
+
let fence: { readonly marker: string; readonly lines: string[] } | undefined;
|
|
61
|
+
for (const line of markdown.split(/\r?\n/)) {
|
|
62
|
+
const match = FENCE.exec(line);
|
|
63
|
+
if (fence !== undefined) {
|
|
64
|
+
if (match !== null && closesFence(match, fence.marker)) {
|
|
65
|
+
out.push(`<pre><code>${escapeHtml(fence.lines.join("\n"))}</code></pre>`);
|
|
66
|
+
fence = undefined;
|
|
67
|
+
} else {
|
|
68
|
+
fence.lines.push(line);
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (match !== null) {
|
|
73
|
+
fence = { marker: match[1] ?? "```", lines: [] };
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const heading = /^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$/.exec(line);
|
|
77
|
+
if (heading !== null) {
|
|
78
|
+
out.push(`<b>${inline(heading[1] ?? "")}</b>`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
|
|
82
|
+
out.push("――――");
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const item = /^(\s*)[-*+]\s+(.*)$/.exec(line);
|
|
86
|
+
if (item !== null) {
|
|
87
|
+
out.push(`${item[1] ?? ""}• ${inline(item[2] ?? "")}`);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const quote = /^\s{0,3}>\s?(.*)$/.exec(line);
|
|
91
|
+
if (quote !== null) {
|
|
92
|
+
out.push(`▎${inline(quote[1] ?? "")}`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
out.push(inline(line));
|
|
96
|
+
}
|
|
97
|
+
if (fence !== undefined) out.push(`<pre><code>${escapeHtml(fence.lines.join("\n"))}</code></pre>`);
|
|
98
|
+
return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Splits Markdown into pieces of at most `limit` characters, never inside a fence without closing it. */
|
|
102
|
+
export function splitMarkdown(markdown: string, limit: number): string[] {
|
|
103
|
+
const chunks: string[] = [];
|
|
104
|
+
let current: string[] = [];
|
|
105
|
+
let size = 0;
|
|
106
|
+
let fence: string | undefined;
|
|
107
|
+
let marker: string | undefined;
|
|
108
|
+
const flush = (): void => {
|
|
109
|
+
if (current.length === 0) return;
|
|
110
|
+
const body = current.join("\n");
|
|
111
|
+
chunks.push(fence === undefined ? body : `${body}\n\`\`\``);
|
|
112
|
+
current = fence === undefined ? [] : [fence];
|
|
113
|
+
size = fence === undefined ? 0 : fence.length + 1;
|
|
114
|
+
};
|
|
115
|
+
for (const original of markdown.split(/\r?\n/)) {
|
|
116
|
+
// A line longer than the limit is cut; the cut ignores word boundaries.
|
|
117
|
+
const pieces: string[] = [];
|
|
118
|
+
const width = limit - 8;
|
|
119
|
+
for (let at = 0; at < Math.max(original.length, 1); ) {
|
|
120
|
+
let end = Math.min(at + width, original.length);
|
|
121
|
+
// Never cut between the two halves of a surrogate pair.
|
|
122
|
+
if (end < original.length && isHighSurrogate(original.charCodeAt(end - 1)) && end - 1 > at) end -= 1;
|
|
123
|
+
pieces.push(original.slice(at, end));
|
|
124
|
+
at = Math.max(end, at + 1);
|
|
125
|
+
}
|
|
126
|
+
for (const line of pieces) {
|
|
127
|
+
if (size + line.length + 1 > limit - 4 && current.length > 0 && !(current.length === 1 && fence !== undefined)) flush();
|
|
128
|
+
current.push(line);
|
|
129
|
+
size += line.length + 1;
|
|
130
|
+
const match = FENCE.exec(line);
|
|
131
|
+
if (match !== null) {
|
|
132
|
+
// The same rule as `markdownToTelegramHtml`: any fence line opens one,
|
|
133
|
+
// only a bare marker of at least the opening's length closes it.
|
|
134
|
+
if (fence === undefined) {
|
|
135
|
+
fence = line;
|
|
136
|
+
marker = match[1];
|
|
137
|
+
} else if (closesFence(match, marker)) {
|
|
138
|
+
fence = undefined;
|
|
139
|
+
marker = undefined;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (current.length > 0 && !(current.length === 1 && fence !== undefined && chunks.length > 0)) {
|
|
145
|
+
chunks.push(current.join("\n"));
|
|
146
|
+
}
|
|
147
|
+
return chunks.filter((chunk) => chunk.trim().length > 0);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** One message ready to send: the HTML Telegram takes and the Markdown it came from. */
|
|
151
|
+
export interface TelegramChunk {
|
|
152
|
+
readonly html: string;
|
|
153
|
+
/** The Markdown of this piece, sent as plain text if Telegram refuses the HTML. */
|
|
154
|
+
readonly plain: string;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** A reply as the messages to send, each within Telegram's limit. */
|
|
158
|
+
export function telegramChunks(markdown: string, limit = CHUNK_TARGET): readonly TelegramChunk[] {
|
|
159
|
+
const out: TelegramChunk[] = [];
|
|
160
|
+
for (const piece of splitMarkdown(markdown, limit)) {
|
|
161
|
+
const html = markdownToTelegramHtml(piece);
|
|
162
|
+
if (html.length > TELEGRAM_MAX_CHARS && limit > 64) {
|
|
163
|
+
out.push(...telegramChunks(piece, Math.floor(limit / 2)));
|
|
164
|
+
} else if (html.length > 0) {
|
|
165
|
+
out.push({ html, plain: piece.slice(0, TELEGRAM_MAX_CHARS) });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|