@theholocron/holocron-plugin-discord 5.0.0-alpha.205 → 5.0.0-alpha.207

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
@@ -1,4 +1,4 @@
1
- import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsDelivery, NotificationsEveryoneLayout, NotificationsLayout, NotificationsMember, NotificationsOnboardingLayout, NotificationsServerLayout, NotificationsSignIn, NotificationsWelcomeLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsDelivery, NotificationsEveryoneLayout, NotificationsLayout, NotificationsMember, NotificationsOnboardingLayout, NotificationsPinnedLayout, NotificationsServerLayout, NotificationsSignIn, NotificationsWelcomeLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordOAuthClient, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
@@ -66,6 +66,8 @@ declare class DiscordNotifications implements Notifications {
66
66
  * the layout, not with the server.
67
67
  */
68
68
  inspect(layout: NotificationsLayout): Promise<ServerInspection>;
69
+ /** What the bot keeps: the usual set, and Pin Messages when the layout pins messages. */
70
+ private needs;
69
71
  /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
70
72
  private inviteUrl;
71
73
  /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
@@ -85,6 +87,31 @@ declare class DiscordNotifications implements Notifications {
85
87
  ensureServer(settings: NotificationsServerLayout): Promise<{
86
88
  updated: string[];
87
89
  }>;
90
+ /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
91
+ private serverPermissions;
92
+ holdsPermission(permission: string): Promise<boolean>;
93
+ /**
94
+ * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
95
+ * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
96
+ */
97
+ private channelDenies;
98
+ /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
99
+ private ownMessages;
100
+ /** The layout's messages grouped by channel, in the order the channels first appear. */
101
+ private static pinsByChannel;
102
+ /**
103
+ * What differs in one channel: the declared messages that are not pinned yet, and the bot's pinned messages the
104
+ * layout does not declare (or declares once and the bot pinned twice). The layout is the whole set of the bot's
105
+ * pins in a channel it names.
106
+ */
107
+ private static pinDrift;
108
+ /** Whether each pinned message is in place: pinned by this bot with exactly the layout's text, and nothing else of the bot's pinned beside it. */
109
+ private pinnedStates;
110
+ ensurePinned(pinned: NotificationsPinnedLayout[]): Promise<{
111
+ updated: string[];
112
+ }>;
113
+ /** A 403 on pinning becomes the missing permission and a link that grants it, which `setup` can walk a person through. */
114
+ private pinHint;
88
115
  /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
89
116
  private static communityFeatureHint;
90
117
  /** The numeric code Discord puts in the JSON body of an error, or undefined when the body is not that. */
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ElevationRequiredError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
2
  import { errorMessage } from "@theholocron/misc-utils";
3
3
  import { ApplicationFlag, ChannelType, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
4
  //#region src/auth.ts
@@ -344,6 +344,13 @@ var DiscordNotifications = class DiscordNotifications {
344
344
  } catch (err) {
345
345
  serverError = reason(err);
346
346
  }
347
+ let pinned;
348
+ let pinnedError;
349
+ if (layout.pinned) try {
350
+ pinned = await this.pinnedStates(layout.pinned);
351
+ } catch (err) {
352
+ pinnedError = reason(err);
353
+ }
347
354
  let welcome;
348
355
  let welcomeError;
349
356
  if (layout.welcome) try {
@@ -428,6 +435,8 @@ var DiscordNotifications = class DiscordNotifications {
428
435
  ...serverError ? { serverError } : {},
429
436
  ...welcome ? { welcome } : {},
430
437
  ...welcomeError ? { welcomeError } : {},
438
+ ...pinned ? { pinned } : {},
439
+ ...pinnedError ? { pinnedError } : {},
431
440
  ...onboarding ? { onboarding } : {},
432
441
  ...onboardingError ? { onboardingError } : {},
433
442
  ...application ? { application } : {},
@@ -439,8 +448,12 @@ var DiscordNotifications = class DiscordNotifications {
439
448
  ...rolesError ? { rolesError } : {}
440
449
  };
441
450
  }
451
+ /** What the bot keeps: the usual set, and Pin Messages when the layout pins messages. */
452
+ needs() {
453
+ return this.opts.layout?.pinned?.length ? [...BOT_NEEDS, "PinMessages"] : BOT_NEEDS;
454
+ }
442
455
  /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
443
- async inviteUrl(names = BOT_NEEDS) {
456
+ async inviteUrl(names = this.needs()) {
444
457
  const url = new URL("https://discord.com/oauth2/authorize");
445
458
  url.searchParams.set("client_id", await this.botId());
446
459
  url.searchParams.set("scope", "bot");
@@ -489,7 +502,13 @@ var DiscordNotifications = class DiscordNotifications {
489
502
  const link = await this.inviteOrNothing(["Administrator"]);
490
503
  const byHand = turningOn ? "turn them on once in Discord (Server Settings → Enable Community; setup then keeps everything else in line)" : "turn them off once in Discord (Server Settings → Community Settings → Disable Community)";
491
504
  const viaBot = link ? `give Holonet Administrator for one run and take it away again afterwards: ${link}` : "re-invite Holonet with the Administrator permission for one run, and take it away again afterwards";
492
- return new Error(`${appliedPrefix(applied)}turning community features ${turningOn ? "on" : "off"} was refused (Discord said: ${String(err.details).slice(0, 120)}), which means Holonet lacks the Administrator permission it needs for that. Either ${byHand}, or ${viaBot}. If Holonet already has Administrator, check that it is still in the server`, { cause: err });
505
+ const revoke = await this.inviteOrNothing();
506
+ return new ElevationRequiredError(`${appliedPrefix(applied)}turning community features ${turningOn ? "on" : "off"} was refused (Discord said: ${String(err.details).slice(0, 120)}), which means Holonet lacks the Administrator permission it needs for that. Either ${byHand}, or ${viaBot}. If Holonet already has Administrator, check that it is still in the server`, {
507
+ permission: "Administrator",
508
+ ...link ? { grantUrl: link } : {},
509
+ ...revoke ? { revokeUrl: revoke } : {},
510
+ ...applied.length > 0 ? { applied } : {}
511
+ }, { cause: err });
493
512
  }
494
513
  /** A 403 on a server edit becomes the explanation and the invite link; anything else is passed on as it is. */
495
514
  async manageServerHint(err) {
@@ -580,6 +599,159 @@ var DiscordNotifications = class DiscordNotifications {
580
599
  }
581
600
  return { updated };
582
601
  }
602
+ /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
603
+ async serverPermissions() {
604
+ const bot = this.bot();
605
+ const me = await this.botId();
606
+ if ((await this.serverOwner()).isBot) return {
607
+ owner: true,
608
+ bits: 0n,
609
+ held: /* @__PURE__ */ new Set(),
610
+ me
611
+ };
612
+ const [member, roles] = await Promise.all([bot.guilds.member(this.guild(), me), bot.guilds.roles(this.guild())]);
613
+ const held = /* @__PURE__ */ new Set([this.guild(), ...member.roles]);
614
+ return {
615
+ owner: false,
616
+ bits: roles.filter((r) => held.has(r.id)).reduce((all, r) => all | BigInt(r.permissions ?? "0"), 0n),
617
+ held,
618
+ me
619
+ };
620
+ }
621
+ async holdsPermission(permission) {
622
+ const { owner, bits } = await this.serverPermissions();
623
+ if (owner) return true;
624
+ const has = (name) => {
625
+ const bit = BigInt(permissions([name]));
626
+ return (bits & bit) === bit;
627
+ };
628
+ return has("Administrator") || has(permission);
629
+ }
630
+ /**
631
+ * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
632
+ * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
633
+ */
634
+ async channelDenies(permission, channelId) {
635
+ const { owner, bits, held, me } = await this.serverPermissions();
636
+ const bit = BigInt(permissions([permission]));
637
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n || (bits & bit) !== bit) return false;
638
+ const list = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId)?.permission_overwrites ?? [];
639
+ const apply = (now, found) => {
640
+ const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
641
+ const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
642
+ return now & ~deny | allow;
643
+ };
644
+ let now = apply(bits, list.filter((o) => o.id === this.guild()));
645
+ now = apply(now, list.filter((o) => o.type === 0 && o.id !== this.guild() && held.has(o.id)));
646
+ now = apply(now, list.filter((o) => o.type === 1 && o.id === me));
647
+ return (now & bit) !== bit;
648
+ }
649
+ /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
650
+ async ownMessages(channelId) {
651
+ const me = await this.botId();
652
+ return (await this.bot().channels.messages(channelId, 100)).filter((m) => m.author?.id === me).map((m) => ({
653
+ id: m.id,
654
+ content: m.content,
655
+ pinned: m.pinned === true
656
+ }));
657
+ }
658
+ /** The layout's messages grouped by channel, in the order the channels first appear. */
659
+ static pinsByChannel(pinned) {
660
+ const byChannel = /* @__PURE__ */ new Map();
661
+ for (const pin of pinned) {
662
+ const key = pin.channel.toLowerCase();
663
+ byChannel.set(key, [.../* @__PURE__ */ new Set([...byChannel.get(key) ?? [], pin.content])]);
664
+ }
665
+ return byChannel;
666
+ }
667
+ /**
668
+ * What differs in one channel: the declared messages that are not pinned yet, and the bot's pinned messages the
669
+ * layout does not declare (or declares once and the bot pinned twice). The layout is the whole set of the bot's
670
+ * pins in a channel it names.
671
+ */
672
+ static pinDrift(own, wanted) {
673
+ const pinned = own.filter((m) => m.pinned).sort((a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : 1);
674
+ const kept = /* @__PURE__ */ new Set();
675
+ const extras = pinned.filter((m) => {
676
+ if (!wanted.includes(m.content) || kept.has(m.content)) return true;
677
+ kept.add(m.content);
678
+ return false;
679
+ });
680
+ return {
681
+ missing: wanted.filter((c) => !kept.has(c)),
682
+ extras
683
+ };
684
+ }
685
+ /** Whether each pinned message is in place: pinned by this bot with exactly the layout's text, and nothing else of the bot's pinned beside it. */
686
+ async pinnedStates(pinned) {
687
+ const channels = await this.channelList();
688
+ const verdicts = /* @__PURE__ */ new Map();
689
+ for (const [channel, wanted] of DiscordNotifications.pinsByChannel(pinned)) {
690
+ const own = await this.ownMessages(DiscordNotifications.pickChannelId(channels, channel, "pinned messages"));
691
+ const drift = DiscordNotifications.pinDrift(own, wanted);
692
+ verdicts.set(channel, {
693
+ missing: new Set(drift.missing),
694
+ extras: drift.extras.length,
695
+ anyPinned: own.some((m) => m.pinned)
696
+ });
697
+ }
698
+ return pinned.map((pin) => {
699
+ const v = verdicts.get(pin.channel.toLowerCase());
700
+ const state = v.missing.has(pin.content) ? v.anyPinned ? "different" : "missing" : v.extras > 0 ? "different" : "ok";
701
+ return {
702
+ channel: pin.channel,
703
+ state
704
+ };
705
+ });
706
+ }
707
+ async ensurePinned(pinned) {
708
+ const bot = this.bot();
709
+ const channels = await this.channelList();
710
+ const updated = [];
711
+ for (const [channel, wanted] of DiscordNotifications.pinsByChannel(pinned)) {
712
+ const channelId = DiscordNotifications.pickChannelId(channels, channel, "pinned messages");
713
+ const own = await this.ownMessages(channelId);
714
+ const drift = DiscordNotifications.pinDrift(own, wanted);
715
+ if (drift.missing.length === 0 && drift.extras.length === 0) continue;
716
+ let extras = drift.extras;
717
+ for (const content of drift.missing) {
718
+ const orphan = own.find((m) => !m.pinned && m.content === content);
719
+ const posted = orphan ?? await bot.channels.createMessage(channelId, { content });
720
+ try {
721
+ try {
722
+ await bot.channels.pin(channelId, posted.id);
723
+ } catch (err) {
724
+ if (!(err instanceof ProviderApiError && /\b30003\b/.test(String(err.details))) || extras.length === 0) throw err;
725
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
726
+ extras = [];
727
+ await bot.channels.pin(channelId, posted.id);
728
+ }
729
+ } catch (err) {
730
+ if (!orphan) await bot.channels.deleteMessage(channelId, posted.id).catch(() => void 0);
731
+ throw await this.pinHint(err, channel);
732
+ }
733
+ }
734
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
735
+ if (drift.missing.length > 0) {
736
+ const after = DiscordNotifications.pinDrift(await this.ownMessages(channelId), wanted);
737
+ for (const dup of after.extras) await bot.channels.deleteMessage(channelId, dup.id);
738
+ }
739
+ updated.push(`#${channel}`);
740
+ }
741
+ return { updated };
742
+ }
743
+ /** A 403 on pinning becomes the missing permission and a link that grants it, which `setup` can walk a person through. */
744
+ async pinHint(err, channel) {
745
+ if (!DiscordNotifications.missingPermissions(err)) return err;
746
+ if (await this.channelDenies("PinMessages", DiscordNotifications.pickChannelId(await this.channelList(), channel, "pinned messages")).catch(() => false)) return new Error(`the bot could not pin the message in #${channel}: its role has Pin Messages, but the channel's permissions take it away. Remove that override under Edit Channel → Permissions, then run setup again`, { cause: err });
747
+ const link = await this.inviteOrNothing([...BOT_NEEDS, "PinMessages"]);
748
+ return new ElevationRequiredError(`the bot could not pin the message in #${channel}: its role lacks Pin Messages. Re-invite it with that permission${link ? ` (this updates its role in place): ${link}` : ""}`, {
749
+ permission: "PinMessages",
750
+ label: "Pin Messages",
751
+ keep: true,
752
+ ...link ? { grantUrl: link } : {}
753
+ }, { cause: err });
754
+ }
583
755
  /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
584
756
  static communityFeatureHint(err, what) {
585
757
  if (!(err instanceof ProviderApiError && err.status === 403)) return err;
@@ -851,6 +1023,8 @@ var DiscordNotifications = class DiscordNotifications {
851
1023
  const long = welcome.channels.find((c) => c.description.length > 50);
852
1024
  if (long) return `welcome: the description of \`${long.channel}\` is ${long.description.length} characters; Discord allows up to 50`;
853
1025
  }
1026
+ const long2000 = layout.pinned?.find((p) => p.content.length > 2e3);
1027
+ if (long2000) return `pinned: the message for \`${long2000.channel}\` is ${long2000.content.length} characters; Discord allows up to 2000`;
854
1028
  const server = layout.server;
855
1029
  for (const [field, map] of [
856
1030
  ["verification", VERIFICATION],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.205",
3
+ "version": "5.0.0-alpha.207",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -30,7 +30,7 @@
30
30
  "dist"
31
31
  ],
32
32
  "devDependencies": {
33
- "@theholocron/discord-client": "^1.49.0",
33
+ "@theholocron/discord-client": "^1.50.0",
34
34
  "@theholocron/eslint-config": "^8.8.2",
35
35
  "@theholocron/http-client": "^1.43.1",
36
36
  "@theholocron/misc-utils": "^1.16.0",
@@ -48,12 +48,12 @@
48
48
  "tsx": "4.23.15",
49
49
  "typescript": "^5.9.3",
50
50
  "vitest": "^4.1.11",
51
- "@theholocron/cli": "5.0.0-alpha.205"
51
+ "@theholocron/cli": "5.0.0-alpha.207"
52
52
  },
53
53
  "peerDependencies": {
54
- "@theholocron/discord-client": "^1.49.0",
54
+ "@theholocron/discord-client": "^1.50.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.205"
56
+ "@theholocron/cli": "5.0.0-alpha.207"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"