@theholocron/holocron-plugin-discord 5.0.0-alpha.357 → 5.0.0-alpha.359

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/dist/index.d.mts CHANGED
@@ -79,7 +79,8 @@ export declare class DiscordNotifications implements Notifications {
79
79
  inspect(layout: NotificationsLayout): Promise<ServerInspection>;
80
80
  /**
81
81
  * What the bot keeps: the usual set, Pin Messages when the layout pins messages, and Manage Threads when it
82
- * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads).
82
+ * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads),
83
+ * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
83
84
  */
84
85
  private needs;
85
86
  /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
@@ -113,7 +114,23 @@ export declare class DiscordNotifications implements Notifications {
113
114
  }>;
114
115
  /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
115
116
  private serverPermissions;
117
+ /**
118
+ * The permissions `needs()` lists that the bot's roles do not give it server-wide, in plain words ("Manage Threads"),
119
+ * with the invite link that asks for them again when some are missing. The owner and an Administrator hold every
120
+ * permission. Channel overwrites are not looked at: the forum's own check does that.
121
+ */
122
+ private missingBotPermissions;
116
123
  holdsPermission(permission: string): Promise<boolean>;
124
+ /**
125
+ * What a member holding `bits` through the roles in `held` has in a channel, in the order Discord applies the
126
+ * channel's overwrites: @everyone, then the roles, then the member itself.
127
+ */
128
+ private static afterOverwrites;
129
+ /**
130
+ * What the bot can do with the threads of a forum: start posts and reply (`post`) and tag and close them (`manage`).
131
+ * The owner and an Administrator hold every permission, whatever the forum's overwrites say.
132
+ */
133
+ private botThreadsIn;
117
134
  /**
118
135
  * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
119
136
  * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
@@ -150,6 +167,14 @@ export declare class DiscordNotifications implements Notifications {
150
167
  readDiscussion(channel: string, key: string, url?: string): Promise<DiscussionPost | undefined>;
151
168
  /** Changes a document's post: its title, its tag, the state last synced, the pull request line. */
152
169
  updateDiscussion(channel: string, key: string, patch: DiscussionPatch): Promise<void>;
170
+ /** Appends a message to a document's post, reopening and closing it again if it was closed. */
171
+ postDiscussionMessage(channel: string, key: string, content: string, opts?: {
172
+ quiet?: boolean;
173
+ }): Promise<void>;
174
+ /** The text of a post's recent messages, newest first. */
175
+ readDiscussionMessages(channel: string, key: string, limit?: number): Promise<string[]>;
176
+ /** Keeps the oldest post for `key` and deletes the others; returns how many it deleted. */
177
+ dedupeDiscussion(channel: string, key: string): Promise<number>;
153
178
  /**
154
179
  * Posts `content` (up to 2000 characters) in a text channel as the bot, without letting it mention anyone. A `#name`
155
180
  * that is one of the server's channels is linked.
package/dist/index.mjs CHANGED
@@ -48,9 +48,9 @@ const MAX_MESSAGE = 2e3;
48
48
  /**
49
49
  * The line that ends a post's first message and makes it findable and comparable: `-# sync: <key> | <state>`, where
50
50
  * `-#` is Discord's small print. `key` is the document's path; `state` is the state the post and the document last
51
- * agreed on, empty when none.
51
+ * agreed on, empty when none. A state is a tag's name, which may hold spaces (`changes requested`).
52
52
  */
53
- const FOOTER = /^-# sync: (.+) \| (\S*)$/m;
53
+ const FOOTER = /^-# sync: (.+) \| (.*)$/m;
54
54
  /** The paragraph of a first message that names the pull request, as `discussionBody` writes it. */
55
55
  const PR_LINE = /^PR: \[#\d+\]\(<[^>]*>\)$/m;
56
56
  /**
@@ -100,12 +100,21 @@ var DiscordDiscussions = class DiscordDiscussions {
100
100
  for (const thread of await bot.threads.inChannel(this.deps.guild(), forum.id)) {
101
101
  const first = await bot.channels.message(thread.id, thread.id).catch(() => void 0);
102
102
  const footer = first ? FOOTER.exec(first.content) : null;
103
- if (first && footer) entries.set(footer[1], {
104
- key: footer[1],
105
- thread,
106
- content: first.content,
107
- synced: footer[2] || void 0
108
- });
103
+ if (first && footer) {
104
+ const entry = {
105
+ key: footer[1],
106
+ thread,
107
+ content: first.content,
108
+ synced: footer[2] || void 0,
109
+ duplicates: []
110
+ };
111
+ const held = entries.get(entry.key);
112
+ if (!held) entries.set(entry.key, entry);
113
+ else if (BigInt(thread.id) < BigInt(held.thread.id)) {
114
+ entry.duplicates = [held.thread, ...held.duplicates];
115
+ entries.set(entry.key, entry);
116
+ } else held.duplicates.push(thread);
117
+ }
109
118
  }
110
119
  return entries;
111
120
  }
@@ -200,7 +209,8 @@ var DiscordDiscussions = class DiscordDiscussions {
200
209
  key: input.key,
201
210
  thread,
202
211
  content,
203
- synced: input.state
212
+ synced: input.state,
213
+ duplicates: []
204
214
  };
205
215
  posts.set(input.key, entry);
206
216
  return {
@@ -242,7 +252,8 @@ var DiscordDiscussions = class DiscordDiscussions {
242
252
  if (patch.state !== void 0) change.applied_tags = [this.tagId(forum, patch.state)];
243
253
  const nextKey = patch.key ?? key;
244
254
  const footerEdited = nextKey !== key || patch.synced !== void 0 && patch.synced !== entry.synced;
245
- const withPr = patch.prLine === void 0 ? entry.content : DiscordDiscussions.withPrLine(entry.content, patch.prLine);
255
+ const base = patch.body === void 0 ? entry.content : DiscordDiscussions.message(patch.body, key, entry.synced ?? "");
256
+ const withPr = patch.prLine === void 0 ? base : DiscordDiscussions.withPrLine(base, patch.prLine);
246
257
  const withId = patch.idLine === void 0 ? withPr : DiscordDiscussions.withIdLine(withPr, patch.idLine);
247
258
  const edited = footerEdited || withId !== entry.content;
248
259
  if ((Object.keys(change).length > 0 || edited || reopening) && thread.thread_metadata.archived) change.archived = false;
@@ -271,6 +282,58 @@ var DiscordDiscussions = class DiscordDiscussions {
271
282
  })
272
283
  };
273
284
  }
285
+ /**
286
+ * Append a message to the post for `key`, mentioning no one. A post that is archived or locked is unarchived and
287
+ * unlocked for the write and put back as it was, also when the write fails.
288
+ */
289
+ async post(channel, key, content, opts = {}) {
290
+ const entry = (await this.posts(await this.forum(channel))).get(key);
291
+ if (!entry) throw new Error(`no discussion post for \`${key}\` in \`${channel}\``);
292
+ const bot = this.deps.bot();
293
+ const { archived, locked } = entry.thread.thread_metadata;
294
+ const reopen = archived || locked;
295
+ if (reopen) entry.thread = {
296
+ ...entry.thread,
297
+ ...await bot.threads.modify(entry.thread.id, {
298
+ archived: false,
299
+ locked: false
300
+ })
301
+ };
302
+ try {
303
+ const text = content.length > MAX_MESSAGE ? `${content.slice(0, 1999)}…` : content;
304
+ await bot.channels.createMessage(entry.thread.id, {
305
+ content: text,
306
+ ...opts.quiet ? { flags: MessageFlag.SuppressNotifications } : {}
307
+ });
308
+ } finally {
309
+ if (reopen) entry.thread = {
310
+ ...entry.thread,
311
+ ...await bot.threads.modify(entry.thread.id, {
312
+ archived,
313
+ locked
314
+ })
315
+ };
316
+ }
317
+ }
318
+ /** The text of the recent messages of the post for `key`, newest first; empty when there is no post. */
319
+ async messages(channel, key, limit = 50) {
320
+ const entry = (await this.posts(await this.forum(channel))).get(key);
321
+ if (!entry) return [];
322
+ return (await this.deps.bot().channels.messages(entry.thread.id, Math.min(Math.max(limit, 1), 100))).map((m) => m.content);
323
+ }
324
+ /** Keep the oldest post that carries `key` and delete the others. Returns how many were deleted. */
325
+ async dedupe(channel, key) {
326
+ const entry = (await this.posts(await this.forum(channel))).get(key);
327
+ if (!entry) return 0;
328
+ const bot = this.deps.bot();
329
+ let deleted = 0;
330
+ while (entry.duplicates.length > 0) {
331
+ await bot.threads.delete(entry.duplicates[0].id);
332
+ entry.duplicates.shift();
333
+ deleted++;
334
+ }
335
+ return deleted;
336
+ }
274
337
  };
275
338
  // src/capabilities/notifications.ts
276
339
  /** Discord's numeric settings, by the names the layout uses. */
@@ -533,6 +596,7 @@ var DiscordNotifications = class DiscordNotifications {
533
596
  const channels = await this.channelList();
534
597
  const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
535
598
  const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook || ch.feeds?.monitoring || ch.feeds?.errors).map((ch) => ch.name.toLowerCase())));
599
+ const wantsPrs = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.feeds?.prs).map((ch) => ch.name.toLowerCase())));
536
600
  const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement || c.type === ChannelType.Forum);
537
601
  const found = [];
538
602
  for (const c of text) {
@@ -548,6 +612,13 @@ var DiscordNotifications = class DiscordNotifications {
548
612
  } catch (err) {
549
613
  webhooksError = reason(err);
550
614
  }
615
+ let botThreads;
616
+ let botThreadsError;
617
+ if (c.type === ChannelType.Forum && wantsPrs.has(c.name.toLowerCase())) try {
618
+ botThreads = await this.botThreadsIn(c.permission_overwrites ?? []);
619
+ } catch (err) {
620
+ botThreadsError = reason(err);
621
+ }
551
622
  const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
552
623
  found.push({
553
624
  name: c.name,
@@ -561,7 +632,9 @@ var DiscordNotifications = class DiscordNotifications {
561
632
  webhooks,
562
633
  webhookAvatars,
563
634
  webhookIds,
564
- ...webhooksError ? { webhooksError } : {}
635
+ ...webhooksError ? { webhooksError } : {},
636
+ ...botThreads ? { botThreads } : {},
637
+ ...botThreadsError ? { botThreadsError } : {}
565
638
  });
566
639
  }
567
640
  let roles = [];
@@ -690,9 +763,18 @@ var DiscordNotifications = class DiscordNotifications {
690
763
  });
691
764
  const categoryAccess = {};
692
765
  for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
766
+ let botPermissions;
767
+ let botPermissionsError;
768
+ try {
769
+ botPermissions = await this.missingBotPermissions();
770
+ } catch (err) {
771
+ botPermissionsError = reason(err);
772
+ }
693
773
  return {
694
774
  categories: [...categoryName.values()],
695
775
  categoryAccess,
776
+ ...botPermissions ? { botPermissions } : {},
777
+ ...botPermissionsError ? { botPermissionsError } : {},
696
778
  ...server ? { server } : {},
697
779
  ...serverError ? { serverError } : {},
698
780
  ...welcome ? { welcome } : {},
@@ -712,14 +794,18 @@ var DiscordNotifications = class DiscordNotifications {
712
794
  }
713
795
  /**
714
796
  * What the bot keeps: the usual set, Pin Messages when the layout pins messages, and Manage Threads when it
715
- * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads).
797
+ * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads),
798
+ * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
716
799
  */
717
800
  needs() {
718
- const forum = (this.opts.layout?.categories ?? []).some((c) => (c.channels ?? []).some((ch) => ch.kind === "forum"));
801
+ const channels = (this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []);
802
+ const forum = channels.some((ch) => ch.kind === "forum");
803
+ const reacts = channels.some((ch) => (ch.starterReactions ?? []).length > 0);
719
804
  return [
720
805
  ...BOT_NEEDS,
721
806
  ...this.opts.layout?.pinned?.length ? ["PinMessages"] : [],
722
- ...forum ? ["ManageThreads"] : []
807
+ ...forum ? ["ManageThreads"] : [],
808
+ ...reacts ? ["AddReactions"] : []
723
809
  ];
724
810
  }
725
811
  /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
@@ -902,6 +988,24 @@ var DiscordNotifications = class DiscordNotifications {
902
988
  me
903
989
  };
904
990
  }
991
+ /**
992
+ * The permissions `needs()` lists that the bot's roles do not give it server-wide, in plain words ("Manage Threads"),
993
+ * with the invite link that asks for them again when some are missing. The owner and an Administrator hold every
994
+ * permission. Channel overwrites are not looked at: the forum's own check does that.
995
+ */
996
+ async missingBotPermissions() {
997
+ const { owner, bits } = await this.serverPermissions();
998
+ const has = (name) => {
999
+ const bit = BigInt(permissions([name]));
1000
+ return (bits & bit) === bit;
1001
+ };
1002
+ const missing = owner || has("Administrator") ? [] : [...new Set(this.needs())].filter((n) => !has(n));
1003
+ if (missing.length === 0) return { missing: [] };
1004
+ return {
1005
+ missing: missing.map((n) => n.replace(/([a-z])([A-Z])/g, "$1 $2")),
1006
+ inviteUrl: await this.inviteUrl()
1007
+ };
1008
+ }
905
1009
  async holdsPermission(permission) {
906
1010
  const { owner, bits } = await this.serverPermissions();
907
1011
  if (owner) return true;
@@ -912,6 +1016,44 @@ var DiscordNotifications = class DiscordNotifications {
912
1016
  return has("Administrator") || has(permission);
913
1017
  }
914
1018
  /**
1019
+ * What a member holding `bits` through the roles in `held` has in a channel, in the order Discord applies the
1020
+ * channel's overwrites: @everyone, then the roles, then the member itself.
1021
+ */
1022
+ static afterOverwrites(bits, held, me, guild, list) {
1023
+ const apply = (now, found) => {
1024
+ const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
1025
+ const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
1026
+ return now & ~deny | allow;
1027
+ };
1028
+ let now = apply(bits, list.filter((o) => o.id === guild));
1029
+ now = apply(now, list.filter((o) => o.type === 0 && o.id !== guild && held.has(o.id)));
1030
+ return apply(now, list.filter((o) => o.type === 1 && o.id === me));
1031
+ }
1032
+ /**
1033
+ * What the bot can do with the threads of a forum: start posts and reply (`post`) and tag and close them (`manage`).
1034
+ * The owner and an Administrator hold every permission, whatever the forum's overwrites say.
1035
+ */
1036
+ async botThreadsIn(overwrites) {
1037
+ const { owner, bits, held, me } = await this.serverPermissions();
1038
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n) return {
1039
+ post: true,
1040
+ manage: true
1041
+ };
1042
+ const now = DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), overwrites);
1043
+ const has = (names) => {
1044
+ const bit = BigInt(permissions(names));
1045
+ return (now & bit) === bit;
1046
+ };
1047
+ return {
1048
+ post: has([
1049
+ "ViewChannel",
1050
+ "CreatePublicThreads",
1051
+ "SendMessagesInThreads"
1052
+ ]),
1053
+ manage: has(["ManageThreads"])
1054
+ };
1055
+ }
1056
+ /**
915
1057
  * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
916
1058
  * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
917
1059
  */
@@ -919,16 +1061,8 @@ var DiscordNotifications = class DiscordNotifications {
919
1061
  const { owner, bits, held, me } = await this.serverPermissions();
920
1062
  const bit = BigInt(permissions([permission]));
921
1063
  if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n || (bits & bit) !== bit) return false;
922
- const list = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId)?.permission_overwrites ?? [];
923
- const apply = (now, found) => {
924
- const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
925
- const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
926
- return now & ~deny | allow;
927
- };
928
- let now = apply(bits, list.filter((o) => o.id === this.guild()));
929
- now = apply(now, list.filter((o) => o.type === 0 && o.id !== this.guild() && held.has(o.id)));
930
- now = apply(now, list.filter((o) => o.type === 1 && o.id === me));
931
- return (now & bit) !== bit;
1064
+ const channel = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId);
1065
+ return (DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), channel?.permission_overwrites ?? []) & bit) !== bit;
932
1066
  }
933
1067
  /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
934
1068
  async ownMessages(channelId) {
@@ -1034,6 +1168,18 @@ var DiscordNotifications = class DiscordNotifications {
1034
1168
  updateDiscussion(channel, key, patch) {
1035
1169
  return this.discussions().update(channel, key, patch);
1036
1170
  }
1171
+ /** Appends a message to a document's post, reopening and closing it again if it was closed. */
1172
+ postDiscussionMessage(channel, key, content, opts) {
1173
+ return this.discussions().post(channel, key, content, opts);
1174
+ }
1175
+ /** The text of a post's recent messages, newest first. */
1176
+ readDiscussionMessages(channel, key, limit) {
1177
+ return this.discussions().messages(channel, key, limit);
1178
+ }
1179
+ /** Keeps the oldest post for `key` and deletes the others; returns how many it deleted. */
1180
+ dedupeDiscussion(channel, key) {
1181
+ return this.discussions().dedupe(channel, key);
1182
+ }
1037
1183
  /**
1038
1184
  * Posts `content` (up to 2000 characters) in a text channel as the bot, without letting it mention anyone. A `#name`
1039
1185
  * that is one of the server's channels is linked.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.357",
3
+ "version": "5.0.0-alpha.359",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -41,10 +41,10 @@
41
41
  "tsx": "4.23.15",
42
42
  "typescript": "^5.9.3",
43
43
  "vitest": "^5.0.5",
44
- "@theholocron/cli": "5.0.0-alpha.357",
45
- "@theholocron/discord-client": "^1.58.0-alpha.12",
44
+ "@theholocron/cli": "5.0.0-alpha.359",
45
+ "@theholocron/discord-client": "^1.58.0-alpha.13",
46
46
  "@theholocron/eslint-config": "^8.9.0-alpha.9",
47
- "@theholocron/http-client": "^1.58.0-alpha.12",
47
+ "@theholocron/http-client": "^1.58.0-alpha.13",
48
48
  "@theholocron/misc-utils": "^1.17.0-alpha.1",
49
49
  "@theholocron/tsdown-config": "^8.9.0-alpha.9",
50
50
  "@theholocron/tsconfig": "^8.9.0-alpha.9",
@@ -53,7 +53,7 @@
53
53
  "peerDependencies": {
54
54
  "@theholocron/discord-client": "^1.50.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.357"
56
+ "@theholocron/cli": "5.0.0-alpha.359"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"