@theholocron/holocron-plugin-discord 5.0.0-alpha.490 → 5.0.0-alpha.492

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, DiscussionPatch, DiscussionPost, DuplicateDiscussion, EnsureDiscussionInput, EnsureWebhookResult, EnsuredDiscussion, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsDelivery, NotificationsEveryoneLayout, NotificationsForumTag, NotificationsLayout, NotificationsMember, NotificationsOnboardingLayout, NotificationsPinnedLayout, NotificationsServerLayout, NotificationsSignIn, NotificationsWelcomeLayout, PluginToken, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, DiscussionPatch, DiscussionPost, DuplicateDiscussion, EnsureDiscussionInput, EnsureWebhookResult, EnsuredDiscussion, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsDelivery, NotificationsEveryoneLayout, NotificationsForumTag, NotificationsLayout, NotificationsMember, NotificationsOnboardingLayout, NotificationsPinnedLayout, NotificationsReaction, NotificationsServerLayout, NotificationsSignIn, NotificationsWelcomeLayout, PluginToken, 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
  /** Resolves the Discord webhook URL from `--token`, `HOLOCRON_DISCORD_WEBHOOK`, `DISCORD_WEBHOOK_URL` or the keyring, and throws an `AuthError` when none is set. */
4
4
  export declare const resolveToken: import("@theholocron/cli").TokenResolver;
@@ -294,8 +294,32 @@ export declare class DiscordNotifications implements Notifications {
294
294
  access?: NotificationsAccess;
295
295
  kind?: "text" | "forum";
296
296
  tags?: NotificationsForumTag[];
297
- defaultReaction?: string;
297
+ defaultReaction?: NotificationsReaction;
298
298
  }): Promise<EnsuredResource>;
299
+ /**
300
+ * Finds the server emoji with this name or makes it from `image` (a `data:` URI). One that exists is left exactly as it
301
+ * is: never replaced, renamed or deleted, and the image is not compared with it. Making one needs Create Guild
302
+ * Expressions; without it the error says so and carries the link that invites the bot again asking for it.
303
+ */
304
+ ensureEmoji(input: {
305
+ name: string;
306
+ image: string;
307
+ }): Promise<EnsuredResource>;
308
+ /** The server emoji with this name, or an error naming it and the two ways to get one. */
309
+ private emojiNamed;
310
+ /** A layout reaction as Discord's default reaction takes it: the emoji id of a server emoji, or the Unicode character; never both. */
311
+ private defaultReactionOf;
312
+ /**
313
+ * Whether a forum's default reaction is the wanted one. A server emoji is compared by its id alone (Discord may or may
314
+ * not echo its name); a Unicode one by its character, with no id.
315
+ */
316
+ private static sameReaction;
317
+ /**
318
+ * The starter reactions as the text the reaction route takes: the character of a Unicode emoji, `name:id` of a server
319
+ * one. One the server lacks (or whose list cannot be read) is left out, like any reaction that fails: the post is made
320
+ * and `doctor notifications` names the missing emoji.
321
+ */
322
+ private starterReactionTexts;
299
323
  /** Finds the webhook with this name on the channel, or creates it; the optional avatar is the picture it posts with. */
300
324
  ensureWebhook(input: {
301
325
  channel: string;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthError, ElevationRequiredError, ProviderApiError, connectionProbe, createResolveToken, tokenExpectations } from "@theholocron/cli";
1
+ import { AuthError, ElevationRequiredError, ProviderApiError, connectionProbe, createResolveToken, layoutEmojis, parseReaction, tokenExpectations } from "@theholocron/cli";
2
2
  import { errorMessage } from "@theholocron/misc-utils";
3
3
  import { ApplicationFlag, ChannelType, MessageFlag, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
4
  // src/bot-needs.ts
@@ -18,18 +18,22 @@ const BOT_NEEDS = [
18
18
  /**
19
19
  * What the bot keeps for a layout: the usual set, Pin Messages when the layout pins messages, Manage Threads when it
20
20
  * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads),
21
- * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
21
+ * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made),
22
+ * and Create Guild Expressions (Discord's "Create Expressions") only when the layout gives a server emoji an `image`,
23
+ * which `setup` makes the emoji from.
22
24
  * The one list `setup`'s invite link, `doctor notifications` and `probe discord token` all read.
23
25
  */
24
26
  function botNeeds(layout) {
25
27
  const channels = (layout?.categories ?? []).flatMap((c) => c.channels ?? []);
26
28
  const forum = channels.some((ch) => ch.kind === "forum");
27
29
  const reacts = channels.some((ch) => (ch.starterReactions ?? []).length > 0);
30
+ const makesEmoji = layoutEmojis(layout).some((emoji) => emoji.image);
28
31
  return [
29
32
  ...BOT_NEEDS,
30
33
  ...layout?.pinned?.length ? ["PinMessages"] : [],
31
34
  ...forum ? ["ManageThreads"] : [],
32
- ...reacts ? ["AddReactions"] : []
35
+ ...reacts ? ["AddReactions"] : [],
36
+ ...makesEmoji ? ["CreateGuildExpressions"] : []
33
37
  ];
34
38
  }
35
39
  // src/probes/token/expectations.ts
@@ -309,7 +313,7 @@ var DiscordDiscussions = class DiscordDiscussions {
309
313
  * missing reaction must not fail the sync.
310
314
  */
311
315
  async react(post, channel) {
312
- for (const emoji of this.deps.starterReactions?.(channel) ?? []) await this.deps.bot().channels.addReaction(post, post, emoji).catch(() => void 0);
316
+ for (const emoji of await this.deps.starterReactions?.(channel) ?? []) await this.deps.bot().channels.addReaction(post, post, emoji).catch(() => void 0);
313
317
  }
314
318
  /** The post for `key` (or the one `url` names, when the file moved), or `undefined`. It writes nothing. */
315
319
  async read(channel, key, url) {
@@ -681,6 +685,24 @@ var DiscordNotifications = class DiscordNotifications {
681
685
  const bot = this.bot();
682
686
  const channels = await this.channelList();
683
687
  const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
688
+ let emojis;
689
+ let emojisError;
690
+ const emojiById = /* @__PURE__ */ new Map();
691
+ if (layoutEmojis(layout).length > 0) try {
692
+ const list = await bot.guilds.emojis(this.guild());
693
+ emojis = [];
694
+ for (const e of list) {
695
+ if (!e.id || !e.name) continue;
696
+ emojis.push(e.name);
697
+ emojiById.set(e.id, e.name);
698
+ }
699
+ } catch (err) {
700
+ emojisError = reason(err);
701
+ }
702
+ const reactionText = (r) => {
703
+ if (r?.emoji_id) return emojiById.get(r.emoji_id) ? `:${emojiById.get(r.emoji_id)}:` : `custom emoji ${r.emoji_id}`;
704
+ return r?.emoji_name || void 0;
705
+ };
684
706
  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())));
685
707
  const wantsPrs = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.feeds?.prs).map((ch) => ch.name.toLowerCase())));
686
708
  const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement || c.type === ChannelType.Forum);
@@ -713,7 +735,7 @@ var DiscordNotifications = class DiscordNotifications {
713
735
  ...c.type === ChannelType.Forum ? {
714
736
  kind: "forum",
715
737
  tags: (c.available_tags ?? []).map(DiscordNotifications.tagOf),
716
- ...c.default_reaction_emoji?.emoji_name ? { defaultReaction: c.default_reaction_emoji.emoji_name } : {}
738
+ ...reactionText(c.default_reaction_emoji) ? { defaultReaction: reactionText(c.default_reaction_emoji) } : {}
717
739
  } : {},
718
740
  webhooks,
719
741
  webhookAvatars,
@@ -861,6 +883,8 @@ var DiscordNotifications = class DiscordNotifications {
861
883
  categoryAccess,
862
884
  ...botPermissions ? { botPermissions } : {},
863
885
  ...botPermissionsError ? { botPermissionsError } : {},
886
+ ...emojis ? { emojis } : {},
887
+ ...emojisError ? { emojisError } : {},
864
888
  ...server ? { server } : {},
865
889
  ...serverError ? { serverError } : {},
866
890
  ...welcome ? { welcome } : {},
@@ -1231,7 +1255,7 @@ var DiscordNotifications = class DiscordNotifications {
1231
1255
  bot: () => this.bot(),
1232
1256
  guild: () => this.guild(),
1233
1257
  channels: () => this.channelList(),
1234
- starterReactions: (channel) => (this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []).find((c) => DiscordNotifications.same(c.name, channel))?.starterReactions ?? [],
1258
+ starterReactions: (channel) => this.starterReactionTexts((this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []).find((c) => DiscordNotifications.same(c.name, channel))?.starterReactions ?? []),
1235
1259
  suppressEmbeds: (channel) => Boolean((this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []).find((c) => DiscordNotifications.same(c.name, channel))?.feeds?.prs)
1236
1260
  });
1237
1261
  }
@@ -1856,6 +1880,7 @@ var DiscordNotifications = class DiscordNotifications {
1856
1880
  const channels = await this.channelList();
1857
1881
  const existing = DiscordNotifications.findChannel(channels, input.name, parent, forum);
1858
1882
  if (!existing && DiscordNotifications.findChannel(channels, input.name, parent, !forum)) throw new Error(`\`${input.name}\` exists as ${forum ? "a text channel" : "a forum"}, and Discord cannot turn it into ${forum ? "a forum" : "a text channel"}. Delete it in Discord (its messages go with it), then run setup again`);
1883
+ const reaction = forum && input.defaultReaction !== void 0 ? await this.defaultReactionOf(input.defaultReaction) : void 0;
1859
1884
  const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
1860
1885
  if (existing) {
1861
1886
  const updated = [];
@@ -1865,15 +1890,9 @@ var DiscordNotifications = class DiscordNotifications {
1865
1890
  patch.available_tags = tags;
1866
1891
  updated.push("tags");
1867
1892
  }
1868
- if (forum && input.defaultReaction !== void 0) {
1869
- const have = existing.default_reaction_emoji;
1870
- if (have?.emoji_name !== input.defaultReaction || have.emoji_id) {
1871
- patch.default_reaction_emoji = {
1872
- emoji_id: null,
1873
- emoji_name: input.defaultReaction
1874
- };
1875
- updated.push("default reaction");
1876
- }
1893
+ if (reaction && !DiscordNotifications.sameReaction(existing.default_reaction_emoji, reaction)) {
1894
+ patch.default_reaction_emoji = reaction;
1895
+ updated.push("default reaction");
1877
1896
  }
1878
1897
  if (parent && existing.parent_id !== parent) {
1879
1898
  patch.parent_id = parent;
@@ -1899,10 +1918,7 @@ var DiscordNotifications = class DiscordNotifications {
1899
1918
  name: input.name,
1900
1919
  type: forum ? ChannelType.Forum : ChannelType.Text,
1901
1920
  ...forum && input.tags ? { available_tags: input.tags.map((t) => DiscordNotifications.tagInput(t)) } : {},
1902
- ...forum && input.defaultReaction ? { default_reaction_emoji: {
1903
- emoji_id: null,
1904
- emoji_name: input.defaultReaction
1905
- } } : {},
1921
+ ...reaction ? { default_reaction_emoji: reaction } : {},
1906
1922
  ...input.topic ? { topic: input.topic } : {},
1907
1923
  ...parent ? { parent_id: parent } : {},
1908
1924
  ...overwrites ? { permission_overwrites: overwrites } : {}
@@ -1910,6 +1926,77 @@ var DiscordNotifications = class DiscordNotifications {
1910
1926
  created: true
1911
1927
  };
1912
1928
  }
1929
+ /**
1930
+ * Finds the server emoji with this name or makes it from `image` (a `data:` URI). One that exists is left exactly as it
1931
+ * is: never replaced, renamed or deleted, and the image is not compared with it. Making one needs Create Guild
1932
+ * Expressions; without it the error says so and carries the link that invites the bot again asking for it.
1933
+ */
1934
+ async ensureEmoji(input) {
1935
+ const bot = this.bot();
1936
+ const have = (await bot.guilds.emojis(this.guild())).find((e) => e.id && e.name === input.name);
1937
+ if (have?.id) return {
1938
+ id: have.id,
1939
+ created: false
1940
+ };
1941
+ try {
1942
+ return {
1943
+ id: (await bot.guilds.createEmoji(this.guild(), {
1944
+ name: input.name,
1945
+ image: input.image
1946
+ })).id,
1947
+ created: true
1948
+ };
1949
+ } catch (err) {
1950
+ if (err instanceof ProviderApiError && err.status === 403) throw new Error(`Discord refused: the bot lacks Create Guild Expressions, which making emoji \`:${input.name}:\` needs. Invite it again with it (updates its role in place): ${await this.inviteUrl()}`, { cause: err });
1951
+ throw err;
1952
+ }
1953
+ }
1954
+ /** The server emoji with this name, or an error naming it and the two ways to get one. */
1955
+ async emojiNamed(name) {
1956
+ const emoji = (await this.bot().guilds.emojis(this.guild())).find((e) => e.id && e.name === name);
1957
+ if (!emoji?.id) throw new Error(`the server has no emoji named \`:${name}:\`; add it in the server's settings, or give the reaction an \`image\` so setup can make it`);
1958
+ return emoji;
1959
+ }
1960
+ /** A layout reaction as Discord's default reaction takes it: the emoji id of a server emoji, or the Unicode character; never both. */
1961
+ async defaultReactionOf(reaction) {
1962
+ const parsed = parseReaction(reaction);
1963
+ if (parsed.kind === "unicode") return {
1964
+ emoji_id: null,
1965
+ emoji_name: parsed.value
1966
+ };
1967
+ return {
1968
+ emoji_id: (await this.emojiNamed(parsed.name)).id,
1969
+ emoji_name: null
1970
+ };
1971
+ }
1972
+ /**
1973
+ * Whether a forum's default reaction is the wanted one. A server emoji is compared by its id alone (Discord may or may
1974
+ * not echo its name); a Unicode one by its character, with no id.
1975
+ */
1976
+ static sameReaction(have, want) {
1977
+ if (want.emoji_id) return have?.emoji_id === want.emoji_id;
1978
+ return !have?.emoji_id && have?.emoji_name === want.emoji_name;
1979
+ }
1980
+ /**
1981
+ * The starter reactions as the text the reaction route takes: the character of a Unicode emoji, `name:id` of a server
1982
+ * one. One the server lacks (or whose list cannot be read) is left out, like any reaction that fails: the post is made
1983
+ * and `doctor notifications` names the missing emoji.
1984
+ */
1985
+ async starterReactionTexts(reactions) {
1986
+ const texts = [];
1987
+ let emojis;
1988
+ for (const reaction of reactions) {
1989
+ const parsed = parseReaction(reaction);
1990
+ if (parsed.kind === "unicode") {
1991
+ texts.push(parsed.value);
1992
+ continue;
1993
+ }
1994
+ emojis ??= await this.bot().guilds.emojis(this.guild()).catch(() => []);
1995
+ const emoji = emojis.find((e) => e.id && e.name === parsed.name);
1996
+ if (emoji?.id) texts.push(`${emoji.name}:${emoji.id}`);
1997
+ }
1998
+ return texts;
1999
+ }
1913
2000
  /** Finds the webhook with this name on the channel, or creates it; the optional avatar is the picture it posts with. */
1914
2001
  async ensureWebhook(input) {
1915
2002
  const bot = this.bot();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.490",
3
+ "version": "5.0.0-alpha.492",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -41,19 +41,19 @@
41
41
  "tsx": "4.23.15",
42
42
  "typescript": "^5.9.3",
43
43
  "vitest": "^5.1.0",
44
- "@theholocron/cli": "5.0.0-alpha.490",
45
- "@theholocron/discord-client": "^1.58.0-alpha.42",
46
- "@theholocron/http-client": "^1.58.0-alpha.42",
47
- "@theholocron/eslint-config": "^8.9.0-alpha.21",
44
+ "@theholocron/cli": "5.0.0-alpha.492",
45
+ "@theholocron/discord-client": "^1.58.0-alpha.44",
48
46
  "@theholocron/misc-utils": "^1.17.0-alpha.5",
49
- "@theholocron/tsdown-config": "^8.9.0-alpha.21",
47
+ "@theholocron/eslint-config": "^8.9.0-alpha.21",
50
48
  "@theholocron/tsconfig": "^8.9.0-alpha.21",
51
- "@theholocron/vitest-config": "^8.9.0-alpha.21"
49
+ "@theholocron/tsdown-config": "^8.9.0-alpha.21",
50
+ "@theholocron/vitest-config": "^8.9.0-alpha.21",
51
+ "@theholocron/http-client": "^1.58.0-alpha.44"
52
52
  },
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.490"
56
+ "@theholocron/cli": "5.0.0-alpha.492"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"