@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/index.ts
CHANGED
|
@@ -9,19 +9,35 @@
|
|
|
9
9
|
|
|
10
10
|
import pkg from "../package.json" with { type: "json" };
|
|
11
11
|
import { definePlugin, type SourceHandle } from "@operad-io/engine";
|
|
12
|
-
import { createBotApi } from "./api.ts";
|
|
12
|
+
import { createBotApi, type BotApi } from "./api.ts";
|
|
13
|
+
import { CommandSender, pendingCommandAction } from "./commands.ts";
|
|
14
|
+
import { TelegramEvents } from "./events.ts";
|
|
13
15
|
import { TELEGRAM_SETTINGS, TOKEN_SECRET } from "./settings.ts";
|
|
14
16
|
import { PendingSender } from "./pending.ts";
|
|
17
|
+
import { ProgressSender } from "./progress.ts";
|
|
15
18
|
import { ReplySender } from "./replies.ts";
|
|
16
19
|
import { TelegramSource, delay } from "./source.ts";
|
|
20
|
+
import { TypingSender } from "./typing.ts";
|
|
21
|
+
|
|
22
|
+
/** What a test gives the plugin instead of what it builds itself. */
|
|
23
|
+
export interface TelegramPluginOptions {
|
|
24
|
+
/** The Bot API to use; by default the real one, from the token. */
|
|
25
|
+
readonly api?: BotApi | undefined;
|
|
26
|
+
readonly clock?: (() => number) | undefined;
|
|
27
|
+
readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
|
|
28
|
+
readonly intervalMs?: number | undefined;
|
|
29
|
+
}
|
|
17
30
|
|
|
18
31
|
/** Builds the Telegram source plugin. */
|
|
19
|
-
export function createTelegramPlugin() {
|
|
32
|
+
export function createTelegramPlugin(options: TelegramPluginOptions = {}) {
|
|
33
|
+
/** The pending side of the running source, which `/pending` reads. */
|
|
34
|
+
let pendingSender: PendingSender | undefined;
|
|
20
35
|
return definePlugin({
|
|
21
36
|
name: "telegram",
|
|
22
37
|
kind: "source",
|
|
23
38
|
version: pkg.version,
|
|
24
39
|
settings: TELEGRAM_SETTINGS,
|
|
40
|
+
actions: [pendingCommandAction(() => pendingSender)],
|
|
25
41
|
async start(ctx): Promise<SourceHandle> {
|
|
26
42
|
const token = await ctx.secrets.get(TOKEN_SECRET);
|
|
27
43
|
if (token === undefined) {
|
|
@@ -29,16 +45,52 @@ export function createTelegramPlugin() {
|
|
|
29
45
|
"the telegram plugin has no token; set it with `operad secret set telegram token`",
|
|
30
46
|
);
|
|
31
47
|
}
|
|
32
|
-
const api = createBotApi({ token });
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
-
|
|
48
|
+
const api = options.api ?? createBotApi({ token });
|
|
49
|
+
const wait = options.wait ?? delay;
|
|
50
|
+
const events = new TelegramEvents(ctx, { wait });
|
|
51
|
+
const pending = new PendingSender(ctx, { api, wait });
|
|
52
|
+
pendingSender = pending;
|
|
53
|
+
const commands = new CommandSender(ctx, { api });
|
|
54
|
+
const typingSender = new TypingSender(ctx, {
|
|
55
|
+
api,
|
|
56
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
57
|
+
wait,
|
|
58
|
+
...(options.intervalMs === undefined ? {} : { intervalMs: options.intervalMs }),
|
|
59
|
+
});
|
|
60
|
+
const typing = typingSender.start(events);
|
|
61
|
+
const replySender = new ReplySender(ctx, { api, wait });
|
|
62
|
+
const replies = replySender.start(events);
|
|
63
|
+
const progressSender = new ProgressSender(ctx, {
|
|
64
|
+
api,
|
|
65
|
+
replies: replySender,
|
|
66
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
67
|
+
wait,
|
|
68
|
+
});
|
|
69
|
+
const progress = progressSender.start(events);
|
|
70
|
+
const telegram = new TelegramSource(ctx, { api, pending, commands, typing: typingSender });
|
|
71
|
+
const source = telegram.start();
|
|
72
|
+
const menu = commands.start(events);
|
|
73
|
+
const sent = pending.start(events);
|
|
74
|
+
const watching = events.start({
|
|
75
|
+
progress: (event) => progressSender.handleEvent(event),
|
|
76
|
+
replies: (event) => replySender.handleEvent(event),
|
|
77
|
+
typing: (event) => typingSender.handleEvent(event),
|
|
78
|
+
pending: (event) => pending.handleEvent(event),
|
|
79
|
+
commands: () => {
|
|
80
|
+
void commands.refresh();
|
|
81
|
+
},
|
|
82
|
+
source: (chatId) => telegram.changed(chatId),
|
|
83
|
+
});
|
|
37
84
|
return {
|
|
38
85
|
stop: async () => {
|
|
39
86
|
await source.stop();
|
|
87
|
+
await menu.stop();
|
|
88
|
+
await watching.stop();
|
|
89
|
+
await typing.stop();
|
|
90
|
+
await progress.stop();
|
|
40
91
|
await replies.stop();
|
|
41
92
|
await sent.stop();
|
|
93
|
+
if (pendingSender === pending) pendingSender = undefined;
|
|
42
94
|
},
|
|
43
95
|
};
|
|
44
96
|
},
|
|
@@ -48,9 +100,12 @@ export function createTelegramPlugin() {
|
|
|
48
100
|
export default createTelegramPlugin();
|
|
49
101
|
|
|
50
102
|
export * from "./api.ts";
|
|
103
|
+
export * from "./commands.ts";
|
|
51
104
|
export * from "./format.ts";
|
|
52
105
|
export * from "./pending.ts";
|
|
106
|
+
export * from "./progress.ts";
|
|
53
107
|
export * from "./replies.ts";
|
|
54
108
|
export * from "./settings.ts";
|
|
55
109
|
export * from "./source.ts";
|
|
56
110
|
export * from "./state.ts";
|
|
111
|
+
export * from "./typing.ts";
|
package/src/pending.ts
CHANGED
|
@@ -14,11 +14,18 @@
|
|
|
14
14
|
* An action that needs a note, and a free answer, are answered by replying to
|
|
15
15
|
* the item's message. After an answer, from Telegram or anywhere else, the
|
|
16
16
|
* buttons go and the message reads "answered: X".
|
|
17
|
+
*
|
|
18
|
+
* `/pending` sends every answerable item now, whatever the `pending` setting
|
|
19
|
+
* lists: its count line goes first, then the items that were not already sent
|
|
20
|
+
* to that chat, through the same build and send path as a pushed item. The
|
|
21
|
+
* count line holds the pending pass so nothing slips in before the items; if
|
|
22
|
+
* the line never comes the items are sent after a deadline and the pass goes.
|
|
17
23
|
*/
|
|
18
24
|
|
|
19
25
|
import { CHAT_TYPE, chatData } from "@operad-io/chat";
|
|
20
26
|
import {
|
|
21
27
|
messageOf,
|
|
28
|
+
parseObjectId,
|
|
22
29
|
type Actor,
|
|
23
30
|
type ClientApi,
|
|
24
31
|
type PendingItem,
|
|
@@ -26,9 +33,12 @@ import {
|
|
|
26
33
|
type ViewAction,
|
|
27
34
|
} from "@operad-io/engine";
|
|
28
35
|
import { BotApiError, type BotApi, type InlineButton, type TelegramCallback, type TelegramMessage } from "./api.ts";
|
|
36
|
+
import { PENDING_NOTHING } from "./commands.ts";
|
|
37
|
+
import { TelegramEvents, type TelegramEvent } from "./events.ts";
|
|
29
38
|
import { telegramChatsOf } from "./replies.ts";
|
|
39
|
+
import { delay } from "./source.ts";
|
|
30
40
|
import { telegramSettings, type TelegramSettings } from "./settings.ts";
|
|
31
|
-
import { readPending, writePending, type PendingState, type SentItem, type SentOption } from "./state.ts";
|
|
41
|
+
import { prunePending, readPending, writePending, type PendingState, type SentItem, type SentOption } from "./state.ts";
|
|
32
42
|
|
|
33
43
|
/** The `via` of every answer this plugin gives. */
|
|
34
44
|
const VIA = "telegram";
|
|
@@ -36,17 +46,27 @@ const VIA = "telegram";
|
|
|
36
46
|
/** The longest item text sent; Telegram's own limit is 4096 characters. */
|
|
37
47
|
const TEXT_MAX = 3_500;
|
|
38
48
|
|
|
49
|
+
/** How long `/pending` waits for its count line before it sends the items anyway. */
|
|
50
|
+
export const HOLD_MS = 30_000;
|
|
51
|
+
|
|
52
|
+
/** How long stored changes are gathered before one pending pass reads them. */
|
|
53
|
+
export const PENDING_DEBOUNCE_MS = 100;
|
|
54
|
+
|
|
39
55
|
/** What the source asks of the pending side for a tap or a reply. */
|
|
40
56
|
export interface PendingResponder {
|
|
41
57
|
/** A tap on a button; true when the tap belonged to a pending item message. */
|
|
42
58
|
handleCallback(callback: TelegramCallback): Promise<boolean>;
|
|
43
59
|
/** A reply to a message; true when the reply answered (or tried to answer) a pending item. */
|
|
44
60
|
handleReply(message: TelegramMessage): Promise<boolean>;
|
|
61
|
+
/** Sends the item messages `/pending` prepared for this Telegram chat. */
|
|
62
|
+
show(target: number): Promise<void>;
|
|
45
63
|
}
|
|
46
64
|
|
|
47
65
|
export interface PendingSenderOptions {
|
|
48
66
|
readonly api: BotApi;
|
|
49
67
|
readonly clock?: (() => number) | undefined;
|
|
68
|
+
/** Waits `ms` unless `signal` aborts first; a test gives one it moves itself. */
|
|
69
|
+
readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
|
|
50
70
|
}
|
|
51
71
|
|
|
52
72
|
/** The data a button carries: its option's position on the message. */
|
|
@@ -67,55 +87,127 @@ function itemKeyOf(key: string): string {
|
|
|
67
87
|
return key.slice(0, key.lastIndexOf("/"));
|
|
68
88
|
}
|
|
69
89
|
|
|
90
|
+
/** An item and the message `/pending` will send for it. */
|
|
91
|
+
interface PlannedItem {
|
|
92
|
+
readonly item: PendingItem;
|
|
93
|
+
readonly text: string;
|
|
94
|
+
readonly options: readonly SentOption[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The items `/pending` prepared for one Telegram chat, and the way to let the pass go. */
|
|
98
|
+
interface HeldItems {
|
|
99
|
+
readonly items: readonly PlannedItem[];
|
|
100
|
+
readonly release: () => void;
|
|
101
|
+
/** Ends the deadline once `show` sends the items. */
|
|
102
|
+
readonly deadline: AbortController;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** An option with what the asker says about its choice. */
|
|
106
|
+
interface BuiltOption {
|
|
107
|
+
readonly option: SentOption;
|
|
108
|
+
readonly info?: { readonly hint?: string | undefined; readonly role?: "primary" | "destructive" | undefined } | undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Primary first, the other choices in their order, destructive last. */
|
|
112
|
+
function orderedOptions(built: readonly BuiltOption[]): readonly BuiltOption[] {
|
|
113
|
+
const rank = (entry: BuiltOption): number =>
|
|
114
|
+
entry.info?.role === "primary" ? 0 : entry.info?.role === "destructive" ? 2 : 1;
|
|
115
|
+
return built
|
|
116
|
+
.map((entry, index) => ({ entry, index }))
|
|
117
|
+
.sort((left, right) => rank(left.entry) - rank(right.entry) || left.index - right.index)
|
|
118
|
+
.map(({ entry }) => entry);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The name a fact carries for an option: a raw choice or an action's own name. */
|
|
122
|
+
function optionName(option: SentOption): string {
|
|
123
|
+
if (option.how === "choice") return option.choice ?? option.label;
|
|
124
|
+
if (option.how === "act" && option.action !== undefined) {
|
|
125
|
+
return option.action.slice(option.action.lastIndexOf(":") + 1);
|
|
126
|
+
}
|
|
127
|
+
return option.label;
|
|
128
|
+
}
|
|
129
|
+
|
|
70
130
|
export class PendingSender implements PendingResponder {
|
|
71
131
|
private readonly ctx: SourceContext;
|
|
72
132
|
private readonly api: BotApi;
|
|
73
133
|
private readonly client: ClientApi;
|
|
74
134
|
private readonly clock: () => number;
|
|
135
|
+
private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
75
136
|
private readonly settings: TelegramSettings;
|
|
76
137
|
private readonly controller = new AbortController();
|
|
77
138
|
private state: PendingState;
|
|
78
139
|
private stopped = false;
|
|
79
140
|
private watching: Promise<void> = Promise.resolve();
|
|
141
|
+
private following: { readonly stop: () => Promise<void> } | undefined;
|
|
142
|
+
/** The one wait that gathers a burst of stored changes into a pass. */
|
|
143
|
+
private debounce: AbortController | undefined;
|
|
80
144
|
/** Everything that reads or writes the state runs one at a time. */
|
|
81
145
|
private tail: Promise<unknown> = Promise.resolve();
|
|
82
146
|
private queued = false;
|
|
147
|
+
/** The item messages `/pending` prepared for a Telegram chat, waiting for its count line. */
|
|
148
|
+
private readonly held = new Map<number, HeldItems>();
|
|
83
149
|
|
|
84
150
|
constructor(ctx: SourceContext, options: PendingSenderOptions) {
|
|
85
151
|
this.ctx = ctx;
|
|
86
152
|
this.api = options.api;
|
|
87
153
|
this.client = ctx.client;
|
|
88
154
|
this.clock = options.clock ?? ctx.clock;
|
|
155
|
+
this.wait = options.wait ?? delay;
|
|
89
156
|
this.settings = telegramSettings(ctx.settings);
|
|
90
157
|
this.state = readPending(ctx.home);
|
|
91
158
|
if (ctx.signal.aborted) this.controller.abort();
|
|
92
159
|
else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
|
|
93
160
|
}
|
|
94
161
|
|
|
95
|
-
/** Sends what waits now, then follows the
|
|
96
|
-
start(): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
|
|
97
|
-
const
|
|
162
|
+
/** Sends what waits now, then follows changes, alone or through the plugin's one loop. */
|
|
163
|
+
start(events?: TelegramEvents): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
|
|
164
|
+
const local = events === undefined ? new TelegramEvents(this.ctx, { wait: this.wait }) : undefined;
|
|
98
165
|
const initial = this.sync();
|
|
99
166
|
this.watching = (async () => {
|
|
100
167
|
await initial;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}
|
|
168
|
+
if (this.stopped) return;
|
|
169
|
+
this.following = local?.start({
|
|
170
|
+
pending: (event) => this.handleEvent(event),
|
|
171
|
+
});
|
|
106
172
|
})();
|
|
107
173
|
return {
|
|
108
174
|
ready: initial,
|
|
109
175
|
stop: async () => {
|
|
110
176
|
this.stopped = true;
|
|
111
177
|
this.controller.abort();
|
|
112
|
-
|
|
178
|
+
this.debounce?.abort();
|
|
179
|
+
this.debounce = undefined;
|
|
180
|
+
this.releaseHeld();
|
|
181
|
+
await this.following?.stop();
|
|
113
182
|
await this.watching.catch(() => undefined);
|
|
114
183
|
await this.tail.catch(() => undefined);
|
|
115
184
|
},
|
|
116
185
|
};
|
|
117
186
|
}
|
|
118
187
|
|
|
188
|
+
/** A stored change; a burst of them is gathered into one later pending pass. */
|
|
189
|
+
handleEvent(event: TelegramEvent): void {
|
|
190
|
+
if (event.section !== undefined || this.stopped) return;
|
|
191
|
+
// The first change opens the window; changes during it join the same pass.
|
|
192
|
+
// Restarting the window on every change would let a steady stream postpone
|
|
193
|
+
// the pass forever.
|
|
194
|
+
if (this.debounce !== undefined) return;
|
|
195
|
+
const timer = new AbortController();
|
|
196
|
+
this.debounce = timer;
|
|
197
|
+
void this.wait(PENDING_DEBOUNCE_MS, timer.signal).then(
|
|
198
|
+
() => {
|
|
199
|
+
if (this.debounce !== timer) return;
|
|
200
|
+
this.debounce = undefined;
|
|
201
|
+
void this.sync().catch((error: unknown) =>
|
|
202
|
+
this.ctx.logger.write(`could not send pending items: ${messageOf(error)}`),
|
|
203
|
+
);
|
|
204
|
+
},
|
|
205
|
+
() => {
|
|
206
|
+
if (this.debounce === timer) this.debounce = undefined;
|
|
207
|
+
},
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
119
211
|
/**
|
|
120
212
|
* One pass: send every item that waits and was not sent, and change the
|
|
121
213
|
* message of every sent item that no longer waits. Passes run one at a time;
|
|
@@ -166,6 +258,113 @@ export class PendingSender implements PendingResponder {
|
|
|
166
258
|
}
|
|
167
259
|
}
|
|
168
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Prepares what `/pending` sends after its count line: every answerable item,
|
|
263
|
+
* whatever `pending` lists, except the ones already sent and still open in
|
|
264
|
+
* this chat. Returns the count line. A Telegram command holds the pending
|
|
265
|
+
* pass until {@link show}, so nothing slips in between the count and the items.
|
|
266
|
+
*/
|
|
267
|
+
async prepare(chatId: string, hold = false): Promise<string> {
|
|
268
|
+
let release = (): void => {};
|
|
269
|
+
const gate = hold
|
|
270
|
+
? new Promise<void>((resolve) => {
|
|
271
|
+
release = resolve;
|
|
272
|
+
})
|
|
273
|
+
: undefined;
|
|
274
|
+
const work = this.tail.catch(() => undefined).then(async () => {
|
|
275
|
+
const target = await this.chatTarget(chatId);
|
|
276
|
+
if (target === undefined) return { line: PENDING_NOTHING, target, items: [] as readonly PlannedItem[] };
|
|
277
|
+
const items: PlannedItem[] = [];
|
|
278
|
+
let already = 0;
|
|
279
|
+
for (const item of await this.client.pending()) {
|
|
280
|
+
if (!this.answerable(item)) continue;
|
|
281
|
+
if (this.state[stateKey(item, target)] !== undefined) {
|
|
282
|
+
already += 1;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const built = await this.build(item);
|
|
286
|
+
if (built === undefined) continue;
|
|
287
|
+
items.push({ item, text: built.text, options: built.options });
|
|
288
|
+
}
|
|
289
|
+
const total = items.length + already;
|
|
290
|
+
const line =
|
|
291
|
+
total === 0
|
|
292
|
+
? PENDING_NOTHING
|
|
293
|
+
: already === 0
|
|
294
|
+
? `${total} waiting`
|
|
295
|
+
: `${total} waiting; ${already} already sent`;
|
|
296
|
+
return { line, target, items };
|
|
297
|
+
});
|
|
298
|
+
this.tail = gate === undefined ? work.catch(() => undefined) : work.then(() => gate).catch(() => undefined);
|
|
299
|
+
try {
|
|
300
|
+
const result = await work;
|
|
301
|
+
if (gate === undefined || result.target === undefined || this.stopped) release();
|
|
302
|
+
else this.hold(result.target, result.items, release);
|
|
303
|
+
return result.line;
|
|
304
|
+
} catch (error) {
|
|
305
|
+
release();
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Holds the pending pass until `/pending`'s count line went; the deadline lets
|
|
312
|
+
* it go and sends the items when that line never comes, so no chat stays shut.
|
|
313
|
+
*/
|
|
314
|
+
private hold(target: number, items: readonly PlannedItem[], release: () => void): void {
|
|
315
|
+
const deadline = new AbortController();
|
|
316
|
+
this.held.set(target, { items, release, deadline });
|
|
317
|
+
void this.wait(HOLD_MS, deadline.signal).then(
|
|
318
|
+
() => {
|
|
319
|
+
// A line that came aborted the deadline; only a live hold reaches here.
|
|
320
|
+
if (this.held.get(target)?.deadline !== deadline) return;
|
|
321
|
+
void this.show(target).catch(() => undefined);
|
|
322
|
+
},
|
|
323
|
+
() => undefined,
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Lets go of every held count line, as stopping does; their items wait for another pass. */
|
|
328
|
+
private releaseHeld(): void {
|
|
329
|
+
for (const [target, held] of this.held) {
|
|
330
|
+
this.held.delete(target);
|
|
331
|
+
held.deadline.abort();
|
|
332
|
+
held.release();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Sends the item messages prepared for this chat, after `/pending`'s count line. */
|
|
337
|
+
async show(target: number): Promise<void> {
|
|
338
|
+
const held = this.held.get(target);
|
|
339
|
+
this.held.delete(target);
|
|
340
|
+
held?.deadline.abort();
|
|
341
|
+
if (held === undefined || held.items.length === 0) {
|
|
342
|
+
held?.release();
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
await this.sendPlanned(target, held.items);
|
|
347
|
+
} finally {
|
|
348
|
+
held.release();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Sends the item messages `/pending` prepared for one chat, skipping ones another pass already sent. */
|
|
353
|
+
private async sendPlanned(target: number, items: readonly PlannedItem[]): Promise<void> {
|
|
354
|
+
for (const entry of items) {
|
|
355
|
+
if (this.stopped) return;
|
|
356
|
+
if (this.state[stateKey(entry.item, target)] !== undefined) continue;
|
|
357
|
+
await this.send(entry.item, target, entry.text, entry.options);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** The Telegram chat a bound chat sends `/pending` to. */
|
|
362
|
+
private async chatTarget(chatId: string): Promise<number | undefined> {
|
|
363
|
+
const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
|
|
364
|
+
if (stored === undefined) return undefined;
|
|
365
|
+
return telegramChatsOf(chatData(stored.data).channels)[0];
|
|
366
|
+
}
|
|
367
|
+
|
|
169
368
|
/** An item a person can answer here: it names a question, or an object to act on. */
|
|
170
369
|
private answerable(item: PendingItem): boolean {
|
|
171
370
|
if (item.kind === "candidate" || item.kind === "refused") return false;
|
|
@@ -194,35 +393,64 @@ export class PendingSender implements PendingResponder {
|
|
|
194
393
|
private async build(item: PendingItem): Promise<{ readonly text: string; readonly options: readonly SentOption[] } | undefined> {
|
|
195
394
|
const infos = await this.actionsOf(item);
|
|
196
395
|
const names = item.choices.length > 0 ? item.choices : item.actions.map((action) => action.action);
|
|
197
|
-
const
|
|
396
|
+
const built: BuiltOption[] = [];
|
|
397
|
+
const seen = new Set<string>();
|
|
198
398
|
for (const name of names) {
|
|
199
|
-
if (
|
|
399
|
+
if (seen.has(name)) continue;
|
|
400
|
+
seen.add(name);
|
|
401
|
+
const choiceInfo = item.choiceInfo?.[name];
|
|
200
402
|
const action = item.actions.find((candidate) => candidate.action === name);
|
|
201
403
|
if (action !== undefined && item.object !== undefined) {
|
|
202
404
|
const info = infos.find((candidate) => candidate.plugin === action.plugin && candidate.action === action.action);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
405
|
+
const note =
|
|
406
|
+
choiceInfo?.note === "required" || info?.noteRequired === true
|
|
407
|
+
? "required"
|
|
408
|
+
: choiceInfo?.note === "optional"
|
|
409
|
+
? "optional"
|
|
410
|
+
: undefined;
|
|
411
|
+
built.push({
|
|
412
|
+
info: choiceInfo,
|
|
413
|
+
option: {
|
|
414
|
+
label: choiceInfo?.label ?? name,
|
|
415
|
+
how: "act",
|
|
416
|
+
action: `${action.plugin}:${action.action}`,
|
|
417
|
+
...(note === undefined ? {} : { note }),
|
|
418
|
+
},
|
|
208
419
|
});
|
|
209
420
|
} else if (item.waitId !== undefined && item.choices.length > 0) {
|
|
210
|
-
|
|
421
|
+
built.push({
|
|
422
|
+
info: choiceInfo,
|
|
423
|
+
option: {
|
|
424
|
+
label: choiceInfo?.label ?? name,
|
|
425
|
+
how: "choice",
|
|
426
|
+
choice: name,
|
|
427
|
+
...(choiceInfo?.note === undefined ? {} : { note: choiceInfo.note }),
|
|
428
|
+
},
|
|
429
|
+
});
|
|
211
430
|
}
|
|
212
431
|
}
|
|
213
|
-
if (
|
|
214
|
-
|
|
432
|
+
if (built.length === 0 && item.waitId !== undefined) {
|
|
433
|
+
built.push({ option: { label: "answer", how: "free", note: "required" } });
|
|
434
|
+
}
|
|
435
|
+
if (built.length === 0) return undefined;
|
|
436
|
+
const ordered = orderedOptions(built);
|
|
437
|
+
const options = ordered.map((entry) => entry.option);
|
|
215
438
|
|
|
216
439
|
const lines: string[] = [];
|
|
217
440
|
const title = item.row?.title;
|
|
218
441
|
if (title !== undefined && title.length > 0 && !item.prompt.includes(title)) lines.push(title);
|
|
219
442
|
lines.push(item.prompt);
|
|
443
|
+
for (const entry of ordered) {
|
|
444
|
+
if (entry.info?.hint !== undefined) lines.push(entry.info.hint);
|
|
445
|
+
}
|
|
220
446
|
for (const option of options) {
|
|
221
|
-
if (option.note
|
|
447
|
+
if (option.note === undefined) continue;
|
|
222
448
|
lines.push(
|
|
223
449
|
option.how === "free"
|
|
224
450
|
? "Reply to this message with your answer."
|
|
225
|
-
:
|
|
451
|
+
: option.note === "optional"
|
|
452
|
+
? `Reply to this message to ${option.label} with a note; your reply is the note.`
|
|
453
|
+
: `Reply to this message to ${option.label}; your reply is the note.`,
|
|
226
454
|
);
|
|
227
455
|
}
|
|
228
456
|
const text = lines.join("\n\n");
|
|
@@ -242,7 +470,7 @@ export class PendingSender implements PendingResponder {
|
|
|
242
470
|
private async send(item: PendingItem, chatId: number, text: string, options: readonly SentOption[]): Promise<void> {
|
|
243
471
|
const keyboard: InlineButton[][] = [];
|
|
244
472
|
options.forEach((option, index) => {
|
|
245
|
-
if (option.note !==
|
|
473
|
+
if (option.note !== "required") keyboard.push([{ text: option.label, data: buttonData(index) }]);
|
|
246
474
|
});
|
|
247
475
|
let messageId: number;
|
|
248
476
|
try {
|
|
@@ -272,9 +500,8 @@ export class PendingSender implements PendingResponder {
|
|
|
272
500
|
/** What an item answered somewhere else was answered with: the latest action run on its object since it was sent. */
|
|
273
501
|
private async answeredWith(sent: SentItem): Promise<string | undefined> {
|
|
274
502
|
if (sent.object === undefined) return undefined;
|
|
275
|
-
const
|
|
276
|
-
if (
|
|
277
|
-
const ref = { type: sent.object.slice(0, split), id: sent.object.slice(split + 1) };
|
|
503
|
+
const ref = parseObjectId(sent.object, { allowEmptyId: true });
|
|
504
|
+
if (ref === undefined) return undefined;
|
|
278
505
|
let latest: string | undefined;
|
|
279
506
|
try {
|
|
280
507
|
let cursor: string | undefined;
|
|
@@ -285,7 +512,8 @@ export class PendingSender implements PendingResponder {
|
|
|
285
512
|
const action = fact.data.action;
|
|
286
513
|
if (typeof action !== "string") continue;
|
|
287
514
|
const name = action.slice(action.lastIndexOf("/") + 1);
|
|
288
|
-
|
|
515
|
+
const matched = sent.options.find((option) => optionName(option) === name);
|
|
516
|
+
if (matched !== undefined) latest = matched.label;
|
|
289
517
|
}
|
|
290
518
|
cursor = page.next;
|
|
291
519
|
} while (cursor !== undefined);
|
|
@@ -305,14 +533,18 @@ export class PendingSender implements PendingResponder {
|
|
|
305
533
|
} catch {
|
|
306
534
|
return undefined;
|
|
307
535
|
}
|
|
308
|
-
const
|
|
536
|
+
const choices = sent.options.flatMap((option) =>
|
|
537
|
+
option.how === "choice" ? [{ raw: option.choice ?? option.label, label: option.label }] : [],
|
|
538
|
+
);
|
|
309
539
|
let chosen: string | undefined;
|
|
310
540
|
for (const line of markdown.split("\n")) {
|
|
311
541
|
const at = line.indexOf("you chose ");
|
|
312
542
|
if (at < 0) continue;
|
|
313
543
|
const rest = line.slice(at + "you chose ".length);
|
|
314
|
-
const found =
|
|
315
|
-
|
|
544
|
+
const found = choices.find(
|
|
545
|
+
(choice) => rest.startsWith(choice.raw) && !/^\w/.test(rest.slice(choice.raw.length)),
|
|
546
|
+
);
|
|
547
|
+
if (found !== undefined) chosen = found.label;
|
|
316
548
|
}
|
|
317
549
|
return chosen;
|
|
318
550
|
}
|
|
@@ -343,7 +575,7 @@ export class PendingSender implements PendingResponder {
|
|
|
343
575
|
}
|
|
344
576
|
|
|
345
577
|
private remember(key: string, item: SentItem): void {
|
|
346
|
-
this.state = { ...this.state, [key]: item };
|
|
578
|
+
this.state = prunePending({ ...this.state, [key]: item });
|
|
347
579
|
writePending(this.ctx.home, this.state);
|
|
348
580
|
}
|
|
349
581
|
|
|
@@ -383,7 +615,7 @@ export class PendingSender implements PendingResponder {
|
|
|
383
615
|
}
|
|
384
616
|
const index = /^o:(\d+)$/.exec(callback.data ?? "")?.[1];
|
|
385
617
|
const option = index === undefined ? undefined : sent.options[Number(index)];
|
|
386
|
-
if (option === undefined || option.note ===
|
|
618
|
+
if (option === undefined || option.note === "required") {
|
|
387
619
|
await this.tell(callback.id, "this button is no longer valid");
|
|
388
620
|
return true;
|
|
389
621
|
}
|
|
@@ -409,7 +641,7 @@ export class PendingSender implements PendingResponder {
|
|
|
409
641
|
const found = this.find(message.chat.id, to);
|
|
410
642
|
if (found === undefined || !this.listed(message.from?.id)) return false;
|
|
411
643
|
const { key, sent } = found;
|
|
412
|
-
const noted = sent.options.filter((option) => option.note
|
|
644
|
+
const noted = sent.options.filter((option) => option.note !== undefined);
|
|
413
645
|
// A reply to an item with nothing to say in a reply is an ordinary message.
|
|
414
646
|
if (noted.length === 0) return false;
|
|
415
647
|
const reply = (words: string): Promise<number> =>
|
|
@@ -460,7 +692,7 @@ export class PendingSender implements PendingResponder {
|
|
|
460
692
|
await this.client.answer({
|
|
461
693
|
runId: sent.runId,
|
|
462
694
|
waitId: sent.waitId,
|
|
463
|
-
choice: option.how === "free" ? (note ?? "") : option.label,
|
|
695
|
+
choice: option.how === "free" ? (note ?? "") : option.choice ?? option.label,
|
|
464
696
|
...(option.how === "choice" && note !== undefined ? { note } : {}),
|
|
465
697
|
actor,
|
|
466
698
|
});
|