@theholocron/holocron-plugin-discord 5.0.0-alpha.194 → 5.0.0-alpha.195

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, NotificationsLayout, NotificationsServerLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsLayout, NotificationsOnboardingLayout, NotificationsServerLayout, NotificationsWelcomeLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
@@ -56,6 +56,10 @@ declare class DiscordNotifications implements Notifications {
56
56
  private inviteUrl;
57
57
  /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
58
58
  preflight(layout: NotificationsLayout): Promise<void>;
59
+ /** The one role with this name, or an error saying why not: two would mean granting something to the wrong members. */
60
+ private static pickRole;
61
+ /** The one text or announcement channel with this name, or an error saying why not. */
62
+ private static pickChannelId;
59
63
  /** True for a 403 that is about permissions, not about the bot being unable to see the server at all. */
60
64
  private static missingPermissions;
61
65
  /** An invite link, or nothing when building it needs a request that fails: the advice must not depend on one. */
@@ -67,6 +71,16 @@ declare class DiscordNotifications implements Notifications {
67
71
  ensureServer(settings: NotificationsServerLayout): Promise<{
68
72
  updated: string[];
69
73
  }>;
74
+ /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
75
+ private static communityFeatureHint;
76
+ ensureWelcome(welcome: NotificationsWelcomeLayout): Promise<{
77
+ updated: string[];
78
+ }>;
79
+ /** An onboarding prompt reduced to what the layout can state, so the server's and the layout's can be compared. */
80
+ private static onboardingKey;
81
+ ensureOnboarding(onboarding: NotificationsOnboardingLayout): Promise<{
82
+ updated: string[];
83
+ }>;
70
84
  validateLayout(layout: NotificationsLayout): string | undefined;
71
85
  private botUser?;
72
86
  private botId;
package/dist/index.mjs CHANGED
@@ -244,11 +244,12 @@ var DiscordNotifications = class DiscordNotifications {
244
244
  } catch (err) {
245
245
  rolesError = reason(err);
246
246
  }
247
+ const nameOfChannel = (id) => channels.find((c) => c.id === id)?.name ?? id;
248
+ const channelName = (id) => id ? nameOfChannel(id) : void 0;
247
249
  let server;
248
250
  let serverError;
249
251
  if (layout.server) try {
250
252
  const guild = await bot.guilds.get(this.guild());
251
- const channelName = (id) => id ? channels.find((c) => c.id === id)?.name ?? id : void 0;
252
253
  const verification = nameOf(VERIFICATION, guild.verification_level);
253
254
  const defaultNotifications = nameOf(NOTIFICATIONS, guild.default_message_notifications);
254
255
  const contentFilter = nameOf(FILTER, guild.explicit_content_filter);
@@ -269,6 +270,47 @@ var DiscordNotifications = class DiscordNotifications {
269
270
  } catch (err) {
270
271
  serverError = reason(err);
271
272
  }
273
+ let welcome;
274
+ let welcomeError;
275
+ if (layout.welcome) try {
276
+ const guild = await bot.guilds.get(this.guild());
277
+ const screen = await bot.guilds.welcomeScreen(this.guild());
278
+ welcome = {
279
+ enabled: (guild.features ?? []).includes("WELCOME_SCREEN_ENABLED"),
280
+ description: screen.description ?? "",
281
+ channels: (screen.welcome_channels ?? []).map((c) => ({
282
+ channel: nameOfChannel(c.channel_id),
283
+ description: c.description,
284
+ ...c.emoji_name ? { emoji: c.emoji_name } : {}
285
+ }))
286
+ };
287
+ } catch (err) {
288
+ welcomeError = reason(err);
289
+ }
290
+ let onboarding;
291
+ let onboardingError;
292
+ if (layout.onboarding) try {
293
+ const found = await bot.guilds.onboarding(this.guild());
294
+ const roleOf = (id) => roles.find((r) => r.id === id)?.name ?? id;
295
+ onboarding = {
296
+ enabled: found.enabled,
297
+ defaultChannels: found.default_channel_ids.map(nameOfChannel),
298
+ prompts: found.prompts.map((p) => ({
299
+ title: p.title,
300
+ singleSelect: p.single_select,
301
+ required: p.required,
302
+ options: p.options.map((o) => ({
303
+ title: o.title,
304
+ ...o.description ? { description: o.description } : {},
305
+ ...o.emoji?.name ?? o.emoji_name ? { emoji: o.emoji?.name ?? o.emoji_name } : {},
306
+ channels: (o.channel_ids ?? []).map(nameOfChannel),
307
+ roles: (o.role_ids ?? []).map(roleOf)
308
+ }))
309
+ }))
310
+ };
311
+ } catch (err) {
312
+ onboardingError = reason(err);
313
+ }
272
314
  const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
273
315
  found.forEach((entry, i) => {
274
316
  entry.access = this.accessOf(text[i].permission_overwrites, roleName);
@@ -280,6 +322,10 @@ var DiscordNotifications = class DiscordNotifications {
280
322
  categoryAccess,
281
323
  ...server ? { server } : {},
282
324
  ...serverError ? { serverError } : {},
325
+ ...welcome ? { welcome } : {},
326
+ ...welcomeError ? { welcomeError } : {},
327
+ ...onboarding ? { onboarding } : {},
328
+ ...onboardingError ? { onboardingError } : {},
283
329
  channels: found,
284
330
  roles,
285
331
  ...rolesError ? { rolesError } : {}
@@ -303,6 +349,20 @@ var DiscordNotifications = class DiscordNotifications {
303
349
  throw await this.manageServerHint(err);
304
350
  }
305
351
  }
352
+ /** The one role with this name, or an error saying why not: two would mean granting something to the wrong members. */
353
+ static pickRole(roles, name, who) {
354
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
355
+ if (found.length === 0) throw new Error(`${who} names the role \`${name}\`, which does not exist on the server yet`);
356
+ if (found.length > 1) throw new Error(`${who} names the role \`${name}\`, but ${found.length} roles have that name (ids ${found.map((r) => r.id).join(", ")}) -- delete or rename the extras`);
357
+ return found[0].id;
358
+ }
359
+ /** The one text or announcement channel with this name, or an error saying why not. */
360
+ static pickChannelId(channels, name, who) {
361
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
362
+ if (named.length === 0) throw new Error(`${who} name the channel \`${name}\`, which does not exist on the server yet`);
363
+ if (named.length > 1) throw new Error(`${who} name the channel \`${name}\`, but ${named.length} channels have that name (ids ${named.map((c) => c.id).join(", ")}) -- rename one`);
364
+ return named[0].id;
365
+ }
306
366
  /** True for a 403 that is about permissions, not about the bot being unable to see the server at all. */
307
367
  static missingPermissions(err) {
308
368
  return err instanceof ProviderApiError && err.status === 403 && !/Missing Access|\b50001\b/.test(String(err.details));
@@ -333,12 +393,7 @@ var DiscordNotifications = class DiscordNotifications {
333
393
  const bot = this.bot();
334
394
  const guild = await bot.guilds.get(this.guild());
335
395
  const channels = await this.channelList();
336
- const idOf = (name) => {
337
- const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
338
- if (named.length === 0) throw new Error(`server settings name the channel \`${name}\`, which does not exist on the server yet`);
339
- if (named.length > 1) throw new Error(`server settings name the channel \`${name}\`, but ${named.length} channels have that name (ids ${named.map((c) => c.id).join(", ")}) -- rename one`);
340
- return named[0].id;
341
- };
396
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "server settings");
342
397
  const patch = {};
343
398
  const updated = [];
344
399
  const set = (label, key, want, have) => {
@@ -417,7 +472,129 @@ var DiscordNotifications = class DiscordNotifications {
417
472
  }
418
473
  return { updated };
419
474
  }
475
+ /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
476
+ static communityFeatureHint(err, what) {
477
+ if (!(err instanceof ProviderApiError && err.status === 403)) return err;
478
+ return new Error(`the bot is not allowed to change ${what} (Discord said: ${String(err.details).slice(0, 120)}). It needs Manage Server, and the server needs community features on`, { cause: err });
479
+ }
480
+ async ensureWelcome(welcome) {
481
+ const bot = this.bot();
482
+ const channels = await this.channelList();
483
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "the welcome screen");
484
+ const wanted = {
485
+ enabled: welcome.enabled ?? true,
486
+ description: welcome.description,
487
+ welcome_channels: welcome.channels.map((c) => ({
488
+ channel_id: idOf(c.channel),
489
+ description: c.description,
490
+ emoji_name: c.emoji ?? null,
491
+ emoji_id: null
492
+ }))
493
+ };
494
+ const normalise = (list) => JSON.stringify(list.map((c) => [
495
+ c.channel_id,
496
+ c.description,
497
+ c.emoji_name ?? null,
498
+ c.emoji_id ?? null
499
+ ]));
500
+ let guild;
501
+ let screen;
502
+ try {
503
+ guild = await bot.guilds.get(this.guild());
504
+ screen = await bot.guilds.welcomeScreen(this.guild());
505
+ } catch (err) {
506
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
507
+ }
508
+ const updated = [];
509
+ if ((guild.features ?? []).includes("WELCOME_SCREEN_ENABLED") !== wanted.enabled) updated.push("enabled");
510
+ if ((screen.description ?? "") !== wanted.description) updated.push("description");
511
+ if (normalise(screen.welcome_channels ?? []) !== normalise(wanted.welcome_channels)) updated.push("channels");
512
+ if (updated.length === 0) return { updated };
513
+ let after;
514
+ try {
515
+ after = await bot.guilds.modifyWelcomeScreen(this.guild(), wanted);
516
+ } catch (err) {
517
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
518
+ }
519
+ if ((after.description ?? "") !== wanted.description || normalise(after.welcome_channels ?? []) !== normalise(wanted.welcome_channels)) throw new Error("sent the welcome screen but it came back different -- Discord may have refused a part of it");
520
+ if (((await bot.guilds.get(this.guild())).features ?? []).includes("WELCOME_SCREEN_ENABLED") !== wanted.enabled) throw new Error(`sent the welcome screen but it is still ${wanted.enabled ? "off" : "on"} -- Discord may have refused the switch`);
521
+ return { updated };
522
+ }
523
+ /** An onboarding prompt reduced to what the layout can state, so the server's and the layout's can be compared. */
524
+ static onboardingKey(prompts) {
525
+ return JSON.stringify(prompts.map((p) => [
526
+ p.type,
527
+ p.in_onboarding,
528
+ p.title,
529
+ p.single_select,
530
+ p.required,
531
+ p.options.map((o) => [
532
+ o.title,
533
+ o.description ?? "",
534
+ [...o.channel_ids ?? []].sort(),
535
+ [...o.role_ids ?? []].sort(),
536
+ o.emoji?.name ?? o.emoji_name ?? null
537
+ ])
538
+ ]));
539
+ }
540
+ async ensureOnboarding(onboarding) {
541
+ const bot = this.bot();
542
+ const channels = await this.channelList();
543
+ const channelId = (name) => DiscordNotifications.pickChannelId(channels, name, "onboarding");
544
+ const roles = (onboarding.prompts ?? []).some((p) => p.options.some((o) => (o.roles ?? []).length > 0)) ? await this.roleList() : [];
545
+ const roleId = (name) => DiscordNotifications.pickRole(roles, name, "onboarding");
546
+ let current;
547
+ try {
548
+ current = await bot.guilds.onboarding(this.guild());
549
+ } catch (err) {
550
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
551
+ }
552
+ const prompts = onboarding.prompts === void 0 ? current.prompts : onboarding.prompts.map((p) => ({
553
+ type: 0,
554
+ title: p.title,
555
+ single_select: p.singleSelect ?? false,
556
+ required: p.required ?? false,
557
+ in_onboarding: true,
558
+ options: p.options.map((o) => ({
559
+ title: o.title,
560
+ description: o.description ?? null,
561
+ channel_ids: (o.channels ?? []).map(channelId),
562
+ role_ids: (o.roles ?? []).map(roleId),
563
+ emoji_name: o.emoji ?? null
564
+ }))
565
+ }));
566
+ const defaultChannels = onboarding.defaultChannels === void 0 ? current.default_channel_ids : onboarding.defaultChannels.map(channelId);
567
+ const enabled = onboarding.enabled ?? current.enabled;
568
+ const updated = [];
569
+ if (enabled !== current.enabled) updated.push("enabled");
570
+ if (JSON.stringify([...defaultChannels].sort()) !== JSON.stringify([...current.default_channel_ids].sort())) updated.push("defaultChannels");
571
+ if (DiscordNotifications.onboardingKey(prompts) !== DiscordNotifications.onboardingKey(current.prompts)) updated.push("prompts");
572
+ if (updated.length === 0) return { updated };
573
+ const body = {
574
+ prompts,
575
+ default_channel_ids: defaultChannels,
576
+ enabled,
577
+ mode: current.mode ?? 0
578
+ };
579
+ let after;
580
+ try {
581
+ after = await bot.guilds.modifyOnboarding(this.guild(), body);
582
+ } catch (err) {
583
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
584
+ }
585
+ if (after.enabled !== enabled || JSON.stringify([...after.default_channel_ids].sort()) !== JSON.stringify([...defaultChannels].sort()) || DiscordNotifications.onboardingKey(after.prompts) !== DiscordNotifications.onboardingKey(prompts)) throw new Error("sent onboarding but it came back different -- Discord may have refused a part of it");
586
+ return { updated };
587
+ }
420
588
  validateLayout(layout) {
589
+ const questions = layout.onboarding?.prompts?.length ?? 0;
590
+ if (questions > 5) return `onboarding: ${questions} questions; Discord allows up to 5`;
591
+ const welcome = layout.welcome;
592
+ if (welcome) {
593
+ if (welcome.description.length > 140) return `welcome: \`description\` is ${welcome.description.length} characters; Discord allows up to 140`;
594
+ if (welcome.channels.length > 5) return `welcome: ${welcome.channels.length} channels; Discord allows up to 5`;
595
+ const long = welcome.channels.find((c) => c.description.length > 50);
596
+ if (long) return `welcome: the description of \`${long.channel}\` is ${long.description.length} characters; Discord allows up to 50`;
597
+ }
421
598
  const server = layout.server;
422
599
  for (const [field, map] of [
423
600
  ["verification", VERIFICATION],
@@ -455,12 +632,7 @@ var DiscordNotifications = class DiscordNotifications {
455
632
  const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
456
633
  if (everyoneDeny.length === 0) return [];
457
634
  const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
458
- const idOf = (name) => {
459
- const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
460
- if (found.length === 0) throw new Error(`access names the role \`${name}\`, which does not exist on the server yet`);
461
- if (found.length > 1) throw new Error(`access names the role \`${name}\`, but ${found.length} roles have that name (ids ${found.map((r) => r.id).join(", ")}) -- delete or rename the extras`);
462
- return found[0].id;
463
- };
635
+ const idOf = (name) => DiscordNotifications.pickRole(roles, name, "access");
464
636
  const allow = /* @__PURE__ */ new Map();
465
637
  const grant = (roleName, names) => {
466
638
  const id = idOf(roleName);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.194",
3
+ "version": "5.0.0-alpha.195",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -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.194"
51
+ "@theholocron/cli": "5.0.0-alpha.195"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@theholocron/discord-client": "^1.44.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.194"
56
+ "@theholocron/cli": "5.0.0-alpha.195"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"