/
JDABuilder.java
1918 lines (1825 loc) · 77.8 KB
/
JDABuilder.java
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
/*
* Copyright 2015-2020 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.api;
import com.neovisionaries.ws.client.WebSocketFactory;
import net.dv8tion.jda.annotations.DeprecatedSince;
import net.dv8tion.jda.annotations.ReplaceWith;
import net.dv8tion.jda.api.audio.factory.IAudioSendFactory;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.hooks.IEventManager;
import net.dv8tion.jda.api.hooks.VoiceDispatchInterceptor;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.utils.*;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.managers.PresenceImpl;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.IOUtil;
import net.dv8tion.jda.internal.utils.config.AuthorizationConfig;
import net.dv8tion.jda.internal.utils.config.MetaConfig;
import net.dv8tion.jda.internal.utils.config.SessionConfig;
import net.dv8tion.jda.internal.utils.config.ThreadingConfig;
import net.dv8tion.jda.internal.utils.config.flags.ConfigFlag;
import okhttp3.OkHttpClient;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.security.auth.login.LoginException;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* Used to create new {@link net.dv8tion.jda.api.JDA} instances. This is also useful for making sure all of
* your {@link net.dv8tion.jda.api.hooks.EventListener EventListeners} are registered
* before {@link net.dv8tion.jda.api.JDA} attempts to log in.
*
* <p>A single JDABuilder can be reused multiple times. Each call to
* {@link net.dv8tion.jda.api.JDABuilder#build() build()}
* creates a new {@link net.dv8tion.jda.api.JDA} instance using the same information.
* This means that you can have listeners easily registered to multiple {@link net.dv8tion.jda.api.JDA} instances.
*/
public class JDABuilder
{
public static final int GUILD_SUBSCRIPTIONS = GatewayIntent.getRaw(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_PRESENCES, GatewayIntent.GUILD_MESSAGE_TYPING);
protected final List<Object> listeners = new LinkedList<>();
protected final EnumSet<CacheFlag> automaticallyDisabled = EnumSet.noneOf(CacheFlag.class);
protected ScheduledExecutorService rateLimitPool = null;
protected boolean shutdownRateLimitPool = true;
protected ScheduledExecutorService mainWsPool = null;
protected boolean shutdownMainWsPool = true;
protected ExecutorService callbackPool = null;
protected boolean shutdownCallbackPool = true;
protected ExecutorService eventPool = null;
protected boolean shutdownEventPool = true;
protected EnumSet<CacheFlag> cacheFlags = EnumSet.allOf(CacheFlag.class);
protected ConcurrentMap<String, String> contextMap = null;
protected SessionController controller = null;
protected VoiceDispatchInterceptor voiceDispatchInterceptor = null;
protected OkHttpClient.Builder httpClientBuilder = null;
protected OkHttpClient httpClient = null;
protected WebSocketFactory wsFactory = null;
protected String token = null;
protected IEventManager eventManager = null;
protected IAudioSendFactory audioSendFactory = null;
protected JDA.ShardInfo shardInfo = null;
protected Compression compression = Compression.ZLIB;
protected Activity activity = null;
protected OnlineStatus status = OnlineStatus.ONLINE;
protected boolean idle = false;
protected int maxReconnectDelay = 900;
protected int largeThreshold = 250;
protected int maxBufferSize = 2048;
protected int intents = -1; // don't use intents by default
protected EnumSet<ConfigFlag> flags = ConfigFlag.getDefault();
protected ChunkingFilter chunkingFilter = ChunkingFilter.ALL;
protected MemberCachePolicy memberCachePolicy = MemberCachePolicy.ALL;
protected GatewayEncoding encoding = GatewayEncoding.JSON;
/**
* Creates a completely empty JDABuilder.
*
* <br>If you use this, you need to set the token using
* {@link net.dv8tion.jda.api.JDABuilder#setToken(String) setToken(String)}
* before calling {@link net.dv8tion.jda.api.JDABuilder#build() build()}
*
* @deprecated Due to breaking changes to the discord api gateway you are now required to explicitly
* state which events your bot needs. For this reason we have changed to new factory methods that require setting
* the gateway intents. Refer to {@link #create(String, Collection)}, {@link #createDefault(String, Collection)}, and {@link #createLight(String, Collection)} instead.
*
* @see #JDABuilder(String)
*/
@Deprecated
@DeprecatedSince("4.2.0")
@ReplaceWith("JDABuilder.create(GatewayIntent...)")
public JDABuilder() {}
/**
* Creates a JDABuilder with the predefined token.
*
* @param token
* The bot token to use
*
* @deprecated Due to breaking changes to the discord api gateway you are now required to explicitly
* state which events your bot needs. For this reason we have changed to new factory methods that require setting
* the gateway intents. Refer to {@link #create(String, Collection)}, {@link #createDefault(String, Collection)}, and {@link #createLight(String, Collection)} instead.
*
* @see #setToken(String)
*/
@Deprecated
@DeprecatedSince("4.2.0")
@ReplaceWith("JDABuilder.create(String, GatewayIntent...)")
public JDABuilder(@Nullable String token)
{
this.token = token;
}
/**
* Creates a completely empty JDABuilder.
* <br>If you use this, you need to set the token using
* {@link net.dv8tion.jda.api.JDABuilder#setToken(String) setToken(String)}
* before calling {@link net.dv8tion.jda.api.JDABuilder#build() build()}
*
* @param accountType
* The {@link net.dv8tion.jda.api.AccountType AccountType}.
*
* @throws IllegalArgumentException
* If the given AccountType is {@code null}
*
* @deprecated This will be removed in a future version, replace with {@link #create(String, Collection)}.
* We no longer support login with {@link AccountType#CLIENT}.
*/
@Deprecated
@ReplaceWith("JDABuilder.create(String)")
@DeprecatedSince("4.2.0")
public JDABuilder(@Nonnull AccountType accountType)
{
Checks.check(accountType == AccountType.BOT, "Client accounts are no longer supported!");
}
private JDABuilder(@Nullable String token, int intents)
{
this.token = token;
this.intents = 1 | intents;
}
/**
* Creates a JDABuilder with recommended default settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#DEFAULT}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>{@link #setEnabledIntents(Collection)} is set to {@link GatewayIntent#DEFAULT}</li>
* <li>This disables {@link CacheFlag#ACTIVITY} and {@link CacheFlag#CLIENT_STATUS}</li>
* </ul>
*
* @param token
* The bot token to use
*
* @return The new JDABuilder
*
* @see #disableIntents(GatewayIntent, GatewayIntent...)
* @see #enableIntents(GatewayIntent, GatewayIntent...)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createDefault(@Nullable String token)
{
return new JDABuilder(token, GatewayIntent.DEFAULT).applyDefault();
}
/**
* Creates a JDABuilder with recommended default settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#DEFAULT}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>This disables {@link CacheFlag#ACTIVITY} and {@link CacheFlag#CLIENT_STATUS}</li>
* </ul>
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intent
* The intent to enable
* @param intents
* Any other intents to enable
*
* @throws IllegalArgumentException
* If provided with null intents
*
* @return The new JDABuilder
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createDefault(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents)
{
Checks.notNull(intent, "GatewayIntent");
Checks.noneNull(intents, "GatewayIntent");
return createDefault(token, EnumSet.of(intent, intents));
}
/**
* Creates a JDABuilder with recommended default settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#DEFAULT}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>This disables {@link CacheFlag#ACTIVITY} and {@link CacheFlag#CLIENT_STATUS}</li>
* </ul>
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intents
* The intents to enable
*
* @throws IllegalArgumentException
* If provided with null intents
*
* @return The new JDABuilder
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createDefault(@Nullable String token, @Nonnull Collection<GatewayIntent> intents)
{
return create(token, intents).applyDefault();
}
private JDABuilder applyDefault()
{
return this.setMemberCachePolicy(MemberCachePolicy.DEFAULT)
.setChunkingFilter(ChunkingFilter.NONE)
.disableCache(CacheFlag.CLIENT_STATUS, CacheFlag.ACTIVITY)
.setLargeThreshold(250);
}
/**
* Creates a JDABuilder with low memory profile settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setEnabledIntents(Collection)} is set to {@link GatewayIntent#DEFAULT}</li>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#NONE}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>This disables all existing {@link CacheFlag CacheFlags}</li>
* </ul>
*
* @param token
* The bot token to use
*
* @return The new JDABuilder
*
* @see #disableIntents(GatewayIntent, GatewayIntent...)
* @see #enableIntents(GatewayIntent, GatewayIntent...)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createLight(@Nullable String token)
{
return new JDABuilder(token, GatewayIntent.DEFAULT).applyLight();
}
/**
* Creates a JDABuilder with low memory profile settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#NONE}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>This disables all existing {@link CacheFlag CacheFlags}</li>
* </ul>
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intent
* The first intent to use
* @param intents
* The other gateway intents to use
*
* @return The new JDABuilder
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createLight(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents)
{
Checks.notNull(intent, "GatewayIntent");
Checks.noneNull(intents, "GatewayIntent");
return createLight(token, EnumSet.of(intent, intents));
}
/**
* Creates a JDABuilder with low memory profile settings.
* <br>Note that these defaults can potentially change in the future.
*
* <ul>
* <li>{@link #setMemberCachePolicy(MemberCachePolicy)} is set to {@link MemberCachePolicy#NONE}</li>
* <li>{@link #setChunkingFilter(ChunkingFilter)} is set to {@link ChunkingFilter#NONE}</li>
* <li>This disables all existing {@link CacheFlag CacheFlags}</li>
* </ul>
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intents
* The gateway intents to use
*
* @return The new JDABuilder
*/
@Nonnull
@CheckReturnValue
public static JDABuilder createLight(@Nullable String token, @Nonnull Collection<GatewayIntent> intents)
{
return create(token, intents).applyLight();
}
private JDABuilder applyLight()
{
return this.setMemberCachePolicy(MemberCachePolicy.NONE)
.setChunkingFilter(ChunkingFilter.NONE)
.disableCache(EnumSet.allOf(CacheFlag.class))
.setLargeThreshold(50);
}
/**
* Creates a completely empty JDABuilder with the predefined intents.
* <br>You can use {@link #create(Collection) JDABuilder.create(EnumSet.noneOf(GatewayIntent.class))} to disable all intents.
*
* <br>If you use this, you need to set the token using
* {@link net.dv8tion.jda.api.JDABuilder#setToken(String) setToken(String)}
* before calling {@link net.dv8tion.jda.api.JDABuilder#build() build()}
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param intent
* The first intent
* @param intents
* The gateway intents to use
*
* @throws IllegalArgumentException
* If the provided intents are null
*
* @return The JDABuilder instance
*
* @see #setToken(String)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder create(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents)
{
return create(null, intent, intents);
}
/**
* Creates a completely empty JDABuilder with the predefined intents.
*
* <br>If you use this, you need to set the token using
* {@link net.dv8tion.jda.api.JDABuilder#setToken(String) setToken(String)}
* before calling {@link net.dv8tion.jda.api.JDABuilder#build() build()}
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param intents
* The gateway intents to use
*
* @throws IllegalArgumentException
* If the provided intents are null
*
* @return The JDABuilder instance
*
* @see #setToken(String)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder create(@Nonnull Collection<GatewayIntent> intents)
{
return create(null, intents);
}
/**
* Creates a JDABuilder with the predefined token.
* <br>You can use {@link #create(String, Collection) JDABuilder.create(token, EnumSet.noneOf(GatewayIntent.class))} to disable all intents.
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intent
* The first gateway intent to use
* @param intents
* Additional gateway intents to use
*
* @throws IllegalArgumentException
* If the provided intents are null
*
* @return The JDABuilder instance
*
* @see #setToken(String)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder create(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents)
{
return new JDABuilder(token, GatewayIntent.getRaw(intent, intents)).applyIntents();
}
/**
* Creates a JDABuilder with the predefined token.
*
* <p>If you don't enable certain intents, the cache will be disabled.
* For instance, if the {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} intent is disabled, then members will only
* be cached when a voice state is available.
* If both {@link GatewayIntent#GUILD_MEMBERS GUILD_MEMBERS} and {@link GatewayIntent#GUILD_VOICE_STATES GUILD_VOICE_STATES} are disabled
* then no members will be cached.
*
* <p>The individual {@link CacheFlag CacheFlags} will also be disabled
* if the {@link CacheFlag#getRequiredIntent() required intent} is not enabled.
*
* @param token
* The bot token to use
* @param intents
* The gateway intents to use
*
* @throws IllegalArgumentException
* If the provided intents are null
*
* @return The JDABuilder instance
*
* @see #setToken(String)
*/
@Nonnull
@CheckReturnValue
public static JDABuilder create(@Nullable String token, @Nonnull Collection<GatewayIntent> intents)
{
return new JDABuilder(token, GatewayIntent.getRaw(intents)).applyIntents();
}
private JDABuilder applyIntents()
{
EnumSet<CacheFlag> disabledCache = EnumSet.allOf(CacheFlag.class);
for (CacheFlag flag : CacheFlag.values())
{
GatewayIntent requiredIntent = flag.getRequiredIntent();
if (requiredIntent == null || (requiredIntent.getRawValue() & intents) != 0)
disabledCache.remove(flag);
}
boolean enableMembers = (intents & GatewayIntent.GUILD_MEMBERS.getRawValue()) != 0;
return setChunkingFilter(enableMembers ? ChunkingFilter.ALL : ChunkingFilter.NONE)
.setMemberCachePolicy(enableMembers ? MemberCachePolicy.ALL : MemberCachePolicy.DEFAULT)
.setDisabledCache(disabledCache);
}
private JDABuilder setDisabledCache(EnumSet<CacheFlag> flags)
{
disableCache(flags);
this.automaticallyDisabled.addAll(flags);
return this;
}
/**
* Choose which {@link GatewayEncoding} JDA should use.
*
* @param encoding
* The {@link GatewayEncoding} (default: JSON)
*
* @throws IllegalArgumentException
* If null is provided
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setGatewayEncoding(@Nonnull GatewayEncoding encoding)
{
Checks.notNull(encoding, "GatewayEncoding");
this.encoding = encoding;
return this;
}
/**
* Whether JDA should fire {@link net.dv8tion.jda.api.events.RawGatewayEvent} for every discord event.
* <br>Default: {@code false}
*
* @param enable
* True, if JDA should fire {@link net.dv8tion.jda.api.events.RawGatewayEvent}.
*
* @return The JDABuilder instance. Useful for chaining.
*
* @since 4.0.0
*/
@Nonnull
public JDABuilder setRawEventsEnabled(boolean enable)
{
return setFlag(ConfigFlag.RAW_EVENTS, enable);
}
/**
* Whether the rate-limit should be relative to the current time plus latency.
* <br>By default we use the {@code X-RateLimit-Reset-After} header to determine when
* a rate-limit is no longer imminent. This has the disadvantage that it might wait longer than needed due
* to the latency which is ignored by the reset-after relative delay.
*
* <p>When disabled, we will use the {@code X-RateLimit-Reset} absolute timestamp instead which accounts for
* latency but requires a properly NTP synchronized clock to be present.
* If your system does have this feature you might gain a little quicker rate-limit handling than the default allows.
*
* <p>Default: <b>true</b>
*
* @param enable
* True, if the relative {@code X-RateLimit-Reset-After} header should be used.
*
* @return The JDABuilder instance. Useful for chaining.
*
* @since 4.1.0
*/
@Nonnull
public JDABuilder setRelativeRateLimit(boolean enable)
{
return setFlag(ConfigFlag.USE_RELATIVE_RATELIMIT, enable);
}
/**
* Flags used to enable selective parts of the JDA cache to reduce the runtime memory footprint.
* <br><b>It is highly recommended to use {@link #setDisabledCacheFlags(EnumSet)} instead
* for backwards compatibility</b>. We might add more flags in the future which you then effectively disable
* when updating and not changing your setting here.
*
* @param flags
* EnumSet containing the flags for cache services that should be <b>enabled</b>
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see #setDisabledCacheFlags(EnumSet)
*
* @deprecated We add CacheFlags to the enum over time which will be disabled when using this method.
* This introduces breaking changes due to the way the setter works.
* You should use {@link #enableCache(Collection)} and {@link #disableCache(Collection)} instead,
* to disable and enable cache flags without side-effects that may break in future versions.
*/
@Nonnull
@Deprecated
@ReplaceWith("enableCache(flags) and disableCache(flags)")
@DeprecatedSince("4.2.0")
public JDABuilder setEnabledCacheFlags(@Nullable EnumSet<CacheFlag> flags)
{
this.cacheFlags = flags == null ? EnumSet.noneOf(CacheFlag.class) : EnumSet.copyOf(flags);
return this;
}
/**
* Enable specific cache flags.
* <br>This will not disable any currently set cache flags.
*
* @param flags
* The {@link CacheFlag CacheFlags} to enable
*
* @throws IllegalArgumentException
* If provided with null
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see #enableCache(CacheFlag, CacheFlag...)
* @see #disableCache(Collection)
*/
@Nonnull
public JDABuilder enableCache(@Nonnull Collection<CacheFlag> flags)
{
Checks.noneNull(flags, "CacheFlags");
cacheFlags.addAll(flags);
return this;
}
/**
* Enable specific cache flags.
* <br>This will not disable any currently set cache flags.
*
* @param flag
* {@link CacheFlag} to enable
* @param flags
* Other flags to enable
*
* @throws IllegalArgumentException
* If provided with null
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see #enableCache(Collection)
* @see #disableCache(CacheFlag, CacheFlag...)
*/
@Nonnull
public JDABuilder enableCache(@Nonnull CacheFlag flag, @Nonnull CacheFlag... flags)
{
Checks.notNull(flag, "CacheFlag");
Checks.noneNull(flags, "CacheFlag");
cacheFlags.addAll(EnumSet.of(flag, flags));
return this;
}
/**
* Flags used to disable parts of the JDA cache to reduce the runtime memory footprint.
* <br>Shortcut for {@code setEnabledCacheFlags(EnumSet.complementOf(flags))}
*
* @param flags
* EnumSet containing the flags for cache services that should be <b>disabled</b>
*
* @return The JDABuilder instance. Useful for chaining.
*
* @deprecated We add CacheFlags to the enum over time which will be disabled when using this method.
* This introduces breaking changes due to the way the setter works.
* You should use {@link #enableCache(Collection)} and {@link #disableCache(Collection)} instead,
* to disable and enable cache flags without side-effects that may break in future versions.
*/
@Nonnull
@Deprecated
@ReplaceWith("enableCache(flags) and disableCache(flags)")
@DeprecatedSince("4.2.0")
public JDABuilder setDisabledCacheFlags(@Nullable EnumSet<CacheFlag> flags)
{
return setEnabledCacheFlags(flags == null ? EnumSet.allOf(CacheFlag.class) : EnumSet.complementOf(flags));
}
/**
* Disable specific cache flags.
* <br>This will not enable any currently unset cache flags.
*
* @param flags
* The {@link CacheFlag CacheFlags} to disable
*
* @throws IllegalArgumentException
* If provided with null
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see #disableCache(CacheFlag, CacheFlag...)
* @see #enableCache(Collection)
*/
@Nonnull
public JDABuilder disableCache(@Nonnull Collection<CacheFlag> flags)
{
Checks.noneNull(flags, "CacheFlags");
automaticallyDisabled.removeAll(flags);
cacheFlags.removeAll(flags);
return this;
}
/**
* Disable specific cache flags.
* <br>This will not enable any currently unset cache flags.
*
* @param flag
* {@link CacheFlag} to disable
* @param flags
* Other flags to disable
*
* @throws IllegalArgumentException
* If provided with null
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see #disableCache(Collection)
* @see #enableCache(CacheFlag, CacheFlag...)
*/
@Nonnull
public JDABuilder disableCache(@Nonnull CacheFlag flag, @Nonnull CacheFlag... flags)
{
Checks.notNull(flag, "CacheFlag");
Checks.noneNull(flags, "CacheFlag");
return disableCache(EnumSet.of(flag, flags));
}
/**
* Configure the member caching policy.
* This will decide whether to cache a member (and its respective user).
* <br>All members are cached by default. If a guild is enabled for chunking, all members will be cached for it.
*
* <p>You can use this to define a custom caching policy that will greatly improve memory usage.
* <p>It is not recommended to disable {@link GatewayIntent#GUILD_MEMBERS GatewayIntent.GUILD_MEMBERS} when
* using {@link MemberCachePolicy#ALL MemberCachePolicy.ALL} as the members cannot be removed from cache by a leave event without this intent.
*
* <h2>Example</h2>
* <pre>{@code
* public void configureCache(JDABuilder builder) {
* // Cache members who are in a voice channel
* MemberCachePolicy policy = MemberCachePolicy.VOICE;
* // Cache members who are in a voice channel
* // AND are also online
* policy = policy.and(MemberCachePolicy.ONLINE);
* // Cache members who are in a voice channel
* // AND are also online
* // OR are the owner of the guild
* policy = policy.or(MemberCachePolicy.OWNER);
*
* builder.setMemberCachePolicy(policy);
* }
* }</pre>
*
* @param policy
* The {@link MemberCachePolicy} or null to use default {@link MemberCachePolicy#ALL}
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see MemberCachePolicy
* @see #setEnabledIntents(Collection)
*
* @since 4.2.0
*/
@Nonnull
public JDABuilder setMemberCachePolicy(@Nullable MemberCachePolicy policy)
{
if (policy == null)
this.memberCachePolicy = MemberCachePolicy.ALL;
else
this.memberCachePolicy = policy;
return this;
}
/**
* Sets the {@link org.slf4j.MDC MDC} mappings to use in JDA.
* <br>If sharding is enabled JDA will automatically add a {@code jda.shard} context with the format {@code [SHARD_ID / TOTAL]}
* where {@code SHARD_ID} and {@code TOTAL} are the shard configuration.
* Additionally it will provide context for the id via {@code jda.shard.id} and the total via {@code jda.shard.total}.
*
* <p>If provided with non-null map this automatically enables MDC context using {@link #setContextEnabled(boolean) setContextEnable(true)}!
*
* @param map
* The <b>modifiable</b> context map to use in JDA, or {@code null} to reset
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see <a href="https://www.slf4j.org/api/org/slf4j/MDC.html" target="_blank">MDC Javadoc</a>
* @see #setContextEnabled(boolean)
*/
@Nonnull
public JDABuilder setContextMap(@Nullable ConcurrentMap<String, String> map)
{
this.contextMap = map;
if (map != null)
setContextEnabled(true);
return this;
}
/**
* Whether JDA should use a synchronized MDC context for all of its controlled threads.
* <br>Default: {@code true}
*
* @param enable
* True, if JDA should provide an MDC context map
*
* @return The JDABuilder instance. Useful for chaining.
*
* @see <a href="https://www.slf4j.org/api/org/slf4j/MDC.html" target="_blank">MDC Javadoc</a>
* @see #setContextMap(java.util.concurrent.ConcurrentMap)
*/
@Nonnull
public JDABuilder setContextEnabled(boolean enable)
{
return setFlag(ConfigFlag.MDC_CONTEXT, enable);
}
/**
* Sets the compression algorithm used with the gateway connection,
* this will decrease the amount of used bandwidth for the running bot instance
* for the cost of a few extra cycles for decompression.
* Compression can be entirely disabled by setting this to {@link net.dv8tion.jda.api.utils.Compression#NONE}.
* <br><b>Default: {@link net.dv8tion.jda.api.utils.Compression#ZLIB}</b>
*
* <p><b>We recommend to keep this on the default unless you have issues with the decompression.</b>
* <br>This mode might become obligatory in a future version, do not rely on this switch to stay.
*
* @param compression
* The compression algorithm to use with the gateway connection
*
* @throws java.lang.IllegalArgumentException
* If provided with null
*
* @return The JDABuilder instance. Useful for chaining
*
* @see <a href="https://discord.com/developers/docs/topics/gateway#transport-compression" target="_blank">Official Discord Documentation - Transport Compression</a>
*/
@Nonnull
public JDABuilder setCompression(@Nonnull Compression compression)
{
Checks.notNull(compression, "Compression");
this.compression = compression;
return this;
}
/**
* Whether the Requester should retry when
* a {@link java.net.SocketTimeoutException SocketTimeoutException} occurs.
* <br><b>Default</b>: {@code true}
*
* <p>This value can be changed at any time with {@link net.dv8tion.jda.api.JDA#setRequestTimeoutRetry(boolean) JDA.setRequestTimeoutRetry(boolean)}!
*
* @param retryOnTimeout
* True, if the Request should retry once on a socket timeout
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setRequestTimeoutRetry(boolean retryOnTimeout)
{
return setFlag(ConfigFlag.RETRY_TIMEOUT, retryOnTimeout);
}
/**
* Sets the token that will be used by the {@link net.dv8tion.jda.api.JDA} instance to log in when
* {@link net.dv8tion.jda.api.JDABuilder#build() build()} is called.
*
* <h2>For {@link net.dv8tion.jda.api.AccountType#BOT}</h2>
* <ol>
* <li>Go to your <a href="https://discord.com/developers/applications/me">Discord Applications</a></li>
* <li>Create or select an already existing application</li>
* <li>Verify that it has already been turned into a Bot. If you see the "Create a Bot User" button, click it.</li>
* <li>Click the <i>click to reveal</i> link beside the <b>Token</b> label to show your Bot's {@code token}</li>
* </ol>
*
* @param token
* The token of the account that you would like to login with.
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setToken(@Nullable String token)
{
this.token = token;
return this;
}
/**
* Sets the {@link okhttp3.OkHttpClient.Builder Builder} that will be used by JDAs requester.
* <br>This can be used to set things such as connection timeout and proxy.
*
* @param builder
* The new {@link okhttp3.OkHttpClient.Builder Builder} to use
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setHttpClientBuilder(@Nullable OkHttpClient.Builder builder)
{
this.httpClientBuilder = builder;
return this;
}
/**
* Sets the {@link okhttp3.OkHttpClient OkHttpClient} that will be used by JDAs requester.
* <br>This can be used to set things such as connection timeout and proxy.
*
* @param client
* The new {@link okhttp3.OkHttpClient OkHttpClient} to use
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setHttpClient(@Nullable OkHttpClient client)
{
this.httpClient = client;
return this;
}
/**
* Sets the {@link com.neovisionaries.ws.client.WebSocketFactory WebSocketFactory} that will be used by JDA's websocket client.
* This can be used to set things such as connection timeout and proxy.
*
* @param factory
* The new {@link com.neovisionaries.ws.client.WebSocketFactory WebSocketFactory} to use.
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setWebsocketFactory(@Nullable WebSocketFactory factory)
{
this.wsFactory = factory;
return this;
}
/**
* Sets the {@link ScheduledExecutorService ScheduledExecutorService} that should be used in
* the JDA rate-limit handler. Changing this can drastically change the JDA behavior for RestAction execution
* and should be handled carefully. <b>Only change this pool if you know what you're doing.</b>
* <br><b>This automatically disables the automatic shutdown of the rate-limit pool, you can enable
* it using {@link #setRateLimitPool(ScheduledExecutorService, boolean) setRateLimitPool(executor, true)}</b>
*
* <p>This is used mostly by the Rate-Limiter to handle backoff delays by using scheduled executions.
* Besides that it is also used by planned execution for {@link net.dv8tion.jda.api.requests.RestAction#queueAfter(long, TimeUnit)}
* and similar methods.
*
* <p>Default: {@link ScheduledThreadPoolExecutor} with 5 threads.
*
* @param pool
* The thread-pool to use for rate-limit handling
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setRateLimitPool(@Nullable ScheduledExecutorService pool)
{
return setRateLimitPool(pool, pool == null);
}
/**
* Sets the {@link ScheduledExecutorService ScheduledExecutorService} that should be used in
* the JDA rate-limit handler. Changing this can drastically change the JDA behavior for RestAction execution
* and should be handled carefully. <b>Only change this pool if you know what you're doing.</b>
*
* <p>This is used mostly by the Rate-Limiter to handle backoff delays by using scheduled executions.
* Besides that it is also used by planned execution for {@link net.dv8tion.jda.api.requests.RestAction#queueAfter(long, TimeUnit)}
* and similar methods.
*
* <p>Default: {@link ScheduledThreadPoolExecutor} with 5 threads.
*
* @param pool
* The thread-pool to use for rate-limit handling
* @param automaticShutdown
* Whether {@link JDA#shutdown()} should shutdown this pool
*
* @return The JDABuilder instance. Useful for chaining.
*/
@Nonnull
public JDABuilder setRateLimitPool(@Nullable ScheduledExecutorService pool, boolean automaticShutdown)
{
this.rateLimitPool = pool;
this.shutdownRateLimitPool = automaticShutdown;
return this;
}