@spatulox/simplediscordbot 3.1.2 → 4.0.0

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