@spatulox/simplediscordbot 3.2.0 → 4.0.1

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.mjs CHANGED
@@ -1,17 +1,24 @@
1
1
  // src/core/Bot.ts
2
- import { Events, version } from "discord.js";
2
+ import { Events, version as version2 } from "discord.js";
3
3
  import { Time } from "@spatulox/utils";
4
4
  import { Log as Log3 } from "@spatulox/utils";
5
5
  import { InternetChecker } from "@spatulox/utils";
6
6
 
7
7
  // src/core/BotLog.ts
8
8
  import {
9
- EmbedBuilder,
9
+ EmbedBuilder as EmbedBuilder2
10
+ } from "discord.js";
11
+ import { Log } from "@spatulox/utils";
12
+
13
+ // src/manager/builder/SendableComponentBuilder.ts
14
+ import {
10
15
  ActionRowBuilder as ActionRowBuilder2,
16
+ EmbedBuilder,
17
+ MessageFlags as MessageFlags2,
11
18
  ContainerBuilder,
12
- MessageFlags as MessageFlags2
19
+ TextDisplayBuilder,
20
+ BaseSelectMenuBuilder
13
21
  } from "discord.js";
14
- import { Log } from "@spatulox/utils";
15
22
 
16
23
  // src/manager/interactible/SelectMenuManager.ts
17
24
  import {
@@ -131,11 +138,20 @@ var SelectMenuManager = class _SelectMenuManager {
131
138
  flags: ephemeral ? [MessageFlags.Ephemeral] : []
132
139
  };
133
140
  }
134
- static toInteractionEdit(menus) {
141
+ /**
142
+ * Options to edit an existing message : message.edit()
143
+ */
144
+ static toMessageUpdate(menus) {
135
145
  return {
136
146
  components: this._createRowsToReturn(menus)
137
147
  };
138
148
  }
149
+ /**
150
+ * Options for interaction.update() and interaction.editReply() (buttons, select menus, modals, deferred replies)
151
+ */
152
+ static toInteractionUpdate(menus) {
153
+ return this.toMessageUpdate(menus);
154
+ }
139
155
  static _createRowsToReturn(menus) {
140
156
  if (Array.isArray(menus)) {
141
157
  return menus.map(
@@ -146,6 +162,65 @@ var SelectMenuManager = class _SelectMenuManager {
146
162
  }
147
163
  };
148
164
 
165
+ // src/manager/builder/SendableComponentBuilder.ts
166
+ var SendableComponentBuilder = class {
167
+ static isSendableComponent(thing) {
168
+ return thing instanceof EmbedBuilder || thing instanceof ContainerBuilder || thing instanceof BaseSelectMenuBuilder || thing instanceof ActionRowBuilder2;
169
+ }
170
+ /**
171
+ * A ContainerBuilder turns the whole message into a Components V2 one
172
+ */
173
+ static isComponentsV2(components) {
174
+ const comps = Array.isArray(components) ? components : [components];
175
+ return comps.some((comp) => comp instanceof ContainerBuilder);
176
+ }
177
+ static build(base, content, components) {
178
+ const comps = (Array.isArray(components) ? components : [components]).filter((comp) => !!comp);
179
+ const componentsV2 = this.isComponentsV2(comps);
180
+ const embeds = [];
181
+ const rows = [];
182
+ if (content) {
183
+ if (componentsV2) {
184
+ rows.push(new TextDisplayBuilder().setContent(content));
185
+ } else {
186
+ base.content = content;
187
+ }
188
+ }
189
+ for (const comp of comps) {
190
+ if (comp instanceof EmbedBuilder) {
191
+ if (componentsV2) {
192
+ throw new Error("An EmbedBuilder cannot be sent alongside a ContainerBuilder (Components V2 messages don't support embeds)");
193
+ }
194
+ embeds.push(comp);
195
+ } else if (SelectMenuManager.isSelectMenuList(comp)) {
196
+ rows.push(SelectMenuManager.row(comp));
197
+ } else if (comp instanceof ContainerBuilder || comp instanceof ActionRowBuilder2) {
198
+ rows.push(comp);
199
+ }
200
+ }
201
+ if (embeds.length > 0) base.embeds = embeds;
202
+ if (rows.length > 0) base.components = rows;
203
+ if (componentsV2) base.flags = [MessageFlags2.IsComponentsV2];
204
+ return base;
205
+ }
206
+ static buildInteraction(content, component, ephemeral) {
207
+ const base = this.build({}, content, component);
208
+ if (ephemeral) {
209
+ base.flags = [...Array.isArray(base.flags) ? base.flags : [], MessageFlags2.Ephemeral];
210
+ }
211
+ return base;
212
+ }
213
+ static buildMessage(contentOrComponent, component) {
214
+ const content = typeof contentOrComponent === "string" ? contentOrComponent : null;
215
+ const components = typeof contentOrComponent === "string" || contentOrComponent === null || contentOrComponent === void 0 ? component : contentOrComponent;
216
+ const hasComponents = Array.isArray(components) ? components.length > 0 : !!components;
217
+ if (!content && !hasComponents) {
218
+ throw new Error("At least content or component need to be defined to build a message");
219
+ }
220
+ return this.build({}, content, components);
221
+ }
222
+ };
223
+
149
224
  // src/core/BotEnv.ts
150
225
  var BotEnv = {
151
226
  get token() {
@@ -154,7 +229,7 @@ var BotEnv = {
154
229
  return token;
155
230
  },
156
231
  get dev() {
157
- return !!process.env.DISCORD_BOT_DEV;
232
+ return ["true", "1"].includes(process.env.DISCORD_BOT_DEV?.trim().toLowerCase() ?? "");
158
233
  }
159
234
  };
160
235
 
@@ -164,10 +239,8 @@ var BotLog = class _BotLog {
164
239
  static warnChannel = null;
165
240
  static debugChannel = null;
166
241
  static errorChannel = null;
167
- constructor() {
168
- }
169
242
  static config() {
170
- return Bot.config.log;
243
+ return Bot.config?.log;
171
244
  }
172
245
  /**
173
246
  * Initialize Discord logging channels and update Bot.log references
@@ -198,91 +271,28 @@ var BotLog = class _BotLog {
198
271
  }
199
272
  }
200
273
  }
201
- /*public static async initDiscordLogging(): Promise<void> {
202
- if (!Bot.client.isReady()) {
203
- Log.warn('Client not ready for Discord logging init');
204
- return;
205
- }
206
-
207
- if (Bot.config.log?.info.channelId) {
208
- try {
209
- const logCh = await Bot.client.channels.fetch(Bot.config.log.info.channelId) as TextChannel;
210
- if (logCh?.isTextBased()) {
211
- BotLog.logChannel = logCh;
212
- } else {
213
- Log.warn(`Log channel ${Bot.config.log.info.channelId} invalid`);
214
- }
215
- } catch (error) {
216
- Log.error(`Log channel fetch failed: ${error}`);
217
- }
218
- }
219
-
220
- if (Bot.config.log?.warn.channelId) {
221
- try {
222
- const errorCh = await Bot.client.channels.fetch(Bot.config.log.warn.channelId) as TextChannel;
223
- if (errorCh?.isTextBased()) {
224
- BotLog.warnChannel = errorCh;
225
- } else {
226
- Log.warn(`Warn channel ${Bot.config.log.warn.channelId} invalid`);
227
- }
228
- } catch (error) {
229
- Log.error(`Warn channel fetch failed: ${error}`);
230
- }
231
- }
232
-
233
- if (Bot.config.log?.error.channelId) {
234
- try {
235
- const errorCh = await Bot.client.channels.fetch(Bot.config.log.error.channelId) as TextChannel;
236
- if (errorCh?.isTextBased()) {
237
- BotLog.errorChannel = errorCh;
238
- } else {
239
- Log.warn(`Error channel ${Bot.config.log.error.channelId} invalid`);
240
- }
241
- } catch (error) {
242
- Log.error(`Error channel fetch failed: ${error}`);
243
- }
244
- }
245
-
246
- if (Bot.config.log?.debug.channelId) {
247
- try {
248
- const errorCh = await Bot.client.channels.fetch(Bot.config.log.debug.channelId) as TextChannel;
249
- if (errorCh?.isTextBased()) {
250
- BotLog.debugChannel = errorCh;
251
- } else {
252
- Log.warn(`Debug channel ${Bot.config.log.debug.channelId} invalid`);
253
- }
254
- } catch (error) {
255
- Log.error(`Debug channel fetch failed: ${error}`);
256
- }
257
- }
258
- }*/
259
274
  /**
260
275
  * Send content to specific Discord channel
261
276
  */
262
277
  static async _sendToChannel(channel, content, prefix = "info") {
263
278
  if (!channel) return;
264
- let msg;
265
279
  try {
266
- if (content instanceof EmbedBuilder) {
267
- const text = content.data.description ?? content.data.title;
268
- if (text) {
269
- Log.info(text);
270
- }
271
- msg = await channel.send({ embeds: [content] });
272
- } else if (SelectMenuManager.isSelectMenuList(content)) {
273
- msg = await channel.send({ components: SelectMenuManager.rows(content) });
274
- } else if (content instanceof ContainerBuilder) {
275
- msg = await channel.send({ components: [content], flags: MessageFlags2.IsComponentsV2 });
276
- } else if (content instanceof ActionRowBuilder2) {
277
- msg = await channel.send({ components: [content] });
278
- } else {
280
+ if (typeof content === "string") {
279
281
  const timestamp = `\`${(/* @__PURE__ */ new Date()).toISOString()}\``;
280
- msg = await channel.send(`[${timestamp}] [${prefix.toUpperCase()}] ${content}`);
282
+ return await channel.send(`[${timestamp}] [${prefix.toUpperCase()}] ${content}`);
281
283
  }
284
+ return await channel.send(SendableComponentBuilder.buildMessage(content));
282
285
  } catch (error) {
283
286
  Log.error(`Failed to send to Discord channel: ${error}`);
284
287
  }
285
- return msg;
288
+ }
289
+ /**
290
+ * Text printed in the console : the string itself, or the description / title of an embed
291
+ */
292
+ static _consoleText(content) {
293
+ if (typeof content === "string") return content;
294
+ if (content instanceof EmbedBuilder2) return content.data.description ?? content.data.title ?? null;
295
+ return null;
286
296
  }
287
297
  /**
288
298
  * Send INFO log - TEXT or EMBED ! Respecte config.log.info
@@ -290,8 +300,9 @@ var BotLog = class _BotLog {
290
300
  static async info(content) {
291
301
  const logConfig = Bot.config?.log;
292
302
  if (!logConfig || logConfig.info.console) {
293
- if (typeof content == "string") {
294
- Log.info(content);
303
+ const text = this._consoleText(content);
304
+ if (text) {
305
+ Log.info(text);
295
306
  }
296
307
  }
297
308
  if (logConfig?.info.discord && this.logChannel) {
@@ -302,10 +313,11 @@ var BotLog = class _BotLog {
302
313
  * Send ERROR log - TEXT or EMBED ! Respecte config.log.error
303
314
  */
304
315
  static async error(content) {
305
- const logConfig = Bot.config.log;
316
+ const logConfig = Bot.config?.log;
306
317
  if (!logConfig || logConfig.error.console) {
307
- if (typeof content == "string") {
308
- Log.error(content);
318
+ const text = this._consoleText(content);
319
+ if (text) {
320
+ Log.error(text);
309
321
  }
310
322
  }
311
323
  if (logConfig?.error.discord && this.errorChannel) {
@@ -316,10 +328,11 @@ var BotLog = class _BotLog {
316
328
  * Send WARNING log - TEXT or EMBED ! Respecte config.log.warn
317
329
  */
318
330
  static async warn(content) {
319
- const logConfig = Bot.config.log;
331
+ const logConfig = Bot.config?.log;
320
332
  if (!logConfig || logConfig?.warn.console) {
321
- if (typeof content == "string") {
322
- Log.warn(content);
333
+ const text = this._consoleText(content);
334
+ if (text) {
335
+ Log.warn(text);
323
336
  }
324
337
  }
325
338
  if (logConfig?.warn.discord && this.warnChannel) {
@@ -331,10 +344,11 @@ var BotLog = class _BotLog {
331
344
  */
332
345
  static async debug(content) {
333
346
  if (!BotEnv.dev) return;
334
- const logConfig = Bot.config.log;
347
+ const logConfig = Bot.config?.log;
335
348
  if (!logConfig || logConfig?.debug.console) {
336
- if (typeof content == "string") {
337
- Log.debug(content);
349
+ const text = this._consoleText(content);
350
+ if (text) {
351
+ Log.debug(text);
338
352
  }
339
353
  }
340
354
  if (logConfig?.debug.discord && this.debugChannel) {
@@ -345,7 +359,7 @@ var BotLog = class _BotLog {
345
359
 
346
360
  // src/manager/messages/EmbedManager.ts
347
361
  import {
348
- EmbedBuilder as EmbedBuilder2,
362
+ EmbedBuilder as EmbedBuilder3,
349
363
  MessageFlags as MessageFlags3
350
364
  } from "discord.js";
351
365
 
@@ -397,13 +411,13 @@ var EmbedManager = class {
397
411
  return Bot.client?.user?.displayAvatarURL({ forceStatic: false, size: 128 }) || "";
398
412
  }
399
413
  static get DEFAULT_COLOR() {
400
- return Bot.config.defaultSimpleColor || 6064856 /* default */;
414
+ return Bot.config?.defaultSimpleColor ?? 6064856 /* default */;
401
415
  }
402
416
  /**
403
417
  * Creates base embed - SAME SIMPLE API !
404
418
  */
405
419
  static create(color = null) {
406
- const embed = new EmbedBuilder2().setTimestamp(/* @__PURE__ */ new Date());
420
+ const embed = new EmbedBuilder3().setTimestamp(/* @__PURE__ */ new Date());
407
421
  const colorC = color ?? this.DEFAULT_COLOR;
408
422
  if (colorC !== "transparent" /* transparent */) {
409
423
  embed.setColor(colorC);
@@ -422,32 +436,32 @@ var EmbedManager = class {
422
436
  /**
423
437
  * Creates simple embed with just description
424
438
  */
425
- static simple(description, color = null) {
426
- return this.create(color).setDescription(description);
439
+ static simple(description2, color = null) {
440
+ return this.create(color).setDescription(description2);
427
441
  }
428
442
  /**
429
443
  * Creates error embed
430
444
  */
431
- static error(description) {
432
- return this.create(8912917 /* error */).setTitle("Something went Wrong").setDescription(description);
445
+ static error(description2) {
446
+ return this.create(8912917 /* error */).setTitle("Something went Wrong").setDescription(description2);
433
447
  }
434
448
  /**
435
449
  * Creates success embed
436
450
  */
437
- static success(description) {
438
- return this.create(25600 /* minecraft */).setTitle("Success").setDescription(description);
451
+ static success(description2) {
452
+ return this.create(25600 /* minecraft */).setTitle("Success").setDescription(description2);
439
453
  }
440
454
  /**
441
455
  * Creates a simple description embed
442
456
  */
443
- static description(description) {
444
- return this.create().setDescription(description).setFooter(null).setTimestamp(null);
457
+ static description(description2) {
458
+ return this.create().setDescription(description2).setFooter(null).setTimestamp(null);
445
459
  }
446
460
  /**
447
461
  * Creates debug embed
448
462
  */
449
- static debug(description) {
450
- return this.create(65280 /* green */).setTitle("Debug").setDescription(description);
463
+ static debug(description2) {
464
+ return this.create(65280 /* green */).setTitle("Debug").setDescription(description2);
451
465
  }
452
466
  /**
453
467
  * Defer ephemeral reply
@@ -477,13 +491,19 @@ var EmbedManager = class {
477
491
  };
478
492
  }
479
493
  /**
480
- * Transform embed into objet for interaction.editReply()
494
+ * Options to edit an existing message : message.edit()
481
495
  */
482
- static toInteractionEdit(embed) {
496
+ static toMessageUpdate(embed) {
483
497
  return {
484
498
  embeds: [embed]
485
499
  };
486
500
  }
501
+ /**
502
+ * Options for interaction.update() and interaction.editReply() (buttons, select menus, modals, deferred replies)
503
+ */
504
+ static toInteractionUpdate(embed) {
505
+ return this.toMessageUpdate(embed);
506
+ }
487
507
  /**
488
508
  * Transform embed into objet to send a message
489
509
  */
@@ -500,72 +520,6 @@ import {
500
520
  GuildMember
501
521
  } from "discord.js";
502
522
  import { Log as Log2 } from "@spatulox/utils";
503
-
504
- // src/manager/builder/SendableComponentBuilder.ts
505
- import {
506
- ActionRowBuilder as ActionRowBuilder3,
507
- EmbedBuilder as EmbedBuilder3,
508
- MessageFlags as MessageFlags4,
509
- ContainerBuilder as ContainerBuilder2
510
- } from "discord.js";
511
- import { BaseSelectMenuBuilder } from "@discordjs/builders";
512
- var SendableComponentBuilder = class {
513
- static isSendableComponent(thing) {
514
- return thing instanceof EmbedBuilder3 || thing instanceof ContainerBuilder2 || thing instanceof BaseSelectMenuBuilder || thing instanceof ActionRowBuilder3;
515
- }
516
- static build(base, content, components) {
517
- if (content) {
518
- base.content = content;
519
- }
520
- const comps = Array.isArray(components) ? components : [components].filter(Boolean);
521
- for (const comp of comps) {
522
- base.embeds = base.embeds || [];
523
- base.components = base.components || [];
524
- if (comp instanceof EmbedBuilder3) {
525
- base.embeds.push(comp);
526
- }
527
- if (SelectMenuManager.isSelectMenuList(comp)) {
528
- base.components.push(SelectMenuManager.row(comp));
529
- }
530
- if (comp instanceof ContainerBuilder2) {
531
- base.components.push(comp);
532
- }
533
- if (comp instanceof ActionRowBuilder3) {
534
- base.components.push(comp);
535
- }
536
- }
537
- return base;
538
- }
539
- static buildInteraction(content, component, ephemeral) {
540
- let base = {};
541
- this.build(base, content, component);
542
- if (ephemeral) {
543
- base.flags = [MessageFlags4.Ephemeral];
544
- }
545
- return base;
546
- }
547
- static buildMessage(contentOrComponent, component) {
548
- let base = {};
549
- if (typeof contentOrComponent === "string" && !component) {
550
- return this.build(base, contentOrComponent);
551
- }
552
- if (typeof contentOrComponent !== "string" && !component) {
553
- if (contentOrComponent instanceof ContainerBuilder2) {
554
- base.flags = [MessageFlags4.IsComponentsV2];
555
- }
556
- return this.build(base, null, contentOrComponent);
557
- }
558
- if (typeof contentOrComponent == "string" && component) {
559
- if (component instanceof ContainerBuilder2) {
560
- base.flags = [MessageFlags4.IsComponentsV2];
561
- }
562
- return this.build(base, contentOrComponent, component);
563
- }
564
- throw new Error("At least content or component need to be defined to build a message");
565
- }
566
- };
567
-
568
- // src/core/BotMessage.ts
569
523
  var BotMessage = class {
570
524
  static async send(channel, content, component) {
571
525
  try {
@@ -574,42 +528,34 @@ var BotMessage = class {
574
528
  return null;
575
529
  }
576
530
  if (typeof channel === "string") {
577
- const fetchedChannel = Bot.client.channels.cache.get(channel);
531
+ const fetchedChannel = Bot.client.channels.cache.get(channel) ?? await Bot.client.channels.fetch(channel).catch(() => null);
578
532
  if (!fetchedChannel?.isTextBased()) {
579
533
  Log2.warn(`Cannot send message : Invalid channel ID: ${channel}`);
580
534
  return null;
581
535
  }
582
536
  channel = fetchedChannel;
583
537
  }
584
- let messageCreate;
585
- if (typeof content !== "string" && !component) {
586
- if (SendableComponentBuilder.isSendableComponent(content)) {
587
- messageCreate = SendableComponentBuilder.buildMessage(content);
588
- } else {
589
- messageCreate = content;
590
- }
591
- } else {
592
- content = content;
593
- if (content && component) {
594
- messageCreate = SendableComponentBuilder.buildMessage(content, component);
595
- } else if (content) {
596
- messageCreate = SendableComponentBuilder.buildMessage(content);
597
- } else if (component) {
598
- messageCreate = SendableComponentBuilder.buildMessage(component);
599
- } else {
600
- throw new Error("Cannot send message : content and component cannot be null at the same time");
601
- }
602
- }
603
- try {
604
- return await channel.send(messageCreate);
605
- } catch (e) {
606
- throw e;
607
- }
538
+ return await channel.send(this.buildPayload(content, component));
608
539
  } catch (e) {
609
540
  Log2.error(`Cannot send message : ${e}`);
610
541
  return null;
611
542
  }
612
543
  }
544
+ static buildPayload(content, component) {
545
+ if (typeof content === "string") {
546
+ return component ? SendableComponentBuilder.buildMessage(content, component) : SendableComponentBuilder.buildMessage(content);
547
+ }
548
+ if (content === null || content === void 0) {
549
+ if (!component) {
550
+ throw new Error("Cannot send message : content and component cannot be null at the same time");
551
+ }
552
+ return SendableComponentBuilder.buildMessage(component);
553
+ }
554
+ if (SendableComponentBuilder.isSendableComponent(content) || Array.isArray(content)) {
555
+ return SendableComponentBuilder.buildMessage(content);
556
+ }
557
+ return content;
558
+ }
613
559
  static async sendDM(userOrId, content, component) {
614
560
  try {
615
561
  if (!userOrId) {
@@ -627,17 +573,7 @@ var BotMessage = class {
627
573
  }
628
574
  targetUser = fetchedUser;
629
575
  }
630
- let messageCreate;
631
- if (typeof content === "string" && component) {
632
- messageCreate = SendableComponentBuilder.buildMessage(content, component);
633
- } else if (typeof content === "string") {
634
- messageCreate = SendableComponentBuilder.buildMessage(content);
635
- } else if (SendableComponentBuilder.isSendableComponent(content)) {
636
- messageCreate = SendableComponentBuilder.buildMessage(content);
637
- } else {
638
- messageCreate = content;
639
- }
640
- return await targetUser.send(messageCreate);
576
+ return await targetUser.send(this.buildPayload(content, component));
641
577
  } catch (error) {
642
578
  Log2.error(`Cannot send DM to ${userOrId}: ${error}`);
643
579
  return null;
@@ -649,9 +585,9 @@ var BotMessage = class {
649
585
  static success(channel, message) {
650
586
  const embed = EmbedManager.success(message);
651
587
  if (channel instanceof User || channel instanceof GuildMember) {
652
- return this.sendDM(channel, message, embed);
588
+ return this.sendDM(channel, embed);
653
589
  }
654
- return this.send(channel, message, embed);
590
+ return this.send(channel, embed);
655
591
  }
656
592
  /**
657
593
  * Quick error message
@@ -659,62 +595,64 @@ var BotMessage = class {
659
595
  static error(channel, message) {
660
596
  const embed = EmbedManager.error(message);
661
597
  if (channel instanceof User || channel instanceof GuildMember) {
662
- return this.sendDM(channel, message, embed);
598
+ return this.sendDM(channel, embed);
663
599
  }
664
- return this.send(channel, message, embed);
600
+ return this.send(channel, embed);
665
601
  }
666
602
  };
667
603
 
668
604
  // src/core/BotInteraction.ts
605
+ import {
606
+ MessageFlags as MessageFlags4
607
+ } from "discord.js";
669
608
  var BotInteraction = class {
670
609
  /**
671
610
  * InteractionReplyOptions && InteractionUpdateOptions
672
611
  * The two have "content", "embeds" & "flags" field, so an internal cast is ok, unless discord/discordjs deprecate it
673
612
  */
674
613
  static buildReplyOptions(content, component, ephemeral) {
675
- return this._buildOptions(content, component, ephemeral);
614
+ return SendableComponentBuilder.buildInteraction(content, component, ephemeral);
676
615
  }
677
616
  static buildUpdateOptions(content, component) {
678
- return this._buildOptions(content, component, false);
617
+ return SendableComponentBuilder.buildInteraction(content, component, false);
679
618
  }
680
- static _buildOptions(content, component, ephemeral) {
681
- return SendableComponentBuilder.buildInteraction(content, component, ephemeral);
619
+ /**
620
+ * Normalize the (content, component, ephemeral) overloads :
621
+ * (string, ephemeral?) | (component, ephemeral?) | (string, component, ephemeral?)
622
+ */
623
+ static resolveArgs(content, component, ephemeral) {
624
+ if (typeof content === "string") {
625
+ if (typeof component === "boolean") {
626
+ return this.buildReplyOptions(content, null, component);
627
+ }
628
+ return this.buildReplyOptions(content, component ?? null, ephemeral);
629
+ }
630
+ return this.buildReplyOptions(null, content, typeof component === "boolean" ? component : ephemeral);
682
631
  }
683
- static async send(interaction, content, component = false, ephemeral = false) {
632
+ static async send(interaction, content, component, ephemeral = false) {
684
633
  if (!interaction.isRepliable()) return false;
685
- const options = this.buildReplyOptions(
686
- typeof content === "string" ? content : null,
687
- typeof content === "string" ? component : content,
688
- typeof content === "string" ? ephemeral : component
689
- );
634
+ const options = this.resolveArgs(content, component, ephemeral);
690
635
  if (!interaction.deferred && !interaction.replied) {
691
636
  return await interaction.reply(options);
692
637
  } else {
693
638
  return await interaction.followUp(options);
694
639
  }
695
640
  }
696
- static async reply(interaction, content, component = false, ephemeral = false) {
641
+ static async reply(interaction, content, component, ephemeral = false) {
697
642
  if (!interaction.isRepliable()) return false;
698
- const options = this.buildReplyOptions(
699
- typeof content === "string" ? content : "",
700
- typeof content === "string" ? component : content,
701
- typeof content === "string" ? ephemeral : component
702
- );
703
- return await interaction.reply(options);
704
- }
705
- static async followUp(interaction, content, component = false, ephemeral = false) {
706
- if (!interaction.isMessageComponent()) return false;
707
- const options = this.buildReplyOptions(
708
- typeof content === "string" ? content : "",
709
- typeof content === "string" ? component : content,
710
- typeof content === "string" ? ephemeral : component
711
- );
712
- return await interaction.followUp(options);
643
+ return await interaction.reply(this.resolveArgs(content, component, ephemeral));
644
+ }
645
+ static async followUp(interaction, content, component, ephemeral = false) {
646
+ if (!interaction.isRepliable()) return false;
647
+ return await interaction.followUp(this.resolveArgs(content, component, ephemeral));
713
648
  }
714
- static async defer(interaction) {
649
+ /**
650
+ * @param ephemeral Only used by commands : components and modals defer the message they come from
651
+ */
652
+ static async defer(interaction, ephemeral = false) {
715
653
  if (interaction.isChatInputCommand() || interaction.isContextMenuCommand()) {
716
654
  if (!interaction.deferred && !interaction.replied) {
717
- return await interaction.deferReply();
655
+ return await interaction.deferReply(ephemeral ? { flags: MessageFlags4.Ephemeral } : void 0);
718
656
  }
719
657
  return;
720
658
  }
@@ -726,81 +664,37 @@ var BotInteraction = class {
726
664
  }
727
665
  static async update(interaction, content, component) {
728
666
  const options = this.buildUpdateOptions(
729
- typeof content === "string" ? content : "",
730
- typeof content === "string" ? component : content
667
+ typeof content === "string" ? content : null,
668
+ typeof content === "string" ? component ?? null : content
731
669
  );
670
+ if (!interaction.isRepliable()) return false;
671
+ if (interaction.deferred || interaction.replied) {
672
+ return await interaction.editReply(options);
673
+ }
732
674
  if (interaction.isMessageComponent()) {
733
675
  return await interaction.update(options);
734
676
  }
735
- if (!interaction.isCommand()) return false;
736
- if (interaction.deferred || interaction.replied) {
737
- return await interaction.editReply(options);
677
+ if (interaction.isModalSubmit() && interaction.isFromMessage()) {
678
+ return await interaction.update(options);
738
679
  }
739
680
  return false;
740
681
  }
741
682
  };
742
683
 
743
684
  // package.json
744
- var package_default = {
745
- name: "@spatulox/simplediscordbot",
746
- version: "3.1.2",
747
- author: "Spatulox",
748
- description: "Simple discord bot framework to set up a bot under 30 secondes",
749
- exports: {
750
- types: "./dist/index.d.ts",
751
- import: "./dist/index.js",
752
- require: "./dist/index.js"
753
- },
754
- types: "./dist/index.d.ts",
755
- scripts: {
756
- "type-check": "tsc --noEmit",
757
- build: "npm run type-check && rm -rf ./dist/ && tsup",
758
- dev: "npm run type-check && tsx watch src/test/index.ts",
759
- patch: "npm run build && npm version patch",
760
- minor: "npm run build && npm version minor",
761
- major: "npm run build && npm version major",
762
- "pub:patch": "npm run patch && npm publish --access public",
763
- "pub:minor": "npm run minor && npm publish --access public",
764
- "pub:major": "npm run major && npm publish --access public"
765
- },
766
- license: "MIT",
767
- dependencies: {
768
- "@spatulox/discord-interaction-manager": "^2.4.0",
769
- "@spatulox/utils": "^0.2.0"
770
- },
771
- peerDependencies: {
772
- "discord.js": "^14.26.0"
773
- },
774
- devDependencies: {
775
- "@types/node": "^22.14.0",
776
- "@types/node-schedule": "^2.1.7",
777
- "discord.js": "^14.26.0",
778
- dotenv: "^17.2.4",
779
- tsup: "^8.5.1",
780
- tsx: "^4.20.3",
781
- typescript: "^5.9.3"
782
- },
783
- keywords: [
784
- "discord",
785
- "framework",
786
- "bot",
787
- "client",
788
- "discordjs",
789
- "discord.js",
790
- "node"
791
- ],
792
- bugs: {
793
- url: "https://github.com/spatulox-discord/SimpleDiscordBot/issues"
794
- }
795
- };
685
+ var name = "@spatulox/simplediscordbot";
686
+ var version = "4.0.0";
687
+ var author = "Spatulox";
688
+ var description = "Simple discord bot framework to set up a bot under 30 secondes";
689
+ var license = "MIT";
796
690
 
797
691
  // src/SimpleDiscordBotInfo.ts
798
692
  var SimpleDiscordBotInfo = {
799
- name: package_default.name,
800
- version: package_default.version,
801
- author: package_default.author,
802
- description: package_default.description,
803
- license: package_default.license
693
+ name,
694
+ version,
695
+ author,
696
+ description,
697
+ license
804
698
  };
805
699
 
806
700
  // src/core/Bot.ts
@@ -811,8 +705,9 @@ var Bot = class _Bot {
811
705
  static interaction = BotInteraction;
812
706
  // Instance properties
813
707
  static _client;
814
- static criticConfig;
708
+ static token;
815
709
  static _config;
710
+ static randomActivityInterval = null;
816
711
  get config() {
817
712
  return _Bot._config;
818
713
  }
@@ -825,34 +720,41 @@ var Bot = class _Bot {
825
720
  static get config() {
826
721
  return _Bot._config;
827
722
  }
723
+ /**
724
+ * Resolves once the login is done (true) or has definitively failed (false)
725
+ */
726
+ started;
828
727
  constructor(client, config = {}) {
829
728
  Log3.info("----------------------------------------------------");
830
729
  Log3.info("Starting Bot");
831
- _Bot.criticConfig = { dev: BotEnv.dev, token: BotEnv.token };
730
+ _Bot.token = BotEnv.token;
832
731
  _Bot._config = config;
833
732
  _Bot._client = client;
834
- (async () => {
835
- Log3.info(`Using discord.js version: ${version}`);
733
+ _Bot._client.once(Events.ClientReady, async () => {
734
+ if (_Bot._client.user) {
735
+ await _Bot.log.initDiscordLogging();
736
+ Log3.info(`Connected on ${_Bot._client.guilds.cache.size} servers as ${_Bot._client.user.tag}`);
737
+ _Bot.log.info(EmbedManager.description("Bot Started"));
738
+ }
739
+ });
740
+ this.started = (async () => {
741
+ Log3.info(`Using discord.js version: ${version2}`);
836
742
  Log3.info(`Using simplediscordbot version: ${SimpleDiscordBotInfo.version}`);
837
743
  Log3.info("Trying to connect to Discord Servers");
838
744
  await InternetChecker.checkConnection(3);
839
- await this.login();
840
- })();
745
+ return await this.login();
746
+ })().catch((error) => {
747
+ Log3.error(`Failed to start the bot: ${error}`);
748
+ return false;
749
+ });
841
750
  }
842
751
  async login(maxTries = 3) {
843
- let success = false;
752
+ if (_Bot._client.isReady()) return true;
844
753
  let tries = 0;
845
- while (!success && tries < maxTries) {
754
+ while (tries < maxTries) {
846
755
  try {
847
- await _Bot._client.login(_Bot.criticConfig.token);
848
- success = true;
849
- _Bot._client.on(Events.ClientReady, async () => {
850
- if (_Bot._client.user) {
851
- await _Bot.log.initDiscordLogging();
852
- Log3.info(`Connected on ${_Bot._client.guilds.cache.size} servers as ${_Bot._client.user.tag}`);
853
- _Bot.log.info(EmbedManager.description("Bot Started"));
854
- }
855
- });
756
+ await _Bot._client.login(_Bot.token);
757
+ return true;
856
758
  } catch (error) {
857
759
  Log3.error(`Connection error : ${error}. Trying again...`);
858
760
  tries++;
@@ -861,11 +763,8 @@ var Bot = class _Bot {
861
763
  );
862
764
  }
863
765
  }
864
- if (!success) {
865
- Log3.error("Impossible to connect the bot after 3 attempts");
866
- return false;
867
- }
868
- return true;
766
+ Log3.error(`Impossible to connect the bot after ${maxTries} attempts`);
767
+ return false;
869
768
  }
870
769
  static setActivity(message, type) {
871
770
  if (_Bot._client.user) {
@@ -878,6 +777,7 @@ var Bot = class _Bot {
878
777
  Log3.error("Bot.randomActivity = [{}] is empty");
879
778
  return;
880
779
  }
780
+ _Bot.stopRandomActivity();
881
781
  const pickRandom = () => {
882
782
  const random = randomActivity[Math.floor(Math.random() * randomActivity.length)];
883
783
  _Bot.setActivity(random.message, random.type);
@@ -889,12 +789,19 @@ var Bot = class _Bot {
889
789
  return;
890
790
  }
891
791
  pickRandom();
892
- setInterval(async () => {
893
- pickRandom();
894
- }, intervalMs);
895
- Log3.info(`Random activity started (every ${Math.round(intervalMs / 6e4)}min)`);
792
+ _Bot.randomActivityInterval = setInterval(pickRandom, intervalMs);
793
+ Log3.info(`Random activity started (every ${intervalMs >= 6e4 ? `${Math.round(intervalMs / 6e4)}min` : `${Math.round(intervalMs / 1e3)}s`})`);
896
794
  return;
897
795
  }
796
+ /**
797
+ * Stop the rotation started by setRandomActivity(), the current activity is kept
798
+ */
799
+ static stopRandomActivity() {
800
+ if (_Bot.randomActivityInterval) {
801
+ clearInterval(_Bot.randomActivityInterval);
802
+ _Bot.randomActivityInterval = null;
803
+ }
804
+ }
898
805
  };
899
806
 
900
807
  // src/index.ts
@@ -911,15 +818,16 @@ import {
911
818
  import { readFile } from "fs/promises";
912
819
  import { resolve } from "path";
913
820
  var WebhookManager = class {
914
- constructor(client, name, avatarPathOrUrl) {
821
+ constructor(client, name2, avatarPathOrUrl) {
915
822
  this.client = client;
916
- this.name = name;
823
+ this.name = name2;
917
824
  this.avatarPathOrUrl = avatarPathOrUrl;
918
825
  }
919
826
  client;
920
827
  name;
921
828
  avatarPathOrUrl;
922
- webhook = null;
829
+ /** One webhook per channel id (the parent channel id for threads) */
830
+ webhooks = /* @__PURE__ */ new Map();
923
831
  async getAvatar() {
924
832
  if (!this.avatarPathOrUrl) return null;
925
833
  if (this.avatarPathOrUrl.startsWith("http://") || this.avatarPathOrUrl.startsWith("https://")) {
@@ -947,42 +855,46 @@ var WebhookManager = class {
947
855
  return channel;
948
856
  }
949
857
  /**
950
- * Get or create webhook (lazy initialization)
858
+ * Channel owning the webhook : the parent channel when targeting a thread
859
+ */
860
+ getWebhookChannel(channel) {
861
+ if (!(channel instanceof ThreadChannel2)) return channel;
862
+ const parent = channel.parent;
863
+ if (!parent || !(parent instanceof BaseGuildTextChannel) && !(parent instanceof ThreadOnlyChannel)) {
864
+ throw new Error("Targeted channel parent is not a BaseGuildTextChannel or ThreadOnlyChannel");
865
+ }
866
+ return parent;
867
+ }
868
+ /**
869
+ * Get or create webhook (lazy initialization, cached per channel)
951
870
  * Create the webhook in the parent channel if it's in a thread
952
871
  */
953
- async getWebhook(channelId) {
954
- if (this.webhook) return this.webhook;
872
+ async getWebhook(channel) {
955
873
  try {
956
- const textThreadChannel = await this.getChannel(channelId);
957
- let textChannel;
958
- if (textThreadChannel instanceof ThreadChannel2) {
959
- const parent = textThreadChannel.parent;
960
- if (!parent || !(parent instanceof BaseGuildTextChannel) && !(parent instanceof ThreadOnlyChannel)) {
961
- throw new Error("Targeted channel parent is not a BaseGuildTextChannel or ThreadOnlyChannel");
962
- }
963
- textChannel = parent;
964
- } else {
965
- textChannel = textThreadChannel;
966
- }
874
+ const textChannel = this.getWebhookChannel(channel);
875
+ const cached = this.webhooks.get(textChannel.id);
876
+ if (cached) return cached;
967
877
  const webhooks = await textChannel.fetchWebhooks();
968
- this.webhook = webhooks.find(
878
+ const webhook = webhooks.find(
969
879
  (h) => h.name === this.name && h.owner?.id === this.client.user?.id
970
880
  ) ?? await textChannel.createWebhook({
971
881
  name: this.name,
972
882
  avatar: await this.getAvatar(),
973
883
  reason: "Auto-created by WebhookManager"
974
884
  });
975
- Bot.log.debug(`Webhook ${this.webhook.id} ready for channel ${channelId}`);
976
- return this.webhook;
885
+ this.webhooks.set(textChannel.id, webhook);
886
+ Bot.log.debug(`Webhook ${webhook.id} ready for channel ${channel.id}`);
887
+ return webhook;
977
888
  } catch (error) {
978
- Bot.log.error(`Failed to setup webhook for ${channelId}: ${error}`);
889
+ Bot.log.error(`Failed to setup webhook for ${channel.id}: ${error}`);
979
890
  throw error;
980
891
  }
981
892
  }
982
893
  async send(channelId, content) {
983
- const webhook = await this.getWebhook(channelId);
894
+ const channel = await this.getChannel(channelId);
895
+ const webhook = await this.getWebhook(channel);
984
896
  let options = {};
985
- if (SendableComponentBuilder.isSendableComponent(content)) {
897
+ if (SendableComponentBuilder.isSendableComponent(content) || Array.isArray(content)) {
986
898
  options = SendableComponentBuilder.buildMessage(content);
987
899
  } else if (typeof content === "string") {
988
900
  options.content = content;
@@ -991,8 +903,7 @@ var WebhookManager = class {
991
903
  } else {
992
904
  options.content = String(content);
993
905
  }
994
- const channelType = await this.getChannel(channelId);
995
- if (channelType instanceof ThreadChannel2) {
906
+ if (channel instanceof ThreadChannel2) {
996
907
  options.threadId = channelId;
997
908
  }
998
909
  try {
@@ -1018,10 +929,13 @@ var WebhookManager = class {
1018
929
  * Delete webhook
1019
930
  */
1020
931
  async delete(channelId, reason) {
1021
- if (!this.webhook) return;
932
+ const channel = await this.getChannel(channelId);
933
+ const webhookChannelId = this.getWebhookChannel(channel).id;
934
+ const webhook = this.webhooks.get(webhookChannelId);
935
+ if (!webhook) return;
1022
936
  try {
1023
- await this.webhook.delete(reason ?? "Deleted by WebhookManager");
1024
- Bot.log.info(`Webhook ${this.webhook.id} deleted from ${channelId}`);
937
+ await webhook.delete(reason ?? "Deleted by WebhookManager");
938
+ Bot.log.info(`Webhook ${webhook.id} deleted from ${channelId}`);
1025
939
  } catch (error) {
1026
940
  if (error.message.includes("Unknown Webhook")) {
1027
941
  Bot.log.warn(`Webhook already deleted from ${channelId}`);
@@ -1029,244 +943,37 @@ var WebhookManager = class {
1029
943
  Bot.log.error(`Failed to delete webhook from ${channelId}: ${error}`);
1030
944
  }
1031
945
  } finally {
1032
- this.webhook = null;
946
+ this.webhooks.delete(webhookChannelId);
1033
947
  }
1034
948
  }
1035
949
  };
1036
950
 
1037
951
  // src/manager/messages/ReactionManager.ts
1038
- import { Log as Log7 } from "@spatulox/utils";
1039
-
1040
- // src/manager/guild/ChannelManager/GuildTextChannelManager.ts
1041
- import { TextChannel as TextChannel4, ChannelType as ChannelType2 } from "discord.js";
1042
-
1043
- // src/manager/guild/ChannelManager/GuildChannelManager.ts
1044
- import { Log as Log5 } from "@spatulox/utils";
1045
-
1046
- // src/manager/guild/ChannelManager/GuildMessageManager.ts
952
+ import {
953
+ parseEmoji
954
+ } from "discord.js";
1047
955
  import { Log as Log4 } from "@spatulox/utils";
1048
- var GuildMessageManager = class {
1049
- /**
1050
- * Impl
1051
- */
1052
- static async send(channelId, content_or_component_or_options) {
1053
- try {
1054
- const channel = await GuildTextChannelManager.find(channelId);
1055
- if (!channel) {
1056
- Log4.error(`Channel ${channelId} not found in guild`);
1057
- return null;
1058
- }
1059
- let payload;
1060
- if (typeof content_or_component_or_options === "string") {
1061
- payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1062
- } else if (SendableComponentBuilder.isSendableComponent(content_or_component_or_options) || Array.isArray(content_or_component_or_options)) {
1063
- payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1064
- } else {
1065
- payload = content_or_component_or_options;
1066
- }
1067
- return await channel.send(payload);
1068
- } catch (error) {
1069
- Log4.error(`Failed to send message to ${channelId}: ${error}`);
1070
- throw error;
1071
- }
1072
- }
1073
- /**
1074
- * Delete message
1075
- */
1076
- static async delete(channelId, messageId) {
1077
- try {
1078
- const channel = await GuildTextChannelManager.find(channelId);
1079
- if (!channel) {
1080
- Log4.error(`Channel ${channelId} not found`);
1081
- return false;
1082
- }
1083
- const message = await channel.messages.fetch(messageId);
1084
- await message.delete();
1085
- Log4.info(`Deleted message ${messageId} from ${channelId}`);
1086
- return true;
1087
- } catch (error) {
1088
- Log4.error(`Failed to delete message ${messageId} from ${channelId}: ${error}`);
1089
- return false;
1090
- }
1091
- }
1092
- /**
1093
- * Fetch messages (last X messages, default 10)
1094
- */
1095
- static async fetch(channelId, limit = 10) {
1096
- try {
1097
- const channel = await GuildTextChannelManager.find(channelId);
1098
- if (!channel) {
1099
- Log4.error(`Channel ${channelId} not found`);
1100
- return [];
1101
- }
1102
- const messages = await channel.messages.fetch({ limit });
1103
- Log4.info(`Fetched ${messages.size} messages from ${channelId}`);
1104
- return Array.from(messages.values());
1105
- } catch (error) {
1106
- Log4.error(`Failed to fetch messages from ${channelId}: ${error}`);
1107
- return [];
1108
- }
1109
- }
1110
- /**
1111
- * Fetch single message
1112
- */
1113
- static async fetchOne(channelId, messageId) {
1114
- try {
1115
- const channel = await GuildTextChannelManager.find(channelId);
1116
- if (!channel) {
1117
- Log4.error(`Channel ${channelId} not found`);
1118
- return null;
1119
- }
1120
- const message = await channel.messages.fetch(messageId);
1121
- return message;
1122
- } catch (error) {
1123
- Log4.error(`Failed to fetch message ${messageId} from ${channelId}: ${error}`);
1124
- return null;
1125
- }
1126
- }
1127
- };
1128
-
1129
- // src/manager/guild/ChannelManager/GuildChannelManager.ts
1130
- var GuildChannelManager = class _GuildChannelManager {
1131
- static message = GuildMessageManager;
1132
- /**
1133
- * Recherche un channel par ID dans une guild spécifique
1134
- */
1135
- static async findInGuild(guildId, channelId) {
1136
- try {
1137
- const guild = Bot.client.guilds.cache.get(guildId);
1138
- if (!guild) {
1139
- Log5.warn(`Guild ${guildId} not found`);
1140
- return null;
1141
- }
1142
- const channel = await guild.channels.fetch(channelId);
1143
- return channel ?? null;
1144
- } catch (error) {
1145
- Log5.error(`Failed to find channel ${channelId} in guild ${guildId}: ${error}`);
1146
- return null;
1147
- }
1148
- }
1149
- static async find(channelId) {
1150
- try {
1151
- const cached = Bot.client.channels.cache.get(channelId);
1152
- if (cached && !cached.isDMBased()) return cached;
1153
- const channel = await Bot.client.channels.fetch(channelId);
1154
- if (channel && !channel.isDMBased()) return channel;
1155
- Log5.warn(`Channel ${channelId} not found in any guild`);
1156
- return null;
1157
- } catch (error) {
1158
- Log5.error(`Failed to find channel ${channelId}: ${error}`);
1159
- return null;
1160
- }
1161
- }
1162
- static findAll(guildId) {
1163
- try {
1164
- const guild = Bot.client.guilds.cache.get(guildId);
1165
- if (!guild) {
1166
- Log5.warn(`Guild ${guildId} not found`);
1167
- return [];
1168
- }
1169
- return Array.from(guild.channels.cache.values());
1170
- } catch (error) {
1171
- Log5.error(`Failed to find channel ${guildId}: ${error}`);
1172
- return [];
1173
- }
1174
- }
956
+ var ReactionManager = class {
1175
957
  /**
1176
- * Recherche channels par nom (insensible à la casse)
958
+ * Any text based channel : guild channels, threads and DMs
1177
959
  */
1178
- static findByName(guildId, name) {
1179
- try {
1180
- const guild = Bot.client.guilds.cache.get(guildId);
1181
- if (!guild) {
1182
- Log5.warn(`Guild ${guildId} not found`);
1183
- return [];
1184
- }
1185
- return Array.from(guild.channels.cache.values()).filter(
1186
- (channel) => channel.name.toLowerCase().includes(name.toLowerCase())
1187
- );
1188
- } catch (error) {
1189
- Log5.error(`Failed to find channel ${guildId}: ${error}`);
1190
- return [];
1191
- }
1192
- }
1193
- static async _create(guildId, options) {
1194
- try {
1195
- const guild = Bot.client.guilds.cache.get(guildId);
1196
- if (!guild) {
1197
- throw new Error(`Guild ${guildId} not found`);
1198
- }
1199
- const channel = await guild.channels.create(options);
1200
- Log5.info(`Created channel ${channel.name} (${channel.id}) in guild ${guildId}`);
1201
- return channel;
1202
- } catch (error) {
1203
- Log5.error(`Failed to create channel in guild ${guildId}: ${error}`);
1204
- throw error;
1205
- }
1206
- }
1207
- static async delete(channelId) {
1208
- try {
1209
- const channel = await _GuildChannelManager.find(channelId);
1210
- if (!channel) {
1211
- throw new Error(`Channel ${channelId} not found`);
1212
- }
1213
- await channel.delete();
1214
- Log5.info(`Deleted channel ${channelId}`);
1215
- return true;
1216
- } catch (error) {
1217
- Log5.error(`Failed to delete channel ${channelId}: ${error}`);
1218
- throw error;
1219
- }
1220
- }
1221
- };
1222
-
1223
- // src/manager/guild/ChannelManager/GuildTextChannelManager.ts
1224
- import { Log as Log6 } from "@spatulox/utils";
1225
- var GuildTextChannelManager = class extends GuildChannelManager {
1226
- static async findInGuild(guildId, channelId) {
1227
- const channel = await super.findInGuild(guildId, channelId);
1228
- return channel?.isTextBased() ? channel : null;
1229
- }
1230
- static async find(channelId) {
1231
- const channel = await super.find(channelId);
1232
- return channel?.isTextBased() ? channel : null;
1233
- }
1234
- static findAll(guildId) {
1235
- const guild = Bot.client.guilds.cache.get(guildId);
1236
- if (!guild) {
1237
- Log6.warn(`Guild ${guildId} not found`);
1238
- return [];
960
+ static async fetchMessage(channelId, messageId) {
961
+ const channel = Bot.client.channels.cache.get(channelId) ?? await Bot.client.channels.fetch(channelId);
962
+ if (!channel?.isTextBased()) {
963
+ throw new Error(`Channel ${channelId} not found or not text based`);
1239
964
  }
1240
- return Array.from(guild.channels.cache.values()).filter((c) => c instanceof TextChannel4);
1241
- }
1242
- static async create(guildId, name, options) {
1243
- return await super._create(guildId, {
1244
- name,
1245
- type: ChannelType2.GuildText,
1246
- ...options
1247
- });
965
+ return await channel.messages.fetch(messageId);
1248
966
  }
1249
- };
1250
-
1251
- // src/manager/messages/ReactionManager.ts
1252
- var ReactionManager = class {
1253
967
  /**
1254
968
  * Add a reaction to a message
1255
969
  */
1256
970
  static async add(channelId, messageId, emoji) {
1257
971
  try {
1258
- const channel = await GuildTextChannelManager.find(channelId);
1259
- if (!channel) {
1260
- throw new Error(`Channel ${channelId} not found`);
1261
- }
1262
- if (!channel.isTextBased()) {
1263
- throw new Error(`Channel ${channelId} is not text based`);
1264
- }
1265
- const message = await channel.messages.fetch(messageId);
972
+ const message = await this.fetchMessage(channelId, messageId);
1266
973
  await message.react(emoji);
1267
- Log7.info(`Added reaction ${emoji} to message ${messageId}`);
974
+ Log4.info(`Added reaction ${emoji} to message ${messageId}`);
1268
975
  } catch (error) {
1269
- Log7.error(`Failed to add reaction to ${messageId}: ${error}`);
976
+ Log4.error(`Failed to add reaction to ${messageId}: ${error}`);
1270
977
  throw error;
1271
978
  }
1272
979
  }
@@ -1275,20 +982,16 @@ var ReactionManager = class {
1275
982
  */
1276
983
  static async remove(channelId, messageId, emoji, userId) {
1277
984
  try {
1278
- const channel = await GuildTextChannelManager.find(channelId);
1279
- if (!channel) {
1280
- throw new Error(`Channel ${channelId} not found`);
1281
- }
1282
- const message = await channel.messages.fetch(messageId);
1283
- const reaction = message.reactions.resolve(emoji);
985
+ const message = await this.fetchMessage(channelId, messageId);
986
+ const reaction = message.reactions.resolve(parseEmoji(emoji)?.id ?? emoji);
1284
987
  if (!reaction) {
1285
988
  throw new Error(`Reaction ${emoji} not found on message ${messageId}`);
1286
989
  }
1287
990
  const user = await Bot.client.users.fetch(userId);
1288
991
  await reaction.users.remove(user);
1289
- Log7.info(`Removed reaction ${emoji} from user ${userId} on message ${messageId}`);
992
+ Log4.info(`Removed reaction ${emoji} from user ${userId} on message ${messageId}`);
1290
993
  } catch (error) {
1291
- Log7.error(`Failed to remove reaction from ${messageId}: ${error}`);
994
+ Log4.error(`Failed to remove reaction from ${messageId}: ${error}`);
1292
995
  throw error;
1293
996
  }
1294
997
  }
@@ -1297,11 +1000,7 @@ var ReactionManager = class {
1297
1000
  */
1298
1001
  static async getAll(channelId, messageId) {
1299
1002
  try {
1300
- const channel = await GuildTextChannelManager.find(channelId);
1301
- if (!channel) {
1302
- throw new Error(`Channel ${channelId} not found`);
1303
- }
1304
- const message = await channel.messages.fetch(messageId);
1003
+ const message = await this.fetchMessage(channelId, messageId);
1305
1004
  const reactions = message.reactions.cache;
1306
1005
  const reactionList = [];
1307
1006
  for (const reaction of reactions.values()) {
@@ -1312,10 +1011,10 @@ var ReactionManager = class {
1312
1011
  users: Array.from(users.values())
1313
1012
  });
1314
1013
  }
1315
- Log7.info(`Fetched ${reactionList.length} reactions for message ${messageId}`);
1014
+ Log4.info(`Fetched ${reactionList.length} reactions for message ${messageId}`);
1316
1015
  return reactionList;
1317
1016
  } catch (error) {
1318
- Log7.error(`Failed to fetch reactions for ${messageId}: ${error}`);
1017
+ Log4.error(`Failed to fetch reactions for ${messageId}: ${error}`);
1319
1018
  throw error;
1320
1019
  }
1321
1020
  }
@@ -1324,15 +1023,11 @@ var ReactionManager = class {
1324
1023
  */
1325
1024
  static async clear(channelId, messageId) {
1326
1025
  try {
1327
- const channel = await GuildTextChannelManager.find(channelId);
1328
- if (!channel) {
1329
- throw new Error(`Channel ${channelId} not found`);
1330
- }
1331
- const message = await channel.messages.fetch(messageId);
1026
+ const message = await this.fetchMessage(channelId, messageId);
1332
1027
  await message.reactions.removeAll();
1333
- Log7.info(`Cleared all reactions from message ${messageId}`);
1028
+ Log4.info(`Cleared all reactions from message ${messageId}`);
1334
1029
  } catch (error) {
1335
- Log7.error(`Failed to clear reactions from ${messageId}: ${error}`);
1030
+ Log4.error(`Failed to clear reactions from ${messageId}: ${error}`);
1336
1031
  throw error;
1337
1032
  }
1338
1033
  }
@@ -1344,11 +1039,11 @@ import { Log as Log16 } from "@spatulox/utils";
1344
1039
  import { Time as Time2 } from "@spatulox/utils";
1345
1040
 
1346
1041
  // src/manager/guild/GuildUserManager.ts
1347
- import { Log as Log9 } from "@spatulox/utils";
1042
+ import { Log as Log6 } from "@spatulox/utils";
1348
1043
 
1349
1044
  // src/manager/direct/BasicUserManager.ts
1350
1045
  import { GuildMember as GuildMember2 } from "discord.js";
1351
- import { Log as Log8 } from "@spatulox/utils";
1046
+ import { Log as Log5 } from "@spatulox/utils";
1352
1047
  var BasicUserManager = class {
1353
1048
  /**
1354
1049
  * Find member in specific guild
@@ -1364,7 +1059,7 @@ var BasicUserManager = class {
1364
1059
  const cached = targetGuild.members.cache.get(memberId);
1365
1060
  if (cached) return cached;
1366
1061
  const member = await targetGuild.members.fetch(memberId).catch(() => null);
1367
- if (!member) Log8.error(`UserManager: Member ${memberId} not found in guild ${targetGuild.id}`);
1062
+ if (!member) Log5.error(`UserManager: Member ${memberId} not found in guild ${targetGuild.id}`);
1368
1063
  return member;
1369
1064
  }
1370
1065
  /**
@@ -1400,26 +1095,27 @@ var BasicUserManager = class {
1400
1095
  );
1401
1096
  } else if (typeof content_or_component_or_options === "string") {
1402
1097
  payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1403
- } else if (SendableComponentBuilder.isSendableComponent(content_or_component_or_options)) {
1098
+ } else if (SendableComponentBuilder.isSendableComponent(content_or_component_or_options) || Array.isArray(content_or_component_or_options)) {
1404
1099
  payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1405
1100
  } else {
1406
1101
  payload = content_or_component_or_options;
1407
1102
  }
1408
1103
  const message = await dmChannel.send(payload);
1409
1104
  if (user instanceof GuildMember2) {
1410
- Log8.info(`Sent DM to ${user.id} (${user.user.username}): "${(payload.content || "Embed/Component").substring(0, 50)}..."`);
1105
+ Log5.info(`Sent DM to ${user.id} (${user.user.username}): "${(payload.content || "Embed/Component").substring(0, 50)}..."`);
1411
1106
  } else {
1412
- Log8.info(`Sent DM to ${user.id} (${user.username}): "${(payload.content || "Embed/Component").substring(0, 50)}..."`);
1107
+ Log5.info(`Sent DM to ${user.id} (${user.username}): "${(payload.content || "Embed/Component").substring(0, 50)}..."`);
1413
1108
  }
1414
1109
  return message;
1415
1110
  } catch (error) {
1416
- Log8.error(`Failed to send DM to ${user_id_or_user}: ${error}`);
1111
+ Log5.error(`Failed to send DM to ${user_id_or_user}: ${error}`);
1417
1112
  throw new Error(`Cannot send DM to ${user_id_or_user}`);
1418
1113
  }
1419
1114
  }
1420
1115
  };
1421
1116
 
1422
1117
  // src/manager/guild/GuildUserManager.ts
1118
+ import { RESTJSONErrorCodes } from "discord.js";
1423
1119
  import { setTimeout as setTimeout2 } from "timers/promises";
1424
1120
  var MAX_NICKNAME_LENGTH = 32;
1425
1121
  var GuildUserManager = class extends BasicUserManager {
@@ -1431,15 +1127,18 @@ var GuildUserManager = class extends BasicUserManager {
1431
1127
  try {
1432
1128
  const oldName = member.displayName;
1433
1129
  await member.setNickname(nickname.trim());
1434
- Log9.info(`Renaming user: ${oldName} \u2192 ${nickname.trim()}`);
1130
+ Log6.info(`Renaming user: ${oldName} \u2192 ${nickname.trim()}`);
1435
1131
  await setTimeout2(1500);
1436
1132
  return true;
1437
1133
  } catch (error) {
1438
- console.error(`Attempt ${attempts + 1} failed when renaming ${member.displayName} into ${nickname.trim()}:`, error);
1134
+ Log6.error(`Attempt ${attempts + 1} failed when renaming ${member.displayName} into ${nickname.trim()}: ${error}`);
1135
+ if (error?.code === RESTJSONErrorCodes.MissingPermissions || error?.code === RESTJSONErrorCodes.MissingAccess) {
1136
+ break;
1137
+ }
1439
1138
  await setTimeout2(1e3);
1440
1139
  }
1441
1140
  }
1442
- Bot.log.info(EmbedManager.error(`Failed to rename ${member.displayName} to ${nickname.trim()} after ${maxAttempts} attempts.`));
1141
+ Bot.log.error(EmbedManager.error(`Failed to rename ${member.displayName} to ${nickname.trim()}.`));
1443
1142
  return false;
1444
1143
  }
1445
1144
  /**
@@ -1449,13 +1148,13 @@ var GuildUserManager = class extends BasicUserManager {
1449
1148
  try {
1450
1149
  const guild = await GuildManager.find(guildId);
1451
1150
  if (!guild) {
1452
- Log9.warn(`Guild ${guildId} not found`);
1151
+ Log6.warn(`Guild ${guildId} not found`);
1453
1152
  return false;
1454
1153
  }
1455
1154
  const ban = await guild.bans.fetch(userId);
1456
1155
  return !!ban;
1457
1156
  } catch (error) {
1458
- Log9.debug(`User ${userId} is not banned from guild ${guildId}`);
1157
+ Log6.debug(`User ${userId} is not banned from guild ${guildId}`);
1459
1158
  return false;
1460
1159
  }
1461
1160
  }
@@ -1469,170 +1168,356 @@ var GuildUserManager = class extends BasicUserManager {
1469
1168
  throw new Error(`Member ${memberId} not found or not in a voice channel`);
1470
1169
  }
1471
1170
  await member.voice.disconnect();
1472
- Log9.info(`Disconnected member ${memberId} from voice in guild ${guildId}`);
1171
+ Log6.info(`Disconnected member ${memberId} from voice in guild ${guildId}`);
1473
1172
  } catch (error) {
1474
- Log9.error(`Failed to disconnect member ${memberId} from voice in ${guildId}: ${error}`);
1173
+ Log6.error(`Failed to disconnect member ${memberId} from voice in ${guildId}: ${error}`);
1475
1174
  throw error;
1476
1175
  }
1477
1176
  }
1478
1177
  /**
1479
1178
  * Check if a member is in voice
1480
1179
  */
1481
- static async isInVoice(memberId, guildId) {
1180
+ static async isInVoice(guildId, memberId) {
1181
+ try {
1182
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1183
+ if (!member) {
1184
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1185
+ }
1186
+ return member.voice.channelId !== null;
1187
+ } catch (error) {
1188
+ Log6.debug(`Member ${memberId} not found or not in voice in guild ${guildId}`);
1189
+ return false;
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Mute a member
1194
+ */
1195
+ static async mute(guildId, memberId, reason) {
1482
1196
  try {
1483
1197
  const member = await GuildManager.user.findInGuild(guildId, memberId);
1484
1198
  if (!member) {
1485
- throw new Error(`User ${guildId} not found`);
1199
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1200
+ }
1201
+ await member.voice.setMute(true, reason);
1202
+ Log6.info(`Server muted ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1203
+ } catch (error) {
1204
+ Log6.error(`Failed to server mute ${memberId} in ${guildId}: ${error}`);
1205
+ throw error;
1206
+ }
1207
+ }
1208
+ /**
1209
+ * Unmute a member
1210
+ */
1211
+ static async unmute(guildId, memberId, reason) {
1212
+ try {
1213
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1214
+ if (!member) {
1215
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1216
+ }
1217
+ await member.voice.setMute(false, reason);
1218
+ Log6.info(`Server unmuted ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1219
+ } catch (error) {
1220
+ Log6.error(`Failed to server unmute ${memberId} in ${guildId}: ${error}`);
1221
+ throw error;
1222
+ }
1223
+ }
1224
+ /**
1225
+ * Deafen a member
1226
+ */
1227
+ static async deafen(guildId, memberId, reason) {
1228
+ try {
1229
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1230
+ if (!member) {
1231
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1232
+ }
1233
+ await member.voice.setDeaf(true, reason);
1234
+ Log6.info(`Server deafened ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1235
+ } catch (error) {
1236
+ Log6.error(`Failed to server deafen ${memberId} in ${guildId}: ${error}`);
1237
+ throw error;
1238
+ }
1239
+ }
1240
+ /**
1241
+ * Undeafen member voice
1242
+ */
1243
+ static async undeafen(guildId, memberId, reason) {
1244
+ try {
1245
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1246
+ if (!member) {
1247
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1248
+ }
1249
+ await member.voice.setDeaf(false, reason);
1250
+ Log6.info(`Server undeafened ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1251
+ } catch (error) {
1252
+ Log6.error(`Failed to server undeafen ${memberId} in ${guildId}: ${error}`);
1253
+ throw error;
1254
+ }
1255
+ }
1256
+ /**
1257
+ * Timeout a member
1258
+ */
1259
+ static async timeout(guildId, memberId, duration, reason) {
1260
+ try {
1261
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1262
+ if (!member) {
1263
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1264
+ }
1265
+ await member.timeout(duration, reason);
1266
+ Log6.info(`Timed out ${memberId} for ${duration}ms in guild ${guildId}: ${reason || "No reason"}`);
1267
+ } catch (error) {
1268
+ Log6.error(`Failed to timeout ${memberId} in ${guildId}: ${error}`);
1269
+ throw error;
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Remove the timeout of a member
1274
+ */
1275
+ static async untimeout(guildId, memberId, reason) {
1276
+ try {
1277
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1278
+ if (!member) {
1279
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1280
+ }
1281
+ await member.timeout(null, reason);
1282
+ Log6.info(`Untimed out ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1283
+ } catch (error) {
1284
+ Log6.error(`Failed to untimeout ${memberId} in ${guildId}: ${error}`);
1285
+ throw error;
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Kick a member
1290
+ */
1291
+ static async kick(guildId, memberId, reason) {
1292
+ try {
1293
+ const member = await GuildManager.user.findInGuild(guildId, memberId);
1294
+ if (!member) {
1295
+ throw new Error(`Member ${memberId} not found in guild ${guildId}`);
1296
+ }
1297
+ await member.kick(reason);
1298
+ Log6.info(`Kicked ${memberId} from guild ${guildId}: ${reason || "No reason"}`);
1299
+ } catch (error) {
1300
+ Log6.error(`Failed to kick ${memberId} from ${guildId}: ${error}`);
1301
+ throw error;
1302
+ }
1303
+ }
1304
+ static async ban(guildId, userId, banOption) {
1305
+ const guild = await GuildManager.find(guildId);
1306
+ if (!guild) {
1307
+ throw new Error(`Guild ${guildId} not found`);
1308
+ }
1309
+ try {
1310
+ await guild.members.ban(userId, banOption);
1311
+ Log6.info(`Banned user ${userId} from guild ${guildId}`);
1312
+ } catch (error) {
1313
+ Log6.error(`Failed to ban user ${userId} from guild ${guildId}: ${error}`);
1314
+ throw error;
1315
+ }
1316
+ }
1317
+ static async unban(guildId, userId, reason) {
1318
+ const guild = await GuildManager.find(guildId);
1319
+ if (!guild) {
1320
+ throw new Error(`Guild ${guildId} not found`);
1321
+ }
1322
+ try {
1323
+ await guild.members.unban(userId, reason);
1324
+ Log6.info(`Unbanned user ${userId} from guild ${guildId}`);
1325
+ } catch (error) {
1326
+ Log6.error(`Failed to unban user ${userId} from guild ${guildId}: ${error}`);
1327
+ throw error;
1328
+ }
1329
+ }
1330
+ };
1331
+
1332
+ // src/manager/guild/ChannelManager/GuildChannelManager.ts
1333
+ import { Log as Log8 } from "@spatulox/utils";
1334
+
1335
+ // src/manager/guild/ChannelManager/GuildMessageManager.ts
1336
+ import { Log as Log7 } from "@spatulox/utils";
1337
+ var GuildMessageManager = class {
1338
+ /**
1339
+ * Any guild channel able to hold messages : text, announcement, thread, voice / stage text chat
1340
+ */
1341
+ static async findTextBased(channelId) {
1342
+ const channel = await GuildChannelManager.find(channelId);
1343
+ return channel?.isTextBased() ? channel : null;
1344
+ }
1345
+ /**
1346
+ * Impl
1347
+ */
1348
+ static async send(channelId, content_or_component_or_options) {
1349
+ try {
1350
+ const channel = await this.findTextBased(channelId);
1351
+ if (!channel) {
1352
+ Log7.error(`Channel ${channelId} not found in guild`);
1353
+ return null;
1354
+ }
1355
+ let payload;
1356
+ if (typeof content_or_component_or_options === "string") {
1357
+ payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1358
+ } else if (SendableComponentBuilder.isSendableComponent(content_or_component_or_options) || Array.isArray(content_or_component_or_options)) {
1359
+ payload = SendableComponentBuilder.buildMessage(content_or_component_or_options);
1360
+ } else {
1361
+ payload = content_or_component_or_options;
1486
1362
  }
1487
- return member.voice.channelId !== null;
1363
+ return await channel.send(payload);
1488
1364
  } catch (error) {
1489
- Log9.debug(`Member ${memberId} not found or not in voice in guild ${guildId}`);
1490
- return false;
1365
+ Log7.error(`Failed to send message to ${channelId}: ${error}`);
1366
+ throw error;
1491
1367
  }
1492
1368
  }
1493
1369
  /**
1494
- * Mute a member
1370
+ * Delete message
1495
1371
  */
1496
- static async mute(guildId, memberId, reason) {
1372
+ static async delete(channelId, messageId) {
1497
1373
  try {
1498
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1499
- if (!member) {
1500
- throw new Error(`User ${guildId} not found`);
1374
+ const channel = await this.findTextBased(channelId);
1375
+ if (!channel) {
1376
+ Log7.error(`Channel ${channelId} not found`);
1377
+ return false;
1501
1378
  }
1502
- await member.voice.setMute(true, reason);
1503
- Log9.info(`Server muted ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1379
+ const message = await channel.messages.fetch(messageId);
1380
+ await message.delete();
1381
+ Log7.info(`Deleted message ${messageId} from ${channelId}`);
1382
+ return true;
1504
1383
  } catch (error) {
1505
- Log9.error(`Failed to server mute ${memberId} in ${guildId}:, error`);
1506
- throw error;
1384
+ Log7.error(`Failed to delete message ${messageId} from ${channelId}: ${error}`);
1385
+ return false;
1507
1386
  }
1508
1387
  }
1509
1388
  /**
1510
- * Unmute a member
1389
+ * Fetch messages (last X messages, default 10)
1511
1390
  */
1512
- static async unmute(guildId, memberId, reason) {
1391
+ static async fetch(channelId, limit = 10) {
1513
1392
  try {
1514
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1515
- if (!member) {
1516
- throw new Error(`User ${guildId} not found`);
1393
+ const channel = await this.findTextBased(channelId);
1394
+ if (!channel) {
1395
+ Log7.error(`Channel ${channelId} not found`);
1396
+ return [];
1517
1397
  }
1518
- await member.voice.setMute(false, reason);
1519
- Log9.info(`Server unmuted ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1398
+ const messages = await channel.messages.fetch({ limit });
1399
+ Log7.info(`Fetched ${messages.size} messages from ${channelId}`);
1400
+ return Array.from(messages.values());
1520
1401
  } catch (error) {
1521
- Log9.error(`Failed to server unmute ${memberId} in ${guildId}: ${error}`);
1522
- throw error;
1402
+ Log7.error(`Failed to fetch messages from ${channelId}: ${error}`);
1403
+ return [];
1523
1404
  }
1524
1405
  }
1525
1406
  /**
1526
- * Deafen a member
1407
+ * Fetch single message
1527
1408
  */
1528
- static async deafen(guildId, memberId, reason) {
1409
+ static async fetchOne(channelId, messageId) {
1529
1410
  try {
1530
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1531
- if (!member) {
1532
- throw new Error(`User ${guildId} not found`);
1411
+ const channel = await this.findTextBased(channelId);
1412
+ if (!channel) {
1413
+ Log7.error(`Channel ${channelId} not found`);
1414
+ return null;
1533
1415
  }
1534
- await member.voice.setDeaf(true, reason);
1535
- Log9.info(`Server deafened ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1416
+ const message = await channel.messages.fetch(messageId);
1417
+ return message;
1536
1418
  } catch (error) {
1537
- Log9.error(`Failed to server deafen ${memberId} in ${guildId}: ${error}`);
1538
- throw error;
1419
+ Log7.error(`Failed to fetch message ${messageId} from ${channelId}: ${error}`);
1420
+ return null;
1539
1421
  }
1540
1422
  }
1423
+ };
1424
+
1425
+ // src/manager/guild/ChannelManager/GuildChannelManager.ts
1426
+ var GuildChannelManager = class _GuildChannelManager {
1427
+ static message = GuildMessageManager;
1541
1428
  /**
1542
- * Undeafen member voice
1429
+ * Recherche un channel par ID dans une guild spécifique
1543
1430
  */
1544
- static async undeafen(guildId, memberId, reason) {
1431
+ static async findInGuild(guildId, channelId) {
1545
1432
  try {
1546
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1547
- if (!member) {
1548
- throw new Error(`User ${guildId} not found`);
1433
+ const guild = Bot.client.guilds.cache.get(guildId);
1434
+ if (!guild) {
1435
+ Log8.warn(`Guild ${guildId} not found`);
1436
+ return null;
1549
1437
  }
1550
- await member.voice.setDeaf(false, reason);
1551
- Log9.info(`Server undeafened ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1438
+ const channel = await guild.channels.fetch(channelId);
1439
+ return channel ?? null;
1552
1440
  } catch (error) {
1553
- Log9.error(`Failed to server undeafen ${memberId} in ${guildId}: ${error}`);
1554
- throw error;
1441
+ Log8.error(`Failed to find channel ${channelId} in guild ${guildId}: ${error}`);
1442
+ return null;
1555
1443
  }
1556
1444
  }
1557
- /**
1558
- * Timeout a member
1559
- */
1560
- static async timeout(guildId, memberId, duration, reason) {
1445
+ static async find(channelId) {
1561
1446
  try {
1562
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1563
- if (!member) {
1564
- throw new Error(`User ${guildId} not found`);
1565
- }
1566
- const expires = Date.now() + duration;
1567
- await member.timeout(expires, reason);
1568
- Log9.info(`Timed out ${memberId} for ${duration}ms in guild ${guildId}: ${reason || "No reason"}`);
1447
+ const cached = Bot.client.channels.cache.get(channelId);
1448
+ if (cached && !cached.isDMBased()) return cached;
1449
+ const channel = await Bot.client.channels.fetch(channelId);
1450
+ if (channel && !channel.isDMBased()) return channel;
1451
+ Log8.warn(`Channel ${channelId} not found in any guild`);
1452
+ return null;
1569
1453
  } catch (error) {
1570
- Log9.error(`Failed to timeout ${memberId} in ${guildId}: ${error}`);
1571
- throw error;
1454
+ Log8.error(`Failed to find channel ${channelId}: ${error}`);
1455
+ return null;
1572
1456
  }
1573
1457
  }
1574
- /**
1575
- * Remove the timeout of a member
1576
- */
1577
- static async untimeout(guildId, memberId, reason) {
1458
+ static findAll(guildId) {
1578
1459
  try {
1579
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1580
- if (!member) {
1581
- throw new Error(`User ${guildId} not found`);
1460
+ const guild = Bot.client.guilds.cache.get(guildId);
1461
+ if (!guild) {
1462
+ Log8.warn(`Guild ${guildId} not found`);
1463
+ return [];
1582
1464
  }
1583
- await member.timeout(null, reason);
1584
- Log9.info(`Untimed out ${memberId} in guild ${guildId}: ${reason || "No reason"}`);
1465
+ return Array.from(guild.channels.cache.values());
1585
1466
  } catch (error) {
1586
- Log9.error(`Failed to untimeout ${memberId} in ${guildId}: ${error}`);
1587
- throw error;
1467
+ Log8.error(`Failed to find channel ${guildId}: ${error}`);
1468
+ return [];
1588
1469
  }
1589
1470
  }
1590
1471
  /**
1591
- * Kick a member
1472
+ * Recherche channels par nom (insensible à la casse)
1592
1473
  */
1593
- static async kick(guildId, memberId, reason) {
1474
+ static findByName(guildId, name2) {
1594
1475
  try {
1595
- const member = await GuildManager.user.findInGuild(guildId, memberId);
1596
- if (!member) {
1597
- throw new Error(`User ${guildId} not found`);
1476
+ const guild = Bot.client.guilds.cache.get(guildId);
1477
+ if (!guild) {
1478
+ Log8.warn(`Guild ${guildId} not found`);
1479
+ return [];
1598
1480
  }
1599
- await member.kick(reason);
1600
- Log9.info(`Kicked ${memberId} from guild ${guildId}: ${reason || "No reason"}`);
1481
+ return Array.from(guild.channels.cache.values()).filter(
1482
+ (channel) => channel.name.toLowerCase().includes(name2.toLowerCase())
1483
+ );
1601
1484
  } catch (error) {
1602
- Log9.error(`Failed to kick ${memberId} from ${guildId}: ${error}`);
1603
- throw error;
1485
+ Log8.error(`Failed to find channel ${guildId}: ${error}`);
1486
+ return [];
1604
1487
  }
1605
1488
  }
1606
- static async ban(guildId, userId, banOption) {
1607
- const guild = await GuildManager.find(guildId);
1608
- if (!guild) {
1609
- throw new Error(`Guild ${guildId} not found`);
1610
- }
1489
+ static async _create(guildId, options) {
1611
1490
  try {
1612
- await guild.members.ban(userId, banOption);
1613
- Log9.info(`Banned user ${userId} from guild ${guildId}`);
1491
+ const guild = Bot.client.guilds.cache.get(guildId);
1492
+ if (!guild) {
1493
+ throw new Error(`Guild ${guildId} not found`);
1494
+ }
1495
+ const channel = await guild.channels.create(options);
1496
+ Log8.info(`Created channel ${channel.name} (${channel.id}) in guild ${guildId}`);
1497
+ return channel;
1614
1498
  } catch (error) {
1615
- Log9.error(`Failed to ban user ${userId} from guild ${guildId}: ${error}`);
1499
+ Log8.error(`Failed to create channel in guild ${guildId}: ${error}`);
1616
1500
  throw error;
1617
1501
  }
1618
1502
  }
1619
- static async unban(guildId, userId, reason) {
1620
- const guild = await GuildManager.find(guildId);
1621
- if (!guild) {
1622
- throw new Error(`Guild ${guildId} not found`);
1623
- }
1503
+ static async delete(channelId) {
1624
1504
  try {
1625
- await guild.members.unban(userId, reason);
1626
- Log9.info(`Unbanned user ${userId} from guild ${guildId}`);
1505
+ const channel = await _GuildChannelManager.find(channelId);
1506
+ if (!channel) {
1507
+ throw new Error(`Channel ${channelId} not found`);
1508
+ }
1509
+ await channel.delete();
1510
+ Log8.info(`Deleted channel ${channelId}`);
1511
+ return true;
1627
1512
  } catch (error) {
1628
- Log9.error(`Failed to unban user ${userId} from guild ${guildId}: ${error}`);
1629
- throw error;
1513
+ Log8.error(`Failed to delete channel ${channelId}: ${error}`);
1514
+ return false;
1630
1515
  }
1631
1516
  }
1632
1517
  };
1633
1518
 
1634
1519
  // src/manager/guild/RoleManager.ts
1635
- import { Log as Log10 } from "@spatulox/utils";
1520
+ import { Log as Log9 } from "@spatulox/utils";
1636
1521
  var RoleManager = class {
1637
1522
  /**
1638
1523
  * Add role - CACHE ONLY
@@ -1643,14 +1528,14 @@ var RoleManager = class {
1643
1528
  try {
1644
1529
  const role = member.guild.roles.cache.get(roleId);
1645
1530
  if (!role) {
1646
- Log10.warn(`Role ${roleId} not found in cache`);
1531
+ Log9.warn(`Role ${roleId} not found in cache`);
1647
1532
  return false;
1648
1533
  }
1649
1534
  await member.roles.add(role);
1650
- Log10.info(`\u2705 Added ${role.name} to ${member.displayName}`);
1535
+ Log9.info(`\u2705 Added ${role.name} to ${member.displayName}`);
1651
1536
  return true;
1652
1537
  } catch (error) {
1653
- Log10.error(`Failed to add role ${roleId}: ${error}`);
1538
+ Log9.error(`Failed to add role ${roleId}: ${error}`);
1654
1539
  return false;
1655
1540
  }
1656
1541
  }
@@ -1661,23 +1546,16 @@ var RoleManager = class {
1661
1546
  */
1662
1547
  static async remove(member, roleIdOrName) {
1663
1548
  try {
1664
- let role;
1665
- if (typeof roleIdOrName === "string" && roleIdOrName.length === 18) {
1666
- role = member.roles.cache.get(roleIdOrName);
1667
- } else {
1668
- role = member.roles.cache.find(
1669
- (r) => r.id === roleIdOrName || r.name.toLowerCase() === roleIdOrName.toString().toLowerCase()
1670
- );
1671
- }
1549
+ const role = this.resolve(member.roles.cache, roleIdOrName);
1672
1550
  if (!role) {
1673
- Log10.warn(`Role ${roleIdOrName} not found for ${member.displayName}`);
1551
+ Log9.warn(`Role ${roleIdOrName} not found for ${member.displayName}`);
1674
1552
  return false;
1675
1553
  }
1676
1554
  await member.roles.remove(role);
1677
- Log10.info(`\u2705 Removed ${role.name} from ${member.displayName}`);
1555
+ Log9.info(`\u2705 Removed ${role.name} from ${member.displayName}`);
1678
1556
  return true;
1679
1557
  } catch (error) {
1680
- Log10.error(`Failed to remove role ${roleIdOrName}: ${error}`);
1558
+ Log9.error(`Failed to remove role ${roleIdOrName}: ${error}`);
1681
1559
  return false;
1682
1560
  }
1683
1561
  }
@@ -1685,9 +1563,9 @@ var RoleManager = class {
1685
1563
  * Toggle role (add/remove)
1686
1564
  */
1687
1565
  static async toggle(member, roleIdOrName) {
1688
- const role = member.roles.cache.get(roleIdOrName) || member.roles.cache.find((r) => r.name.toLowerCase() === roleIdOrName.toString().toLowerCase());
1566
+ const role = this.resolve(member.guild.roles.cache, roleIdOrName);
1689
1567
  if (!role) {
1690
- Log10.warn(`Role ${roleIdOrName} not found`);
1568
+ Log9.warn(`Role ${roleIdOrName} not found`);
1691
1569
  throw new Error(`Role not found`);
1692
1570
  }
1693
1571
  if (member.roles.cache.has(role.id)) {
@@ -1702,18 +1580,20 @@ var RoleManager = class {
1702
1580
  * Check if member has role
1703
1581
  */
1704
1582
  static hasRole(member, roleIdOrName) {
1705
- if (typeof roleIdOrName === "string" && roleIdOrName.length === 18) {
1706
- return member.roles.cache.has(roleIdOrName);
1707
- }
1708
- return member.roles.cache.some(
1709
- (r) => r.id === roleIdOrName || r.name.toLowerCase() === roleIdOrName.toString().toLowerCase()
1710
- );
1583
+ return !!this.resolve(member.roles.cache, roleIdOrName);
1584
+ }
1585
+ /**
1586
+ * Search by id first, then by name (case insensitive). Snowflakes are 17 to 20 digits long,
1587
+ * so the length of the string can't tell an id from a name
1588
+ */
1589
+ static resolve(roles, roleIdOrName) {
1590
+ return roles.get(roleIdOrName) ?? roles.find((r) => r.name.toLowerCase() === roleIdOrName.toLowerCase());
1711
1591
  }
1712
1592
  };
1713
1593
 
1714
1594
  // src/manager/guild/ChannelManager/ForumChannelManager.ts
1715
- import { ChannelType as ChannelType3, ForumChannel } from "discord.js";
1716
- import { Log as Log11 } from "@spatulox/utils";
1595
+ import { ChannelType as ChannelType2, ForumChannel } from "discord.js";
1596
+ import { Log as Log10 } from "@spatulox/utils";
1717
1597
  var ForumChannelManager = class extends GuildChannelManager {
1718
1598
  static async findInGuild(guildId, channelId) {
1719
1599
  const channel = await super.findInGuild(guildId, channelId);
@@ -1726,23 +1606,23 @@ var ForumChannelManager = class extends GuildChannelManager {
1726
1606
  static findAll(guildId) {
1727
1607
  const guild = Bot.client.guilds.cache.get(guildId);
1728
1608
  if (!guild) {
1729
- Log11.warn(`Guild ${guildId} not found`);
1609
+ Log10.warn(`Guild ${guildId} not found`);
1730
1610
  return [];
1731
1611
  }
1732
1612
  return Array.from(guild.channels.cache.values()).filter((c) => c instanceof ForumChannel);
1733
1613
  }
1734
- static async create(guildId, name, options) {
1614
+ static async create(guildId, name2, options) {
1735
1615
  return await super._create(guildId, {
1736
- name,
1737
- type: ChannelType3.GuildForum,
1616
+ name: name2,
1617
+ type: ChannelType2.GuildForum,
1738
1618
  ...options
1739
1619
  });
1740
1620
  }
1741
1621
  };
1742
1622
 
1743
1623
  // src/manager/guild/ChannelManager/NewsChannelManager.ts
1744
- import { ChannelType as ChannelType4, NewsChannel } from "discord.js";
1745
- import { Log as Log12 } from "@spatulox/utils";
1624
+ import { ChannelType as ChannelType3, NewsChannel } from "discord.js";
1625
+ import { Log as Log11 } from "@spatulox/utils";
1746
1626
  var NewsChannelManager = class extends GuildChannelManager {
1747
1627
  static async findInGuild(guildId, channelId) {
1748
1628
  const channel = await super.findInGuild(guildId, channelId);
@@ -1755,23 +1635,23 @@ var NewsChannelManager = class extends GuildChannelManager {
1755
1635
  static findAll(guildId) {
1756
1636
  const guild = Bot.client.guilds.cache.get(guildId);
1757
1637
  if (!guild) {
1758
- Log12.warn(`Guild ${guildId} not found`);
1638
+ Log11.warn(`Guild ${guildId} not found`);
1759
1639
  return [];
1760
1640
  }
1761
1641
  return Array.from(guild.channels.cache.values()).filter((c) => c instanceof NewsChannel);
1762
1642
  }
1763
- static async create(guildId, name, options) {
1643
+ static async create(guildId, name2, options) {
1764
1644
  return await super._create(guildId, {
1765
- name,
1766
- type: ChannelType4.GuildAnnouncement,
1645
+ name: name2,
1646
+ type: ChannelType3.GuildAnnouncement,
1767
1647
  ...options
1768
1648
  });
1769
1649
  }
1770
1650
  };
1771
1651
 
1772
1652
  // src/manager/guild/ChannelManager/StageChannelManager.ts
1773
- import { ChannelType as ChannelType5, StageChannel } from "discord.js";
1774
- import { Log as Log13 } from "@spatulox/utils";
1653
+ import { ChannelType as ChannelType4, StageChannel } from "discord.js";
1654
+ import { Log as Log12 } from "@spatulox/utils";
1775
1655
  var StageChannelManager = class extends GuildChannelManager {
1776
1656
  static async findInGuild(guildId, channelId) {
1777
1657
  const channel = await super.findInGuild(guildId, channelId);
@@ -1784,21 +1664,54 @@ var StageChannelManager = class extends GuildChannelManager {
1784
1664
  static findAll(guildId) {
1785
1665
  const guild = Bot.client.guilds.cache.get(guildId);
1786
1666
  if (!guild) {
1787
- Log13.warn(`Guild ${guildId} not found`);
1667
+ Log12.warn(`Guild ${guildId} not found`);
1788
1668
  return [];
1789
1669
  }
1790
1670
  return Array.from(guild.channels.cache.values()).filter((c) => c instanceof StageChannel);
1791
1671
  }
1792
- static async create(guildId, name, options) {
1672
+ static async create(guildId, name2, options) {
1673
+ return await super._create(guildId, {
1674
+ name: name2,
1675
+ type: ChannelType4.GuildStageVoice,
1676
+ ...options
1677
+ });
1678
+ }
1679
+ };
1680
+
1681
+ // src/manager/guild/ChannelManager/GuildTextChannelManager.ts
1682
+ import { TextChannel as TextChannel4, ChannelType as ChannelType5 } from "discord.js";
1683
+ import { Log as Log13 } from "@spatulox/utils";
1684
+ var GuildTextChannelManager = class extends GuildChannelManager {
1685
+ static async findInGuild(guildId, channelId) {
1686
+ const channel = await super.findInGuild(guildId, channelId);
1687
+ return channel instanceof TextChannel4 ? channel : null;
1688
+ }
1689
+ static async find(channelId) {
1690
+ const channel = await super.find(channelId);
1691
+ return channel instanceof TextChannel4 ? channel : null;
1692
+ }
1693
+ static findAll(guildId) {
1694
+ const guild = Bot.client.guilds.cache.get(guildId);
1695
+ if (!guild) {
1696
+ Log13.warn(`Guild ${guildId} not found`);
1697
+ return [];
1698
+ }
1699
+ return Array.from(guild.channels.cache.values()).filter((c) => c instanceof TextChannel4);
1700
+ }
1701
+ static async create(guildId, name2, options) {
1793
1702
  return await super._create(guildId, {
1794
- name,
1795
- type: ChannelType5.GuildStageVoice,
1703
+ name: name2,
1704
+ type: ChannelType5.GuildText,
1796
1705
  ...options
1797
1706
  });
1798
1707
  }
1799
1708
  };
1800
1709
 
1801
1710
  // src/manager/guild/ChannelManager/ThreadChannelManager.ts
1711
+ import {
1712
+ NewsChannel as NewsChannel2,
1713
+ TextChannel as TextChannel5
1714
+ } from "discord.js";
1802
1715
  var ThreadChannelManager = class {
1803
1716
  static async findInGuild(guildId, channelId) {
1804
1717
  const channel = await GuildChannelManager.findInGuild(guildId, channelId);
@@ -1813,16 +1726,15 @@ var ThreadChannelManager = class {
1813
1726
  return channels.filter((c) => c.isThread());
1814
1727
  }
1815
1728
  static async createFromChannel(parentId, options) {
1816
- const channel = await GuildTextChannelManager.find(parentId);
1817
- if (!channel || !channel.isTextBased()) {
1818
- throw new Error("Parent must be a text-based channel");
1729
+ const channel = await GuildChannelManager.find(parentId);
1730
+ if (!(channel instanceof TextChannel5) && !(channel instanceof NewsChannel2)) {
1731
+ throw new Error("Parent must be a text or announcement channel");
1819
1732
  }
1820
1733
  const thread = await channel.threads.create(options);
1821
1734
  return thread;
1822
1735
  }
1823
1736
  static async createFromMessage(message, options) {
1824
- const channel = await GuildChannelManager.find(message.id);
1825
- if (!channel) throw new Error("Message channel not found");
1737
+ if (!message.inGuild()) throw new Error("Cannot start a thread from a message outside of a guild");
1826
1738
  return await message.startThread(options);
1827
1739
  }
1828
1740
  /**
@@ -1845,11 +1757,11 @@ import { Log as Log14 } from "@spatulox/utils";
1845
1757
  var GuildVoiceChannelManager = class extends GuildChannelManager {
1846
1758
  static async findInGuild(guildId, channelId) {
1847
1759
  const channel = await super.findInGuild(guildId, channelId);
1848
- return channel?.isVoiceBased() ? channel : null;
1760
+ return channel instanceof VoiceChannel ? channel : null;
1849
1761
  }
1850
1762
  static async find(channelId) {
1851
1763
  const channel = await super.find(channelId);
1852
- return channel?.isVoiceBased() ? channel : null;
1764
+ return channel instanceof VoiceChannel ? channel : null;
1853
1765
  }
1854
1766
  static findAll(guildId) {
1855
1767
  const guild = Bot.client.guilds.cache.get(guildId);
@@ -1859,9 +1771,9 @@ var GuildVoiceChannelManager = class extends GuildChannelManager {
1859
1771
  }
1860
1772
  return Array.from(guild.channels.cache.values()).filter((c) => c instanceof VoiceChannel);
1861
1773
  }
1862
- static async create(guildId, name, options) {
1774
+ static async create(guildId, name2, options) {
1863
1775
  return await super._create(guildId, {
1864
- name,
1776
+ name: name2,
1865
1777
  type: ChannelType6.GuildVoice,
1866
1778
  ...options
1867
1779
  });
@@ -1880,6 +1792,7 @@ var GuildChannelList = class {
1880
1792
  };
1881
1793
 
1882
1794
  // src/manager/guild/InviteManager.ts
1795
+ import { setTimeout as setTimeout3 } from "timers/promises";
1883
1796
  import { Log as Log15 } from "@spatulox/utils";
1884
1797
  var InviteManager = class {
1885
1798
  /**
@@ -1907,9 +1820,19 @@ var InviteManager = class {
1907
1820
  }
1908
1821
  }
1909
1822
  /**
1910
- * Delete an invitation
1823
+ * Find an invite by its code or its url (discord.gg/code, discord.com/invite/code)
1911
1824
  */
1912
- static async delete(invite) {
1825
+ static async find(codeOrUrl) {
1826
+ try {
1827
+ return await Bot.client.fetchInvite(codeOrUrl);
1828
+ } catch (error) {
1829
+ Log15.error(`Failed to find invite ${codeOrUrl}: ${error}`);
1830
+ return null;
1831
+ }
1832
+ }
1833
+ static async delete(inviteOrCode) {
1834
+ const invite = typeof inviteOrCode === "string" ? await this.find(inviteOrCode) : inviteOrCode;
1835
+ if (!invite) return false;
1913
1836
  try {
1914
1837
  await invite.delete();
1915
1838
  Log15.info(`Deleted invite ${invite.code} from guild ${invite.guild?.id}`);
@@ -1937,6 +1860,33 @@ var InviteManager = class {
1937
1860
  throw error;
1938
1861
  }
1939
1862
  }
1863
+ /**
1864
+ * Check if an invite is older than maxAgeMs (default 1 hour).
1865
+ * Permanent invites (maxAge = 0) and excluded codes are never considered old
1866
+ */
1867
+ static isOld(invite, excludedCodes = [], maxAgeMs = 60 * 60 * 1e3) {
1868
+ if (!invite.createdAt) return false;
1869
+ return invite.maxAge !== 0 && !excludedCodes.includes(invite.code) && invite.createdAt.getTime() < Date.now() - maxAgeMs;
1870
+ }
1871
+ /**
1872
+ * Delete every old invite of a guild, returns the number of deleted invites
1873
+ */
1874
+ static async cleanup(guildId, excludedCodes = [], maxAgeMs) {
1875
+ try {
1876
+ const invites = await this.list(guildId);
1877
+ let deletedCount = 0;
1878
+ for (const invite of invites) {
1879
+ if (!this.isOld(invite, excludedCodes, maxAgeMs)) continue;
1880
+ if (await this.delete(invite)) deletedCount++;
1881
+ await setTimeout3(100);
1882
+ }
1883
+ Log15.info(`Invite cleanup ${guildId}: ${deletedCount} old invites deleted`);
1884
+ return deletedCount;
1885
+ } catch (error) {
1886
+ Log15.error(`Invite cleanup failed for ${guildId}: ${error}`);
1887
+ return 0;
1888
+ }
1889
+ }
1940
1890
  };
1941
1891
 
1942
1892
  // src/manager/guild/GuildManager.ts
@@ -1972,9 +1922,9 @@ var GuildManager = class {
1972
1922
  /**
1973
1923
  * Search guild member by ID
1974
1924
  */
1975
- static async searchMember(memberId, guildId) {
1925
+ static async searchMember(guildId, memberId) {
1976
1926
  try {
1977
- return await this.user.findInGuild(guildId, guildId);
1927
+ return await this.user.findInGuild(guildId, memberId);
1978
1928
  } catch (error) {
1979
1929
  Log16.error(`Failed to fetch member ${memberId} in guild ${guildId}: ${error}`);
1980
1930
  return null;
@@ -1983,9 +1933,9 @@ var GuildManager = class {
1983
1933
  /**
1984
1934
  * Check if member is still in guild
1985
1935
  */
1986
- static async isMemberInGuild(memberId, guildId) {
1936
+ static async isMemberInGuild(guildId, memberId) {
1987
1937
  try {
1988
- return await this.user.isInGuild(memberId, guildId);
1938
+ return await this.user.isInGuild(guildId, memberId);
1989
1939
  } catch (error) {
1990
1940
  return error.code !== 10007;
1991
1941
  }
@@ -2145,7 +2095,7 @@ var ModalManager = class {
2145
2095
  const modal = this.create(modalTitle ?? Bot.config?.botName ?? "Bot", customId);
2146
2096
  const opt = {
2147
2097
  ...field,
2148
- customId: `${customId}_input`,
2098
+ customId: field.customId ?? `${customId}_input`,
2149
2099
  placeholder: "placeholder" in field && field.placeholder ? field.placeholder : `Enter ${field.label.toLowerCase()}`,
2150
2100
  value: field.value
2151
2101
  };
@@ -2155,21 +2105,23 @@ var ModalManager = class {
2155
2105
  /**
2156
2106
  * Title + Description modal preset
2157
2107
  */
2158
- static titleDescription(customId, modalTitle, title, description) {
2108
+ static titleDescription(customId, modalTitle, title, description2) {
2159
2109
  const modal = this.create(modalTitle, customId);
2160
2110
  const titleField = {
2161
2111
  customId: `${customId}_title`,
2162
2112
  label: title.label,
2163
2113
  placeholder: title.placeholder ?? `Enter ${title.label.toLowerCase()}`,
2164
2114
  type: 0 /* SHORT */,
2165
- required: title.required
2115
+ required: title.required,
2116
+ value: title.value
2166
2117
  };
2167
2118
  const descField = {
2168
2119
  customId: `${customId}_desc`,
2169
- label: description.label,
2170
- placeholder: description.placeholder ?? `Enter ${description.label.toLowerCase()}`,
2120
+ label: description2.label,
2121
+ placeholder: description2.placeholder ?? `Enter ${description2.label.toLowerCase()}`,
2171
2122
  type: 1 /* LONG */,
2172
- required: description.required
2123
+ required: description2.required,
2124
+ value: description2.value
2173
2125
  };
2174
2126
  modal.addLabelComponents(this._createField(titleField));
2175
2127
  modal.addLabelComponents(this._createField(descField));
@@ -2177,21 +2129,25 @@ var ModalManager = class {
2177
2129
  }
2178
2130
  /**
2179
2131
  * Date modal preset
2132
+ * @param suffix true (default) : the modal customId is `${customId}_date` and the input `${customId}_date_input`,
2133
+ * false : the modal keeps `customId` and the input is `${customId}_input`. Same for number() (_number) and phone() (_phone_number)
2180
2134
  */
2181
- static date(customId, modalTitle = "Select Date", inputLabel = "Date") {
2182
- return this.simple(`${customId}_date`, modalTitle, { label: inputLabel, type: 3 /* DATE */ });
2135
+ static date(customId, modalTitle = "Select Date", inputLabel = "Date", suffix = true) {
2136
+ return this.simple(suffix ? `${customId}_date` : customId, modalTitle, { label: inputLabel, type: 3 /* DATE */ });
2183
2137
  }
2184
2138
  /**
2185
2139
  * Number modal preset
2140
+ * @param suffix See date() : `${customId}_number` by default, `customId` when false
2186
2141
  */
2187
- static number(customId, modalTitle = "Enter a Number", inputLabel = "Number") {
2188
- return this.simple(`${customId}_number`, modalTitle, { label: inputLabel, type: 2 /* NUMBER */, placeholder: "Enter a number" });
2142
+ static number(customId, modalTitle = "Enter a Number", inputLabel = "Number", suffix = true) {
2143
+ return this.simple(suffix ? `${customId}_number` : customId, modalTitle, { label: inputLabel, type: 2 /* NUMBER */, placeholder: "Enter a number" });
2189
2144
  }
2190
2145
  /**
2191
- * Number modal preset
2146
+ * Phone modal preset
2147
+ * @param suffix See date() : `${customId}_phone_number` by default, `customId` when false
2192
2148
  */
2193
- static phone(customId, modalTitle = "Enter a Phone number", inputLabel = "Phone number") {
2194
- return this.simple(`${customId}_phone_number`, modalTitle, { label: inputLabel, type: 4 /* PHONE */, placeholder: "Enter a phone number" });
2149
+ static phone(customId, modalTitle = "Enter a Phone number", inputLabel = "Phone number", suffix = true) {
2150
+ return this.simple(suffix ? `${customId}_phone_number` : customId, modalTitle, { label: inputLabel, type: 4 /* PHONE */, placeholder: "Enter a phone number" });
2195
2151
  }
2196
2152
  static add(modal, field) {
2197
2153
  if (Array.isArray(field)) {
@@ -2202,7 +2158,7 @@ var ModalManager = class {
2202
2158
  }
2203
2159
  const opt = {
2204
2160
  ...field,
2205
- customId: `${modal.data.custom_id}_${field.label}`
2161
+ customId: field.customId ?? `${modal.data.custom_id}_${field.label}`
2206
2162
  };
2207
2163
  modal.addLabelComponents(this._createField(opt));
2208
2164
  return modal;
@@ -2221,32 +2177,36 @@ var ModalManager = class {
2221
2177
  static parseDate(value) {
2222
2178
  if (/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/.test(value)) {
2223
2179
  const [year, month, day] = value.split("-").map(Number);
2224
- const date = new Date(year, month - 1, day);
2225
- return isNaN(date.getTime()) ? null : date;
2180
+ return this.buildDate(year, month, day);
2226
2181
  }
2227
2182
  if (/^(0[1-9]|[12]\d|3[01])-(0[1-9]|1[0-2])-\d{4}$/.test(value)) {
2228
2183
  const [day, month, year] = value.split("-").map(Number);
2229
- const date = new Date(year, month - 1, day);
2230
- return isNaN(date.getTime()) ? null : date;
2184
+ return this.buildDate(year, month, day);
2231
2185
  }
2232
2186
  if (/^(0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/.test(value)) {
2233
2187
  const [day, month, year] = value.split("/").map(Number);
2234
- const date = new Date(year, month - 1, day);
2235
- return isNaN(date.getTime()) ? null : date;
2188
+ return this.buildDate(year, month, day);
2236
2189
  }
2237
2190
  if (/^\d{4}\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/.test(value)) {
2238
2191
  const [year, month, day] = value.split("/").map(Number);
2239
- const date = new Date(year, month - 1, day);
2240
- return isNaN(date.getTime()) ? null : date;
2192
+ return this.buildDate(year, month, day);
2241
2193
  }
2242
2194
  return null;
2243
2195
  }
2196
+ /**
2197
+ * new Date() silently rolls an impossible date over (31/02 becomes 02/03) : reject any date that doesn't round-trip
2198
+ */
2199
+ static buildDate(year, month, day) {
2200
+ const date = new Date(year, month - 1, day);
2201
+ if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
2202
+ return date;
2203
+ }
2244
2204
  };
2245
2205
 
2246
2206
  // src/manager/messages/ComponentManager.ts
2247
2207
  import {
2248
- ContainerBuilder as ContainerBuilder3,
2249
- TextDisplayBuilder,
2208
+ ContainerBuilder as ContainerBuilder2,
2209
+ TextDisplayBuilder as TextDisplayBuilder2,
2250
2210
  SeparatorBuilder,
2251
2211
  SeparatorSpacingSize,
2252
2212
  MessageFlags as MessageFlags5,
@@ -2256,17 +2216,17 @@ import {
2256
2216
  MediaGalleryItemBuilder,
2257
2217
  AttachmentBuilder,
2258
2218
  FileBuilder,
2259
- ActionRowBuilder as ActionRowBuilder4
2219
+ ActionRowBuilder as ActionRowBuilder3
2260
2220
  } from "discord.js";
2261
2221
  var ComponentManager = class {
2262
2222
  static get DEFAULT_COLOR() {
2263
- return Bot.config?.defaultSimpleColor || 6064856 /* default */;
2223
+ return Bot.config?.defaultSimpleColor ?? 6064856 /* default */;
2264
2224
  }
2265
2225
  /**
2266
2226
  * Creates base ComponentV2
2267
2227
  */
2268
2228
  static create(option) {
2269
- const container = new ContainerBuilder3();
2229
+ const container = new ContainerBuilder2();
2270
2230
  const colorC = option?.color ?? this.DEFAULT_COLOR;
2271
2231
  if (colorC !== "transparent" /* transparent */) {
2272
2232
  container.setAccentColor(colorC);
@@ -2274,7 +2234,7 @@ var ComponentManager = class {
2274
2234
  if (option?.title || option?.thumbnailUrl) {
2275
2235
  if (option?.thumbnailUrl) {
2276
2236
  const headerSection = new SectionBuilder().addTextDisplayComponents(
2277
- new TextDisplayBuilder().setContent(
2237
+ new TextDisplayBuilder2().setContent(
2278
2238
  option?.title ? option.title : "\u200B"
2279
2239
  )
2280
2240
  ).setThumbnailAccessory(
@@ -2283,44 +2243,44 @@ var ComponentManager = class {
2283
2243
  container.addSectionComponents(headerSection);
2284
2244
  } else {
2285
2245
  container.addTextDisplayComponents(
2286
- new TextDisplayBuilder().setContent(option.title)
2246
+ new TextDisplayBuilder2().setContent(option.title)
2287
2247
  );
2288
2248
  }
2289
- if (option?.description) {
2290
- container.addTextDisplayComponents(new TextDisplayBuilder().setContent(option.description));
2291
- }
2292
- if (option?.separator) {
2293
- container.addSeparatorComponents(this.separator(option.separator));
2294
- }
2249
+ }
2250
+ if (option?.description) {
2251
+ container.addTextDisplayComponents(new TextDisplayBuilder2().setContent(option.description));
2252
+ }
2253
+ if (option?.separator && (option.title || option.thumbnailUrl || option.description)) {
2254
+ container.addSeparatorComponents(this.separator(option.separator));
2295
2255
  }
2296
2256
  return container;
2297
2257
  }
2298
2258
  /**
2299
2259
  * Creates simple ComponentV2 with just description
2300
2260
  */
2301
- static simple(description, color = null) {
2302
- return this.create({ color }).addTextDisplayComponents(new TextDisplayBuilder().setContent(description)).addSeparatorComponents(this.separator());
2261
+ static simple(description2, color = null) {
2262
+ return this.create({ color }).addTextDisplayComponents(new TextDisplayBuilder2().setContent(description2)).addSeparatorComponents(this.separator());
2303
2263
  }
2304
2264
  /**
2305
2265
  * Creates success ComponentV2
2306
2266
  */
2307
- static success(description) {
2308
- return this.create({ title: "Success", color: 65280 /* success */ }).addTextDisplayComponents(new TextDisplayBuilder().setContent(description)).addSeparatorComponents(this.separator());
2267
+ static success(description2) {
2268
+ return this.create({ title: "Success", color: 65280 /* success */ }).addTextDisplayComponents(new TextDisplayBuilder2().setContent(description2)).addSeparatorComponents(this.separator());
2309
2269
  }
2310
2270
  /**
2311
2271
  * Creates debug ComponentV2
2312
2272
  */
2313
- static debug(description) {
2273
+ static debug(description2) {
2314
2274
  return this.create({ title: "Debug", color: 25600 /* minecraft */ }).addTextDisplayComponents(
2315
- new TextDisplayBuilder().setContent(description)
2275
+ new TextDisplayBuilder2().setContent(description2)
2316
2276
  ).addSeparatorComponents(this.separator());
2317
2277
  }
2318
2278
  /**
2319
2279
  * Creates error ComponentV2
2320
2280
  */
2321
- static error(description) {
2281
+ static error(description2) {
2322
2282
  return this.create({ title: "Something went wrong", color: 8912917 /* error */ }).addTextDisplayComponents(
2323
- new TextDisplayBuilder().setContent(description)
2283
+ new TextDisplayBuilder2().setContent(description2)
2324
2284
  ).addSeparatorComponents(this.separator());
2325
2285
  }
2326
2286
  static separator(spacing = SeparatorSpacingSize.Small) {
@@ -2330,13 +2290,13 @@ var ComponentManager = class {
2330
2290
  * Quick field adder
2331
2291
  */
2332
2292
  static fieldAddText(container, options) {
2333
- options.name && container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`__**${options.name}**__`));
2334
- options.value && container.addTextDisplayComponents(new TextDisplayBuilder().setContent(options.value));
2293
+ options.name && container.addTextDisplayComponents(new TextDisplayBuilder2().setContent(`__**${options.name}**__`));
2294
+ options.value && container.addTextDisplayComponents(new TextDisplayBuilder2().setContent(options.value));
2335
2295
  }
2336
2296
  static field(container, field) {
2337
2297
  const hasText = ("name" in field || "value" in field) && (field.name || field.value);
2338
2298
  if ("button" in field && Array.isArray(field.button) && field.button.length > 0) {
2339
- const actionRow = new ActionRowBuilder4().addComponents(field.button);
2299
+ const actionRow = new ActionRowBuilder3().addComponents(field.button);
2340
2300
  if (hasText) this.fieldAddText(container, { name: field.name, value: field.value });
2341
2301
  container.addActionRowComponents(actionRow);
2342
2302
  } else if ("button" in field && !Array.isArray(field.button) || "thumbnailUrl" in field) {
@@ -2351,7 +2311,7 @@ var ComponentManager = class {
2351
2311
  container.addSectionComponents(section);
2352
2312
  } else {
2353
2313
  if ("button" in field && !Array.isArray(field.button)) {
2354
- const actionRow = new ActionRowBuilder4().addComponents(field.button);
2314
+ const actionRow = new ActionRowBuilder3().addComponents(field.button);
2355
2315
  container.addActionRowComponents(actionRow);
2356
2316
  }
2357
2317
  }
@@ -2420,11 +2380,14 @@ var ComponentManager = class {
2420
2380
  });
2421
2381
  return { container, files };
2422
2382
  }
2383
+ /**
2384
+ * Returns a copy with the footer, so calling toMessage() / toInteraction() twice on the same
2385
+ * container doesn't stack footers
2386
+ */
2423
2387
  static footer(container) {
2424
- container.addTextDisplayComponents(
2425
- new TextDisplayBuilder().setContent(`-# **${Bot.config?.botName || "Bot"} \xB7 <t:${Math.floor(Date.now() / 1e3)}:d> <t:${Math.floor(Date.now() / 1e3)}:t>**`)
2388
+ return new ContainerBuilder2(container.toJSON()).addTextDisplayComponents(
2389
+ new TextDisplayBuilder2().setContent(`-# **${Bot.config?.botName || "Bot"} \xB7 <t:${Math.floor(Date.now() / 1e3)}:d> <t:${Math.floor(Date.now() / 1e3)}:t>**`)
2426
2390
  );
2427
- return container;
2428
2391
  }
2429
2392
  /**
2430
2393
  * Transform ComponentV2 into object for channel.send()
@@ -2434,7 +2397,7 @@ var ComponentManager = class {
2434
2397
  */
2435
2398
  static toMessage(container, file = null, footer = true) {
2436
2399
  if (footer) {
2437
- this.footer(container);
2400
+ container = this.footer(container);
2438
2401
  }
2439
2402
  if (file) {
2440
2403
  return {
@@ -2448,13 +2411,13 @@ var ComponentManager = class {
2448
2411
  flags: [MessageFlags5.IsComponentsV2]
2449
2412
  };
2450
2413
  }
2451
- static toInteraction(container, file = null, footer = true) {
2414
+ static toInteraction(container, file = null, footer = true, ephemeral = false) {
2452
2415
  if (footer) {
2453
- this.footer(container);
2416
+ container = this.footer(container);
2454
2417
  }
2455
2418
  const base = {
2456
2419
  components: [container],
2457
- flags: [MessageFlags5.IsComponentsV2]
2420
+ flags: ephemeral ? [MessageFlags5.IsComponentsV2, MessageFlags5.Ephemeral] : [MessageFlags5.IsComponentsV2]
2458
2421
  };
2459
2422
  if (file) {
2460
2423
  return {
@@ -2464,12 +2427,16 @@ var ComponentManager = class {
2464
2427
  }
2465
2428
  return base;
2466
2429
  }
2467
- static toInteractionEdit(container, file = null, footer = true) {
2430
+ /**
2431
+ * Options to edit an existing message : message.edit(). The Components V2 flag is set, so a legacy message can be turned into a V2 one
2432
+ */
2433
+ static toMessageUpdate(container, file = null, footer = true) {
2468
2434
  if (footer) {
2469
- this.footer(container);
2435
+ container = this.footer(container);
2470
2436
  }
2471
2437
  const base = {
2472
- components: [container]
2438
+ components: [container],
2439
+ flags: [MessageFlags5.IsComponentsV2]
2473
2440
  };
2474
2441
  if (file) {
2475
2442
  return {
@@ -2479,10 +2446,16 @@ var ComponentManager = class {
2479
2446
  }
2480
2447
  return base;
2481
2448
  }
2449
+ /**
2450
+ * Options for interaction.update() and interaction.editReply() (buttons, select menus, modals, deferred replies), with the Components V2 flag
2451
+ */
2452
+ static toInteractionUpdate(container, file = null, footer = true) {
2453
+ return this.toMessageUpdate(container, file, footer);
2454
+ }
2482
2455
  };
2483
2456
 
2484
2457
  // src/manager/messages/ChartManager.ts
2485
- import { TextDisplayBuilder as TextDisplayBuilder2 } from "discord.js";
2458
+ import { TextDisplayBuilder as TextDisplayBuilder3 } from "discord.js";
2486
2459
  var SPARK_BLOCKS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
2487
2460
  var DEFAULT_MAX_POINTS = 50;
2488
2461
  var EMPTY = "\u2014";
@@ -2492,7 +2465,7 @@ var ChartManager = class _ChartManager {
2492
2465
  */
2493
2466
  static progressBar(label, value, max = 100, options = {}) {
2494
2467
  const line = `${label} : ${_ChartManager.renderBar(value, max, options)}`;
2495
- return new TextDisplayBuilder2().setContent(_ChartManager.wrap(line, options.codeBlock));
2468
+ return new TextDisplayBuilder3().setContent(_ChartManager.wrap(line, options.codeBlock));
2496
2469
  }
2497
2470
  /**
2498
2471
  * Several gauges in ONE TextDisplay, so a dashboard of 6 metrics still costs 1 component.
@@ -2504,7 +2477,7 @@ var ChartManager = class _ChartManager {
2504
2477
  const opts = { ...options, ...row.options };
2505
2478
  return `${row.label.padEnd(width, " ")} : ${_ChartManager.renderBar(row.value, row.max ?? 100, opts)}`;
2506
2479
  });
2507
- return new TextDisplayBuilder2().setContent(_ChartManager.wrap(lines.join("\n"), options.codeBlock));
2480
+ return new TextDisplayBuilder3().setContent(_ChartManager.wrap(lines.join("\n"), options.codeBlock));
2508
2481
  }
2509
2482
  /**
2510
2483
  * A one line curve : `RAM : ▁▂▃▅▇█▆▄▃▂▁ 62 %`. One block character per point, the last
@@ -2512,7 +2485,7 @@ var ChartManager = class _ChartManager {
2512
2485
  */
2513
2486
  static sparkline(label, values, options = {}) {
2514
2487
  const line = `${label} : ${_ChartManager.renderSpark(values, options)}`;
2515
- return new TextDisplayBuilder2().setContent(_ChartManager.wrap(line, options.codeBlock));
2488
+ return new TextDisplayBuilder3().setContent(_ChartManager.wrap(line, options.codeBlock));
2516
2489
  }
2517
2490
  /**
2518
2491
  * Several curves in ONE TextDisplay, the sparkline counterpart of progressBars().
@@ -2525,7 +2498,7 @@ var ChartManager = class _ChartManager {
2525
2498
  const opts = { ...base, ...row.options };
2526
2499
  return `${row.label.padEnd(width, " ")} : ${_ChartManager.renderSpark(row.values, opts)}`;
2527
2500
  });
2528
- return new TextDisplayBuilder2().setContent(_ChartManager.wrap(lines.join("\n"), options.codeBlock));
2501
+ return new TextDisplayBuilder3().setContent(_ChartManager.wrap(lines.join("\n"), options.codeBlock));
2529
2502
  }
2530
2503
  /**
2531
2504
  * Only fills the bounds that were not given explicitly, and only when asked : a row
@@ -2590,12 +2563,15 @@ var ChartManager = class _ChartManager {
2590
2563
  import {
2591
2564
  ButtonBuilder as ButtonBuilder2,
2592
2565
  ButtonStyle,
2593
- ActionRowBuilder as ActionRowBuilder5,
2566
+ ActionRowBuilder as ActionRowBuilder4,
2594
2567
  MessageFlags as MessageFlags6
2595
2568
  } from "discord.js";
2596
2569
  var ButtonManager = class _ButtonManager {
2597
2570
  static create(options) {
2598
- const btn = new ButtonBuilder2().setCustomId(options.customId).setLabel(options.label ?? "Button").setStyle(options.style).setDisabled(options.disabled ?? false);
2571
+ const btn = new ButtonBuilder2().setCustomId(options.customId).setStyle(options.style).setDisabled(options.disabled ?? false);
2572
+ if (options.label || !options.emoji) {
2573
+ btn.setLabel(options.label ?? "Button");
2574
+ }
2599
2575
  if (options.emoji) {
2600
2576
  btn.setEmoji(options.emoji);
2601
2577
  }
@@ -2626,7 +2602,7 @@ var ButtonManager = class _ButtonManager {
2626
2602
  }
2627
2603
  static row(but) {
2628
2604
  const buttons = Array.isArray(but) ? but.slice(0, 5) : [but];
2629
- return new ActionRowBuilder5().addComponents(buttons);
2605
+ return new ActionRowBuilder4().addComponents(buttons);
2630
2606
  }
2631
2607
  static toMessage(button) {
2632
2608
  return {
@@ -2639,37 +2615,155 @@ var ButtonManager = class _ButtonManager {
2639
2615
  flags: ephemeral ? [MessageFlags6.Ephemeral] : []
2640
2616
  };
2641
2617
  }
2642
- static toInteractionEdit(button) {
2618
+ /**
2619
+ * Options to edit an existing message : message.edit()
2620
+ */
2621
+ static toMessageUpdate(button) {
2643
2622
  return {
2644
2623
  components: this.createRowsToReturn(button)
2645
2624
  };
2646
2625
  }
2626
+ /**
2627
+ * Options for interaction.update() and interaction.editReply() (buttons, select menus, modals, deferred replies)
2628
+ */
2629
+ static toInteractionUpdate(button) {
2630
+ return this.toMessageUpdate(button);
2631
+ }
2632
+ /**
2633
+ * Consecutive buttons are grouped by 5 in the same row (like row() does), action rows are kept as is
2634
+ */
2647
2635
  static createRowsToReturn(button) {
2648
- if (Array.isArray(button)) {
2649
- return button.map(
2650
- (btn) => btn instanceof ActionRowBuilder5 ? btn : _ButtonManager.row(btn)
2651
- );
2636
+ const items = Array.isArray(button) ? button : [button];
2637
+ const rows = [];
2638
+ let pending = [];
2639
+ const flush = () => {
2640
+ for (let i = 0; i < pending.length; i += 5) {
2641
+ rows.push(_ButtonManager.row(pending.slice(i, i + 5)));
2642
+ }
2643
+ pending = [];
2644
+ };
2645
+ for (const item of items) {
2646
+ if (item instanceof ActionRowBuilder4) {
2647
+ flush();
2648
+ rows.push(item);
2649
+ } else {
2650
+ pending.push(item);
2651
+ }
2652
+ }
2653
+ flush();
2654
+ return rows;
2655
+ }
2656
+ };
2657
+
2658
+ // src/manager/interactible/PaginationManager.ts
2659
+ import {
2660
+ ActionRowBuilder as ActionRowBuilder5,
2661
+ ComponentType,
2662
+ MessageFlags as MessageFlags7
2663
+ } from "discord.js";
2664
+ import { Log as Log18 } from "@spatulox/utils";
2665
+ var PaginationManager = class {
2666
+ /**
2667
+ * Reply to the interaction (or edit the deferred reply) with the first page and navigation buttons.
2668
+ * Only the user who triggered the interaction can navigate, and the buttons are disabled when the
2669
+ * collector ends.
2670
+ */
2671
+ static async send(interaction, pages, options = {}) {
2672
+ if (pages.length === 0) {
2673
+ Log18.error("PaginationManager: at least one page is required");
2674
+ return null;
2675
+ }
2676
+ const prefix = `pag_${interaction.id}_`;
2677
+ let currentPage = 0;
2678
+ const payload = (disabled = false) => {
2679
+ const page = pages[currentPage];
2680
+ return {
2681
+ content: page.content ?? "",
2682
+ embeds: [page.embed],
2683
+ components: [this.row(prefix, currentPage, pages.length, disabled)]
2684
+ };
2685
+ };
2686
+ let message;
2687
+ if (interaction.deferred || interaction.replied) {
2688
+ message = await interaction.editReply(payload());
2689
+ } else {
2690
+ const response = await interaction.reply({
2691
+ ...payload(),
2692
+ flags: options.ephemeral ? [MessageFlags7.Ephemeral] : [],
2693
+ withResponse: true
2694
+ });
2695
+ message = response.resource?.message ?? await interaction.fetchReply();
2652
2696
  }
2653
- return button instanceof ActionRowBuilder5 ? [button] : [_ButtonManager.row(button)];
2697
+ const collector = message.createMessageComponentCollector({
2698
+ componentType: ComponentType.Button,
2699
+ filter: (i) => i.customId.startsWith(prefix),
2700
+ time: options.time ?? 6e4,
2701
+ idle: options.idle ?? 15e3
2702
+ });
2703
+ collector.on("collect", async (i) => {
2704
+ try {
2705
+ if (i.user.id !== interaction.user.id) {
2706
+ await i.reply({ content: "Only the user who opened this pagination can use it", flags: [MessageFlags7.Ephemeral] });
2707
+ return;
2708
+ }
2709
+ switch (i.customId.slice(prefix.length)) {
2710
+ case "first":
2711
+ currentPage = 0;
2712
+ break;
2713
+ case "prev":
2714
+ currentPage = Math.max(0, currentPage - 1);
2715
+ break;
2716
+ case "next":
2717
+ currentPage = Math.min(pages.length - 1, currentPage + 1);
2718
+ break;
2719
+ case "last":
2720
+ currentPage = pages.length - 1;
2721
+ break;
2722
+ }
2723
+ await i.update(payload());
2724
+ } catch (error) {
2725
+ Log18.error(`PaginationManager: failed to update the page: ${error}`);
2726
+ }
2727
+ });
2728
+ collector.on("end", async () => {
2729
+ await interaction.editReply({ components: [this.row(prefix, currentPage, pages.length, true)] }).catch((error) => Log18.warn(`PaginationManager: failed to disable the buttons: ${error}`));
2730
+ });
2731
+ return collector;
2732
+ }
2733
+ static row(prefix, currentPage, pageCount, disabled) {
2734
+ const isFirst = currentPage === 0;
2735
+ const isLast = currentPage === pageCount - 1;
2736
+ return new ActionRowBuilder5().addComponents(
2737
+ ButtonManager.secondary({ customId: `${prefix}first`, emoji: "\u23EA", disabled: disabled || isFirst }),
2738
+ ButtonManager.secondary({ customId: `${prefix}prev`, emoji: "\u2B05\uFE0F", disabled: disabled || isFirst }),
2739
+ // Page indicator only : always disabled, it can't be clicked
2740
+ ButtonManager.secondary({ customId: `${prefix}page`, label: `${currentPage + 1}/${pageCount}`, disabled: true }),
2741
+ ButtonManager.secondary({ customId: `${prefix}next`, emoji: "\u27A1\uFE0F", disabled: disabled || isLast }),
2742
+ ButtonManager.secondary({ customId: `${prefix}last`, emoji: "\u23E9", disabled: disabled || isLast })
2743
+ );
2654
2744
  }
2655
2745
  };
2656
2746
 
2657
2747
  // src/index.ts
2658
2748
  import { Time as Time3 } from "@spatulox/utils";
2659
- import { Log as Log18 } from "@spatulox/utils";
2749
+ import { Log as Log19 } from "@spatulox/utils";
2660
2750
  import { SimpleMutex } from "@spatulox/utils";
2661
2751
 
2662
2752
  // src/constants/DiscordRegex.ts
2663
- var DiscordRegex = class {
2753
+ var DiscordRegex = class _DiscordRegex {
2664
2754
  // Caractères spéciaux
2665
2755
  static SPACE = "\u200B";
2666
2756
  // URLs basiques
2667
2757
  static URL_REGEX = /(https?:\/\/[^\s<>]+)/i;
2758
+ // URL on a Discord domain (discord.com, discord.gg, discordapp.com, cdn.discordapp.com, discord.media...)
2759
+ static DISCORD_URL = /^https?:\/\/(?:[\w-]+\.)*(?:discord\.com|discord\.gg|discordapp\.com|discordapp\.net|discord\.media)(?:[\/?#]\S*)?$/i;
2668
2760
  /* DISCORD REGEX */
2669
- static USER_REGEX = /<@\d{18}>/;
2670
- static BOT_REGEX = /<@\d{19}>/;
2671
- static CHANNEL_REGEX = /(<#\d{19}>)|(<id:(browse|customize|guide)>)/;
2672
- static ROLE_REGEX = /<@&\d{19}>/;
2761
+ // Snowflakes (user, bot, channel, role, guild ids) are 17 to 20 digits long, their length says nothing about their type
2762
+ static USER_REGEX = /<@!?\d{17,20}>/;
2763
+ /** @deprecated A bot mention can't be told apart from a user mention : same as USER_REGEX */
2764
+ static BOT_REGEX = _DiscordRegex.USER_REGEX;
2765
+ static CHANNEL_REGEX = /(<#\d{17,20}>)|(<id:(browse|customize|guide)>)/;
2766
+ static ROLE_REGEX = /<@&\d{17,20}>/;
2673
2767
  /**
2674
2768
  * Mention a User
2675
2769
  * Mention a Role
@@ -2686,32 +2780,33 @@ var DiscordRegex = class {
2686
2780
  `(${this.DISCORD_PING_REGEX.source})|(${this.CHANNEL_REGEX.source})`
2687
2781
  );
2688
2782
  // ID Discord (user, channel guild)
2689
- static USER_ID = /^[0-9]{18}$/;
2690
- static CHANNEL_ID = /^[0-9]{18}$/;
2691
- static GUILD_ID = /^[0-9]{19}$/;
2692
- static BOT_ID = /^[0-9]{19}$/;
2783
+ static SNOWFLAKE = /^[0-9]{17,20}$/;
2784
+ static USER_ID = _DiscordRegex.SNOWFLAKE;
2785
+ static CHANNEL_ID = _DiscordRegex.SNOWFLAKE;
2786
+ static GUILD_ID = _DiscordRegex.SNOWFLAKE;
2787
+ static BOT_ID = _DiscordRegex.SNOWFLAKE;
2693
2788
  // Username Discord (2-32 caractères alphanumériques + _ .)
2694
- static USERNAME = /^[a-zA-Z0-9_]{2,32}$/;
2789
+ static USERNAME = /^[a-zA-Z0-9_.]{2,32}$/;
2695
2790
  // Username + discrim (ancien format)
2696
2791
  static USERNAME_DISCRIM = /^[a-zA-Z0-9_]{2,32}#\d{4}$/;
2697
2792
  // Channel mention <#123456789012345678>
2698
- static CHANNEL_MENTION = /^<#([0-9]{18})>$/;
2793
+ static CHANNEL_MENTION = /^<#([0-9]{17,20})>$/;
2699
2794
  // User mention <@123456789012345678> ou <@!123456789012345678>
2700
- static USER_MENTION = /^<@!?([0-9]{18})>$/;
2795
+ static USER_MENTION = /^<@!?([0-9]{17,20})>$/;
2701
2796
  // Role mention <@&123456789012345678>
2702
- static ROLE_MENTION = /^<@&([0-9]{18})>$/;
2703
- // URL Invite Discord
2704
- static INVITE = /^discord(?:app\.com\/invite|gg)\/[a-zA-Z0-9]+$/;
2705
- // Emoji Discord (custom or unicode)
2706
- static EMOJI = /^<a?:[a-zA-Z0-9_]{2,32}:[0-9]{18}>$|^[\u{1F300}-\u{1F5FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]+$/u;
2797
+ static ROLE_MENTION = /^<@&([0-9]{17,20})>$/;
2798
+ // URL Invite Discord : discord.gg/code, discord.com/invite/code, discordapp.com/invite/code (with or without https://)
2799
+ static INVITE = /^(?:https?:\/\/)?(?:www\.)?(?:discord\.gg|discord(?:app)?\.com\/invite)\/[a-zA-Z0-9-]+$/i;
2800
+ // Emoji Discord (custom or unicode, skin tones / ZWJ sequences / flags included)
2801
+ static EMOJI = /^<a?:[a-zA-Z0-9_]{2,32}:[0-9]{17,20}>$|^[\p{Extended_Pictographic}\p{Regional_Indicator}][\p{Extended_Pictographic}\p{Regional_Indicator}\p{Emoji_Modifier}\u200D\uFE0F]*$/u;
2707
2802
  /**
2708
- * Validate Discord ID Discord (18)
2803
+ * Validate a Discord ID (snowflake, 17 to 20 digits)
2709
2804
  */
2710
2805
  static isDiscordId(id) {
2711
- return this.USER_ID.test(id) || this.GUILD_ID.test(id) || this.CHANNEL_ID.test(id);
2806
+ return this.SNOWFLAKE.test(id);
2712
2807
  }
2713
2808
  /**
2714
- * Validate a bot ID (19)
2809
+ * @deprecated A bot mention can't be told apart from a user mention : same as isUserMention()
2715
2810
  */
2716
2811
  static isBotMention(mention) {
2717
2812
  return this.BOT_REGEX.test(mention);
@@ -2729,7 +2824,7 @@ var DiscordRegex = class {
2729
2824
  return this.USERNAME.test(username);
2730
2825
  }
2731
2826
  /**
2732
- * Type guard for Discord ID
2827
+ * @deprecated Same as isDiscordId()
2733
2828
  */
2734
2829
  static isDiscordIdType(id) {
2735
2830
  return this.isDiscordId(id);
@@ -2738,7 +2833,7 @@ var DiscordRegex = class {
2738
2833
  * Any Discord URL
2739
2834
  */
2740
2835
  static isDiscordUrl(url) {
2741
- return this.URL_REGEX.test(url) || this.INVITE.test(url);
2836
+ return this.DISCORD_URL.test(url) || this.INVITE.test(url);
2742
2837
  }
2743
2838
  /**
2744
2839
  * Any discord mention
@@ -2753,15 +2848,18 @@ var DiscordRegex = class {
2753
2848
  return {
2754
2849
  SPACE: this.SPACE,
2755
2850
  URL_REGEX: this.URL_REGEX,
2851
+ DISCORD_URL: this.DISCORD_URL,
2756
2852
  USER_REGEX: this.USER_REGEX,
2757
2853
  BOT_REGEX: this.BOT_REGEX,
2758
2854
  CHANNEL_REGEX: this.CHANNEL_REGEX,
2759
2855
  ROLE_REGEX: this.ROLE_REGEX,
2760
2856
  DISCORD_PING_REGEX: this.DISCORD_PING_REGEX,
2761
2857
  DISCORD_MENTION_REGEX: this.DISCORD_MENTION_REGEX,
2858
+ SNOWFLAKE: this.SNOWFLAKE,
2762
2859
  USER_ID: this.USER_ID,
2763
2860
  CHANNEL_ID: this.CHANNEL_ID,
2764
2861
  GUILD_ID: this.GUILD_ID,
2862
+ BOT_ID: this.BOT_ID,
2765
2863
  USERNAME: this.USERNAME,
2766
2864
  USERNAME_DISCRIM: this.USERNAME_DISCRIM,
2767
2865
  CHANNEL_MENTION: this.CHANNEL_MENTION,
@@ -2783,9 +2881,10 @@ export {
2783
2881
  EmbedManager,
2784
2882
  FileManager,
2785
2883
  GuildManager,
2786
- Log18 as Log,
2884
+ Log19 as Log,
2787
2885
  ModalFieldType,
2788
2886
  ModalManager,
2887
+ PaginationManager,
2789
2888
  ReactionManager,
2790
2889
  SelectMenuManager,
2791
2890
  SimpleColor,