@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/src/index.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The `telegram` plugin: the first channel and the first outside source.
3
+ *
4
+ * `start(ctx)` long-polls the Bot API and turns a private message from a listed
5
+ * user into one user message on that user's chat, opened on the configured bot
6
+ * and bound through the chat's `channels`. The token is the plugin's secret
7
+ * `token`; it never reaches a fact, a log line or an error.
8
+ */
9
+
10
+ import pkg from "../package.json" with { type: "json" };
11
+ import { definePlugin, type SourceHandle } from "@operad-io/engine";
12
+ import { createBotApi } from "./api.ts";
13
+ import { TELEGRAM_SETTINGS, TOKEN_SECRET } from "./settings.ts";
14
+ import { PendingSender } from "./pending.ts";
15
+ import { ReplySender } from "./replies.ts";
16
+ import { TelegramSource, delay } from "./source.ts";
17
+
18
+ /** Builds the Telegram source plugin. */
19
+ export function createTelegramPlugin() {
20
+ return definePlugin({
21
+ name: "telegram",
22
+ kind: "source",
23
+ version: pkg.version,
24
+ settings: TELEGRAM_SETTINGS,
25
+ async start(ctx): Promise<SourceHandle> {
26
+ const token = await ctx.secrets.get(TOKEN_SECRET);
27
+ if (token === undefined) {
28
+ throw new Error(
29
+ "the telegram plugin has no token; set it with `operad secret set telegram token`",
30
+ );
31
+ }
32
+ const api = createBotApi({ token });
33
+ const pending = new PendingSender(ctx, { api });
34
+ const source = new TelegramSource(ctx, { api, pending }).start();
35
+ const replies = new ReplySender(ctx, { api, wait: delay }).start();
36
+ const sent = pending.start();
37
+ return {
38
+ stop: async () => {
39
+ await source.stop();
40
+ await replies.stop();
41
+ await sent.stop();
42
+ },
43
+ };
44
+ },
45
+ });
46
+ }
47
+
48
+ export default createTelegramPlugin();
49
+
50
+ export * from "./api.ts";
51
+ export * from "./format.ts";
52
+ export * from "./pending.ts";
53
+ export * from "./replies.ts";
54
+ export * from "./settings.ts";
55
+ export * from "./source.ts";
56
+ export * from "./state.ts";
package/src/pending.ts ADDED
@@ -0,0 +1,483 @@
1
+ /**
2
+ * The pending side of the Telegram plugin: what waits for a person goes to
3
+ * Telegram as one message per item, with one button per option.
4
+ *
5
+ * What is sent (ADR 0033 D7): an item waiting in a chat bound to Telegram goes
6
+ * to that Telegram chat; an item of a plugin listed in the `pending` setting
7
+ * goes to every listed user; nothing else. The plugin reads the items from the
8
+ * client API's `pending()` whenever `events()` wakes it, and answers through the
9
+ * same client: `act` for an item an action backs, `answer` for a wait no action
10
+ * backs. Both carry the actor `{ via: "telegram", id }`, and only a listed
11
+ * user's tap or reply counts. A second answer is refused by the client, which
12
+ * is what keeps an answer to one item single; this side only reports it.
13
+ *
14
+ * An action that needs a note, and a free answer, are answered by replying to
15
+ * the item's message. After an answer, from Telegram or anywhere else, the
16
+ * buttons go and the message reads "answered: X".
17
+ */
18
+
19
+ import { CHAT_TYPE, chatData } from "@operad-io/chat";
20
+ import {
21
+ messageOf,
22
+ type Actor,
23
+ type ClientApi,
24
+ type PendingItem,
25
+ type SourceContext,
26
+ type ViewAction,
27
+ } from "@operad-io/engine";
28
+ import { BotApiError, type BotApi, type InlineButton, type TelegramCallback, type TelegramMessage } from "./api.ts";
29
+ import { telegramChatsOf } from "./replies.ts";
30
+ import { telegramSettings, type TelegramSettings } from "./settings.ts";
31
+ import { readPending, writePending, type PendingState, type SentItem, type SentOption } from "./state.ts";
32
+
33
+ /** The `via` of every answer this plugin gives. */
34
+ const VIA = "telegram";
35
+
36
+ /** The longest item text sent; Telegram's own limit is 4096 characters. */
37
+ const TEXT_MAX = 3_500;
38
+
39
+ /** What the source asks of the pending side for a tap or a reply. */
40
+ export interface PendingResponder {
41
+ /** A tap on a button; true when the tap belonged to a pending item message. */
42
+ handleCallback(callback: TelegramCallback): Promise<boolean>;
43
+ /** A reply to a message; true when the reply answered (or tried to answer) a pending item. */
44
+ handleReply(message: TelegramMessage): Promise<boolean>;
45
+ }
46
+
47
+ export interface PendingSenderOptions {
48
+ readonly api: BotApi;
49
+ readonly clock?: (() => number) | undefined;
50
+ }
51
+
52
+ /** The data a button carries: its option's position on the message. */
53
+ function buttonData(index: number): string {
54
+ return `o:${index}`;
55
+ }
56
+
57
+ function stateKey(item: { readonly runId: string; readonly waitId?: string | undefined }, chatId: number): string {
58
+ return `${item.runId}/${item.waitId ?? ""}/${chatId}`;
59
+ }
60
+
61
+ function itemKey(item: { readonly runId: string; readonly waitId?: string | undefined }): string {
62
+ return `${item.runId}/${item.waitId ?? ""}`;
63
+ }
64
+
65
+ /** The part of a state key that names the item, without the Telegram chat. */
66
+ function itemKeyOf(key: string): string {
67
+ return key.slice(0, key.lastIndexOf("/"));
68
+ }
69
+
70
+ export class PendingSender implements PendingResponder {
71
+ private readonly ctx: SourceContext;
72
+ private readonly api: BotApi;
73
+ private readonly client: ClientApi;
74
+ private readonly clock: () => number;
75
+ private readonly settings: TelegramSettings;
76
+ private readonly controller = new AbortController();
77
+ private state: PendingState;
78
+ private stopped = false;
79
+ private watching: Promise<void> = Promise.resolve();
80
+ /** Everything that reads or writes the state runs one at a time. */
81
+ private tail: Promise<unknown> = Promise.resolve();
82
+ private queued = false;
83
+
84
+ constructor(ctx: SourceContext, options: PendingSenderOptions) {
85
+ this.ctx = ctx;
86
+ this.api = options.api;
87
+ this.client = ctx.client;
88
+ this.clock = options.clock ?? ctx.clock;
89
+ this.settings = telegramSettings(ctx.settings);
90
+ this.state = readPending(ctx.home);
91
+ if (ctx.signal.aborted) this.controller.abort();
92
+ else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
93
+ }
94
+
95
+ /** Sends what waits now, then follows the client's events. */
96
+ start(): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
97
+ const iterator = this.client.events()[Symbol.asyncIterator]();
98
+ const initial = this.sync();
99
+ this.watching = (async () => {
100
+ await initial;
101
+ while (!this.stopped) {
102
+ const next = await iterator.next();
103
+ if (next.done === true || this.stopped) return;
104
+ void this.sync();
105
+ }
106
+ })();
107
+ return {
108
+ ready: initial,
109
+ stop: async () => {
110
+ this.stopped = true;
111
+ this.controller.abort();
112
+ await iterator.return?.();
113
+ await this.watching.catch(() => undefined);
114
+ await this.tail.catch(() => undefined);
115
+ },
116
+ };
117
+ }
118
+
119
+ /**
120
+ * One pass: send every item that waits and was not sent, and change the
121
+ * message of every sent item that no longer waits. Passes run one at a time;
122
+ * a pass asked for while one runs is done once after it.
123
+ */
124
+ sync(): Promise<void> {
125
+ if (this.queued) return this.tail.then(() => undefined);
126
+ this.queued = true;
127
+ const run = this.tail.catch(() => undefined).then(async () => {
128
+ this.queued = false;
129
+ if (this.stopped) return;
130
+ try {
131
+ await this.pass();
132
+ } catch (error) {
133
+ await this.ctx.logger.write(`could not send pending items: ${messageOf(error)}`);
134
+ }
135
+ });
136
+ this.tail = run;
137
+ return run;
138
+ }
139
+
140
+ private exclusive<T>(work: () => Promise<T>): Promise<T> {
141
+ const run = this.tail.catch(() => undefined).then(work);
142
+ this.tail = run.catch(() => undefined);
143
+ return run;
144
+ }
145
+
146
+ private async pass(): Promise<void> {
147
+ const items = await this.client.pending();
148
+ const waiting = new Set<string>();
149
+ for (const item of items) {
150
+ if (!this.answerable(item)) continue;
151
+ waiting.add(itemKey(item));
152
+ const targets = await this.targetsOf(item);
153
+ const fresh = targets.filter((chatId) => this.state[stateKey(item, chatId)] === undefined);
154
+ if (fresh.length === 0) continue;
155
+ const built = await this.build(item);
156
+ if (built === undefined) continue;
157
+ for (const chatId of fresh) {
158
+ if (this.stopped) return;
159
+ await this.send(item, chatId, built.text, built.options);
160
+ }
161
+ }
162
+ for (const [key, sent] of Object.entries(this.state)) {
163
+ if (this.stopped) return;
164
+ if (sent.answered !== undefined || waiting.has(itemKeyOf(key))) continue;
165
+ await this.settle(key, sent, await this.answeredWith(sent));
166
+ }
167
+ }
168
+
169
+ /** An item a person can answer here: it names a question, or an object to act on. */
170
+ private answerable(item: PendingItem): boolean {
171
+ if (item.kind === "candidate" || item.kind === "refused") return false;
172
+ if (item.announce === false) return false;
173
+ return item.waitId !== undefined || (item.object !== undefined && item.actions.length > 0);
174
+ }
175
+
176
+ /** The Telegram chats an item goes to: its bound chat, and every listed user when its plugin is listed. */
177
+ private async targetsOf(item: PendingItem): Promise<readonly number[]> {
178
+ const targets = new Set<number>();
179
+ if (item.object?.startsWith("chat:") === true) {
180
+ const stored = await this.ctx.store.get(CHAT_TYPE, item.object.slice("chat:".length));
181
+ if (stored !== undefined) {
182
+ for (const chatId of telegramChatsOf(chatData(stored.data).channels)) targets.add(chatId);
183
+ }
184
+ }
185
+ const listed = this.settings.pending;
186
+ const ofListed =
187
+ item.actions.some((action) => listed.includes(action.plugin)) ||
188
+ (item.kind === "standing" && listed.includes(item.flow));
189
+ if (ofListed) for (const user of this.settings.users) targets.add(user);
190
+ return [...targets];
191
+ }
192
+
193
+ /** The text of an item's message and what it offers. */
194
+ private async build(item: PendingItem): Promise<{ readonly text: string; readonly options: readonly SentOption[] } | undefined> {
195
+ const infos = await this.actionsOf(item);
196
+ const names = item.choices.length > 0 ? item.choices : item.actions.map((action) => action.action);
197
+ const options: SentOption[] = [];
198
+ for (const name of names) {
199
+ if (options.some((option) => option.label === name)) continue;
200
+ const action = item.actions.find((candidate) => candidate.action === name);
201
+ if (action !== undefined && item.object !== undefined) {
202
+ const info = infos.find((candidate) => candidate.plugin === action.plugin && candidate.action === action.action);
203
+ options.push({
204
+ label: name,
205
+ how: "act",
206
+ action: `${action.plugin}:${action.action}`,
207
+ ...(info?.noteRequired === true ? { note: true as const } : {}),
208
+ });
209
+ } else if (item.waitId !== undefined && item.choices.length > 0) {
210
+ options.push({ label: name, how: "choice" });
211
+ }
212
+ }
213
+ if (options.length === 0 && item.waitId !== undefined) options.push({ label: "answer", how: "free", note: true });
214
+ if (options.length === 0) return undefined;
215
+
216
+ const lines: string[] = [];
217
+ const title = item.row?.title;
218
+ if (title !== undefined && title.length > 0 && !item.prompt.includes(title)) lines.push(title);
219
+ lines.push(item.prompt);
220
+ for (const option of options) {
221
+ if (option.note !== true) continue;
222
+ lines.push(
223
+ option.how === "free"
224
+ ? "Reply to this message with your answer."
225
+ : `Reply to this message to ${option.label}; your reply is the note.`,
226
+ );
227
+ }
228
+ const text = lines.join("\n\n");
229
+ return { text: text.length > TEXT_MAX ? `${text.slice(0, TEXT_MAX)}…` : text, options };
230
+ }
231
+
232
+ /** The actions an item's object offers, with what each needs; none when they cannot be read. */
233
+ private async actionsOf(item: PendingItem): Promise<readonly ViewAction[]> {
234
+ if (item.object === undefined) return [];
235
+ try {
236
+ return (await this.client.get(item.object)).actions;
237
+ } catch {
238
+ return [];
239
+ }
240
+ }
241
+
242
+ private async send(item: PendingItem, chatId: number, text: string, options: readonly SentOption[]): Promise<void> {
243
+ const keyboard: InlineButton[][] = [];
244
+ options.forEach((option, index) => {
245
+ if (option.note !== true) keyboard.push([{ text: option.label, data: buttonData(index) }]);
246
+ });
247
+ let messageId: number;
248
+ try {
249
+ messageId = await this.api.sendMessage({
250
+ chatId,
251
+ text,
252
+ ...(keyboard.length === 0 ? {} : { keyboard }),
253
+ signal: this.controller.signal,
254
+ });
255
+ } catch (error) {
256
+ if (this.stopped) return;
257
+ await this.ctx.logger.write(`could not send pending item ${item.runId} to ${chatId}: ${messageOf(error)}`);
258
+ return;
259
+ }
260
+ this.remember(stateKey(item, chatId), {
261
+ runId: item.runId,
262
+ ...(item.waitId === undefined ? {} : { waitId: item.waitId }),
263
+ ...(item.object === undefined ? {} : { object: item.object }),
264
+ chatId,
265
+ messageId,
266
+ text,
267
+ options,
268
+ at: this.clock(),
269
+ });
270
+ }
271
+
272
+ /** What an item answered somewhere else was answered with: the latest action run on its object since it was sent. */
273
+ private async answeredWith(sent: SentItem): Promise<string | undefined> {
274
+ if (sent.object === undefined) return undefined;
275
+ const split = sent.object.indexOf(":");
276
+ if (split <= 0) return undefined;
277
+ const ref = { type: sent.object.slice(0, split), id: sent.object.slice(split + 1) };
278
+ let latest: string | undefined;
279
+ try {
280
+ let cursor: string | undefined;
281
+ do {
282
+ const page = this.ctx.store.facts(ref, cursor === undefined ? {} : { cursor });
283
+ for (const fact of page.facts) {
284
+ if (fact.type !== "action_invoked" || fact.at < sent.at) continue;
285
+ const action = fact.data.action;
286
+ if (typeof action !== "string") continue;
287
+ const name = action.slice(action.lastIndexOf("/") + 1);
288
+ if (sent.options.some((option) => option.label === name)) latest = name;
289
+ }
290
+ cursor = page.next;
291
+ } while (cursor !== undefined);
292
+ } catch {
293
+ return undefined;
294
+ }
295
+ if (latest !== undefined) return latest;
296
+ return this.chosenIn(sent);
297
+ }
298
+
299
+ /** The choice a question was answered with, from the object's history ("you chose X"), when no action shows it. */
300
+ private async chosenIn(sent: SentItem): Promise<string | undefined> {
301
+ if (sent.object === undefined || sent.waitId === undefined) return undefined;
302
+ let markdown: string;
303
+ try {
304
+ markdown = (await this.client.section(sent.object, "history")).markdown;
305
+ } catch {
306
+ return undefined;
307
+ }
308
+ const labels = sent.options.filter((option) => option.how === "choice").map((option) => option.label);
309
+ let chosen: string | undefined;
310
+ for (const line of markdown.split("\n")) {
311
+ const at = line.indexOf("you chose ");
312
+ if (at < 0) continue;
313
+ const rest = line.slice(at + "you chose ".length);
314
+ const found = labels.find((label) => rest.startsWith(label) && !/^\w/.test(rest.slice(label.length)));
315
+ if (found !== undefined) chosen = found;
316
+ }
317
+ return chosen;
318
+ }
319
+
320
+ /** Changes the other copies of an item that was answered in one chat, with the same words. */
321
+ private async settleSiblings(key: string, label: string): Promise<void> {
322
+ for (const [other, copy] of Object.entries(this.state)) {
323
+ if (other === key || copy.answered !== undefined || itemKeyOf(other) !== itemKeyOf(key)) continue;
324
+ await this.settle(other, copy, label);
325
+ }
326
+ }
327
+
328
+ /** Changes the message of an answered item: the buttons go, the text ends "answered: X". */
329
+ private async settle(key: string, sent: SentItem, label: string | undefined): Promise<void> {
330
+ const words = label === undefined ? "answered" : `answered: ${label}`;
331
+ try {
332
+ await this.api.editMessage({
333
+ chatId: sent.chatId,
334
+ messageId: sent.messageId,
335
+ text: `${sent.text}\n\n${words}`,
336
+ signal: this.controller.signal,
337
+ });
338
+ } catch (error) {
339
+ if (this.stopped) return;
340
+ await this.ctx.logger.write(`could not change the message of pending item ${sent.runId}: ${messageOf(error)}`);
341
+ }
342
+ this.remember(key, { ...sent, answered: label ?? "answered" });
343
+ }
344
+
345
+ private remember(key: string, item: SentItem): void {
346
+ this.state = { ...this.state, [key]: item };
347
+ writePending(this.ctx.home, this.state);
348
+ }
349
+
350
+ private find(chatId: number, messageId: number): { readonly key: string; readonly sent: SentItem } | undefined {
351
+ for (const [key, sent] of Object.entries(this.state)) {
352
+ if (sent.chatId === chatId && sent.messageId === messageId) return { key, sent };
353
+ }
354
+ return undefined;
355
+ }
356
+
357
+ private listed(userId: number | undefined): userId is number {
358
+ return userId !== undefined && this.settings.users.includes(userId);
359
+ }
360
+
361
+ async handleCallback(callback: TelegramCallback): Promise<boolean> {
362
+ const message = callback.message;
363
+ if (message === undefined) {
364
+ // Telegram shows a spinner on the button until the tap is answered.
365
+ await this.tell(callback.id, undefined);
366
+ return false;
367
+ }
368
+ return this.exclusive(async () => {
369
+ const found = this.find(message.chat.id, message.message_id);
370
+ if (found === undefined) {
371
+ await this.tell(callback.id, undefined);
372
+ return false;
373
+ }
374
+ // Only a listed user's tap counts; nobody else is told anything.
375
+ if (!this.listed(callback.from.id)) {
376
+ await this.tell(callback.id, undefined);
377
+ return true;
378
+ }
379
+ const { key, sent } = found;
380
+ if (sent.answered !== undefined) {
381
+ await this.tell(callback.id, `already answered: ${sent.answered}`);
382
+ return true;
383
+ }
384
+ const index = /^o:(\d+)$/.exec(callback.data ?? "")?.[1];
385
+ const option = index === undefined ? undefined : sent.options[Number(index)];
386
+ if (option === undefined || option.note === true) {
387
+ await this.tell(callback.id, "this button is no longer valid");
388
+ return true;
389
+ }
390
+ const refusal = await this.answer(sent, option, { via: VIA, id: String(callback.from.id) }, undefined);
391
+ if (refusal === undefined) {
392
+ await this.settle(key, sent, option.label);
393
+ await this.settleSiblings(key, option.label);
394
+ await this.tell(callback.id, undefined);
395
+ } else {
396
+ await this.tell(callback.id, refusal);
397
+ // The client refused: if the item was answered elsewhere the message follows.
398
+ await this.pass().catch(() => undefined);
399
+ }
400
+ return true;
401
+ });
402
+ }
403
+
404
+ async handleReply(message: TelegramMessage): Promise<boolean> {
405
+ const to = message.reply_to_message?.message_id;
406
+ const text = (message.text ?? message.caption ?? "").trim();
407
+ if (to === undefined || text.length === 0) return false;
408
+ return this.exclusive(async () => {
409
+ const found = this.find(message.chat.id, to);
410
+ if (found === undefined || !this.listed(message.from?.id)) return false;
411
+ const { key, sent } = found;
412
+ const noted = sent.options.filter((option) => option.note === true);
413
+ // A reply to an item with nothing to say in a reply is an ordinary message.
414
+ if (noted.length === 0) return false;
415
+ const reply = (words: string): Promise<number> =>
416
+ this.api.sendMessage({ chatId: message.chat.id, text: words, signal: this.controller.signal });
417
+ if (sent.answered !== undefined) {
418
+ await reply(`already answered: ${sent.answered}`).catch(() => undefined);
419
+ return true;
420
+ }
421
+ let option = noted[0];
422
+ let note = text;
423
+ if (noted.length > 1) {
424
+ const named = noted.find((candidate) => text.toLowerCase().startsWith(`${candidate.label.toLowerCase()}:`));
425
+ if (named === undefined) {
426
+ const names = noted.map((candidate) => `"${candidate.label}:"`).join(" or ");
427
+ await reply(`Start your reply with ${names}, then your note.`).catch(() => undefined);
428
+ return true;
429
+ }
430
+ option = named;
431
+ note = text.slice(named.label.length + 1).trim();
432
+ }
433
+ if (option === undefined) return false;
434
+ const refusal = await this.answer(sent, option, { via: VIA, id: String(message.from?.id) }, note);
435
+ if (refusal === undefined) {
436
+ const words = option.how === "free" ? note : option.label;
437
+ await this.settle(key, sent, words);
438
+ await this.settleSiblings(key, words);
439
+ } else {
440
+ await reply(refusal).catch(() => undefined);
441
+ await this.pass().catch(() => undefined);
442
+ }
443
+ return true;
444
+ });
445
+ }
446
+
447
+ /** Gives the answer through the client; the refusal in words, or undefined when it was taken. */
448
+ private async answer(sent: SentItem, option: SentOption, actor: Actor, note: string | undefined): Promise<string | undefined> {
449
+ try {
450
+ if (option.how === "act") {
451
+ if (sent.object === undefined || option.action === undefined) return "this item has no object to act on";
452
+ await this.client.act(option.action, sent.object, {
453
+ ...(note === undefined ? {} : { note }),
454
+ // A tap on the button of an action that asks to confirm is the confirmation.
455
+ yes: true,
456
+ actor,
457
+ });
458
+ } else {
459
+ if (sent.waitId === undefined) return "this item names no question";
460
+ await this.client.answer({
461
+ runId: sent.runId,
462
+ waitId: sent.waitId,
463
+ choice: option.how === "free" ? (note ?? "") : option.label,
464
+ ...(option.how === "choice" && note !== undefined ? { note } : {}),
465
+ actor,
466
+ });
467
+ }
468
+ return undefined;
469
+ } catch (error) {
470
+ return messageOf(error);
471
+ }
472
+ }
473
+
474
+ private async tell(callbackId: string, text: string | undefined): Promise<void> {
475
+ try {
476
+ await this.api.answerCallback({ callbackId, ...(text === undefined ? {} : { text }), signal: this.controller.signal });
477
+ } catch (error) {
478
+ if (error instanceof BotApiError || !this.stopped) {
479
+ await this.ctx.logger.write(`could not answer a tap: ${messageOf(error)}`);
480
+ }
481
+ }
482
+ }
483
+ }