pi-durable-bot 0.4.0 → 0.5.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/CHANGELOG.md +31 -0
- package/README.md +21 -14
- package/dist/bot/prompt.js +2 -1
- package/dist/bot/prompt.js.map +1 -1
- package/dist/channels/discord/index.js +955 -0
- package/dist/channels/discord/index.js.map +1 -0
- package/dist/channels/slack/index.js +83 -23
- package/dist/channels/slack/index.js.map +1 -1
- package/dist/channels/slack/sdk.js +12 -0
- package/dist/channels/slack/sdk.js.map +1 -1
- package/dist/channels/telegram/index.js +875 -0
- package/dist/channels/telegram/index.js.map +1 -0
- package/dist/channels/telegram/sdk.js +24 -0
- package/dist/channels/telegram/sdk.js.map +1 -0
- package/dist/channels/test/index.js +1 -1
- package/dist/channels/test/index.js.map +1 -1
- package/dist/cli/ai.js +137 -29
- package/dist/cli/ai.js.map +1 -1
- package/dist/cli/commands.js +2 -1
- package/dist/cli/commands.js.map +1 -1
- package/dist/cli/init.js +11 -7
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/login.js +38 -0
- package/dist/cli/login.js.map +1 -0
- package/dist/core/channel.js +2 -1
- package/dist/core/channel.js.map +1 -1
- package/dist/gateway/channels.js +33 -4
- package/dist/gateway/channels.js.map +1 -1
- package/dist/gateway/gateway.js +1 -0
- package/dist/gateway/gateway.js.map +1 -1
- package/dist/gateway/inbox.js +31 -2
- package/dist/gateway/inbox.js.map +1 -1
- package/dist/gateway/log.js +3 -2
- package/dist/gateway/log.js.map +1 -1
- package/dist/gateway/outbox.js +3 -0
- package/dist/gateway/outbox.js.map +1 -1
- package/dist/gateway/waker.js +24 -3
- package/dist/gateway/waker.js.map +1 -1
- package/dist/main.js +10 -3
- package/dist/main.js.map +1 -1
- package/docs/channels/discord.md +60 -0
- package/docs/channels/slack.md +46 -0
- package/docs/channels/telegram.md +50 -0
- package/docs/for-agents.md +21 -19
- package/package.json +14 -9
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
5
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
+
import { DiscordFormatConverter } from "@chat-adapter/discord";
|
|
7
|
+
import { convertEmojiPlaceholders, defaultEmojiResolver } from "chat";
|
|
8
|
+
import { Client, DiscordAPIError, Events, GatewayIntentBits, MessageType } from "discord.js";
|
|
9
|
+
import { expandHome, readSecrets } from "../../core/env-file.js";
|
|
10
|
+
// Channel types (https://discord.com/developers/docs/resources/channel#channel-object-channel-types).
|
|
11
|
+
const DM = 1;
|
|
12
|
+
const GROUP_DM = 3;
|
|
13
|
+
/** Server channels with their own messages: text, voice, announcement and stage channels. */
|
|
14
|
+
const TEXT = new Set([0, 2, 5, 13]);
|
|
15
|
+
const THREADS = new Set([10, 11, 12]);
|
|
16
|
+
/** Channels that can have threads: text, announcement, forum and media channels. */
|
|
17
|
+
const THREAD_PARENTS = new Set([0, 5, 15, 16]);
|
|
18
|
+
/** Forum and media channels: their posts are threads, and a post's first message is in the thread. */
|
|
19
|
+
const FORUMS = new Set([15, 16]);
|
|
20
|
+
/** The copy of a thread's first message that Discord shows in the thread; the message itself is in the channel. */
|
|
21
|
+
const THREAD_STARTER_MESSAGE = 21;
|
|
22
|
+
/**
|
|
23
|
+
* The system message in a channel when a thread starts from it, with the thread's name as its text. THREAD_CREATE
|
|
24
|
+
* already logs the thread start, so this one is left out; logged as a message, it read as words its author said.
|
|
25
|
+
*/
|
|
26
|
+
const THREAD_CREATED = 18;
|
|
27
|
+
/** The system message a server posts when someone joins it, when the server has its welcome messages on. */
|
|
28
|
+
const USER_JOIN = 7;
|
|
29
|
+
/** Messages that people and apps write. Every other type is a system message, such as a pin or a new channel name. */
|
|
30
|
+
const WRITTEN = new Set([MessageType.Default, MessageType.Reply, MessageType.ChatInputCommand, MessageType.ContextMenuCommand]);
|
|
31
|
+
/** What a system message says, in words, for the types a server sees most; the others give their type's name. */
|
|
32
|
+
const SYSTEM_TEXT = {
|
|
33
|
+
[MessageType.ChannelPinnedMessage]: () => "pinned a message",
|
|
34
|
+
[MessageType.ChannelNameChange]: (content) => `changed the channel's name to "${content}"`,
|
|
35
|
+
[MessageType.ChannelIconChange]: () => "changed the channel's icon",
|
|
36
|
+
[MessageType.Call]: () => "started a call",
|
|
37
|
+
[MessageType.GuildBoost]: () => "boosted the server",
|
|
38
|
+
[MessageType.GuildBoostTier1]: () => "boosted the server to level 1",
|
|
39
|
+
[MessageType.GuildBoostTier2]: () => "boosted the server to level 2",
|
|
40
|
+
[MessageType.GuildBoostTier3]: () => "boosted the server to level 3",
|
|
41
|
+
[MessageType.ChannelFollowAdd]: (content) => `made this channel follow ${content}`,
|
|
42
|
+
[MessageType.PollResult]: () => "a poll ended",
|
|
43
|
+
};
|
|
44
|
+
/** Discord counts a message's length in Unicode code points. */
|
|
45
|
+
const MAX_LENGTH = 2000;
|
|
46
|
+
const CACHE_TTL_MS = 60 * 60_000;
|
|
47
|
+
const DISCORD_EPOCH = 1420070400000n;
|
|
48
|
+
const STORED = new Set([
|
|
49
|
+
"MESSAGE_CREATE",
|
|
50
|
+
"MESSAGE_UPDATE",
|
|
51
|
+
"MESSAGE_DELETE",
|
|
52
|
+
"MESSAGE_DELETE_BULK",
|
|
53
|
+
"MESSAGE_REACTION_ADD",
|
|
54
|
+
"MESSAGE_REACTION_REMOVE",
|
|
55
|
+
"INTERACTION_CREATE",
|
|
56
|
+
"THREAD_CREATE",
|
|
57
|
+
"THREAD_UPDATE",
|
|
58
|
+
"THREAD_DELETE",
|
|
59
|
+
]);
|
|
60
|
+
/** Gateway events that are not stored but tell who the bot is, which servers it is in, and its channels' names. */
|
|
61
|
+
const KEPT = new Set(["READY", "GUILD_CREATE", "GUILD_DELETE", "CHANNEL_CREATE", "CHANNEL_UPDATE", "CHANNEL_DELETE", "THREAD_LIST_SYNC"]);
|
|
62
|
+
const CDN_HOSTS = new Set(["cdn.discordapp.com", "media.discordapp.net"]);
|
|
63
|
+
/**
|
|
64
|
+
* The Chat SDK's Markdown converter, without one step: it turns a plain "@name" into "<@name>", which Discord shows
|
|
65
|
+
* as it is, and so it also breaks "@here" and "@everyone". Mentions come from person addresses instead.
|
|
66
|
+
*/
|
|
67
|
+
const converter = new DiscordFormatConverter();
|
|
68
|
+
converter.convertMentionsToDiscord = (text) => text;
|
|
69
|
+
export function createChannel(config, env) {
|
|
70
|
+
if (typeof config.secrets !== "string")
|
|
71
|
+
throw new Error(`channel ${config.id}: "secrets" must name the env file with DISCORD_BOT_TOKEN`);
|
|
72
|
+
return new DiscordChannel(config.id, expandHome(config.secrets), env);
|
|
73
|
+
}
|
|
74
|
+
export class DiscordChannel {
|
|
75
|
+
id;
|
|
76
|
+
#secrets;
|
|
77
|
+
#env;
|
|
78
|
+
/** Discord's REST base URL. Tests point it at a fake Discord. */
|
|
79
|
+
#api;
|
|
80
|
+
#client;
|
|
81
|
+
#botUserId;
|
|
82
|
+
/** The gateway session, for event IDs: a dispatch is unique by its session and sequence number. */
|
|
83
|
+
#session;
|
|
84
|
+
#readies = 0;
|
|
85
|
+
/** When the last gateway event came, in Unix ms: where a new session's backfill starts. */
|
|
86
|
+
#lastEventAt = 0;
|
|
87
|
+
/** Stopped when the channel stops: after that, a store that fails is tried only once more. */
|
|
88
|
+
#running = new AbortController();
|
|
89
|
+
/** The newest logged message ID of each known place, by channel ID, read when the channel started. */
|
|
90
|
+
#starts = new Map();
|
|
91
|
+
/** Servers the bot is in. A GUILD_CREATE for another one means the bot was added. */
|
|
92
|
+
#servers = new Set();
|
|
93
|
+
/** Gateway events are stored one after another, in the order Discord sent them. */
|
|
94
|
+
#storing = Promise.resolve();
|
|
95
|
+
#refilling = Promise.resolve();
|
|
96
|
+
#channels = new Map();
|
|
97
|
+
#guilds = new Map();
|
|
98
|
+
#people = new Map();
|
|
99
|
+
/** The DM channel with each person the bot sent to. */
|
|
100
|
+
#dms = new Map();
|
|
101
|
+
constructor(id, secrets, env, api = "https://discord.com/api") {
|
|
102
|
+
this.id = id;
|
|
103
|
+
this.#secrets = secrets;
|
|
104
|
+
this.#env = env;
|
|
105
|
+
this.#api = api;
|
|
106
|
+
}
|
|
107
|
+
get me() {
|
|
108
|
+
return this.#botUserId ? { address: this.person(this.#botUserId), name: this.#env.botName } : undefined;
|
|
109
|
+
}
|
|
110
|
+
get #rest() {
|
|
111
|
+
if (!this.#client)
|
|
112
|
+
throw new Error(`channel ${this.id} is not started`);
|
|
113
|
+
return this.#client.rest;
|
|
114
|
+
}
|
|
115
|
+
// ---- Connect ----
|
|
116
|
+
/**
|
|
117
|
+
* Connect to the Discord gateway. discord.js resumes short drops itself, and Discord then sends the missed events
|
|
118
|
+
* again. When a new session starts instead, events in between are lost, so a READY after the first one runs the
|
|
119
|
+
* backfill again.
|
|
120
|
+
*/
|
|
121
|
+
async start(sink) {
|
|
122
|
+
const { DISCORD_BOT_TOKEN: token } = readSecrets(this.#secrets, ["DISCORD_BOT_TOKEN"]);
|
|
123
|
+
// Where the backfill starts in each known place, read before the gateway connects: live messages logged after this
|
|
124
|
+
// must not move it past messages that came while the gateway was down. Overlap is harmless: the log keeps a message once.
|
|
125
|
+
this.#starts = new Map();
|
|
126
|
+
for (const place of await sink.places()) {
|
|
127
|
+
const newest = await sink.newestMessage(place);
|
|
128
|
+
const parsed = newest ? this.#tryParse(newest) : undefined;
|
|
129
|
+
if (parsed && "message" in parsed && parsed.message)
|
|
130
|
+
this.#starts.set(parsed.channel, parsed.message);
|
|
131
|
+
}
|
|
132
|
+
this.#running = new AbortController();
|
|
133
|
+
const client = new Client({
|
|
134
|
+
intents: [
|
|
135
|
+
GatewayIntentBits.Guilds,
|
|
136
|
+
GatewayIntentBits.GuildMessages,
|
|
137
|
+
GatewayIntentBits.MessageContent,
|
|
138
|
+
GatewayIntentBits.DirectMessages,
|
|
139
|
+
GatewayIntentBits.GuildMessageReactions,
|
|
140
|
+
GatewayIntentBits.DirectMessageReactions,
|
|
141
|
+
],
|
|
142
|
+
rest: { api: this.#api },
|
|
143
|
+
});
|
|
144
|
+
client.on(Events.Raw, (packet) => this.#receive(sink, packet));
|
|
145
|
+
client.on(Events.Error, (error) => sink.log("discord.js error", { error: String(error) }));
|
|
146
|
+
client.on(Events.ShardError, (error) => sink.log("gateway error", { error: String(error) }));
|
|
147
|
+
client.on(Events.ShardDisconnect, (event) => sink.log("Discord closed the gateway, and it will not reconnect", { code: event.code }));
|
|
148
|
+
this.#client = client;
|
|
149
|
+
this.#readies = 0;
|
|
150
|
+
try {
|
|
151
|
+
await client.login(token);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (/disallowed intents/i.test(String(error))) {
|
|
155
|
+
throw new Error("Discord refused the Message Content intent: turn it on in the Developer Portal, under Bot, Privileged Gateway Intents");
|
|
156
|
+
}
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
this.#botUserId ??= client.user?.id;
|
|
160
|
+
if (!this.#botUserId)
|
|
161
|
+
throw new Error("Discord did not say who the bot is");
|
|
162
|
+
}
|
|
163
|
+
/** Take no more events, then store the ones already taken before stop ends: Discord does not send them again. */
|
|
164
|
+
async stop() {
|
|
165
|
+
const client = this.#client;
|
|
166
|
+
this.#client = undefined;
|
|
167
|
+
await client?.destroy().catch(() => { });
|
|
168
|
+
this.#running.abort();
|
|
169
|
+
await this.#storing;
|
|
170
|
+
}
|
|
171
|
+
/** One gateway dispatch: keep what translation needs to know, and store the events. Never throws into discord.js. */
|
|
172
|
+
#receive(sink, packet) {
|
|
173
|
+
const { t } = packet;
|
|
174
|
+
if (!t)
|
|
175
|
+
return;
|
|
176
|
+
const previous = this.#lastEventAt;
|
|
177
|
+
this.#lastEventAt = Date.now();
|
|
178
|
+
if (!(STORED.has(t) || KEPT.has(t)))
|
|
179
|
+
return;
|
|
180
|
+
try {
|
|
181
|
+
// A copy, taken now: discord.js changes the packet's data when it handles it after this.
|
|
182
|
+
const d = structuredClone(packet.d);
|
|
183
|
+
switch (t) {
|
|
184
|
+
case "READY":
|
|
185
|
+
this.#session = d.session_id;
|
|
186
|
+
this.#botUserId = d.user.id;
|
|
187
|
+
this.#servers.clear();
|
|
188
|
+
for (const guild of d.guilds)
|
|
189
|
+
this.#servers.add(guild.id);
|
|
190
|
+
if (this.#readies++ > 0) {
|
|
191
|
+
// A new session: what came after the old one's last event is lost. Fill it in every place, from a minute
|
|
192
|
+
// before that event, also on the first run, when there is no last time the gateway ran.
|
|
193
|
+
const since = snowflakeAt(previous - 60_000);
|
|
194
|
+
this.#refilling = this.#refilling.then(() => this.#backfill(sink, () => since)).catch((error) => sink.log("backfill failed", { error: String(error) }));
|
|
195
|
+
}
|
|
196
|
+
return;
|
|
197
|
+
case "GUILD_CREATE":
|
|
198
|
+
this.#rememberGuild(d);
|
|
199
|
+
if (this.#servers.has(d.id))
|
|
200
|
+
return;
|
|
201
|
+
this.#servers.add(d.id);
|
|
202
|
+
// Added to a server. Its channels, roles and members are not kept; the bot can ask for them with call.
|
|
203
|
+
this.#store(sink, `${t}:${d.id}:${d.joined_at}`, { source: "gateway", at: Date.now(), t, d: Object.fromEntries(Object.entries(d).filter(([, value]) => !Array.isArray(value))) });
|
|
204
|
+
return;
|
|
205
|
+
case "GUILD_DELETE":
|
|
206
|
+
// Unavailable is an outage; otherwise the bot was removed.
|
|
207
|
+
if (d.unavailable)
|
|
208
|
+
return;
|
|
209
|
+
this.#servers.delete(d.id);
|
|
210
|
+
this.#store(sink, `${t}:${this.#session}:${packet.s}`, { source: "gateway", at: Date.now(), t, d });
|
|
211
|
+
return;
|
|
212
|
+
case "CHANNEL_CREATE":
|
|
213
|
+
case "CHANNEL_UPDATE":
|
|
214
|
+
case "THREAD_CREATE":
|
|
215
|
+
case "THREAD_UPDATE":
|
|
216
|
+
this.#remember(d);
|
|
217
|
+
break;
|
|
218
|
+
case "CHANNEL_DELETE":
|
|
219
|
+
case "THREAD_DELETE":
|
|
220
|
+
this.#channels.delete(d.id);
|
|
221
|
+
break;
|
|
222
|
+
case "THREAD_LIST_SYNC":
|
|
223
|
+
for (const thread of d.threads ?? [])
|
|
224
|
+
this.#remember({ ...thread, guild_id: d.guild_id });
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (!STORED.has(t))
|
|
228
|
+
return;
|
|
229
|
+
// One event per edit: a later update of an edited message (a link preview, for example) has the same edit time.
|
|
230
|
+
const eventId = t === "MESSAGE_UPDATE" && d.edited_timestamp ? `${t}:${d.id}:${d.edited_timestamp}` : `${t}:${this.#session}:${packet.s}`;
|
|
231
|
+
const parent = this.#parentOf(d.channel_id);
|
|
232
|
+
const raw = { source: "gateway", at: Date.now(), t, d, ...(parent ? { parent } : {}) };
|
|
233
|
+
this.#store(sink, eventId, raw, t === "INTERACTION_CREATE" ? () => void this.#acknowledge(sink, d) : undefined);
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
sink.log("gateway event not handled", { type: t, error: String(error) });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Store an event after the ones before it. Discord does not send an event again, so one that fails is tried again,
|
|
241
|
+
* later each time, until it is stored; once the channel stops, only once more. The events after it wait, so the order
|
|
242
|
+
* stays.
|
|
243
|
+
*/
|
|
244
|
+
#store(sink, eventId, raw, then) {
|
|
245
|
+
const { signal } = this.#running;
|
|
246
|
+
this.#storing = this.#storing.then(async () => {
|
|
247
|
+
for (let attempt = 1;; attempt++) {
|
|
248
|
+
try {
|
|
249
|
+
await sink.receive(eventId, raw);
|
|
250
|
+
then?.();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (signal.aborted) {
|
|
255
|
+
sink.log("gateway event not stored, and the channel stopped", { event: eventId, attempt, error: String(error) });
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const wait = Math.min(1000 * 2 ** (attempt - 1), 30_000);
|
|
259
|
+
sink.log("gateway event not stored; trying again", { event: eventId, attempt, waitMs: wait, error: String(error) });
|
|
260
|
+
await sleep(wait, undefined, { signal }).catch(() => { });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** The channel a thread is in, when the cache knows that this channel is a thread. */
|
|
266
|
+
#parentOf(channelId) {
|
|
267
|
+
const channel = channelId ? this.#channels.get(channelId)?.channel : undefined;
|
|
268
|
+
return channel && THREADS.has(channel.type) ? (channel.parent_id ?? undefined) : undefined;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Discord shows the person an error unless an interaction is answered within 3 seconds, so once it is stored it is
|
|
272
|
+
* answered with "later": a command shows that the bot is thinking, a button shows nothing. The bot answers it with
|
|
273
|
+
* call, as docs/channels/discord.md says.
|
|
274
|
+
*/
|
|
275
|
+
async #acknowledge(sink, interaction) {
|
|
276
|
+
// 2 a command, 3 a button or menu, 5 a form; 4 (autocomplete) cannot wait.
|
|
277
|
+
const type = interaction.type === 2 ? 5 : interaction.type === 3 ? 6 : interaction.type === 5 ? (interaction.message ? 6 : 5) : undefined;
|
|
278
|
+
if (!type || !this.#client)
|
|
279
|
+
return;
|
|
280
|
+
await this.#rest
|
|
281
|
+
.post(`/interactions/${interaction.id}/${interaction.token}/callback`, { body: { type }, auth: false })
|
|
282
|
+
.catch((error) => sink.log("interaction not acknowledged", { error: String(error) }));
|
|
283
|
+
}
|
|
284
|
+
owns(address) {
|
|
285
|
+
return address.startsWith(`${this.id}:`);
|
|
286
|
+
}
|
|
287
|
+
// ---- Addresses ----
|
|
288
|
+
placeOf(address) {
|
|
289
|
+
const parsed = this.#parse(address);
|
|
290
|
+
return "channel" in parsed ? this.place(parsed.channel) : undefined;
|
|
291
|
+
}
|
|
292
|
+
place(channel) {
|
|
293
|
+
return `${this.id}:#${channel}`;
|
|
294
|
+
}
|
|
295
|
+
person(user) {
|
|
296
|
+
return `${this.id}:@${user}`;
|
|
297
|
+
}
|
|
298
|
+
/** The address of a message in a channel, or in a thread whose place is `where.place`. */
|
|
299
|
+
#messageAt(where, message) {
|
|
300
|
+
if (!where.thread)
|
|
301
|
+
return `${this.id}:#${where.place}/${message}`;
|
|
302
|
+
return message === where.thread ? this.#threadAt(where) : `${this.id}:#${where.place}/${where.thread}/${message}`;
|
|
303
|
+
}
|
|
304
|
+
#threadAt(where) {
|
|
305
|
+
return `${this.id}:#${where.place}/${where.thread}`;
|
|
306
|
+
}
|
|
307
|
+
#parse(address) {
|
|
308
|
+
if (!this.owns(address))
|
|
309
|
+
throw new Error(`not a ${this.id} address: ${address}`);
|
|
310
|
+
const rest = address.slice(this.id.length + 1);
|
|
311
|
+
const place = /^#(\d+)(?:\/(\d+))?(?:\/(\d+))?$/.exec(rest);
|
|
312
|
+
if (place) {
|
|
313
|
+
if (place[3])
|
|
314
|
+
return { channel: place[1], thread: place[2], message: place[3] };
|
|
315
|
+
return { channel: place[1], ...(place[2] ? { message: place[2] } : {}) };
|
|
316
|
+
}
|
|
317
|
+
const person = /^@(\d+)$/.exec(rest);
|
|
318
|
+
if (person)
|
|
319
|
+
return { user: person[1] };
|
|
320
|
+
throw new Error(`bad ${this.id} address: ${address}`);
|
|
321
|
+
}
|
|
322
|
+
#tryParse(address) {
|
|
323
|
+
try {
|
|
324
|
+
return this.#parse(address);
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// ---- Translate ----
|
|
331
|
+
async translate(value) {
|
|
332
|
+
const raw = value;
|
|
333
|
+
const parent = raw.parent;
|
|
334
|
+
// A welcome message gives a join only when it comes live: as a join is not a message, the log would not see that
|
|
335
|
+
// the backfill's copy is the same one.
|
|
336
|
+
// A system message read again by a backfill would be a second event: system messages are not kept as messages.
|
|
337
|
+
if (raw.source === "history")
|
|
338
|
+
return !WRITTEN.has(raw.message.type ?? MessageType.Default) ? [] : this.#message("message", raw.message, Date.now(), parent);
|
|
339
|
+
if (raw.source === "sent")
|
|
340
|
+
return this.#message("message", raw.message, Date.now(), parent, raw.sendId);
|
|
341
|
+
const { t, d, at } = raw;
|
|
342
|
+
switch (t) {
|
|
343
|
+
case "MESSAGE_CREATE":
|
|
344
|
+
return this.#message("message", d, at, parent);
|
|
345
|
+
case "MESSAGE_UPDATE":
|
|
346
|
+
return d.edited_timestamp ? this.#message("edit", d, at, parent) : this.#update(d, at, parent);
|
|
347
|
+
case "MESSAGE_DELETE":
|
|
348
|
+
return [await this.#deleted(d.id, d.channel_id, d.guild_id, at, d, parent)];
|
|
349
|
+
case "MESSAGE_DELETE_BULK":
|
|
350
|
+
return Promise.all(d.ids.map((id) => this.#deleted(id, d.channel_id, d.guild_id, at, d, parent)));
|
|
351
|
+
case "MESSAGE_REACTION_ADD":
|
|
352
|
+
case "MESSAGE_REACTION_REMOVE": {
|
|
353
|
+
const where = await this.#locate(d.channel_id, undefined, parent);
|
|
354
|
+
const emoji = d.emoji;
|
|
355
|
+
return [
|
|
356
|
+
{
|
|
357
|
+
kind: t === "MESSAGE_REACTION_ADD" ? "reaction_added" : "reaction_removed",
|
|
358
|
+
at,
|
|
359
|
+
place: await this.#placeInfo(where.place, d.guild_id),
|
|
360
|
+
message: this.#messageAt(where, d.message_id),
|
|
361
|
+
...(where.thread ? { thread: this.#threadAt(where) } : {}),
|
|
362
|
+
person: await this.#personInfo(d.member?.user ?? d.user_id),
|
|
363
|
+
fromMe: d.user_id === this.#botUserId,
|
|
364
|
+
text: emoji.id ? `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}>` : (emoji.name ?? "?"),
|
|
365
|
+
raw: d,
|
|
366
|
+
},
|
|
367
|
+
];
|
|
368
|
+
}
|
|
369
|
+
case "THREAD_CREATE":
|
|
370
|
+
case "THREAD_UPDATE":
|
|
371
|
+
case "THREAD_DELETE": {
|
|
372
|
+
const thread = d;
|
|
373
|
+
if (!thread.parent_id)
|
|
374
|
+
return [];
|
|
375
|
+
const where = { place: thread.parent_id, thread: thread.id };
|
|
376
|
+
const owner = t === "THREAD_CREATE" ? thread.owner_id : undefined;
|
|
377
|
+
return [
|
|
378
|
+
{
|
|
379
|
+
// A deleted thread is only logged, as a deleted message is.
|
|
380
|
+
kind: t === "THREAD_DELETE" ? "delete" : "system",
|
|
381
|
+
at,
|
|
382
|
+
place: await this.#placeInfo(thread.parent_id, thread.guild_id),
|
|
383
|
+
thread: this.#threadAt(where),
|
|
384
|
+
...(owner ? { person: await this.#personInfo(owner) } : {}),
|
|
385
|
+
fromMe: owner !== undefined && owner === this.#botUserId,
|
|
386
|
+
...(t === "THREAD_DELETE" ? (thread.name ? { text: thread.name } : {}) : { text: threadText(t, thread) }),
|
|
387
|
+
raw: d,
|
|
388
|
+
},
|
|
389
|
+
];
|
|
390
|
+
}
|
|
391
|
+
case "GUILD_CREATE":
|
|
392
|
+
return [{ kind: "join", at: Date.parse(d.joined_at) || at, ...this.#meAsPerson(), fromMe: false, text: `added to the server "${d.name}" (ID ${d.id})`, raw: d }];
|
|
393
|
+
case "GUILD_DELETE": {
|
|
394
|
+
const name = this.#guilds.get(d.id)?.guild.name;
|
|
395
|
+
return [{ kind: "leave", at, ...this.#meAsPerson(), fromMe: false, text: `removed from the server ${name ? `"${name}" ` : ""}(ID ${d.id})`, raw: d }];
|
|
396
|
+
}
|
|
397
|
+
case "INTERACTION_CREATE":
|
|
398
|
+
// An interaction names its channel's parent itself.
|
|
399
|
+
return [await this.#interaction(d, at, parent ?? (THREADS.has(d.channel?.type) ? d.channel.parent_id : undefined))];
|
|
400
|
+
default:
|
|
401
|
+
return [];
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async #message(kind, message, at, parent, sendId) {
|
|
405
|
+
if (message.type === THREAD_STARTER_MESSAGE || message.type === THREAD_CREATED)
|
|
406
|
+
return [];
|
|
407
|
+
if (message.type === USER_JOIN)
|
|
408
|
+
return this.#joined(message, at, parent);
|
|
409
|
+
if (!WRITTEN.has(message.type ?? MessageType.Default))
|
|
410
|
+
return this.#system(message, at, parent);
|
|
411
|
+
const where = await this.#locate(message.channel_id, message.channel_type, parent);
|
|
412
|
+
const guildId = message.guild_id ?? (await this.#channel(where.place).catch(() => undefined))?.guild_id;
|
|
413
|
+
const guild = guildId ? await this.#guild(guildId).catch(() => undefined) : undefined;
|
|
414
|
+
const author = message.author;
|
|
415
|
+
const mentionsMe = (message.mentions ?? []).some((user) => user.id === this.#botUserId) || (message.mention_roles ?? []).some((role) => guild?.mine.has(role) === true);
|
|
416
|
+
const time = Date.parse((kind === "edit" ? message.edited_timestamp : message.timestamp) ?? "");
|
|
417
|
+
const thread = where.thread ? this.#threadAt(where) : undefined;
|
|
418
|
+
return [
|
|
419
|
+
{
|
|
420
|
+
kind,
|
|
421
|
+
at: Number.isFinite(time) ? time : at,
|
|
422
|
+
place: await this.#placeInfo(where.place, guildId),
|
|
423
|
+
message: this.#messageAt(where, message.id),
|
|
424
|
+
...(thread ? { thread, ...(kind === "message" ? { threadRoot: thread } : {}) } : {}),
|
|
425
|
+
...(author ? { person: await this.#personInfo(author) } : {}),
|
|
426
|
+
fromMe: author !== undefined && author.id === this.#botUserId,
|
|
427
|
+
mentionsMe,
|
|
428
|
+
text: await this.#text(message, guild),
|
|
429
|
+
mentions: (message.mentions ?? []).map((user) => this.person(user.id)),
|
|
430
|
+
...files(message),
|
|
431
|
+
...(sendId ? { sendId } : {}),
|
|
432
|
+
raw: message,
|
|
433
|
+
},
|
|
434
|
+
];
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Someone joined the server, from its welcome message: a join in the channel it was posted in. The bot's own is left
|
|
438
|
+
* out: GUILD_CREATE already says it was added.
|
|
439
|
+
*/
|
|
440
|
+
/**
|
|
441
|
+
* A system message, such as a pin or a new channel name: a notice from Discord, not words its author wrote, so it is
|
|
442
|
+
* logged as a system event and not as a message. A pin is about the message that was pinned.
|
|
443
|
+
*/
|
|
444
|
+
async #system(message, at, parent) {
|
|
445
|
+
const where = await this.#locate(message.channel_id, message.channel_type, parent);
|
|
446
|
+
const guildId = message.guild_id ?? (await this.#channel(where.place).catch(() => undefined))?.guild_id;
|
|
447
|
+
const time = Date.parse(message.timestamp ?? "");
|
|
448
|
+
const type = message.type ?? MessageType.Default;
|
|
449
|
+
const about = (type === MessageType.ChannelPinnedMessage ? message.message_reference?.message_id : undefined) ?? message.id;
|
|
450
|
+
return [
|
|
451
|
+
{
|
|
452
|
+
kind: "system",
|
|
453
|
+
at: Number.isFinite(time) ? time : at,
|
|
454
|
+
place: await this.#placeInfo(where.place, guildId),
|
|
455
|
+
message: this.#messageAt(where, about),
|
|
456
|
+
...(where.thread ? { thread: this.#threadAt(where) } : {}),
|
|
457
|
+
...(message.author ? { person: await this.#personInfo(message.author) } : {}),
|
|
458
|
+
fromMe: message.author !== undefined && message.author.id === this.#botUserId,
|
|
459
|
+
text: SYSTEM_TEXT[type]?.(message.content ?? "") ?? `Discord system message ${MessageType[type] ?? `of type ${type}`}${message.content ? `: ${message.content}` : ""}`,
|
|
460
|
+
raw: message,
|
|
461
|
+
},
|
|
462
|
+
];
|
|
463
|
+
}
|
|
464
|
+
async #joined(message, at, parent) {
|
|
465
|
+
const author = message.author;
|
|
466
|
+
if (!author || author.id === this.#botUserId)
|
|
467
|
+
return [];
|
|
468
|
+
const where = await this.#locate(message.channel_id, message.channel_type, parent);
|
|
469
|
+
const time = Date.parse(message.timestamp ?? "");
|
|
470
|
+
return [
|
|
471
|
+
{
|
|
472
|
+
kind: "join",
|
|
473
|
+
at: Number.isFinite(time) ? time : at,
|
|
474
|
+
place: await this.#placeInfo(where.place, message.guild_id),
|
|
475
|
+
person: await this.#personInfo(author),
|
|
476
|
+
fromMe: false,
|
|
477
|
+
raw: message,
|
|
478
|
+
},
|
|
479
|
+
];
|
|
480
|
+
}
|
|
481
|
+
/** A message changed but not edited: a link preview came, or it was pinned. Nobody did it, so no person. */
|
|
482
|
+
async #update(message, at, parent) {
|
|
483
|
+
const where = await this.#locate(message.channel_id, message.channel_type, parent);
|
|
484
|
+
return [
|
|
485
|
+
{
|
|
486
|
+
kind: "update",
|
|
487
|
+
at,
|
|
488
|
+
place: await this.#placeInfo(where.place, message.guild_id),
|
|
489
|
+
message: this.#messageAt(where, message.id),
|
|
490
|
+
...(where.thread ? { thread: this.#threadAt(where) } : {}),
|
|
491
|
+
fromMe: message.author !== undefined && message.author.id === this.#botUserId,
|
|
492
|
+
...files(message),
|
|
493
|
+
raw: message,
|
|
494
|
+
},
|
|
495
|
+
];
|
|
496
|
+
}
|
|
497
|
+
/** Discord does not say who deleted a message, or whose it was. */
|
|
498
|
+
async #deleted(message, channel, guildId, at, raw, parent) {
|
|
499
|
+
const where = await this.#locate(channel, undefined, parent);
|
|
500
|
+
return {
|
|
501
|
+
kind: "delete",
|
|
502
|
+
at,
|
|
503
|
+
place: await this.#placeInfo(where.place, guildId),
|
|
504
|
+
message: this.#messageAt(where, message),
|
|
505
|
+
...(where.thread ? { thread: this.#threadAt(where) } : {}),
|
|
506
|
+
fromMe: false,
|
|
507
|
+
raw,
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
/** Someone used a command, a button, a menu or a form of the app. */
|
|
511
|
+
async #interaction(d, at, parent) {
|
|
512
|
+
const where = d.channel_id ? await this.#locate(d.channel_id, d.channel?.type, parent) : undefined;
|
|
513
|
+
const user = d.member?.user ?? d.user;
|
|
514
|
+
let text;
|
|
515
|
+
if (d.type === 2) {
|
|
516
|
+
const parts = [`/${d.data?.name ?? "?"}`];
|
|
517
|
+
const walk = (options = []) => {
|
|
518
|
+
for (const option of options) {
|
|
519
|
+
if (option.options) {
|
|
520
|
+
parts.push(option.name);
|
|
521
|
+
walk(option.options);
|
|
522
|
+
}
|
|
523
|
+
else
|
|
524
|
+
parts.push(`${option.name}: ${String(option.value)}`);
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
walk(d.data?.options);
|
|
528
|
+
text = parts.join(" ");
|
|
529
|
+
}
|
|
530
|
+
else if (d.data?.custom_id)
|
|
531
|
+
text = d.data.custom_id;
|
|
532
|
+
return {
|
|
533
|
+
kind: "interaction",
|
|
534
|
+
at,
|
|
535
|
+
...(where ? { place: await this.#placeInfo(where.place, d.guild_id) } : {}),
|
|
536
|
+
...(where && d.message?.id ? { message: this.#messageAt(where, d.message.id) } : {}),
|
|
537
|
+
...(where?.thread ? { thread: this.#threadAt(where) } : {}),
|
|
538
|
+
...(user ? { person: await this.#personInfo(user) } : {}),
|
|
539
|
+
fromMe: false,
|
|
540
|
+
...(text ? { text } : {}),
|
|
541
|
+
raw: d,
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
#meAsPerson() {
|
|
545
|
+
const me = this.me;
|
|
546
|
+
return me ? { person: me } : {};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* A message's text as Discord Markdown, with mentions as names: <@id> becomes @name, <@&id> @role and <#id> #channel.
|
|
550
|
+
* The text of a forwarded message and of embeds that bots and webhooks post is added after it.
|
|
551
|
+
*/
|
|
552
|
+
async #text(message, guild) {
|
|
553
|
+
const parts = [
|
|
554
|
+
message.content ?? "",
|
|
555
|
+
...(message.embeds ?? [])
|
|
556
|
+
.filter((embed) => embed.type === "rich")
|
|
557
|
+
.flatMap((embed) => [embed.title ?? "", embed.description ?? "", ...(embed.fields ?? []).map((field) => `${field.name}: ${field.value}`)]),
|
|
558
|
+
...(message.message_snapshots ?? []).map((snapshot) => snapshot.message.content ?? ""),
|
|
559
|
+
];
|
|
560
|
+
let text = parts.filter(Boolean).join("\n\n");
|
|
561
|
+
const users = new Map((message.mentions ?? []).map((user) => [user.id, user.member?.nick || displayName(user)]));
|
|
562
|
+
text = text.replace(/<@!?(\d+)>/g, (token, id) => (users.has(id) ? `@${users.get(id)}` : token));
|
|
563
|
+
text = text.replace(/<@&(\d+)>/g, (token, id) => (guild?.roles.has(id) ? `@${guild.roles.get(id)}` : token));
|
|
564
|
+
const channels = new Map();
|
|
565
|
+
for (const [, id] of text.matchAll(/<#(\d+)>/g)) {
|
|
566
|
+
const name = (await this.#channel(id).catch(() => undefined))?.name;
|
|
567
|
+
if (name)
|
|
568
|
+
channels.set(id, name);
|
|
569
|
+
}
|
|
570
|
+
return text.replace(/<#(\d+)>/g, (token, id) => (channels.has(id) ? `#${channels.get(id)}` : token));
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Where a channel's messages are: in the channel itself, or in a thread, whose place is its parent channel. The
|
|
574
|
+
* parent stored with the event comes first, then the channel type the event gives, then the cache or Discord.
|
|
575
|
+
*/
|
|
576
|
+
async #locate(channelId, type, parent) {
|
|
577
|
+
if (parent)
|
|
578
|
+
return { place: parent, thread: channelId };
|
|
579
|
+
if (type !== undefined && !THREADS.has(type))
|
|
580
|
+
return { place: channelId };
|
|
581
|
+
const channel = await this.#channel(channelId).catch(() => undefined);
|
|
582
|
+
if (channel && THREADS.has(channel.type) && channel.parent_id)
|
|
583
|
+
return { place: channel.parent_id, thread: channel.id };
|
|
584
|
+
return { place: channelId };
|
|
585
|
+
}
|
|
586
|
+
/** guildId: the server the event names; without one, a lookup that fails says "dm". */
|
|
587
|
+
async #placeInfo(channelId, guildId) {
|
|
588
|
+
const address = this.place(channelId);
|
|
589
|
+
try {
|
|
590
|
+
const channel = await this.#channel(channelId);
|
|
591
|
+
if (channel.type === DM || channel.type === GROUP_DM) {
|
|
592
|
+
const others = (channel.recipients ?? []).filter((user) => user.id !== this.#botUserId);
|
|
593
|
+
const name = channel.name || others.map(displayName).join(", ");
|
|
594
|
+
return { address, kind: channel.type === DM ? "dm" : "group", ...(name ? { name } : {}) };
|
|
595
|
+
}
|
|
596
|
+
const server = channel.guild_id ? (await this.#guild(channel.guild_id).catch(() => undefined))?.name : undefined;
|
|
597
|
+
const name = channel.name ? `${server ? `${server} ` : ""}#${channel.name}` : server;
|
|
598
|
+
return { address, kind: "channel", ...(name ? { name } : {}) };
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
this.#env.log("place lookup failed", { channel: channelId, error: String(error) });
|
|
602
|
+
return { address, kind: guildId ? "channel" : "dm" };
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
async #personInfo(user) {
|
|
606
|
+
const id = typeof user === "string" ? user : user.id;
|
|
607
|
+
if (id === this.#botUserId)
|
|
608
|
+
return this.me;
|
|
609
|
+
if (typeof user !== "string" && user.username) {
|
|
610
|
+
const person = { address: this.person(id), name: displayName(user) };
|
|
611
|
+
this.#people.set(id, { person, at: Date.now() });
|
|
612
|
+
return person;
|
|
613
|
+
}
|
|
614
|
+
const cached = this.#people.get(id);
|
|
615
|
+
if (cached && Date.now() - cached.at < CACHE_TTL_MS)
|
|
616
|
+
return cached.person;
|
|
617
|
+
try {
|
|
618
|
+
return await this.#personInfo((await this.#rest.get(`/users/${id}`)));
|
|
619
|
+
}
|
|
620
|
+
catch (error) {
|
|
621
|
+
this.#env.log("person lookup failed", { user: id, error: String(error) });
|
|
622
|
+
return { address: this.person(id) };
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
async #channel(id) {
|
|
626
|
+
const cached = this.#channels.get(id);
|
|
627
|
+
if (cached && Date.now() - cached.at < CACHE_TTL_MS)
|
|
628
|
+
return cached.channel;
|
|
629
|
+
return this.#remember((await this.#rest.get(`/channels/${id}`)));
|
|
630
|
+
}
|
|
631
|
+
#remember(channel) {
|
|
632
|
+
this.#channels.set(channel.id, { channel, at: Date.now() });
|
|
633
|
+
return channel;
|
|
634
|
+
}
|
|
635
|
+
async #guild(id) {
|
|
636
|
+
const cached = this.#guilds.get(id);
|
|
637
|
+
if (cached && Date.now() - cached.at < CACHE_TTL_MS)
|
|
638
|
+
return cached.guild;
|
|
639
|
+
const [guild, member] = (await Promise.all([this.#rest.get(`/guilds/${id}`), this.#rest.get(`/guilds/${id}/members/${this.#botUserId}`)]));
|
|
640
|
+
const info = { ...(guild.name ? { name: guild.name } : {}), roles: new Map((guild.roles ?? []).map((role) => [role.id, role.name])), mine: new Set(member.roles ?? []) };
|
|
641
|
+
this.#guilds.set(id, { guild: info, at: Date.now() });
|
|
642
|
+
return info;
|
|
643
|
+
}
|
|
644
|
+
/** A server as GUILD_CREATE gives it: its name, roles, channels and threads, and the bot's own roles. */
|
|
645
|
+
#rememberGuild(d) {
|
|
646
|
+
for (const channel of [...(d.channels ?? []), ...(d.threads ?? [])])
|
|
647
|
+
this.#remember({ ...channel, guild_id: d.id });
|
|
648
|
+
const mine = d.members?.find((member) => member.user?.id === this.#botUserId);
|
|
649
|
+
if (!mine)
|
|
650
|
+
return;
|
|
651
|
+
const guild = { ...(d.name ? { name: d.name } : {}), roles: new Map((d.roles ?? []).map((role) => [role.id, role.name])), mine: new Set(mine.roles ?? []) };
|
|
652
|
+
this.#guilds.set(d.id, { guild, at: Date.now() });
|
|
653
|
+
}
|
|
654
|
+
// ---- Backfill ----
|
|
655
|
+
/**
|
|
656
|
+
* Store the messages that came while the gateway was down: in every text channel, active thread and recently archived
|
|
657
|
+
* thread of every server, and in every DM the log knows. Each place starts after its newest message that was logged
|
|
658
|
+
* when the channel started; a place with nothing logged starts at the last time the gateway ran. On the first start
|
|
659
|
+
* there is nothing to fill. Oldest first in each channel.
|
|
660
|
+
*/
|
|
661
|
+
async backfill(sink) {
|
|
662
|
+
const lastAlive = sink.lastAlive();
|
|
663
|
+
if (lastAlive === undefined)
|
|
664
|
+
return;
|
|
665
|
+
const starts = this.#starts;
|
|
666
|
+
const since = snowflakeAt(lastAlive);
|
|
667
|
+
await this.#backfill(sink, (place) => starts.get(place) ?? since);
|
|
668
|
+
}
|
|
669
|
+
/** startOf: the message ID after which a place's missed messages begin, by the place's channel ID. */
|
|
670
|
+
async #backfill(sink, startOf) {
|
|
671
|
+
const rest = this.#rest;
|
|
672
|
+
const channels = [];
|
|
673
|
+
const parents = [];
|
|
674
|
+
for (const guild of await this.#myGuilds()) {
|
|
675
|
+
try {
|
|
676
|
+
const listed = (await rest.get(`/guilds/${guild}/channels`));
|
|
677
|
+
const active = (await rest.get(`/guilds/${guild}/threads/active`));
|
|
678
|
+
for (const channel of [...listed, ...(active.threads ?? [])]) {
|
|
679
|
+
this.#remember({ ...channel, guild_id: guild });
|
|
680
|
+
if (TEXT.has(channel.type) || THREADS.has(channel.type))
|
|
681
|
+
channels.push(channel);
|
|
682
|
+
if (THREAD_PARENTS.has(channel.type))
|
|
683
|
+
parents.push(channel);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
catch (error) {
|
|
687
|
+
sink.log("backfill skipped a server", { server: guild, error: String(error) });
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
const known = new Set(channels.map((channel) => channel.id));
|
|
691
|
+
// A thread that got messages while the gateway was down may be archived by now, and then it is not active.
|
|
692
|
+
for (const parent of parents) {
|
|
693
|
+
try {
|
|
694
|
+
for (const thread of await this.#archivedSince(parent.id, timeOf(startOf(parent.id)))) {
|
|
695
|
+
if (known.has(thread.id))
|
|
696
|
+
continue;
|
|
697
|
+
known.add(thread.id);
|
|
698
|
+
channels.push(this.#remember({ ...thread, guild_id: parent.guild_id ?? thread.guild_id }));
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
if (!noAccess(error))
|
|
703
|
+
sink.log("backfill skipped a place", { channel: parent.id, error: String(error) });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
for (const place of await sink.places()) {
|
|
707
|
+
const parsed = this.#tryParse(place);
|
|
708
|
+
if (!parsed || !("channel" in parsed) || known.has(parsed.channel))
|
|
709
|
+
continue;
|
|
710
|
+
// A DM: read it again for its newest message ID. A channel of a server the bot left fails or is not a DM.
|
|
711
|
+
const channel = await rest.get(`/channels/${parsed.channel}`).then((found) => this.#remember(found)).catch(() => undefined);
|
|
712
|
+
if (channel && (channel.type === DM || channel.type === GROUP_DM))
|
|
713
|
+
channels.push(channel);
|
|
714
|
+
}
|
|
715
|
+
let added = 0;
|
|
716
|
+
for (const channel of channels) {
|
|
717
|
+
const parent = THREADS.has(channel.type) && channel.parent_id ? channel.parent_id : undefined;
|
|
718
|
+
try {
|
|
719
|
+
added += await this.#backfillChannel(sink, channel, startOf(parent ?? channel.id), parent);
|
|
720
|
+
}
|
|
721
|
+
catch (error) {
|
|
722
|
+
if (!noAccess(error))
|
|
723
|
+
sink.log("backfill skipped a place", { channel: channel.id, error: String(error) });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
sink.log("backfill done", { messages: added });
|
|
727
|
+
}
|
|
728
|
+
/** parent: the channel the thread is in, when this channel is a thread. */
|
|
729
|
+
async #backfillChannel(sink, channel, after, parent) {
|
|
730
|
+
if (!channel.last_message_id || BigInt(channel.last_message_id) <= BigInt(after))
|
|
731
|
+
return 0;
|
|
732
|
+
let added = 0;
|
|
733
|
+
for (let cursor = after;;) {
|
|
734
|
+
const page = (await this.#rest.get(`/channels/${channel.id}/messages`, { query: new URLSearchParams({ after: cursor, limit: "100" }) }));
|
|
735
|
+
page.sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
|
|
736
|
+
for (const message of page) {
|
|
737
|
+
await sink.receive(`history:${message.id}:${message.edited_timestamp ?? ""}`, { source: "history", message, ...(parent ? { parent } : {}) });
|
|
738
|
+
added++;
|
|
739
|
+
}
|
|
740
|
+
if (page.length < 100)
|
|
741
|
+
return added;
|
|
742
|
+
cursor = page.at(-1).id;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
/** The public threads of a channel archived at or after a time, in Unix ms. Discord lists the last archived first. */
|
|
746
|
+
async #archivedSince(channel, since) {
|
|
747
|
+
const found = [];
|
|
748
|
+
for (let before;;) {
|
|
749
|
+
const query = new URLSearchParams({ limit: "100", ...(before ? { before } : {}) });
|
|
750
|
+
const page = (await this.#rest.get(`/channels/${channel}/threads/archived/public`, { query }));
|
|
751
|
+
for (const thread of page.threads ?? []) {
|
|
752
|
+
before = thread.thread_metadata?.archive_timestamp;
|
|
753
|
+
if (!(Date.parse(before ?? "") >= since))
|
|
754
|
+
return found;
|
|
755
|
+
found.push(thread);
|
|
756
|
+
}
|
|
757
|
+
if (!page.has_more || !page.threads?.length)
|
|
758
|
+
return found;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
async #myGuilds() {
|
|
762
|
+
const guilds = [];
|
|
763
|
+
for (let after = "0";;) {
|
|
764
|
+
const page = (await this.#rest.get("/users/@me/guilds", { query: new URLSearchParams({ after, limit: "200" }) }));
|
|
765
|
+
guilds.push(...page.map((guild) => guild.id));
|
|
766
|
+
if (page.length < 200)
|
|
767
|
+
return guilds;
|
|
768
|
+
after = page.at(-1).id;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
// ---- Send ----
|
|
772
|
+
checkText(_to, text) {
|
|
773
|
+
return refusal(outgoing(this.id, text));
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Post the text. It carries a nonce made from the send ID, with enforce_nonce: Discord then returns the message
|
|
777
|
+
* already sent with that nonce in the last few minutes instead of making a new one, so a resend after a crash does
|
|
778
|
+
* not post twice. A text over Discord's limit is refused, never cut.
|
|
779
|
+
*/
|
|
780
|
+
async send(to, text, sendId) {
|
|
781
|
+
const content = outgoing(this.id, text);
|
|
782
|
+
const refused = refusal(content);
|
|
783
|
+
if (refused)
|
|
784
|
+
throw new Error(refused);
|
|
785
|
+
const target = await this.#target(to);
|
|
786
|
+
const message = (await this.#rest.post(`/channels/${target.thread ?? target.place}/messages`, {
|
|
787
|
+
body: {
|
|
788
|
+
content,
|
|
789
|
+
nonce: createHash("sha256").update(sendId).digest("base64url").slice(0, 25),
|
|
790
|
+
enforce_nonce: true,
|
|
791
|
+
...(target.reply ? { message_reference: { message_id: target.reply } } : {}),
|
|
792
|
+
},
|
|
793
|
+
}));
|
|
794
|
+
const raw = { source: "sent", sendId, message, ...(target.thread ? { parent: target.place } : {}) };
|
|
795
|
+
return { message: this.#messageAt(target, message.id), place: this.place(target.place), raw };
|
|
796
|
+
}
|
|
797
|
+
/** Discord's API does not give nonces back when it lists messages, so a sent message cannot be found by its send ID. */
|
|
798
|
+
async findSent(_to, _sendId, _since) {
|
|
799
|
+
return undefined;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Where a send goes. A place: post in it. A person: post in the DM with them. A message: a reply to it in its channel,
|
|
803
|
+
* or in its thread. A thread's first message (the thread's address): post in the thread, as a reply only when that
|
|
804
|
+
* message is in the thread (a forum post); a message that has no thread gets a reply in its channel.
|
|
805
|
+
*/
|
|
806
|
+
async #target(to) {
|
|
807
|
+
const parsed = this.#parse(to);
|
|
808
|
+
if ("user" in parsed) {
|
|
809
|
+
let dm = this.#dms.get(parsed.user);
|
|
810
|
+
if (!dm) {
|
|
811
|
+
dm = this.#remember((await this.#rest.post("/users/@me/channels", { body: { recipient_id: parsed.user } }))).id;
|
|
812
|
+
this.#dms.set(parsed.user, dm);
|
|
813
|
+
}
|
|
814
|
+
return { place: dm };
|
|
815
|
+
}
|
|
816
|
+
if (!parsed.message)
|
|
817
|
+
return this.#locate(parsed.channel);
|
|
818
|
+
if (parsed.thread)
|
|
819
|
+
return { place: parsed.channel, thread: parsed.thread, reply: parsed.message };
|
|
820
|
+
const channel = await this.#channel(parsed.channel);
|
|
821
|
+
if (channel.type === DM || channel.type === GROUP_DM)
|
|
822
|
+
return { place: parsed.channel, reply: parsed.message };
|
|
823
|
+
const thread = await this.#threadOf(parsed.message);
|
|
824
|
+
if (thread?.parent_id === parsed.channel)
|
|
825
|
+
return { place: parsed.channel, thread: thread.id, ...(FORUMS.has(channel.type) ? { reply: thread.id } : {}) };
|
|
826
|
+
return { place: parsed.channel, reply: parsed.message };
|
|
827
|
+
}
|
|
828
|
+
/** The thread with this ID, if there is one the bot can see. */
|
|
829
|
+
async #threadOf(id) {
|
|
830
|
+
try {
|
|
831
|
+
const channel = await this.#channel(id);
|
|
832
|
+
return THREADS.has(channel.type) ? channel : undefined;
|
|
833
|
+
}
|
|
834
|
+
catch (error) {
|
|
835
|
+
if (error instanceof DiscordAPIError && (error.status === 404 || error.status === 403))
|
|
836
|
+
return undefined;
|
|
837
|
+
throw error;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* React with a Unicode emoji, a custom emoji as name:id or <:name:id>, or a name such as :thumbsup:. Adding a
|
|
842
|
+
* reaction that is there, or removing one that is not, changes nothing and is not an error.
|
|
843
|
+
*/
|
|
844
|
+
async react(message, emoji, remove) {
|
|
845
|
+
const parsed = this.#parse(message);
|
|
846
|
+
if (!("channel" in parsed) || !parsed.message)
|
|
847
|
+
throw new Error(`not a message address: ${message}`);
|
|
848
|
+
// A forum post's first message is in the post's thread.
|
|
849
|
+
const channel = parsed.thread ?? (FORUMS.has((await this.#channel(parsed.channel)).type) ? parsed.message : parsed.channel);
|
|
850
|
+
const route = `/channels/${channel}/messages/${parsed.message}/reactions/${encodeURIComponent(reactionEmoji(emoji))}/@me`;
|
|
851
|
+
if (remove)
|
|
852
|
+
await this.#rest.delete(route);
|
|
853
|
+
else
|
|
854
|
+
await this.#rest.put(route);
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* The content of a file of a message. Discord's file URLs are signed and need no token; only Discord's own file
|
|
858
|
+
* hosts are fetched.
|
|
859
|
+
*/
|
|
860
|
+
async fetchFile(file, signal) {
|
|
861
|
+
const url = new URL(file.url ?? "");
|
|
862
|
+
if (url.protocol !== "https:" || !CDN_HOSTS.has(url.hostname))
|
|
863
|
+
throw new Error(`not a Discord file URL: ${url.origin}`);
|
|
864
|
+
const response = await fetch(url, { signal });
|
|
865
|
+
if (!response.ok || !response.body)
|
|
866
|
+
throw new Error(`Discord answered ${response.status} ${response.statusText}`);
|
|
867
|
+
return Readable.fromWeb(response.body);
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Any Discord REST endpoint with the bot token. method is "<HTTP method> <path>", for example
|
|
871
|
+
* "POST /channels/123/threads". params are the query for GET and DELETE, and the JSON body for the others. A "file"
|
|
872
|
+
* param that is a local path is uploaded with the body.
|
|
873
|
+
*/
|
|
874
|
+
async call(method, params) {
|
|
875
|
+
const match = /^(GET|POST|PUT|PATCH|DELETE) (\/\S+)$/.exec(method.trim());
|
|
876
|
+
if (!match)
|
|
877
|
+
throw new Error(`call takes "<GET|POST|PUT|PATCH|DELETE> /<path>", for example "POST /channels/123/threads"; not ${JSON.stringify(method)}`);
|
|
878
|
+
const verb = match[1];
|
|
879
|
+
const request = { method: verb, fullRoute: match[2] };
|
|
880
|
+
const { file, ...body } = params;
|
|
881
|
+
let result;
|
|
882
|
+
if (verb === "GET" || verb === "DELETE") {
|
|
883
|
+
const query = new URLSearchParams(Object.entries(params).map(([key, value]) => [key, String(value)]));
|
|
884
|
+
result = await this.#rest.request({ ...request, ...(query.size ? { query } : {}) });
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
const files = typeof file === "string" ? [{ name: basename(file), data: await readFile(expandHome(file)) }] : undefined;
|
|
888
|
+
result = await this.#rest.request({ ...request, body, ...(files ? { files } : {}) });
|
|
889
|
+
}
|
|
890
|
+
// An answer with no content (204).
|
|
891
|
+
return result instanceof ArrayBuffer ? null : result;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
/** The text as Discord gets it: person and place addresses in angle brackets become mentions, then Markdown is converted. */
|
|
895
|
+
function outgoing(id, text) {
|
|
896
|
+
const prefix = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
897
|
+
const mentions = text.replace(new RegExp(`<${prefix}:@(\\d+)>`, "g"), "<@$1>").replace(new RegExp(`<${prefix}:#(\\d+)>`, "g"), "<#$1>");
|
|
898
|
+
return convertEmojiPlaceholders(converter.renderPostable({ markdown: mentions }), "discord");
|
|
899
|
+
}
|
|
900
|
+
function refusal(content) {
|
|
901
|
+
const length = [...content].length;
|
|
902
|
+
return length > MAX_LENGTH ? `Discord allows at most ${MAX_LENGTH} characters in one message; this one has ${length}. Send it in parts.` : undefined;
|
|
903
|
+
}
|
|
904
|
+
/** A thread that started or changed, in words. Discord does not say who changed a thread. */
|
|
905
|
+
function threadText(t, thread) {
|
|
906
|
+
const name = `"${thread.name ?? thread.id}"`;
|
|
907
|
+
if (t === "THREAD_CREATE")
|
|
908
|
+
return `started the thread ${name}`;
|
|
909
|
+
if (thread.thread_metadata?.archived)
|
|
910
|
+
return `the thread ${name} was archived`;
|
|
911
|
+
return `the thread ${name} changed`;
|
|
912
|
+
}
|
|
913
|
+
function reactionEmoji(emoji) {
|
|
914
|
+
const text = emoji.trim();
|
|
915
|
+
const custom = /^<?a?:?(\w+):(\d+)>?$/.exec(text);
|
|
916
|
+
if (custom)
|
|
917
|
+
return `${custom[1]}:${custom[2]}`;
|
|
918
|
+
// A name, with or without colons (eyes, :eyes:), as the react tool's examples give it.
|
|
919
|
+
const named = /^:?([\w+-]+):?$/.exec(text);
|
|
920
|
+
if (!named)
|
|
921
|
+
return text;
|
|
922
|
+
const unicode = defaultEmojiResolver.toDiscord(defaultEmojiResolver.fromSlack(named[1]));
|
|
923
|
+
if (/^[\w+-]+$/.test(unicode))
|
|
924
|
+
throw new Error(`unknown emoji ${text}: give the emoji itself, or name:id for a custom emoji`);
|
|
925
|
+
return unicode;
|
|
926
|
+
}
|
|
927
|
+
function displayName(user) {
|
|
928
|
+
return user.global_name || user.username || user.id;
|
|
929
|
+
}
|
|
930
|
+
function files(message) {
|
|
931
|
+
const attachments = [...(message.attachments ?? []), ...(message.message_snapshots ?? []).flatMap((snapshot) => snapshot.message.attachments ?? [])];
|
|
932
|
+
if (!attachments.length)
|
|
933
|
+
return {};
|
|
934
|
+
return {
|
|
935
|
+
files: attachments.map((file) => ({
|
|
936
|
+
...(file.filename ? { name: file.filename } : {}),
|
|
937
|
+
...(file.content_type ? { type: file.content_type } : {}),
|
|
938
|
+
...(file.url ? { url: file.url } : {}),
|
|
939
|
+
...(typeof file.size === "number" ? { size: file.size } : {}),
|
|
940
|
+
})),
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
/** The smallest Discord ID made at this time, for "messages after". */
|
|
944
|
+
function snowflakeAt(ms) {
|
|
945
|
+
return String((BigInt(Math.floor(ms)) - DISCORD_EPOCH) << 22n);
|
|
946
|
+
}
|
|
947
|
+
/** When a Discord ID was made, in Unix ms. */
|
|
948
|
+
function timeOf(id) {
|
|
949
|
+
return Number((BigInt(id) >> 22n) + DISCORD_EPOCH);
|
|
950
|
+
}
|
|
951
|
+
/** Discord answered that the bot may not read this. The server decides who reads what, so this is not a failure. */
|
|
952
|
+
function noAccess(error) {
|
|
953
|
+
return error instanceof DiscordAPIError && error.status === 403;
|
|
954
|
+
}
|
|
955
|
+
//# sourceMappingURL=index.js.map
|