@operad-io/telegram 0.0.0-stage → 0.1.1
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/src/replies.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The reply side of the Telegram plugin: every new assistant message of a chat
|
|
3
|
+
* bound to a Telegram chat is sent to that chat, once.
|
|
4
|
+
*
|
|
5
|
+
* It wakes on the client API's `events()`, which names a chat whenever it
|
|
6
|
+
* changes. What it then reads, the chat's bindings and its messages with their
|
|
7
|
+
* ids and roles, the client API does not give (a row has no channels; the
|
|
8
|
+
* transcript section is rendered Markdown with no message ids), so those two
|
|
9
|
+
* reads stay on the plugin's store. What was sent
|
|
10
|
+
* is recorded in the plugin's own file, per message and per chunk, so a restart
|
|
11
|
+
* sends neither a sent message again nor skips one written while the process was
|
|
12
|
+
* down. A send that fails is retried on the injected wait; a send that gives up
|
|
13
|
+
* is recorded as a `send_failed` event of the plugin and is not tried again. Only replies are sent,
|
|
14
|
+
* never the tool calls (ADR 0033 D7).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { CHAT_TYPE, allMessages, chatData, type Message } from "@operad-io/chat";
|
|
18
|
+
import { messageOf, type SourceContext } from "@operad-io/engine";
|
|
19
|
+
import { BotApiError, type BotApi } from "./api.ts";
|
|
20
|
+
import { telegramChunks, type TelegramChunk } from "./format.ts";
|
|
21
|
+
import { TELEGRAM_SOURCE } from "./source.ts";
|
|
22
|
+
import { readSent, writeSent, type SentRecord, type SentState } from "./state.ts";
|
|
23
|
+
|
|
24
|
+
/** How a failed send is tried again. */
|
|
25
|
+
export interface RetryPolicy {
|
|
26
|
+
/** How many sends of one chunk before giving up. */
|
|
27
|
+
readonly attempts: number;
|
|
28
|
+
/** The wait before the second send; each next wait doubles. */
|
|
29
|
+
readonly baseMs: number;
|
|
30
|
+
/** The longest wait. */
|
|
31
|
+
readonly maxMs: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The event type that records a reply Telegram never took. */
|
|
35
|
+
export const SEND_FAILED_EVENT = "send_failed";
|
|
36
|
+
|
|
37
|
+
export const DEFAULT_RETRY: RetryPolicy = { attempts: 5, baseMs: 1_000, maxMs: 60_000 };
|
|
38
|
+
|
|
39
|
+
export interface ReplySenderOptions {
|
|
40
|
+
readonly api: BotApi;
|
|
41
|
+
readonly clock?: (() => number) | undefined;
|
|
42
|
+
readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
43
|
+
readonly retry?: RetryPolicy | undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The Telegram chat ids a chat is bound to. */
|
|
47
|
+
export function telegramChatsOf(channels: readonly string[]): readonly number[] {
|
|
48
|
+
const found: number[] = [];
|
|
49
|
+
for (const channel of channels) {
|
|
50
|
+
if (!channel.startsWith(`${TELEGRAM_SOURCE}:`)) continue;
|
|
51
|
+
const id = Number(channel.slice(TELEGRAM_SOURCE.length + 1));
|
|
52
|
+
if (Number.isInteger(id)) found.push(id);
|
|
53
|
+
}
|
|
54
|
+
return found;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A chunk that was tried and not taken: how many sends it took, and the last refusal. */
|
|
58
|
+
class SendGaveUp extends Error {
|
|
59
|
+
constructor(
|
|
60
|
+
readonly tries: number,
|
|
61
|
+
readonly last: unknown,
|
|
62
|
+
) {
|
|
63
|
+
super(messageOf(last));
|
|
64
|
+
this.name = "SendGaveUp";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class ReplySender {
|
|
69
|
+
private readonly ctx: SourceContext;
|
|
70
|
+
private readonly api: BotApi;
|
|
71
|
+
private readonly clock: () => number;
|
|
72
|
+
private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
73
|
+
private readonly retry: RetryPolicy;
|
|
74
|
+
private readonly controller = new AbortController();
|
|
75
|
+
private readonly queues = new Map<string, Promise<void>>();
|
|
76
|
+
private state: SentState;
|
|
77
|
+
private stopped = false;
|
|
78
|
+
private watching: Promise<void> = Promise.resolve();
|
|
79
|
+
|
|
80
|
+
constructor(ctx: SourceContext, options: ReplySenderOptions) {
|
|
81
|
+
this.ctx = ctx;
|
|
82
|
+
this.api = options.api;
|
|
83
|
+
this.clock = options.clock ?? ctx.clock;
|
|
84
|
+
this.wait = options.wait;
|
|
85
|
+
this.retry = options.retry ?? DEFAULT_RETRY;
|
|
86
|
+
const existing = readSent(ctx.home);
|
|
87
|
+
this.state = existing ?? { since: this.clock(), sent: {} };
|
|
88
|
+
if (existing === undefined) writeSent(ctx.home, this.state);
|
|
89
|
+
if (ctx.signal.aborted) this.controller.abort();
|
|
90
|
+
else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Sends what is waiting on every bound chat, then follows the client's events. */
|
|
94
|
+
start(): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
|
|
95
|
+
const iterator = this.ctx.client.events()[Symbol.asyncIterator]();
|
|
96
|
+
// Wake-ups are pulled before the sweep so a change during it is not missed.
|
|
97
|
+
const initial = this.sweepAll().catch((error: unknown) => this.log(`could not send replies: ${messageOf(error)}`));
|
|
98
|
+
this.watching = (async () => {
|
|
99
|
+
await initial;
|
|
100
|
+
while (!this.stopped) {
|
|
101
|
+
const next = await iterator.next();
|
|
102
|
+
if (next.done === true || this.stopped) return;
|
|
103
|
+
const id = next.value.id;
|
|
104
|
+
if (id.length > 0) void this.sweepChat(id).catch((error: unknown) => this.log(`could not send replies: ${messageOf(error)}`));
|
|
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 Promise.all([...this.queues.values()]);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Sweeps every chat bound to Telegram once. */
|
|
120
|
+
async sweepAll(): Promise<void> {
|
|
121
|
+
const ids: string[] = [];
|
|
122
|
+
let cursor: string | undefined;
|
|
123
|
+
do {
|
|
124
|
+
const page = await this.ctx.store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
125
|
+
for (const object of page.objects) {
|
|
126
|
+
if (telegramChatsOf(chatData(object.data).channels).length > 0) ids.push(object.id);
|
|
127
|
+
}
|
|
128
|
+
cursor = page.next;
|
|
129
|
+
} while (cursor !== undefined);
|
|
130
|
+
await Promise.all(ids.map((id) => this.sweepChat(id)));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Sends the unsent assistant messages of one chat; one sweep of a chat runs at a time. */
|
|
134
|
+
sweepChat(chatId: string): Promise<void> {
|
|
135
|
+
const previous = this.queues.get(chatId) ?? Promise.resolve();
|
|
136
|
+
const run = previous.then(() => this.sweep(chatId));
|
|
137
|
+
const settled = run.catch(() => undefined);
|
|
138
|
+
this.queues.set(chatId, settled);
|
|
139
|
+
void settled.then(() => {
|
|
140
|
+
if (this.queues.get(chatId) === settled) this.queues.delete(chatId);
|
|
141
|
+
});
|
|
142
|
+
return run;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private async sweep(chatId: string): Promise<void> {
|
|
146
|
+
if (this.stopped) return;
|
|
147
|
+
const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
|
|
148
|
+
if (stored === undefined) return;
|
|
149
|
+
const targets = telegramChatsOf(chatData(stored.data).channels);
|
|
150
|
+
const target = targets[0];
|
|
151
|
+
if (target === undefined) return;
|
|
152
|
+
for (const message of allMessages(this.ctx.store, chatId)) {
|
|
153
|
+
if (this.stopped) return;
|
|
154
|
+
if (message.role !== "assistant" || message.at < this.state.since) continue;
|
|
155
|
+
const key = `${chatId}/${message.id}`;
|
|
156
|
+
const record = this.state.sent[key];
|
|
157
|
+
if (record?.done === true) continue;
|
|
158
|
+
await this.send(chatId, key, message, target, record);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private async send(
|
|
163
|
+
chatId: string,
|
|
164
|
+
key: string,
|
|
165
|
+
message: Message,
|
|
166
|
+
target: number,
|
|
167
|
+
record: SentRecord | undefined,
|
|
168
|
+
): Promise<void> {
|
|
169
|
+
const chunks = telegramChunks(message.text);
|
|
170
|
+
let sent = record?.chunks ?? 0;
|
|
171
|
+
let telegramId = record?.telegramId;
|
|
172
|
+
if (chunks.length === 0) {
|
|
173
|
+
this.remember(key, { chunks: 0, done: true });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
while (sent < chunks.length) {
|
|
177
|
+
const chunk = chunks[sent];
|
|
178
|
+
if (chunk === undefined) break;
|
|
179
|
+
let id: number;
|
|
180
|
+
try {
|
|
181
|
+
id = await this.sendChunk(target, chunk);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (this.stopped) return;
|
|
184
|
+
const tries = error instanceof SendGaveUp ? error.tries : 1;
|
|
185
|
+
await this.giveUp(chatId, message, sent, chunks.length, tries, error instanceof SendGaveUp ? error.last : error);
|
|
186
|
+
this.remember(key, { chunks: sent, ...(telegramId === undefined ? {} : { telegramId }), done: true, failed: true });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
sent += 1;
|
|
190
|
+
telegramId = id;
|
|
191
|
+
this.remember(key, { chunks: sent, telegramId, done: sent >= chunks.length });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** One chunk: HTML first, plain text when Telegram cannot read the markup, retried on failure. */
|
|
196
|
+
private async sendChunk(target: number, chunk: TelegramChunk): Promise<number> {
|
|
197
|
+
let plain = false;
|
|
198
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
199
|
+
try {
|
|
200
|
+
return await this.api.sendMessage({
|
|
201
|
+
chatId: target,
|
|
202
|
+
text: plain ? chunk.plain : chunk.html,
|
|
203
|
+
...(plain ? {} : { parseMode: "HTML" as const }),
|
|
204
|
+
signal: this.controller.signal,
|
|
205
|
+
});
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (this.stopped) throw error;
|
|
208
|
+
if (error instanceof BotApiError && error.badMarkup && !plain) {
|
|
209
|
+
plain = true;
|
|
210
|
+
attempt -= 1;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const retryable = error instanceof BotApiError ? error.retryable : true;
|
|
214
|
+
if (!retryable || attempt >= this.retry.attempts) throw new SendGaveUp(attempt, error);
|
|
215
|
+
const backoff = Math.min(this.retry.maxMs, this.retry.baseMs * 2 ** (attempt - 1));
|
|
216
|
+
const asked = error instanceof BotApiError && error.retryAfterSecs !== undefined ? error.retryAfterSecs * 1_000 : 0;
|
|
217
|
+
await this.wait(Math.max(backoff, asked), this.controller.signal);
|
|
218
|
+
if (this.stopped) throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Says that a reply did not reach Telegram: a line in the plugin's log and a
|
|
225
|
+
* `telegram/send_failed` event on the chat, keyed by the message so a retry
|
|
226
|
+
* after a crash records it once. It is the plugin's own record; nothing is
|
|
227
|
+
* written into the chat's messages or entries, which are the chat plugin's.
|
|
228
|
+
*/
|
|
229
|
+
private async giveUp(chatId: string, message: Message, sent: number, total: number, tries: number, error: unknown): Promise<void> {
|
|
230
|
+
const part = total > 1 ? ` (part ${sent + 1} of ${total})` : "";
|
|
231
|
+
const text = `could not send the reply${part}; gave up after ${tries} ${tries === 1 ? "try" : "tries"}: ${messageOf(error)}`;
|
|
232
|
+
await this.ctx.logger.write(`reply ${message.id} of chat ${chatId}: ${text}`);
|
|
233
|
+
await this.ctx.emit({
|
|
234
|
+
source: TELEGRAM_SOURCE,
|
|
235
|
+
type: SEND_FAILED_EVENT,
|
|
236
|
+
key: `${SEND_FAILED_EVENT}:${chatId}/${message.id}`,
|
|
237
|
+
object: `chat:${chatId}`,
|
|
238
|
+
summary: text,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private remember(key: string, record: SentRecord): void {
|
|
243
|
+
this.state = { since: this.state.since, sent: { ...this.state.sent, [key]: record } };
|
|
244
|
+
writeSent(this.ctx.home, this.state);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private async log(message: string): Promise<void> {
|
|
248
|
+
await this.ctx.logger.write(message);
|
|
249
|
+
}
|
|
250
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** The `telegram` section of `config.json`, and what its values mean. */
|
|
2
|
+
|
|
3
|
+
import type { ActionArgsSchema, JsonValue } from "@operad-io/engine";
|
|
4
|
+
|
|
5
|
+
/** The bot a chat is opened on when the settings name none. */
|
|
6
|
+
export const DEFAULT_BOT = "default";
|
|
7
|
+
|
|
8
|
+
/** The name of the secret that holds the Bot API token. */
|
|
9
|
+
export const TOKEN_SECRET = "token";
|
|
10
|
+
|
|
11
|
+
/** The JSON Schema of the `telegram` section (also shipped as `telegram.schema.json`). */
|
|
12
|
+
export const TELEGRAM_SETTINGS: ActionArgsSchema = {
|
|
13
|
+
type: "object",
|
|
14
|
+
properties: {
|
|
15
|
+
users: {
|
|
16
|
+
type: "array",
|
|
17
|
+
items: { type: "integer", minimum: 1 },
|
|
18
|
+
default: [],
|
|
19
|
+
description:
|
|
20
|
+
"The Telegram user ids whose private messages become chat messages. A message from anyone else is recorded and answered with nothing.",
|
|
21
|
+
},
|
|
22
|
+
bot: {
|
|
23
|
+
type: "string",
|
|
24
|
+
minLength: 1,
|
|
25
|
+
default: DEFAULT_BOT,
|
|
26
|
+
description: "The bot a chat is opened on when a listed user writes first.",
|
|
27
|
+
},
|
|
28
|
+
pending: {
|
|
29
|
+
type: "array",
|
|
30
|
+
items: { type: "string", minLength: 1 },
|
|
31
|
+
default: [],
|
|
32
|
+
description:
|
|
33
|
+
"The plugins whose pending items are also sent to Telegram, such as [\"dev\"]. Items of a chat bound to Telegram are always sent.",
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** The settings as the source reads them, with every default filled. */
|
|
40
|
+
export interface TelegramSettings {
|
|
41
|
+
readonly users: readonly number[];
|
|
42
|
+
readonly bot: string;
|
|
43
|
+
readonly pending: readonly string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Reads a validated settings section. Values the schema refused never reach here. */
|
|
47
|
+
export function telegramSettings(settings: Readonly<Record<string, JsonValue>>): TelegramSettings {
|
|
48
|
+
const users = Array.isArray(settings.users)
|
|
49
|
+
? settings.users.filter((value): value is number => typeof value === "number" && Number.isInteger(value))
|
|
50
|
+
: [];
|
|
51
|
+
const bot = typeof settings.bot === "string" && settings.bot.length > 0 ? settings.bot : DEFAULT_BOT;
|
|
52
|
+
const pending = Array.isArray(settings.pending)
|
|
53
|
+
? settings.pending.filter((value): value is string => typeof value === "string" && value.length > 0)
|
|
54
|
+
: [];
|
|
55
|
+
return { users, bot, pending };
|
|
56
|
+
}
|
package/src/source.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The source side of the Telegram plugin: long-polls `getUpdates` and turns a
|
|
3
|
+
* private message from a listed user into one user message on that user's bound
|
|
4
|
+
* chat. A message from anyone else is recorded and starts nothing.
|
|
5
|
+
*
|
|
6
|
+
* Dedupe is never the offset. Every update is recorded once as
|
|
7
|
+
* `telegram/update` keyed by its `update_id`, but what keeps a resent update
|
|
8
|
+
* from writing a second message is the bound chat itself: a message is written
|
|
9
|
+
* only when no message of a chat bound to this Telegram chat has a source ref
|
|
10
|
+
* equal to the update id. The settings (`users`, `bot`) are read once, when
|
|
11
|
+
* the source starts.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
CHAT_TYPE,
|
|
16
|
+
MESSAGE_EVENT,
|
|
17
|
+
allMessages,
|
|
18
|
+
chatData,
|
|
19
|
+
titleFromMessage,
|
|
20
|
+
} from "@operad-io/chat";
|
|
21
|
+
import { messageOf, type SourceContext, type SourceHandle } from "@operad-io/engine";
|
|
22
|
+
import type { BotApi, TelegramMessage, TelegramUpdate } from "./api.ts";
|
|
23
|
+
import type { PendingResponder } from "./pending.ts";
|
|
24
|
+
import { telegramSettings } from "./settings.ts";
|
|
25
|
+
import { readOffset, writeOffset } from "./state.ts";
|
|
26
|
+
|
|
27
|
+
/** The event type the source records an incoming update as. */
|
|
28
|
+
export const UPDATE_EVENT = "update";
|
|
29
|
+
|
|
30
|
+
/** The source of every event this plugin sends. */
|
|
31
|
+
export const TELEGRAM_SOURCE = "telegram";
|
|
32
|
+
|
|
33
|
+
/** The longest summary an update event carries. */
|
|
34
|
+
const SUMMARY_MAX = 300;
|
|
35
|
+
|
|
36
|
+
/** A delay that ends early when the signal is aborted. */
|
|
37
|
+
export function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
if (signal.aborted) {
|
|
40
|
+
resolve();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const finish = (): void => {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
signal.removeEventListener("abort", finish);
|
|
46
|
+
resolve();
|
|
47
|
+
};
|
|
48
|
+
const timer = setTimeout(finish, ms);
|
|
49
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface TelegramSourceOptions {
|
|
54
|
+
readonly api: BotApi;
|
|
55
|
+
readonly clock?: (() => number) | undefined;
|
|
56
|
+
/** How long Telegram may hold a long poll open. */
|
|
57
|
+
readonly longPollSecs?: number | undefined;
|
|
58
|
+
/** The pause between two polls once one returns. */
|
|
59
|
+
readonly pollIntervalMs?: number | undefined;
|
|
60
|
+
readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
|
|
61
|
+
/** Takes the taps on pending items' buttons and the replies to their messages. */
|
|
62
|
+
readonly pending?: PendingResponder | undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One bound chat and whether it still takes messages. */
|
|
66
|
+
interface BoundChat {
|
|
67
|
+
readonly id: string;
|
|
68
|
+
readonly closed: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The message text the source reads: text, else a caption. */
|
|
72
|
+
function messageText(message: TelegramMessage): string | undefined {
|
|
73
|
+
const text = (message.text ?? message.caption ?? "").trim();
|
|
74
|
+
return text.length === 0 ? undefined : text;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function summaryOf(message: TelegramMessage | undefined): string | undefined {
|
|
78
|
+
if (message === undefined) return undefined;
|
|
79
|
+
const text = messageText(message);
|
|
80
|
+
if (text === undefined) return undefined;
|
|
81
|
+
const first = text.split(/\r?\n/)[0]?.trim() ?? "";
|
|
82
|
+
return first.length === 0 ? undefined : first.slice(0, SUMMARY_MAX);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The channel a Telegram chat binds a chat by. */
|
|
86
|
+
export function telegramChannel(chatId: string | number): string {
|
|
87
|
+
return `${TELEGRAM_SOURCE}:${chatId}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class TelegramSource {
|
|
91
|
+
private readonly ctx: SourceContext;
|
|
92
|
+
private readonly api: BotApi;
|
|
93
|
+
private readonly clock: () => number;
|
|
94
|
+
private readonly longPollSecs: number;
|
|
95
|
+
private readonly pollIntervalMs: number;
|
|
96
|
+
private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
97
|
+
private readonly controller = new AbortController();
|
|
98
|
+
private readonly pending: PendingResponder | undefined;
|
|
99
|
+
private readonly users: readonly number[];
|
|
100
|
+
private readonly bot: string;
|
|
101
|
+
|
|
102
|
+
constructor(ctx: SourceContext, options: TelegramSourceOptions) {
|
|
103
|
+
this.ctx = ctx;
|
|
104
|
+
this.api = options.api;
|
|
105
|
+
this.clock = options.clock ?? ctx.clock;
|
|
106
|
+
this.longPollSecs = options.longPollSecs ?? 30;
|
|
107
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 1_000;
|
|
108
|
+
this.wait = options.wait ?? delay;
|
|
109
|
+
this.pending = options.pending;
|
|
110
|
+
const settings = telegramSettings(ctx.settings);
|
|
111
|
+
this.users = settings.users;
|
|
112
|
+
this.bot = settings.bot;
|
|
113
|
+
if (ctx.signal.aborted) this.controller.abort();
|
|
114
|
+
else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Reads every update after the recorded offset once and handles it. */
|
|
118
|
+
async poll(): Promise<readonly TelegramUpdate[]> {
|
|
119
|
+
const offset = readOffset(this.ctx.home);
|
|
120
|
+
const updates = await this.api.getUpdates({
|
|
121
|
+
offset,
|
|
122
|
+
timeoutSecs: this.longPollSecs,
|
|
123
|
+
signal: this.controller.signal,
|
|
124
|
+
});
|
|
125
|
+
// One update that cannot be handled is logged and does not stop the ones
|
|
126
|
+
// after it. The offset confirms only the updates before the first failure,
|
|
127
|
+
// so the failed one is read again; the event key keeps the rest one.
|
|
128
|
+
let confirmed = offset;
|
|
129
|
+
let blocked = false;
|
|
130
|
+
for (const update of updates) {
|
|
131
|
+
try {
|
|
132
|
+
await this.handle(update);
|
|
133
|
+
if (!blocked) confirmed = update.update_id + 1;
|
|
134
|
+
} catch (error) {
|
|
135
|
+
blocked = true;
|
|
136
|
+
await this.ctx.logger.write(`update ${update.update_id}: ${messageOf(error)}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (confirmed > offset) writeOffset(this.ctx.home, confirmed, this.clock());
|
|
140
|
+
return updates;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The long-poll loop; `stop` ends it and aborts a request in flight. */
|
|
144
|
+
start(): SourceHandle {
|
|
145
|
+
let stopped = false;
|
|
146
|
+
const loop = async (): Promise<void> => {
|
|
147
|
+
while (!stopped && !this.controller.signal.aborted) {
|
|
148
|
+
try {
|
|
149
|
+
await this.poll();
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (stopped || this.controller.signal.aborted) return;
|
|
152
|
+
await this.ctx.logger.write(`could not read updates: ${messageOf(error)}`);
|
|
153
|
+
}
|
|
154
|
+
if (stopped || this.controller.signal.aborted) return;
|
|
155
|
+
await this.wait(this.pollIntervalMs, this.controller.signal);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
void loop();
|
|
159
|
+
return {
|
|
160
|
+
stop: () => {
|
|
161
|
+
stopped = true;
|
|
162
|
+
this.controller.abort();
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private async handle(update: TelegramUpdate): Promise<void> {
|
|
168
|
+
const key = String(update.update_id);
|
|
169
|
+
if (update.callback_query !== undefined) {
|
|
170
|
+
// A tap is handled by the pending side; either way it is recorded once.
|
|
171
|
+
await this.pending?.handleCallback(update.callback_query);
|
|
172
|
+
await this.record(key);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const message = update.message;
|
|
176
|
+
if (message === undefined) {
|
|
177
|
+
await this.record(key);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const summary = summaryOf(message);
|
|
181
|
+
const from = message.from?.id;
|
|
182
|
+
const listed = from !== undefined && this.users.includes(from);
|
|
183
|
+
const text = messageText(message);
|
|
184
|
+
// A group, a channel, an unlisted sender or a message with no text is
|
|
185
|
+
// recorded and stops there: no chat, no reply, nothing started.
|
|
186
|
+
if (message.chat.type !== "private" || !listed || text === undefined) {
|
|
187
|
+
await this.record(key, undefined, summary);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// A reply to an item's message that takes a note is that item's answer;
|
|
192
|
+
// a message that is not one is an ordinary message to the chat.
|
|
193
|
+
if (this.pending !== undefined && message.reply_to_message !== undefined && (await this.pending.handleReply(message))) {
|
|
194
|
+
await this.record(key, undefined, summary);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const channel = telegramChannel(message.chat.id);
|
|
199
|
+
const bound = await this.boundChats(channel);
|
|
200
|
+
for (const chat of bound) {
|
|
201
|
+
const previous = this.messageFrom(chat.id, key);
|
|
202
|
+
if (previous === undefined) continue;
|
|
203
|
+
// The message is already written; recording the event sendMessage uses
|
|
204
|
+
// again finishes a reply whose event was lost and starts nothing twice.
|
|
205
|
+
if (!chat.closed) {
|
|
206
|
+
await this.ctx.emit({
|
|
207
|
+
source: TELEGRAM_SOURCE,
|
|
208
|
+
type: MESSAGE_EVENT,
|
|
209
|
+
key: previous.id,
|
|
210
|
+
object: `chat:${previous.chatId}`,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
await this.record(key, previous.chatId, summary);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const open = bound.find((chat) => !chat.closed);
|
|
218
|
+
const chatId = open?.id ?? (await this.openBoundChat(channel, text, from));
|
|
219
|
+
await this.ctx.client.act("chat:send", chatId, {
|
|
220
|
+
args: { note: text, ref: key },
|
|
221
|
+
actor: { via: TELEGRAM_SOURCE, id: String(from) },
|
|
222
|
+
});
|
|
223
|
+
await this.record(key, chatId, summary);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private async record(key: string, chatId?: string, summary?: string): Promise<void> {
|
|
227
|
+
const event = {
|
|
228
|
+
source: TELEGRAM_SOURCE,
|
|
229
|
+
type: UPDATE_EVENT,
|
|
230
|
+
key,
|
|
231
|
+
...(chatId === undefined ? {} : { object: `chat:${chatId}` }),
|
|
232
|
+
...(summary === undefined ? {} : { summary }),
|
|
233
|
+
};
|
|
234
|
+
await this.ctx.emit(event);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Every chat bound to this channel, newest first. */
|
|
238
|
+
private async boundChats(channel: string): Promise<readonly BoundChat[]> {
|
|
239
|
+
const found: BoundChat[] = [];
|
|
240
|
+
let cursor: string | undefined;
|
|
241
|
+
do {
|
|
242
|
+
const page = await this.ctx.store.list(CHAT_TYPE, {
|
|
243
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
244
|
+
});
|
|
245
|
+
for (const object of page.objects) {
|
|
246
|
+
const data = chatData(object.data);
|
|
247
|
+
if (data.channels.includes(channel)) found.push({ id: object.id, closed: data.closed });
|
|
248
|
+
}
|
|
249
|
+
cursor = page.next;
|
|
250
|
+
} while (cursor !== undefined);
|
|
251
|
+
return found.sort((left, right) => right.id.localeCompare(left.id));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** The message already written for this update on a chat, if any. */
|
|
255
|
+
private messageFrom(chatId: string, key: string): { readonly id: string; readonly chatId: string } | undefined {
|
|
256
|
+
const found = allMessages(this.ctx.store, chatId).find(
|
|
257
|
+
(message) =>
|
|
258
|
+
message.role === "user" &&
|
|
259
|
+
message.source.kind === TELEGRAM_SOURCE &&
|
|
260
|
+
message.source.ref === key,
|
|
261
|
+
);
|
|
262
|
+
return found === undefined ? undefined : { id: found.id, chatId };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private async openBoundChat(channel: string, text: string, userId: number): Promise<string> {
|
|
266
|
+
const opened = await this.ctx.client.act("bot:chat", this.bot, {
|
|
267
|
+
args: { title: titleFromMessage(text) ?? "Telegram", channels: [channel] },
|
|
268
|
+
actor: { via: TELEGRAM_SOURCE, id: String(userId) },
|
|
269
|
+
});
|
|
270
|
+
if (opened.opens === undefined || !opened.opens.startsWith("chat:")) {
|
|
271
|
+
throw new Error("bot:chat opened no chat");
|
|
272
|
+
}
|
|
273
|
+
return opened.opens.slice("chat:".length);
|
|
274
|
+
}
|
|
275
|
+
}
|