generated from sapphiredev/sapphire-template
/
PaginatedMessage.ts
1525 lines (1388 loc) · 55.3 KB
/
PaginatedMessage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Time } from '@sapphire/time-utilities';
import { deepClone, isFunction, isNullish, isObject } from '@sapphire/utilities';
import type { APIMessage } from 'discord-api-types/v9';
import {
Constants,
Formatters,
Intents,
InteractionCollector,
MessageButton,
MessageEmbed,
MessageSelectMenu,
type ButtonInteraction,
type Collection,
type CommandInteraction,
type ContextMenuInteraction,
type Message,
type MessageComponentInteraction,
type MessageOptions,
type SelectMenuInteraction,
type Snowflake,
type TextBasedChannel,
type User,
type WebhookEditMessageOptions
} from 'discord.js';
import { deprecate } from 'node:util';
import { MessageBuilder } from '../builders/MessageBuilder';
import { isGuildBasedChannel, isMessageInstance } from '../type-guards';
import type {
PaginatedMessageAction,
PaginatedMessageEmbedResolvable,
PaginatedMessageInternationalizationContext,
PaginatedMessageMessageOptionsUnion,
PaginatedMessageOptions,
PaginatedMessagePage,
PaginatedMessageSelectMenuOptionsFunction,
PaginatedMessageWrongUserInteractionReplyFunction
} from './PaginatedMessageTypes';
import { actionIsButtonOrMenu, createPartitionedMessageRow, isMessageButtonInteraction, runsOnInteraction, safelyReplyToInteraction } from './utils';
/**
* This is a {@link PaginatedMessage}, a utility to paginate messages (usually embeds).
* You must either use this class directly or extend it.
*
* @remark Please note that for {@link PaginatedMessage} to work in DMs to your client, you need to add the `'CHANNEL'` partial to your `client.options.partials`.
* Message based commands can always be used in DMs, whereas Chat Input interactions can only be used in DMs when they are registered globally.
*
* {@link PaginatedMessage} uses {@linkplain https://discord.js.org/#/docs/main/stable/typedef/MessageComponent MessageComponent} buttons that perform the specified action when clicked.
* You can either use your own actions or the {@link PaginatedMessage.defaultActions}.
* {@link PaginatedMessage.defaultActions} is also static so you can modify these directly.
*
* {@link PaginatedMessage} also uses pages via {@linkplain https://discord.js.org/#/docs/main/stable/class/Message Messages}.
*
* @example
* ```typescript
* const myPaginatedMessage = new PaginatedMessage();
* // Once you have an instance of PaginatedMessage you can call various methods on it to add pages to it.
* // For more details see each method's documentation.
*
* myPaginatedMessage.addPageEmbed((embed) => {
* embed
* .setColor('#FF0000')
* .setDescription('example description');
*
* return embed;
* });
*
* myPaginatedMessage.addPageBuilder((builder) => {
* const embed = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description');
*
* return builder
* .setContent('example content')
* .setEmbeds([embed]);
* });
*
* myPaginatedMessage.addPageContent('Example');
*
* myPaginatedMessage.run(message)
* ```
*
* @remark You can also provide a MessageEmbed template. This will be applied to every page.
* If a page itself has an embed then the two will be merged, with the content of
* the page's embed taking priority over the template.
*
* Furthermore, if the template has a footer then it will be applied _after_ the page index part of the footer
* with a space preceding the template. For example, when setting `- Powered by Sapphire Framework`
* the resulting footer will be `1/2 - Powered by Sapphire Framework`
* @example
* ```typescript
* const myPaginatedMessage = new PaginatedMessage({
* template: new MessageEmbed().setColor('#FF0000').setFooter('- Powered by Sapphire framework')
* });
* ```
*
* @remark To utilize actions you can implement IPaginatedMessageAction into a class.
* @example
* ```typescript
* class ForwardAction implements IPaginatedMessageAction {
* public id = '▶️';
*
* public run({ handler }) {
* if (handler.index !== handler.pages.length - 1) ++handler.index;
* }
* }
*
* // You can also give the object directly.
*
* const StopAction: IPaginatedMessageAction = {
* customId: 'CustomStopAction',
* run: ({ collector }) => {
* collector.stop();
* }
* }
* ```
*/
export class PaginatedMessage {
/** The response we send when someone gets into an invalid flow */
#thisMazeWasNotMeantForYouContent = { content: "This maze wasn't meant for you...what did you do." };
// #region public class properties
/**
* The pages to be converted to {@link PaginatedMessage.messages}
*/
public pages: PaginatedMessagePage[];
/**
* The response message used to edit on page changes.
*/
public response: APIMessage | Message | CommandInteraction | ContextMenuInteraction | SelectMenuInteraction | ButtonInteraction | null = null;
/**
* The collector used for handling component interactions.
*/
public collector: InteractionCollector<MessageComponentInteraction> | null = null;
/**
* The pages which were converted from {@link PaginatedMessage.pages}
*/
public messages: (PaginatedMessagePage | null)[] = [];
/**
* The actions which are to be used.
*/
public actions = new Map<string, PaginatedMessageAction>();
/**
* The handler's current page/message index.
*/
public index = 0;
/**
* The amount of milliseconds to idle before the paginator is closed.
* @default 14.5 minutes
* @remark This is to ensure it is a bit before interactions expire.
*/
public idle = Time.Minute * 14.5;
/**
* The template for this {@link PaginatedMessage}.
* You can use templates to set defaults that will apply to each and every page in the {@link PaginatedMessage}
*/
public template: PaginatedMessageMessageOptionsUnion;
/**
* Custom text to show in front of the page index in the embed footer.
* PaginatedMessage will automatically add a space (` `) after the given text. You do not have to add it yourself.
* @default ```PaginatedMessage.pageIndexPrefix``` (static property)
*/
public pageIndexPrefix = PaginatedMessage.pageIndexPrefix;
/**
* Custom separator to show after the page index in the embed footer.
* PaginatedMessage will automatically add a space (` `) after the given text. You do not have to add it yourself.
* @default ```PaginatedMessage.embedFooterSeparator``` (static property)
*/
public embedFooterSeparator = PaginatedMessage.embedFooterSeparator;
/**
* A list of `customId` that are bound to actions that will stop the {@link PaginatedMessage}
* @default ```PaginatedMessage.stopPaginatedMessageCustomIds``` (static property)
*/
public stopPaginatedMessageCustomIds = PaginatedMessage.stopPaginatedMessageCustomIds;
/**
* Whether to emit the warning about running a {@link PaginatedMessage} in a DM channel without the client having the `'CHANNEL'` partial.
* @remark When using message based commands (as opposed to Application Commands) then you will also need to specify the `DIRECT_MESSAGE` intent for {@link PaginatedMessage} to work.
*
* @default ```PaginatedMessage.emitPartialDMChannelWarning``` (static property)
*/
public emitPartialDMChannelWarning = PaginatedMessage.emitPartialDMChannelWarning;
// #endregion
// #region protected class properties
protected paginatedMessageData: Omit<PaginatedMessageMessageOptionsUnion, 'components'> | null = null;
protected selectMenuOptions: PaginatedMessageSelectMenuOptionsFunction = PaginatedMessage.selectMenuOptions;
protected selectMenuPlaceholder: string | undefined = undefined;
protected wrongUserInteractionReply: PaginatedMessageWrongUserInteractionReplyFunction = PaginatedMessage.wrongUserInteractionReply;
/**
* Tracks whether a warning was already emitted for this {@link PaginatedMessage}
* concerning the maximum amount of pages in the {@link SelectMenu}.
*/
protected hasEmittedMaxPageWarning = false;
/**
* Tracks whether a warning was already emitted for this {@link PaginatedMessage}
* concerning the {@link PaginatedMessage} being called in a `DMChannel`
* without the client having the `'Channel'` partial.
*
* @remark When using message based commands (as opposed to Application Commands) then you will also need to specify the `DIRECT_MESSAGE` intent for {@link PaginatedMessage} to work.
*/
protected hasEmittedPartialDMChannelWarning = false;
// #endregion
/**
* Constructor for the {@link PaginatedMessage} class
* @param __namedParameters The {@link PaginatedMessageOptions} for this instance of the {@link PaginatedMessage} class
*/
public constructor({
pages,
actions,
template,
pageIndexPrefix,
embedFooterSeparator,
paginatedMessageData = null
}: PaginatedMessageOptions = {}) {
this.pages = pages ?? [];
for (const page of this.pages) {
if (isFunction(page) || isObject(page)) {
this.messages.push(page);
}
}
for (const action of actions ?? this.constructor.defaultActions) {
if (actionIsButtonOrMenu(action)) {
this.actions.set(action.customId, action);
} else {
this.actions.set(action.url, action);
}
}
this.template = PaginatedMessage.resolveTemplate(template);
this.pageIndexPrefix = pageIndexPrefix ?? PaginatedMessage.pageIndexPrefix;
this.embedFooterSeparator = embedFooterSeparator ?? PaginatedMessage.embedFooterSeparator;
this.paginatedMessageData = paginatedMessageData;
}
// #region property setters
/**
* Sets the {@link PaginatedMessage.selectMenuOptions} for this instance of {@link PaginatedMessage}.
* This will only apply to this one instance and no others.
* @param newOptions The new options generator to set
* @returns The current instance of {@link PaginatedMessage}
*/
public setSelectMenuOptions(newOptions: PaginatedMessageSelectMenuOptionsFunction): this {
this.selectMenuOptions = newOptions;
return this;
}
/**
* Sets the {@link PaginatedMessage.selectMenuPlaceholder} for this instance of {@link PaginatedMessage}.
* This will only apply to this one instance and no others.
* @param placeholder The new placeholder to set
* @returns The current instance of {@link PaginatedMessage}
*/
public setSelectMenuPlaceholder(placeholder: string | undefined): this {
this.selectMenuPlaceholder = placeholder;
return this;
}
/**
* Sets the {@link PaginatedMessage.wrongUserInteractionReply} for this instance of {@link PaginatedMessage}.
* This will only apply to this one instance and no others.
* @param wrongUserInteractionReply The new `wrongUserInteractionReply` to set
* @returns The current instance of {@link PaginatedMessage}
*/
public setWrongUserInteractionReply(wrongUserInteractionReply: PaginatedMessageWrongUserInteractionReplyFunction): this {
this.wrongUserInteractionReply = wrongUserInteractionReply;
return this;
}
/**
* Sets the {@link PaginatedMessage.stopPaginatedMessageCustomIds} for this instance of {@link PaginatedMessage}.
* This will only apply to this one instance and no others.
* @param stopPaginatedMessageCustomIds The new `stopPaginatedMessageCustomIds` to set
* @returns The current instance of {@link PaginatedMessage}
*/
public setStopPaginatedMessageCustomIds(stopPaginatedMessageCustomIds: string[]): this {
this.stopPaginatedMessageCustomIds = stopPaginatedMessageCustomIds;
return this;
}
/**
* Sets the {@link PaginatedMessage.emitPartialDMChannelWarning} for this instance of {@link PaginatedMessage}.
* This will only apply to this one instance and no others.
* @param emitPartialDMChannelWarning The new `emitPartialDMChannelWarning` to set
* @returns The current instance of {@link PaginatedMessage}
*/
public setEmitPartialDMChannelWarning(emitPartialDMChannelWarning: boolean): this {
this.emitPartialDMChannelWarning = emitPartialDMChannelWarning;
return this;
}
/**
* Sets the handler's current page/message index.
* @param index The number to set the index to.
*/
public setIndex(index: number): this {
this.index = index;
return this;
}
/**
* Sets the amount of time to idle before the paginator is closed.
* @param idle The number to set the idle to.
*/
public setIdle(idle: number): this {
this.idle = idle;
return this;
}
// #endregion
// #region actions related methods
/**
* Clears all current actions and sets them. The order given is the order they will be used.
* @param actions The actions to set. This can be either a Button, Link Button, or Select Menu.
* @param includeDefaultActions Whether to merge in the {@link PaginatedMessage.defaultActions} when setting the actions.
* If you set this to true then you do not need to manually add `...PaginatedMessage.defaultActions` as seen in the first example.
* The default value is `false` for backwards compatibility within the current major version.
*
* @remark You can retrieve the default actions for the regular pagination
* @example
* ```typescript
* const display = new PaginatedMessage();
*
* display.setActions([
* ...PaginatedMessage.defaultActions,
* ])
* ```
*
* @remark You can add custom Message Buttons by providing `style`, `customId`, `type`, `run` and at least one of `label` or `emoji`.
* @example
* ```typescript
* const display = new PaginatedMessage();
*
* display.setActions([
* {
* style: 'PRIMARY',
* label: 'My Button',
* customId: 'custom_button',
* type: Constants.MessageComponentTypes.BUTTON,
* run: (context) => console.log(context)
* }
* ], true);
* ```
*
* @remark You can add custom Message **Link** Buttons by providing `style`, `url`, `type`, and at least one of `label` or `emoji`.
* @example
* ```typescript
* const display = new PaginatedMessage();
*
* display.setActions([
* {
* style: 'LINK',
* label: 'Sapphire Website',
* emoji: '🔷',
* url: 'https://sapphirejs.dev',
* type: Constants.MessageComponentTypes.BUTTON
* }
* ], true);
* ```
*
* @remark You can add custom Select Menus by providing `customId`, `type`, and `run`.
* @example
* ```typescript
* const display = new PaginatedMessage();
*
* display.setActions([
* {
* customId: 'custom_menu',
* type: Constants.MessageComponentTypes.SELECT_MENU,
* run: (context) => console.log(context) // Do something here
* }
* ], true);
* ```
*/
public setActions(actions: PaginatedMessageAction[], includeDefaultActions = false): this {
this.actions.clear();
return this.addActions([...(includeDefaultActions ? PaginatedMessage.defaultActions : []), ...actions]);
}
/**
* Adds actions to the existing ones. The order given is the order they will be used.
* @param actions The actions to add.
* @see {@link PaginatedMessage.setActions} for examples on how to structure the actions.
*/
public addActions(actions: PaginatedMessageAction[]): this {
for (const action of actions) this.addAction(action);
return this;
}
/**
* Adds an action to the existing ones. This will be added as the last action.
* @param action The action to add.
* @see {@link PaginatedMessage.setActions} for examples on how to structure the action.
*/
public addAction(action: PaginatedMessageAction): this {
if (actionIsButtonOrMenu(action)) {
this.actions.set(action.customId, action);
} else {
this.actions.set(action.url, action);
}
return this;
}
// #endregion
// #region page related methods
/**
* Checks whether or not the handler has a specific page.
* @param index The index to check.
*/
public hasPage(index: number): boolean {
return index >= 0 && index < this.pages.length;
}
/**
* Clears all current pages and messages and sets them. The order given is the order they will be used.
* @param pages The pages to set.
*/
public setPages(pages: PaginatedMessagePage[]) {
this.pages = [];
this.messages = [];
this.addPages(pages);
return this;
}
/**
* Adds a page to the existing ones. This will be added as the last page.
* @remark While you can use this method you should first check out
* {@link PaginatedMessage.addPageBuilder},
* {@link PaginatedMessage.addPageContent} and
* {@link PaginatedMessage.addPageEmbed} as
* these are easier functional methods of adding pages and will likely already suffice for your needs.
*
* @param page The page to add.
*/
public addPage(page: PaginatedMessagePage): this {
// Do not allow more than 25 pages, and send a warning when people try to do so.
if (this.pages.length === 25) {
if (!this.hasEmittedMaxPageWarning) {
process.emitWarning(
'Maximum amount of pages exceeded for PaginatedMessage. Please check your instance of PaginatedMessage and ensure that you do not exceed 25 pages total.',
{
type: 'PaginatedMessageExceededMessagePageAmount',
code: 'PAGINATED_MESSAGE_EXCEEDED_MAXIMUM_AMOUNT_OF_PAGES',
detail: `If you do need more than 25 pages you can extend the class and overwrite the actions in the constructor.`
}
);
this.hasEmittedMaxPageWarning = true;
}
return this;
}
this.pages.push(page);
return this;
}
/**
* Adds a page to the existing ones using a {@link MessageBuilder}. This will be added as the last page.
* @param builder Either a callback whose first parameter is `new MessageBuilder()`, or an already constructed {@link MessageBuilder}
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
* const { MessageEmbed } = require('discord.js');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageBuilder((builder) => {
* const embed = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description');
*
* return builder
* .setContent('example content')
* .setEmbeds([embed]);
* });
* ```
* @example
* ```typescript
* const { MessageEmbed } = require('discord.js');
* const { MessageBuilder, PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const embed = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description');
*
* const builder = new MessageBuilder()
* .setContent('example content')
* .setEmbeds([embed]);
*
* const paginatedMessage = new PaginatedMessage()
* .addPageBuilder(builder);
* ```
*/
public addPageBuilder(builder: MessageBuilder | ((builder: MessageBuilder) => MessageBuilder)): this {
return this.addPage(isFunction(builder) ? builder(new MessageBuilder()) : builder);
}
/**
* Adds a page to the existing ones asynchronously using a {@link MessageBuilder}. This wil be added as the last page.
* @param builder Either a callback whose first parameter is `new MessageBuilder()`, or an already constructed {@link MessageBuilder}
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
* const { MessageEmbed } = require('discord.js');
*
* const paginatedMessage = new PaginatedMessage()
* .addAsyncPageBuilder(async (builder) => {
* const someRemoteData = await fetch('https://contoso.com/api/users');
*
* const embed = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription(someRemoteData.data);
*
* return builder
* .setContent('example content')
* .setEmbeds([embed]);
* });
* ```
*/
public addAsyncPageBuilder(builder: MessageBuilder | ((builder: MessageBuilder) => Promise<MessageBuilder>)): this {
return this.addPage(async () => (isFunction(builder) ? builder(new MessageBuilder()) : builder));
}
/**
* Adds a page to the existing ones using simple message content. This will be added as the last page.
* @param content The content to set.
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageContent('example content');
* ```
*/
public addPageContent(content: string): this {
return this.addPage({ content });
}
/**
* Adds a page to the existing ones using a {@link MessageEmbed}. This wil be added as the last page.
* @param embed Either a callback whose first parameter is `new MessageEmbed()`, or an already constructed {@link MessageEmbed}
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageEmbed((embed) => {
* embed
* .setColor('#FF0000')
* .setDescription('example description');
*
* return embed;
* });
* ```
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const embed = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageEmbed(embed);
* ```
*/
public addPageEmbed(embed: MessageEmbed | ((embed: MessageEmbed) => MessageEmbed)): this {
return this.addPage({ embeds: isFunction(embed) ? [embed(new MessageEmbed())] : [embed] });
}
/**
* Adds a page to the existing ones asynchronously using a {@link MessageEmbed}. This wil be added as the last page.
* @param embed Either a callback whose first parameter is `new MessageEmbed()`, or an already constructed {@link MessageEmbed}
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const paginatedMessage = new PaginatedMessage()
* .addAsyncPageEmbed(async (embed) => {
* const someRemoteData = await fetch('https://contoso.com/api/users');
*
* embed
* .setColor('#FF0000')
* .setDescription(someRemoteData.data);
*
* return embed;
* });
* ```
*/
public addAsyncPageEmbed(embed: MessageEmbed | ((builder: MessageEmbed) => Promise<MessageEmbed>)): this {
return this.addPage(async () => ({ embeds: isFunction(embed) ? [await embed(new MessageEmbed())] : [embed] }));
}
/**
* Adds a page to the existing ones asynchronously using multiple {@link MessageEmbed}'s. This wil be added as the last page.
* @remark When using this with a callback this will construct 10 {@link MessageEmbed}'s in the callback parameters, regardless of how many are actually used.
* If this a performance impact you do not want to cope with then it is recommended to use {@link PaginatedMessage.addPageBuilder} instead, which will let you add
* as many embeds as you want, albeit manually
* @param embeds Either a callback which receives 10 parameters of `new MessageEmbed()`, or an array of already constructed {@link MessageEmbed}'s
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageEmbeds((embed1, embed2, embed3) => { // You can add up to 10 embeds
* embed1
* .setColor('#FF0000')
* .setDescription('example description 1');
*
* embed2
* .setColor('#00FF00')
* .setDescription('example description 2');
*
* embed3
* .setColor('#0000FF')
* .setDescription('example description 3');
*
* return [embed1, embed2, embed3];
* });
* ```
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const embed1 = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description 1');
*
* const embed2 = new MessageEmbed()
* .setColor('#00FF00')
* .setDescription('example description 2');
*
* const embed3 = new MessageEmbed()
* .setColor('#0000FF')
* .setDescription('example description 3');
*
* const paginatedMessage = new PaginatedMessage()
* .addPageEmbeds([embed1, embed2, embed3]); // You can add up to 10 embeds
* ```
*/
public addPageEmbeds(
embeds:
| MessageEmbed[]
| ((
embed1: MessageEmbed,
embed2: MessageEmbed,
embed3: MessageEmbed,
embed4: MessageEmbed,
embed5: MessageEmbed,
embed6: MessageEmbed,
embed7: MessageEmbed,
embed8: MessageEmbed,
embed9: MessageEmbed,
embed10: MessageEmbed
) => MessageEmbed[])
): this {
let processedEmbeds = isFunction(embeds)
? embeds(
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed()
)
: embeds;
if (processedEmbeds.length > 10) {
processedEmbeds = processedEmbeds.slice(0, 10);
}
return this.addPage({ embeds: processedEmbeds });
}
/**
* Adds a page to the existing ones using multiple {@link MessageEmbed}'s. This wil be added as the last page.
* @remark When using this with a callback this will construct 10 {@link MessageEmbed}'s in the callback parameters, regardless of how many are actually used.
* If this a performance impact you do not want to cope with then it is recommended to use {@link PaginatedMessage.addPageBuilder} instead, which will let you add
* as many embeds as you want, albeit manually
* @param embeds Either a callback which receives 10 parameters of `new MessageEmbed()`, or an array of already constructed {@link MessageEmbed}'s
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const paginatedMessage = new PaginatedMessage().addAsyncPageEmbeds(async (embed0, embed1, embed2) => {
* const someRemoteData = (await fetch('https://contoso.com/api/users')) as any;
*
* for (const [index, user] of Object.entries(someRemoteData.users.slice(0, 10)) as [`${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}`, any][]) {
* switch (index) {
* case '0': {
* embed0.setColor('#FF0000').setDescription('example description 1').setAuthor(user.name);
* break;
* }
* case '1': {
* embed1.setColor('#00FF00').setDescription('example description 2').setAuthor(user.name);
* break;
* }
* case '2': {
* embed2.setColor('#0000FF').setDescription('example description 3').setAuthor(user.name);
* break;
* }
* }
* }
*
* return [embed0, embed1, embed2];
* });
* ```
* @example
* ```typescript
* const { PaginatedMessage } = require('@sapphire/discord.js-utilities');
*
* const embed1 = new MessageEmbed()
* .setColor('#FF0000')
* .setDescription('example description 1');
*
* const embed2 = new MessageEmbed()
* .setColor('#00FF00')
* .setDescription('example description 2');
*
* const embed3 = new MessageEmbed()
* .setColor('#0000FF')
* .setDescription('example description 3');
*
* const paginatedMessage = new PaginatedMessage()
* .addAsyncPageEmbeds([embed1, embed2, embed3]); // You can add up to 10 embeds
* ```
*/
public addAsyncPageEmbeds(
embeds:
| MessageEmbed[]
| ((
embed1: MessageEmbed,
embed2: MessageEmbed,
embed3: MessageEmbed,
embed4: MessageEmbed,
embed5: MessageEmbed,
embed6: MessageEmbed,
embed7: MessageEmbed,
embed8: MessageEmbed,
embed9: MessageEmbed,
embed10: MessageEmbed
) => Promise<MessageEmbed[]>)
): this {
return this.addPage(async () => {
let processedEmbeds = isFunction(embeds)
? await embeds(
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed(),
new MessageEmbed()
)
: embeds;
if (processedEmbeds.length > 10) {
processedEmbeds = processedEmbeds.slice(0, 10);
}
return { embeds: processedEmbeds };
});
}
/**
* Add pages to the existing ones. The order given is the order they will be used.
* @param pages The pages to add.
*/
public addPages(pages: PaginatedMessagePage[]): this {
for (const page of pages) this.addPage(page);
return this;
}
// #endregion
/**
* Executes the {@link PaginatedMessage} and sends the pages corresponding with {@link PaginatedMessage.index}.
* The handler will start collecting message component interactions.
*
* @remark Please note that for {@link PaginatedMessage} to work in DMs to your client, you need to add the `'CHANNEL'` partial to your `client.options.partials`.
* Message based commands can always be used in DMs, whereas Chat Input interactions can only be used in DMs when they are registered globally.
*
* @param messageOrInteraction The message or interaction that triggered this {@link PaginatedMessage}.
* Generally this will be the command message or an interaction
* (either a {@link CommandInteraction}, a {@link ContextMenuInteraction}, a {@link SelectMenuInteraction} or a {@link ButtonInteraction}),
* but it can also be another message from your client, i.e. to indicate a loading state.
*
* @param target The user who will be able to interact with the buttons of this {@link PaginatedMessage}.
* If `messageOrInteraction` is an instance of {@link Message} then this defaults to {@link Message.author messageOrInteraction.author},
* and if it is an instance of {@link CommandInteraction} then it defaults to {@link CommandInteraction.user messageOrInteraction.user}.
*/
public async run(
messageOrInteraction: Message | CommandInteraction | ContextMenuInteraction | SelectMenuInteraction | ButtonInteraction,
target?: User
): Promise<this> {
// If there is no channel then exit early and potentially emit a warning
if (!messageOrInteraction.channel) {
const isInteraction = runsOnInteraction(messageOrInteraction);
let shouldEmitWarning = this.emitPartialDMChannelWarning;
// If we are to emit a warning,
// then check if a warning was already emitted,
// in which case we don't want to emit a warning.
if (shouldEmitWarning && this.hasEmittedPartialDMChannelWarning) {
shouldEmitWarning = false;
}
// If we are to emit a warning,
// then check if the interaction is an interaction based command,
// and check if the client has the `'CHANNEL'` partial,
// in which case we don't want to emit a warning.
if (shouldEmitWarning && isInteraction && messageOrInteraction.client.options.partials?.includes('CHANNEL')) {
shouldEmitWarning = false;
}
// IF we are to emit a warning,
// then check if the interaction is a message based command,
// and check if the client has the 'CHANNEL' partial,
// and check if the client has the 'DIRECT_MESSAGE' intent',
// in which case we don't want to emit a warning.
if (
shouldEmitWarning &&
!isInteraction &&
messageOrInteraction.client.options.partials?.includes('CHANNEL') &&
new Intents(messageOrInteraction.client.options.intents).has(Intents.FLAGS.DIRECT_MESSAGES)
) {
shouldEmitWarning = false;
}
// If we should emit a warning then do so.
if (shouldEmitWarning) {
process.emitWarning(
[
'PaginatedMessage was initiated in a DM channel without the client having the required partial configured.',
'If you want PaginatedMessage to work in DM channels then make sure you start your client with "CHANNEL" added to "client.options.partials".',
'Furthermore if you are using message based commands (as opposed to application commands) then you will also need to add the "DIRECT_MESSAGE" intent to "client.options.intents"',
'If you do not want to be alerted about this in the future then you can disable this warning by setting "PaginatedMessage.emitPartialDMChannelWarning" to "false", or use "setEmitPartialDMChannelWarning(false)" before calling "run".'
].join('\n'),
{
type: 'PaginatedMessageRunsInNonpartialDMChannel',
code: 'PAGINATED_MESSAGE_RUNS_IN_NON_PARTIAL_DM_CHANNEL'
}
);
this.hasEmittedPartialDMChannelWarning = true;
}
await safelyReplyToInteraction({
messageOrInteraction,
interactionEditReplyContent: this.#thisMazeWasNotMeantForYouContent,
interactionReplyContent: { ...this.#thisMazeWasNotMeantForYouContent, ephemeral: true },
componentUpdateContent: this.#thisMazeWasNotMeantForYouContent,
messageMethod: 'reply',
messageMethodContent: this.#thisMazeWasNotMeantForYouContent
});
return this;
}
// Assign the target based on whether a Message or CommandInteraction was passed in
target ??= runsOnInteraction(messageOrInteraction) ? messageOrInteraction.user : messageOrInteraction.author;
// Try to get the previous PaginatedMessage for this user
const paginatedMessage = PaginatedMessage.handlers.get(target.id);
// If a PaginatedMessage was found then stop it
paginatedMessage?.collector?.stop();
// If the message was sent by a bot, then set the response as this one
if (runsOnInteraction(messageOrInteraction)) {
if (messageOrInteraction.user.bot && messageOrInteraction.user.id === messageOrInteraction.client.user?.id) {
this.response = messageOrInteraction;
}
} else if (messageOrInteraction.author.bot && messageOrInteraction.author.id === messageOrInteraction.client.user?.id) {
this.response = messageOrInteraction;
}
await this.resolvePagesOnRun();
// Sanity checks to handle
if (!this.messages.length) throw new Error('There are no messages.');
if (!this.actions.size) throw new Error('There are no actions.');
await this.setUpMessage(messageOrInteraction, target);
this.setUpCollector(messageOrInteraction.channel, target);
const messageId = this.response!.id;
if (this.collector) {
this.collector.once('end', () => {
PaginatedMessage.messages.delete(messageId);
PaginatedMessage.handlers.delete(target!.id);
});
PaginatedMessage.messages.set(messageId, this);
PaginatedMessage.handlers.set(target.id, this);
}
return this;
}
/**
* Executed whenever {@link PaginatedMessage.run} is called.
*/
public async resolvePagesOnRun(): Promise<void> {
for (let i = 0; i < this.pages.length; i++) {
await this.resolvePage(i);
}
}
/**
* Executed whenever an action is triggered and resolved.
* @param index The index to resolve.
*/
public async resolvePage(index: number): Promise<PaginatedMessagePage> {
// If the message was already processed, do not load it again:
const message = this.messages[index];
if (!isNullish(message)) {
return message;
}
// Load the page and return it:
const resolved = await this.handlePageLoad(this.pages[index], index);
this.messages[index] = resolved;
return resolved;
}
/**
* Clones the current handler into a new instance.
*/
public clone(): PaginatedMessage {
const clone = new this.constructor({ pages: this.pages, actions: [] }).setIndex(this.index).setIdle(this.idle);
clone.actions = this.actions;
clone.response = this.response;
clone.template = this.template;
return clone;
}
/**
* Sets up the message.
*
* @param messageOrInteraction The message or interaction that triggered this {@link PaginatedMessage}.
* Generally this will be the command message or an interaction
* (either a {@link CommandInteraction}, a {@link ContextMenuInteraction}, a {@link SelectMenuInteraction} or a {@link ButtonInteraction}),
* but it can also be another message from your client, i.e. to indicate a loading state.
*
* @param targetUser The author the handler is for.
*/
protected async setUpMessage(
messageOrInteraction: Message | CommandInteraction | ContextMenuInteraction | SelectMenuInteraction | ButtonInteraction,
targetUser: User
): Promise<void> {
// Get the current page
let page = this.messages[this.index]!;
// If the page is a callback function such as with `addAsyncPageEmbed` then resolve it here
page = isFunction(page) ? await page(this.index, this.pages, this) : page;
// Merge in the advanced options
page = { ...page, ...(this.paginatedMessageData ?? {}) };
// If we do not have more than 1 page then there is no reason to add message components
if (this.pages.length > 1) {
const messageComponents = await Promise.all(
[...this.actions.values()].map<Promise<MessageButton | MessageSelectMenu>>(async (interaction) => {
return isMessageButtonInteraction(interaction)
? new MessageButton(interaction)
: new MessageSelectMenu({
options: await Promise.all(
this.pages.map(async (_, index) => {
return {