@operad-io/telegram 0.1.1 → 0.2.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/README.md +24 -8
- package/package.json +5 -4
- package/src/api.ts +94 -12
- package/src/commands.ts +489 -0
- package/src/events.ts +131 -0
- package/src/format.ts +26 -0
- package/src/index.ts +62 -7
- package/src/pending.ts +266 -34
- package/src/progress.ts +494 -0
- package/src/replies.ts +76 -34
- package/src/settings.ts +3 -0
- package/src/source.ts +161 -29
- package/src/state.ts +224 -24
- package/src/typing.ts +328 -0
- package/telegram.schema.json +3 -0
package/src/commands.ts
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The command side of the Telegram plugin: the bot's command menu, the
|
|
3
|
+
* choices a command without its one choice offers, and the greeting `/start`
|
|
4
|
+
* gets.
|
|
5
|
+
*
|
|
6
|
+
* The plugin handles no command's text. It registers the menu from the chat's
|
|
7
|
+
* action declarations, sends a command's text through `chat:send` as any other
|
|
8
|
+
* message (ADR 0037 D2), and, when a command that takes one choice arrives
|
|
9
|
+
* without it, shows the choices as an inline keyboard. The tap is passed back
|
|
10
|
+
* as `/<name> <choice>`, so the `chat` plugin remains the only place a command
|
|
11
|
+
* runs. After a tap the keyboard goes and the message ends `chosen: X`, as an
|
|
12
|
+
* answered pending item ends `answered: X`. The one action the plugin declares
|
|
13
|
+
* is `/pending`, which prepares the items the source sends after its count line.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
CHAT_TYPE,
|
|
18
|
+
chatCommands,
|
|
19
|
+
chatData,
|
|
20
|
+
findCommand,
|
|
21
|
+
parseCommand,
|
|
22
|
+
type ChatCommand,
|
|
23
|
+
} from "@operad-io/chat";
|
|
24
|
+
import {
|
|
25
|
+
messageOf,
|
|
26
|
+
type ActionTypeDefinition,
|
|
27
|
+
type SourceContext,
|
|
28
|
+
} from "@operad-io/engine";
|
|
29
|
+
import {
|
|
30
|
+
BotApiError,
|
|
31
|
+
type BotApi,
|
|
32
|
+
type BotCommand,
|
|
33
|
+
type InlineButton,
|
|
34
|
+
type TelegramCallback,
|
|
35
|
+
} from "./api.ts";
|
|
36
|
+
import { TelegramEvents } from "./events.ts";
|
|
37
|
+
import { telegramChunks } from "./format.ts";
|
|
38
|
+
import { telegramSettings, type TelegramSettings } from "./settings.ts";
|
|
39
|
+
import { boundChats, delay } from "./source.ts";
|
|
40
|
+
import {
|
|
41
|
+
pruneCommands,
|
|
42
|
+
readCommands,
|
|
43
|
+
writeCommands,
|
|
44
|
+
type CommandState,
|
|
45
|
+
type SentCommand,
|
|
46
|
+
} from "./state.ts";
|
|
47
|
+
|
|
48
|
+
/** The source of every answer this plugin gives. */
|
|
49
|
+
const VIA = "telegram";
|
|
50
|
+
|
|
51
|
+
/** A name Telegram's menu takes: lowercase letters, digits and underscores, at most 32 characters. */
|
|
52
|
+
export const TELEGRAM_COMMAND_NAME = /^[a-z0-9_]{1,32}$/;
|
|
53
|
+
|
|
54
|
+
/** How many choices one keyboard page shows. */
|
|
55
|
+
export const COMMAND_PAGE_SIZE = 8;
|
|
56
|
+
|
|
57
|
+
/** The most commands Telegram takes in one menu. */
|
|
58
|
+
const MENU_MAX = 100;
|
|
59
|
+
|
|
60
|
+
/** The longest description Telegram takes for one command. */
|
|
61
|
+
const DESCRIPTION_MAX = 256;
|
|
62
|
+
|
|
63
|
+
/** What `/start` answers with. */
|
|
64
|
+
export const START_GREETING =
|
|
65
|
+
"Hello. Write a message to start a chat; /help lists the commands you can type.";
|
|
66
|
+
|
|
67
|
+
/** The name `/pending` is typed by. */
|
|
68
|
+
export const PENDING_COMMAND = "pending";
|
|
69
|
+
|
|
70
|
+
/** What `/pending` says when nothing waits. */
|
|
71
|
+
export const PENDING_NOTHING = "nothing is waiting";
|
|
72
|
+
|
|
73
|
+
/** What the pending side does for `/pending`. */
|
|
74
|
+
export interface PendingCommandSender {
|
|
75
|
+
/** The count line, with the item messages ready for the source's chat. */
|
|
76
|
+
prepare(chatId: string, hold?: boolean): Promise<string>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The action `/pending` runs. It belongs to `telegram`, not `chat`: only the
|
|
81
|
+
* channel can send the item messages with their buttons, and the chat plugin
|
|
82
|
+
* knows no channel (ADR 0026 D1, ADR 0037 D4).
|
|
83
|
+
*/
|
|
84
|
+
export function pendingCommandAction(
|
|
85
|
+
sender: () => PendingCommandSender | undefined,
|
|
86
|
+
): ActionTypeDefinition {
|
|
87
|
+
const unavailable = "the telegram plugin is not running; /pending needs operad serve";
|
|
88
|
+
return {
|
|
89
|
+
name: PENDING_COMMAND,
|
|
90
|
+
on: CHAT_TYPE,
|
|
91
|
+
command: "Show what is waiting for a person now.",
|
|
92
|
+
when: (state) => sender() !== undefined && !chatData(state).closed,
|
|
93
|
+
why: (object) => {
|
|
94
|
+
if (chatData(object.data).closed) return `${object.id} is closed; it takes no commands`;
|
|
95
|
+
return sender() === undefined ? unavailable : undefined;
|
|
96
|
+
},
|
|
97
|
+
async run(ctx) {
|
|
98
|
+
const current = sender();
|
|
99
|
+
if (current === undefined) throw new Error(unavailable);
|
|
100
|
+
// A Telegram command holds the pending pass until the source sent its count.
|
|
101
|
+
return current.prepare(ctx.object.id, ctx.actor.via === "telegram");
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** What the source asks of the command side. */
|
|
107
|
+
export interface CommandResponder {
|
|
108
|
+
/** Sends the greeting when the text is `/start`; true when it was. */
|
|
109
|
+
greet(text: string, target: number): Promise<boolean>;
|
|
110
|
+
/** The command this chat has by this name, or undefined. */
|
|
111
|
+
command(chatId: string, name: string): Promise<ChatCommand | undefined>;
|
|
112
|
+
/** Sends the choices of a command that gives none; true when the keyboard was sent. */
|
|
113
|
+
offer(command: ChatCommand, text: string, chatId: string, target: number): Promise<boolean>;
|
|
114
|
+
/** Sends what a command returned to the Telegram chat. */
|
|
115
|
+
say(target: number, outcome: string): Promise<void>;
|
|
116
|
+
/** A tap on one of the choice keyboards; true when it was one. */
|
|
117
|
+
handleCallback(callback: TelegramCallback): Promise<boolean>;
|
|
118
|
+
/** Registers the menu when the set of commands changed. */
|
|
119
|
+
refresh(chatId?: string): Promise<void>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface CommandSenderOptions {
|
|
123
|
+
readonly api: BotApi;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The text with a bot mention after the command's name taken away, so
|
|
128
|
+
* `/model@operad_bot sonnet` is the same as `/model sonnet`.
|
|
129
|
+
*/
|
|
130
|
+
export function stripBotName(text: string): string {
|
|
131
|
+
return text.replace(/^(\/[A-Za-z0-9_-]+)@[A-Za-z0-9_]+(?=\s|$)/, "$1");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The data a choice button carries: its position in the whole list. */
|
|
135
|
+
function choiceData(index: number): string {
|
|
136
|
+
return `c:${index}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The data a paging button carries: the page it opens. */
|
|
140
|
+
function pageData(page: number): string {
|
|
141
|
+
return `p:${page}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The rows of one page: its choices, then the way to the other pages. */
|
|
145
|
+
function keyboardFor(
|
|
146
|
+
choices: readonly string[],
|
|
147
|
+
page: number,
|
|
148
|
+
): readonly (readonly InlineButton[])[] {
|
|
149
|
+
const start = page * COMMAND_PAGE_SIZE;
|
|
150
|
+
const rows: InlineButton[][] = choices
|
|
151
|
+
.slice(start, start + COMMAND_PAGE_SIZE)
|
|
152
|
+
.map((choice, offset) => [{ text: choice, data: choiceData(start + offset) }]);
|
|
153
|
+
const pages = Math.ceil(choices.length / COMMAND_PAGE_SIZE);
|
|
154
|
+
if (pages > 1) {
|
|
155
|
+
const arrows: InlineButton[] = [];
|
|
156
|
+
if (page > 0) arrows.push({ text: "«", data: pageData(page - 1) });
|
|
157
|
+
if (page + 1 < pages) arrows.push({ text: "»", data: pageData(page + 1) });
|
|
158
|
+
rows.push(arrows);
|
|
159
|
+
}
|
|
160
|
+
return rows;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The one choice a command takes, when that is all it takes; empty otherwise. */
|
|
164
|
+
function choicesOf(command: ChatCommand): readonly string[] {
|
|
165
|
+
const args = command.info.args;
|
|
166
|
+
const names = Object.keys(args?.properties ?? {});
|
|
167
|
+
if (names.length !== 1) return [];
|
|
168
|
+
const name = names[0];
|
|
169
|
+
if (name === undefined || !(args?.required ?? []).includes(name)) return [];
|
|
170
|
+
const property = args?.properties?.[name];
|
|
171
|
+
if (property?.enum === undefined) return [];
|
|
172
|
+
return property.enum.filter(
|
|
173
|
+
(value): value is string => typeof value === "string" && value.length > 0,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The one line the menu shows for a command. */
|
|
178
|
+
function descriptionOf(command: ChatCommand): string {
|
|
179
|
+
const text = (command.info.command ?? "").replace(/\s+/g, " ").trim();
|
|
180
|
+
if (text.length === 0) return command.name;
|
|
181
|
+
return text.length > DESCRIPTION_MAX ? `${text.slice(0, DESCRIPTION_MAX - 1)}…` : text;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The key one keyboard is remembered by. */
|
|
185
|
+
function keyOf(target: number, messageId: number): string {
|
|
186
|
+
return `${target}/${messageId}`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export class CommandSender implements CommandResponder {
|
|
190
|
+
private readonly ctx: SourceContext;
|
|
191
|
+
private readonly api: BotApi;
|
|
192
|
+
private readonly settings: TelegramSettings;
|
|
193
|
+
private readonly controller = new AbortController();
|
|
194
|
+
private state: CommandState;
|
|
195
|
+
private stopped = false;
|
|
196
|
+
private watching: Promise<void> = Promise.resolve();
|
|
197
|
+
private following: { readonly stop: () => Promise<void> } | undefined;
|
|
198
|
+
/** Everything that reads or writes the state runs one at a time. */
|
|
199
|
+
private tail: Promise<unknown> = Promise.resolve();
|
|
200
|
+
private queued = false;
|
|
201
|
+
/** The chat a refresh was last asked about; the newest bound chat when absent. */
|
|
202
|
+
private hint: string | undefined;
|
|
203
|
+
/** The menu last registered, so an unchanged set is not sent again. */
|
|
204
|
+
private registered: string | undefined;
|
|
205
|
+
|
|
206
|
+
constructor(ctx: SourceContext, options: CommandSenderOptions) {
|
|
207
|
+
this.ctx = ctx;
|
|
208
|
+
this.api = options.api;
|
|
209
|
+
this.settings = telegramSettings(ctx.settings);
|
|
210
|
+
this.state = readCommands(ctx.home);
|
|
211
|
+
if (ctx.signal.aborted) this.controller.abort();
|
|
212
|
+
else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Registers the menu now, then again on stored changes, alone or through the plugin's one loop. */
|
|
216
|
+
start(events?: TelegramEvents): { readonly ready: Promise<void>; readonly stop: () => Promise<void> } {
|
|
217
|
+
const local = events === undefined ? new TelegramEvents(this.ctx, { wait: delay }) : undefined;
|
|
218
|
+
const initial = this.refresh();
|
|
219
|
+
this.watching = (async () => {
|
|
220
|
+
await initial;
|
|
221
|
+
if (this.stopped) return;
|
|
222
|
+
this.following = local?.start({
|
|
223
|
+
commands: () => {
|
|
224
|
+
void this.refresh();
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
})();
|
|
228
|
+
return {
|
|
229
|
+
ready: initial,
|
|
230
|
+
stop: async () => {
|
|
231
|
+
this.stopped = true;
|
|
232
|
+
this.controller.abort();
|
|
233
|
+
await this.following?.stop();
|
|
234
|
+
await this.watching.catch(() => undefined);
|
|
235
|
+
await this.tail.catch(() => undefined);
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Registers the menu when its set of commands changed. Passes run one at a
|
|
242
|
+
* time; a pass asked for while one runs is done once after it.
|
|
243
|
+
*/
|
|
244
|
+
refresh(chatId?: string): Promise<void> {
|
|
245
|
+
this.hint = chatId ?? this.hint;
|
|
246
|
+
if (this.queued) return this.tail.then(() => undefined);
|
|
247
|
+
this.queued = true;
|
|
248
|
+
const run = this.tail.catch(() => undefined).then(async () => {
|
|
249
|
+
this.queued = false;
|
|
250
|
+
const hint = this.hint;
|
|
251
|
+
this.hint = undefined;
|
|
252
|
+
if (this.stopped) return;
|
|
253
|
+
try {
|
|
254
|
+
await this.register(hint);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
await this.ctx.logger.write(`could not set the command menu: ${messageOf(error)}`);
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
this.tail = run;
|
|
260
|
+
return run;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private async register(hint: string | undefined): Promise<void> {
|
|
264
|
+
const chatId = hint ?? (await this.newestChat());
|
|
265
|
+
if (chatId === undefined) return;
|
|
266
|
+
const view = await this.ctx.client.get(`chat:${chatId}`);
|
|
267
|
+
const commands: BotCommand[] = [];
|
|
268
|
+
for (const command of chatCommands(view.actions)) {
|
|
269
|
+
if (!TELEGRAM_COMMAND_NAME.test(command.name)) {
|
|
270
|
+
await this.ctx.logger.write(
|
|
271
|
+
`the command "${command.name}" is not a Telegram command name; it is left out of the menu`,
|
|
272
|
+
);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (commands.some((entry) => entry.command === command.name)) continue;
|
|
276
|
+
commands.push({ command: command.name, description: descriptionOf(command) });
|
|
277
|
+
}
|
|
278
|
+
const menu = commands.slice(0, MENU_MAX);
|
|
279
|
+
const key = JSON.stringify(menu);
|
|
280
|
+
if (key === this.registered) return;
|
|
281
|
+
await this.api.setMyCommands({ commands: menu, signal: this.controller.signal });
|
|
282
|
+
this.registered = key;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The chat whose commands the menu shows: an open bound chat, else a closed one. */
|
|
286
|
+
private async newestChat(): Promise<string | undefined> {
|
|
287
|
+
const chats = await boundChats(this.ctx);
|
|
288
|
+
return (chats.find((chat) => !chat.closed) ?? chats[0])?.id;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async greet(text: string, target: number): Promise<boolean> {
|
|
292
|
+
const parsed = parseCommand(text);
|
|
293
|
+
if (parsed === undefined || parsed.name !== "start") return false;
|
|
294
|
+
await this.api.sendMessage({
|
|
295
|
+
chatId: target,
|
|
296
|
+
text: START_GREETING,
|
|
297
|
+
signal: this.controller.signal,
|
|
298
|
+
});
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async command(chatId: string, name: string): Promise<ChatCommand | undefined> {
|
|
303
|
+
try {
|
|
304
|
+
const view = await this.ctx.client.get(`chat:${chatId}`);
|
|
305
|
+
return findCommand(chatCommands(view.actions), name);
|
|
306
|
+
} catch {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async offer(command: ChatCommand, text: string, chatId: string, target: number): Promise<boolean> {
|
|
312
|
+
const choices = choicesOf(command);
|
|
313
|
+
const parsed = parseCommand(text);
|
|
314
|
+
if (choices.length === 0 || parsed === undefined || parsed.rest.length > 0) return false;
|
|
315
|
+
const message = descriptionOf(command);
|
|
316
|
+
const messageId = await this.api.sendMessage({
|
|
317
|
+
chatId: target,
|
|
318
|
+
text: message,
|
|
319
|
+
keyboard: keyboardFor(choices, 0),
|
|
320
|
+
signal: this.controller.signal,
|
|
321
|
+
});
|
|
322
|
+
this.remember(keyOf(target, messageId), {
|
|
323
|
+
chatId,
|
|
324
|
+
target,
|
|
325
|
+
messageId,
|
|
326
|
+
text: message,
|
|
327
|
+
name: command.name,
|
|
328
|
+
choices,
|
|
329
|
+
page: 0,
|
|
330
|
+
});
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async say(target: number, outcome: string): Promise<void> {
|
|
335
|
+
for (const chunk of telegramChunks(outcome)) {
|
|
336
|
+
if (this.stopped) return;
|
|
337
|
+
try {
|
|
338
|
+
await this.api.sendMessage({
|
|
339
|
+
chatId: target,
|
|
340
|
+
text: chunk.html,
|
|
341
|
+
parseMode: "HTML",
|
|
342
|
+
signal: this.controller.signal,
|
|
343
|
+
});
|
|
344
|
+
} catch (error) {
|
|
345
|
+
// The markup Telegram cannot read goes again as plain text.
|
|
346
|
+
if (error instanceof BotApiError && error.badMarkup) {
|
|
347
|
+
try {
|
|
348
|
+
await this.api.sendMessage({
|
|
349
|
+
chatId: target,
|
|
350
|
+
text: chunk.plain,
|
|
351
|
+
signal: this.controller.signal,
|
|
352
|
+
});
|
|
353
|
+
continue;
|
|
354
|
+
} catch (plain) {
|
|
355
|
+
error = plain;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (this.stopped) return;
|
|
359
|
+
await this.ctx.logger.write(`could not send what a command returned: ${messageOf(error)}`);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private exclusive<T>(work: () => Promise<T>): Promise<T> {
|
|
366
|
+
const run = this.tail.catch(() => undefined).then(work);
|
|
367
|
+
this.tail = run.catch(() => undefined);
|
|
368
|
+
return run;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private find(
|
|
372
|
+
target: number,
|
|
373
|
+
messageId: number,
|
|
374
|
+
): { readonly key: string; readonly sent: SentCommand } | undefined {
|
|
375
|
+
const key = keyOf(target, messageId);
|
|
376
|
+
const sent = this.state[key];
|
|
377
|
+
return sent === undefined ? undefined : { key, sent };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private remember(key: string, sent: SentCommand): void {
|
|
381
|
+
this.state = pruneCommands({ ...this.state, [key]: sent });
|
|
382
|
+
writeCommands(this.ctx.home, this.state);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private listed(userId: number | undefined): userId is number {
|
|
386
|
+
return userId !== undefined && this.settings.users.includes(userId);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async handleCallback(callback: TelegramCallback): Promise<boolean> {
|
|
390
|
+
const message = callback.message;
|
|
391
|
+
if (message === undefined) return false;
|
|
392
|
+
return this.exclusive(async () => {
|
|
393
|
+
const found = this.find(message.chat.id, message.message_id);
|
|
394
|
+
if (found === undefined) return false;
|
|
395
|
+
// Only a listed user's tap counts; nobody else is told anything.
|
|
396
|
+
if (!this.listed(callback.from.id)) {
|
|
397
|
+
await this.tell(callback.id, undefined);
|
|
398
|
+
return true;
|
|
399
|
+
}
|
|
400
|
+
const { key, sent } = found;
|
|
401
|
+
const data = callback.data ?? "";
|
|
402
|
+
const shownPage = /^p:(\d+)$/.exec(data)?.[1];
|
|
403
|
+
if (shownPage !== undefined) {
|
|
404
|
+
await this.show(key, sent, Number(shownPage));
|
|
405
|
+
await this.tell(callback.id, undefined);
|
|
406
|
+
return true;
|
|
407
|
+
}
|
|
408
|
+
const position = /^c:(\d+)$/.exec(data)?.[1];
|
|
409
|
+
const choice = position === undefined ? undefined : sent.choices[Number(position)];
|
|
410
|
+
if (choice === undefined) {
|
|
411
|
+
await this.tell(callback.id, "this button is no longer valid");
|
|
412
|
+
return true;
|
|
413
|
+
}
|
|
414
|
+
if (sent.chosen !== undefined) {
|
|
415
|
+
await this.tell(callback.id, undefined);
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
const words = await this.run(sent, choice, callback.from.id);
|
|
419
|
+
await this.edit(sent, `${sent.text}\n\n${words}`);
|
|
420
|
+
this.remember(key, { ...sent, chosen: choice });
|
|
421
|
+
await this.tell(callback.id, undefined);
|
|
422
|
+
return true;
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Shows another page of choices in the same message. */
|
|
427
|
+
private async show(key: string, sent: SentCommand, page: number): Promise<void> {
|
|
428
|
+
const pages = Math.max(1, Math.ceil(sent.choices.length / COMMAND_PAGE_SIZE));
|
|
429
|
+
const shown = Math.min(Math.max(page, 0), pages - 1);
|
|
430
|
+
try {
|
|
431
|
+
await this.api.editMessage({
|
|
432
|
+
chatId: sent.target,
|
|
433
|
+
messageId: sent.messageId,
|
|
434
|
+
text: sent.text,
|
|
435
|
+
keyboard: keyboardFor(sent.choices, shown),
|
|
436
|
+
signal: this.controller.signal,
|
|
437
|
+
});
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (!this.stopped) {
|
|
440
|
+
await this.ctx.logger.write(`could not change the choices of a command: ${messageOf(error)}`);
|
|
441
|
+
}
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
this.remember(key, { ...sent, page: shown });
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Runs the command with the chosen value as its text; the words the message ends with. */
|
|
448
|
+
private async run(sent: SentCommand, choice: string, userId: number): Promise<string> {
|
|
449
|
+
try {
|
|
450
|
+
const result = await this.ctx.client.act("chat:send", `chat:${sent.chatId}`, {
|
|
451
|
+
args: { note: `/${sent.name} ${choice}` },
|
|
452
|
+
actor: { via: VIA, id: String(userId) },
|
|
453
|
+
});
|
|
454
|
+
const outcome = typeof result.value === "string" ? result.value.trim() : "";
|
|
455
|
+
return outcome.startsWith("refused:") ? outcome : `chosen: ${choice}`;
|
|
456
|
+
} catch (error) {
|
|
457
|
+
return `refused: ${messageOf(error)}`;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
private async edit(sent: SentCommand, text: string): Promise<void> {
|
|
462
|
+
try {
|
|
463
|
+
await this.api.editMessage({
|
|
464
|
+
chatId: sent.target,
|
|
465
|
+
messageId: sent.messageId,
|
|
466
|
+
text,
|
|
467
|
+
signal: this.controller.signal,
|
|
468
|
+
});
|
|
469
|
+
} catch (error) {
|
|
470
|
+
if (!this.stopped) {
|
|
471
|
+
await this.ctx.logger.write(`could not change the message of a command: ${messageOf(error)}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
private async tell(callbackId: string, text: string | undefined): Promise<void> {
|
|
477
|
+
try {
|
|
478
|
+
await this.api.answerCallback({
|
|
479
|
+
callbackId,
|
|
480
|
+
...(text === undefined ? {} : { text }),
|
|
481
|
+
signal: this.controller.signal,
|
|
482
|
+
});
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (!this.stopped) {
|
|
485
|
+
await this.ctx.logger.write(`could not answer a tap: ${messageOf(error)}`);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one place the Telegram plugin follows the client API's changes.
|
|
3
|
+
*
|
|
4
|
+
* Every sender used to keep its own `events()` loop and woke on any id without
|
|
5
|
+
* looking at the event, so one running reply woke all of them. Here the stream
|
|
6
|
+
* is read once and each event goes only where it can matter: a live section's
|
|
7
|
+
* tail goes only to the progress side, a stored change goes to the ones that
|
|
8
|
+
* read stored objects, and a chat's change also wakes the source's dedupe
|
|
9
|
+
* memory. A failure is retried on the injected wait, as the typing side did.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { CHAT_TYPE, TRANSCRIPT } from "@operad-io/chat";
|
|
13
|
+
import { messageOf, type SourceContext } from "@operad-io/engine";
|
|
14
|
+
import { delay } from "./source.ts";
|
|
15
|
+
|
|
16
|
+
/** The part of a client event this plugin reads, without importing the host's view type. */
|
|
17
|
+
export interface TelegramEvent {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly type?: string | undefined;
|
|
20
|
+
readonly section?: string | undefined;
|
|
21
|
+
readonly tail?: string | undefined;
|
|
22
|
+
readonly status?: { readonly text: string; readonly since: number } | undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** How long to wait before following the client's events again after a failure. */
|
|
26
|
+
export const EVENT_RETRY_MS = 1_000;
|
|
27
|
+
|
|
28
|
+
/** What the one event loop tells each part of the plugin. */
|
|
29
|
+
export interface EventSinks {
|
|
30
|
+
/** A live `transcript` tail, or a stored change of a chat with a progress message. */
|
|
31
|
+
readonly progress?: ((event: TelegramEvent) => void) | undefined;
|
|
32
|
+
/** A stored change of a chat bound to Telegram. */
|
|
33
|
+
readonly replies?: ((event: TelegramEvent) => void) | undefined;
|
|
34
|
+
/** A stored change of a chat bound to Telegram. */
|
|
35
|
+
readonly typing?: ((event: TelegramEvent) => void) | undefined;
|
|
36
|
+
/** Any stored change; pending items can be about any object. */
|
|
37
|
+
readonly pending?: ((event: TelegramEvent) => void) | undefined;
|
|
38
|
+
/** A stored change, for the command menu. */
|
|
39
|
+
readonly commands?: (() => void) | undefined;
|
|
40
|
+
/** A chat whose stored state changed, for the source's dedupe memory. */
|
|
41
|
+
readonly source?: ((chatId: string) => void) | undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface TelegramEventsOptions {
|
|
45
|
+
/** Waits `ms` unless `signal` aborts first; a test gives one it moves itself. */
|
|
46
|
+
readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class TelegramEvents {
|
|
50
|
+
private readonly ctx: SourceContext;
|
|
51
|
+
private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
52
|
+
private readonly controller = new AbortController();
|
|
53
|
+
private iterator: AsyncIterator<TelegramEvent> | undefined;
|
|
54
|
+
private stopped = false;
|
|
55
|
+
private watching: Promise<void> = Promise.resolve();
|
|
56
|
+
|
|
57
|
+
constructor(ctx: SourceContext, options: TelegramEventsOptions = {}) {
|
|
58
|
+
this.ctx = ctx;
|
|
59
|
+
this.wait = options.wait ?? delay;
|
|
60
|
+
if (ctx.signal.aborted) this.controller.abort();
|
|
61
|
+
else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Follows the client's changes until stopped, taking the stream again after a failure. */
|
|
65
|
+
start(sinks: EventSinks): { readonly ready: Promise<void>; readonly stop: () => Promise<void> } {
|
|
66
|
+
this.watching = this.follow(sinks);
|
|
67
|
+
return {
|
|
68
|
+
ready: Promise.resolve(),
|
|
69
|
+
stop: async () => {
|
|
70
|
+
this.stopped = true;
|
|
71
|
+
this.controller.abort();
|
|
72
|
+
try {
|
|
73
|
+
await this.iterator?.return?.();
|
|
74
|
+
} catch {
|
|
75
|
+
// The stream is already unusable; stopping is still complete.
|
|
76
|
+
}
|
|
77
|
+
await this.watching.catch(() => undefined);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private async follow(sinks: EventSinks): Promise<void> {
|
|
83
|
+
while (!this.stopped) {
|
|
84
|
+
let iterator: AsyncIterator<TelegramEvent> | undefined;
|
|
85
|
+
try {
|
|
86
|
+
// A client that refuses the stream synchronously is a failure like any
|
|
87
|
+
// other: log it, wait, and take the stream again.
|
|
88
|
+
iterator = this.ctx.client.events()[Symbol.asyncIterator]();
|
|
89
|
+
this.iterator = iterator;
|
|
90
|
+
while (!this.stopped) {
|
|
91
|
+
const next = await iterator.next();
|
|
92
|
+
if (next.done === true || this.stopped) return;
|
|
93
|
+
this.dispatch(next.value, sinks);
|
|
94
|
+
}
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (this.stopped) return;
|
|
97
|
+
void this.ctx.logger.write(`could not follow changes: ${messageOf(error)}`).catch(() => undefined);
|
|
98
|
+
await this.wait(EVENT_RETRY_MS, this.controller.signal).catch(() => undefined);
|
|
99
|
+
} finally {
|
|
100
|
+
if (iterator === undefined) continue;
|
|
101
|
+
if (this.iterator === iterator) this.iterator = undefined;
|
|
102
|
+
try {
|
|
103
|
+
await iterator.return?.();
|
|
104
|
+
} catch {
|
|
105
|
+
// A stream that failed may refuse to close; the next stream is new.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private dispatch(event: TelegramEvent, sinks: EventSinks): void {
|
|
112
|
+
if (event.id.length === 0) return;
|
|
113
|
+
if (event.section !== undefined) {
|
|
114
|
+
// A live tail is not a stored change; only the progress side reads it.
|
|
115
|
+
if (event.section === TRANSCRIPT && (event.type === undefined || event.type === CHAT_TYPE)) {
|
|
116
|
+
sinks.progress?.(event);
|
|
117
|
+
}
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
sinks.pending?.(event);
|
|
121
|
+
sinks.commands?.();
|
|
122
|
+
const isChat =
|
|
123
|
+
event.type === CHAT_TYPE ||
|
|
124
|
+
(event.type === undefined && this.ctx.store.objectTypesOf(event.id).includes(CHAT_TYPE));
|
|
125
|
+
if (!isChat) return;
|
|
126
|
+
sinks.replies?.(event);
|
|
127
|
+
sinks.typing?.(event);
|
|
128
|
+
sinks.progress?.(event);
|
|
129
|
+
sinks.source?.(event.id);
|
|
130
|
+
}
|
|
131
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* tables, images, HTML) becomes plain text or one of those.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { formatElapsed } from "@operad-io/engine";
|
|
9
|
+
|
|
8
10
|
/** The longest text Telegram takes in one message. */
|
|
9
11
|
export const TELEGRAM_MAX_CHARS = 4096;
|
|
10
12
|
|
|
@@ -167,3 +169,27 @@ export function telegramChunks(markdown: string, limit = CHUNK_TARGET): readonly
|
|
|
167
169
|
}
|
|
168
170
|
return out;
|
|
169
171
|
}
|
|
172
|
+
|
|
173
|
+
/** A duration as the progress line writes it, the same as the TUI's list. */
|
|
174
|
+
export const progressElapsed = formatElapsed;
|
|
175
|
+
|
|
176
|
+
/** The one line a progress message ends with: what the reply does and for how long. */
|
|
177
|
+
export function progressStatusLine(status: { readonly text: string; readonly since: number }, now: number): string {
|
|
178
|
+
return `${status.text} · ${progressElapsed(now - status.since)}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The one message a reply's progress shows: the end of a text longer than
|
|
183
|
+
* Telegram takes, reduced like a reply, and the status line at its end. A
|
|
184
|
+
* fence left open is closed, so a half-written code block never breaks the edit.
|
|
185
|
+
*/
|
|
186
|
+
export function telegramProgress(markdown: string, statusLine?: string): TelegramChunk | undefined {
|
|
187
|
+
const limit = statusLine === undefined ? TELEGRAM_MAX_CHARS : Math.max(64, TELEGRAM_MAX_CHARS - statusLine.length - 2);
|
|
188
|
+
const body = markdown.trim().length === 0 ? undefined : telegramChunks(markdown, limit).at(-1);
|
|
189
|
+
if (statusLine === undefined) return body;
|
|
190
|
+
const line = escapeHtml(statusLine);
|
|
191
|
+
return {
|
|
192
|
+
html: body === undefined ? line : `${body.html}\n\n${line}`,
|
|
193
|
+
plain: body === undefined ? statusLine : `${body.plain}\n\n${statusLine}`,
|
|
194
|
+
};
|
|
195
|
+
}
|