-
-
Notifications
You must be signed in to change notification settings - Fork 729
/
JDA.java
2065 lines (1944 loc) · 82.8 KB
/
JDA.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 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 net.dv8tion.jda.annotations.Incubating;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.channel.Channel;
import net.dv8tion.jda.api.entities.channel.attribute.IGuildChannelContainer;
import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji;
import net.dv8tion.jda.api.entities.sticker.*;
import net.dv8tion.jda.api.hooks.IEventManager;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.managers.AudioManager;
import net.dv8tion.jda.api.managers.DirectAudioController;
import net.dv8tion.jda.api.managers.Presence;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.Route;
import net.dv8tion.jda.api.requests.restaction.*;
import net.dv8tion.jda.api.requests.restaction.pagination.EntitlementPaginationAction;
import net.dv8tion.jda.api.sharding.ShardManager;
import net.dv8tion.jda.api.utils.MiscUtil;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.dv8tion.jda.api.utils.cache.CacheView;
import net.dv8tion.jda.api.utils.cache.SnowflakeCacheView;
import net.dv8tion.jda.internal.interactions.CommandDataImpl;
import net.dv8tion.jda.internal.requests.CompletedRestAction;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.EntityString;
import net.dv8tion.jda.internal.utils.Helpers;
import okhttp3.OkHttpClient;
import org.jetbrains.annotations.Unmodifiable;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.List;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.regex.Matcher;
/**
* The core of JDA. Acts as a registry system of JDA. All parts of the API can be accessed starting from this class.
*
* @see JDABuilder
*/
public interface JDA extends IGuildChannelContainer<Channel>
{
/**
* Represents the connection status of JDA and its Main WebSocket.
*/
enum Status
{
/**JDA is currently setting up supporting systems like the AudioSystem.*/
INITIALIZING(true),
/**JDA has finished setting up supporting systems and is ready to log in.*/
INITIALIZED(true),
/**JDA is currently attempting to log in.*/
LOGGING_IN(true),
/**JDA is currently attempting to connect it's websocket to Discord.*/
CONNECTING_TO_WEBSOCKET(true),
/**JDA has successfully connected it's websocket to Discord and is sending authentication*/
IDENTIFYING_SESSION(true),
/**JDA has sent authentication to discord and is awaiting confirmation*/
AWAITING_LOGIN_CONFIRMATION(true),
/**JDA is populating internal objects.
* This process often takes the longest of all Statuses (besides CONNECTED)*/
LOADING_SUBSYSTEMS(true),
/**JDA has finished loading everything, is receiving information from Discord and is firing events.*/
CONNECTED(true),
/**JDA's main websocket has been disconnected. This <b>DOES NOT</b> mean JDA has shutdown permanently.
* This is an in-between status. Most likely ATTEMPTING_TO_RECONNECT or SHUTTING_DOWN/SHUTDOWN will soon follow.*/
DISCONNECTED,
/** JDA session has been added to {@link net.dv8tion.jda.api.utils.SessionController SessionController}
* and is awaiting to be dequeued for reconnecting.*/
RECONNECT_QUEUED,
/**When trying to reconnect to Discord JDA encountered an issue, most likely related to a lack of internet connection,
* and is waiting to try reconnecting again.*/
WAITING_TO_RECONNECT,
/**JDA has been disconnected from Discord and is currently trying to reestablish the connection.*/
ATTEMPTING_TO_RECONNECT,
/**JDA has received a shutdown request or has been disconnected from Discord and reconnect is disabled, thus,
* JDA is in the process of shutting down*/
SHUTTING_DOWN,
/**JDA has finished shutting down and this instance can no longer be used to communicate with the Discord servers.*/
SHUTDOWN,
/**While attempting to authenticate, Discord reported that the provided authentication information was invalid.*/
FAILED_TO_LOGIN;
private final boolean isInit;
Status(boolean isInit)
{
this.isInit = isInit;
}
Status()
{
this.isInit = false;
}
public boolean isInit()
{
return isInit;
}
}
/**
* Represents the information used to create this shard.
*/
class ShardInfo
{
/** Default sharding config with one shard */
public static final ShardInfo SINGLE = new ShardInfo(0, 1);
int shardId;
int shardTotal;
public ShardInfo(int shardId, int shardTotal)
{
this.shardId = shardId;
this.shardTotal = shardTotal;
}
/**
* Represents the id of the shard of the current instance.
* <br>This value will be between 0 and ({@link #getShardTotal()} - 1).
*
* @return The id of the currently logged in shard.
*/
public int getShardId()
{
return shardId;
}
/**
* The total amount of shards based on the value provided during JDA instance creation using
* {@link JDABuilder#useSharding(int, int)}.
* <br>This <b>does not</b> query Discord to determine the total number of shards.
* <br>This <b>does not</b> represent the amount of logged in shards.
* <br>It strictly represents the integer value provided to discord
* representing the total amount of shards that the developer indicated that it was going to use when
* initially starting JDA.
*
* @return The total of shards based on the total provided by the developer during JDA initialization.
*/
public int getShardTotal()
{
return shardTotal;
}
/**
* Provides a shortcut method for easily printing shard info.
* <br>Format: "[# / #]"
* <br>Where the first # is shardId and the second # is shardTotal.
*
* @return A String representing the information used to build this shard.
*/
public String getShardString()
{
return "[" + shardId + " / " + shardTotal + "]";
}
@Override
public String toString()
{
return new EntityString(this)
.addMetadata("currentShard", getShardString())
.addMetadata("totalShards", getShardTotal())
.toString();
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof ShardInfo))
return false;
ShardInfo oInfo = (ShardInfo) o;
return shardId == oInfo.getShardId() && shardTotal == oInfo.getShardTotal();
}
}
/**
* Gets the current {@link net.dv8tion.jda.api.JDA.Status Status} of the JDA instance.
*
* @return Current JDA status.
*/
@Nonnull
Status getStatus();
/**
* The {@link GatewayIntent GatewayIntents} for this JDA session.
*
* @return {@link EnumSet} of active gateway intents
*/
@Nonnull
EnumSet<GatewayIntent> getGatewayIntents();
/**
* The {@link CacheFlag cache flags} that have been enabled for this JDA session.
*
* @return Copy of the EnumSet of cache flags for this session
*/
@Nonnull
EnumSet<CacheFlag> getCacheFlags();
/**
* Attempts to remove the user with the provided id from the cache.
* <br>If you attempt to remove the {@link #getSelfUser() SelfUser} this will simply return {@code false}.
*
* <p>This should be used by an implementation of {@link net.dv8tion.jda.api.utils.MemberCachePolicy MemberCachePolicy}
* as an upstream request to remove a member.
*
* @param userId
* The target user id
*
* @return True, if the cache was changed
*/
boolean unloadUser(long userId);
/**
* The time in milliseconds that discord took to respond to our last heartbeat
* <br>This roughly represents the WebSocket ping of this session
*
* <p><b>{@link net.dv8tion.jda.api.requests.RestAction RestAction} request times do not
* correlate to this value!</b>
*
* <p>The {@link net.dv8tion.jda.api.events.GatewayPingEvent GatewayPingEvent} indicates an update to this value.
*
* @return time in milliseconds between heartbeat and the heartbeat ack response
*
* @see #getRestPing() Getting RestAction ping
*/
long getGatewayPing();
/**
* The time in milliseconds that discord took to respond to a REST request.
* <br>This will request the current user from the API and calculate the time the response took.
*
* <p><b>Example</b><br>
* <pre><code>
* jda.getRestPing().queue( (time) {@literal ->}
* channel.sendMessageFormat("Ping: %d ms", time).queue()
* );
* </code></pre>
*
* @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: long
*
* @since 4.0.0
*
* @see #getGatewayPing()
*/
@Nonnull
default RestAction<Long> getRestPing()
{
AtomicLong time = new AtomicLong();
Route.CompiledRoute route = Route.Self.GET_SELF.compile();
RestActionImpl<Long> action = new RestActionImpl<>(this, route, (response, request) -> System.currentTimeMillis() - time.get());
action.setCheck(() ->
{
time.set(System.currentTimeMillis());
return true;
});
return action;
}
/**
* This method will block until JDA has reached the specified connection status.
*
* <p><b>Login Cycle</b><br>
* <ol>
* <li>{@link net.dv8tion.jda.api.JDA.Status#INITIALIZING INITIALIZING}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#INITIALIZED INITIALIZED}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#LOGGING_IN LOGGING_IN}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#CONNECTING_TO_WEBSOCKET CONNECTING_TO_WEBSOCKET}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#IDENTIFYING_SESSION IDENTIFYING_SESSION}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#AWAITING_LOGIN_CONFIRMATION AWAITING_LOGIN_CONFIRMATION}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#LOADING_SUBSYSTEMS LOADING_SUBSYSTEMS}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#CONNECTED CONNECTED}</li>
* </ol>
*
* @param status
* The init status to wait for, once JDA has reached the specified
* stage of the startup cycle this method will return.
*
* @throws InterruptedException
* If this thread is interrupted while waiting
* @throws IllegalArgumentException
* If the provided status is null or not an init status ({@link Status#isInit()})
* @throws IllegalStateException
* If JDA is shutdown during this wait period
*
* @return The current JDA instance, for chaining convenience
*/
@Nonnull
default JDA awaitStatus(@Nonnull JDA.Status status) throws InterruptedException
{
//This is done to retain backwards compatible ABI as it would otherwise change the signature of the method
// which would require recompilation for all users (including extension libraries)
return awaitStatus(status, new JDA.Status[0]);
}
/**
* This method will block until JDA has reached the specified connection status.
*
* <p><b>Login Cycle</b><br>
* <ol>
* <li>{@link net.dv8tion.jda.api.JDA.Status#INITIALIZING INITIALIZING}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#INITIALIZED INITIALIZED}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#LOGGING_IN LOGGING_IN}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#CONNECTING_TO_WEBSOCKET CONNECTING_TO_WEBSOCKET}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#IDENTIFYING_SESSION IDENTIFYING_SESSION}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#AWAITING_LOGIN_CONFIRMATION AWAITING_LOGIN_CONFIRMATION}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#LOADING_SUBSYSTEMS LOADING_SUBSYSTEMS}</li>
* <li>{@link net.dv8tion.jda.api.JDA.Status#CONNECTED CONNECTED}</li>
* </ol>
*
* @param status
* The init status to wait for, once JDA has reached the specified
* stage of the startup cycle this method will return.
* @param failOn
* Optional failure states that will force a premature return
*
* @throws InterruptedException
* If this thread is interrupted while waiting
* @throws IllegalArgumentException
* If the provided status is null or not an init status ({@link Status#isInit()})
* @throws IllegalStateException
* If JDA is shutdown during this wait period
*
* @return The current JDA instance, for chaining convenience
*/
@Nonnull
JDA awaitStatus(@Nonnull JDA.Status status, @Nonnull JDA.Status... failOn) throws InterruptedException;
/**
* This method will block until JDA has reached the status {@link Status#CONNECTED}.
* <br>This status means that JDA finished setting up its internal cache and is ready to be used.
*
* @throws InterruptedException
* If this thread is interrupted while waiting
* @throws IllegalStateException
* If JDA is shutdown during this wait period
*
* @return The current JDA instance, for chaining convenience
*/
@Nonnull
default JDA awaitReady() throws InterruptedException
{
return awaitStatus(Status.CONNECTED);
}
/**
* Blocks the current thread until {@link #getStatus()} returns {@link Status#SHUTDOWN}.
* <br>This can be useful in certain situations like disabling class loading.
*
* <p>Note that shutdown time depends on the length of the rate-limit queue.
* You can use {@link #shutdownNow()} to cancel all pending requests and immediately shutdown.
*
* <p><b>Example</b>
* <pre>{@code
* jda.shutdown();
* // Allow at most 10 seconds for remaining requests to finish
* if (!jda.awaitShutdown(10, TimeUnit.SECONDS)) {
* jda.shutdownNow(); // Cancel all remaining requests
* jda.awaitShutdown(); // Wait until shutdown is complete (indefinitely)
* }
* }</pre>
*
* <p><b>This will not implicitly call {@code shutdown()}, you are responsible to ensure that the shutdown process has started.</b>
*
* @param duration
* The maximum time to wait, or 0 to wait indefinitely
* @param unit
* The time unit for the duration
*
* @throws IllegalArgumentException
* If the provided unit is null
* @throws InterruptedException
* If the current thread is interrupted while waiting
*
* @return False, if the timeout has elapsed before the shutdown has completed, true otherwise.
*/
@CheckReturnValue
boolean awaitShutdown(long duration, @Nonnull TimeUnit unit) throws InterruptedException;
/**
* Blocks the current thread until {@link #getStatus()} returns {@link Status#SHUTDOWN}.
* <br>This can be useful in certain situations like disabling class loading.
*
* <p>Note that shutdown time depends on the length of the rate-limit queue.
* You can use {@link #shutdownNow()} to cancel all pending requests and immediately shutdown.
*
* <p><b>Example</b>
* <pre>{@code
* jda.shutdown();
* // Allow at most 10 seconds for remaining requests to finish
* if (!jda.awaitShutdown(Duration.ofSeconds(10))) {
* jda.shutdownNow(); // Cancel all remaining requests
* jda.awaitShutdown(); // Wait until shutdown is complete (indefinitely)
* }
* }</pre>
*
* <p><b>This will not implicitly call {@code shutdown()}, you are responsible to ensure that the shutdown process has started.</b>
*
* @param timeout
* The maximum time to wait, or {@link Duration#ZERO} to wait indefinitely
*
* @throws IllegalArgumentException
* If the provided timeout is null
* @throws InterruptedException
* If the current thread is interrupted while waiting
*
* @return False, if the timeout has elapsed before the shutdown has completed, true otherwise.
*/
@CheckReturnValue
default boolean awaitShutdown(@Nonnull Duration timeout) throws InterruptedException
{
Checks.notNull(timeout, "Timeout");
return awaitShutdown(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Blocks the current thread until {@link #getStatus()} returns {@link Status#SHUTDOWN}.
* <br>This can be useful in certain situations like disabling class loading.
*
* <p>This will wait indefinitely by default. Use {@link #awaitShutdown(Duration)} to set a timeout.
*
* <p>Note that shutdown time depends on the length of the rate-limit queue.
* You can use {@link #shutdownNow()} to cancel all pending requests and immediately shutdown.
*
* <p><b>Example</b>
* <pre>{@code
* jda.shutdown();
* // Allow at most 10 seconds for remaining requests to finish
* if (!jda.awaitShutdown(Duration.ofSeconds(10))) {
* jda.shutdownNow(); // Cancel all remaining requests
* jda.awaitShutdown(); // Wait until shutdown is complete (indefinitely)
* }
* }</pre>
*
* <p><b>This will not implicitly call {@code shutdown()}, you are responsible to ensure that the shutdown process has started.</b>
*
* @throws IllegalArgumentException
* If the provided timeout is null
* @throws InterruptedException
* If the current thread is interrupted while waiting
*
* @return Always true
*/
default boolean awaitShutdown() throws InterruptedException
{
return awaitShutdown(0, TimeUnit.MILLISECONDS);
}
/**
* Cancels all currently scheduled {@link RestAction} requests.
* <br>When a {@link RestAction} is cancelled, a {@link java.util.concurrent.CancellationException} will be provided
* to the failure callback. This means {@link RestAction#queue(Consumer, Consumer)} will invoke the second callback
* and {@link RestAction#complete()} will throw an exception.
*
* <p><b>This is only recommended as an extreme last measure to avoid backpressure.</b>
* If you want to stop requests on shutdown you should use {@link #shutdownNow()} instead of this method.
*
* @return how many requests were cancelled
*
* @see RestAction#setCheck(BooleanSupplier)
*/
int cancelRequests();
/**
* {@link ScheduledExecutorService} used to handle rate-limits for {@link RestAction}
* executions. This is also used in other parts of JDA related to http requests.
*
* @return The {@link ScheduledExecutorService} used for http request handling
*
* @since 4.0.0
*/
@Nonnull
ScheduledExecutorService getRateLimitPool();
/**
* {@link ScheduledExecutorService} used to send WebSocket messages to discord.
* <br>This involves initial setup of guilds as well as keeping the connection alive.
*
* @return The {@link ScheduledExecutorService} used for WebSocket transmissions
*
* @since 4.0.0
*/
@Nonnull
ScheduledExecutorService getGatewayPool();
/**
* {@link ExecutorService} used to handle {@link RestAction} callbacks
* and completions. This is also used for handling {@link net.dv8tion.jda.api.entities.Message.Attachment} downloads
* when needed.
* <br>By default this uses the {@link ForkJoinPool#commonPool() CommonPool} of the runtime.
*
* @return The {@link ExecutorService} used for callbacks
*
* @since 4.0.0
*/
@Nonnull
ExecutorService getCallbackPool();
/**
* The {@link OkHttpClient} used for handling http requests from {@link RestAction RestActions}.
*
* @return The http client
*
* @since 4.0.0
*/
@Nonnull
OkHttpClient getHttpClient();
/**
* Direct access to audio (dis-)connect requests.
* <br>This should not be used when normal audio operation is desired.
*
* <p>The correct way to open and close an audio connection is through the {@link Guild Guild's}
* {@link AudioManager}.
*
* @throws IllegalStateException
* If {@link GatewayIntent#GUILD_VOICE_STATES} is disabled
*
* @return The {@link DirectAudioController} for this JDA instance
*
* @since 4.0.0
*/
@Nonnull
DirectAudioController getDirectAudioController();
/**
* Changes the internal EventManager.
*
* <p>The default EventManager is {@link net.dv8tion.jda.api.hooks.InterfacedEventManager InterfacedEventListener}.
* <br>There is also an {@link net.dv8tion.jda.api.hooks.AnnotatedEventManager AnnotatedEventManager} available.
*
* @param manager
* The new EventManager to use
*/
void setEventManager(@Nullable IEventManager manager);
/**
* Adds all provided listeners to the event-listeners that will be used to handle events.
* This uses the {@link net.dv8tion.jda.api.hooks.InterfacedEventManager InterfacedEventListener} by default.
* To switch to the {@link net.dv8tion.jda.api.hooks.AnnotatedEventManager AnnotatedEventManager}, use {@link #setEventManager(IEventManager)}.
*
* <p>Note: when using the {@link net.dv8tion.jda.api.hooks.InterfacedEventManager InterfacedEventListener} (default),
* given listener <b>must</b> be instance of {@link net.dv8tion.jda.api.hooks.EventListener EventListener}!
*
* @param listeners
* The listener(s) which will react to events.
*
* @throws java.lang.IllegalArgumentException
* If either listeners or one of it's objects is {@code null}.
*/
void addEventListener(@Nonnull Object... listeners);
/**
* Removes all provided listeners from the event-listeners and no longer uses them to handle events.
*
* @param listeners
* The listener(s) to be removed.
*
* @throws java.lang.IllegalArgumentException
* If either listeners or one of it's objects is {@code null}.
*/
void removeEventListener(@Nonnull Object... listeners);
/**
* Immutable List of Objects that have been registered as EventListeners.
*
* @return List of currently registered Objects acting as EventListeners.
*/
@Nonnull
List<Object> getRegisteredListeners();
/**
* Retrieves the list of global commands.
* <br>This list does not include guild commands! Use {@link Guild#retrieveCommands()} for guild commands.
* <br>This list does not include localization data. Use {@link #retrieveCommands(boolean)} to get localization data
*
* @return {@link RestAction} - Type: {@link List} of {@link Command}
*/
@Nonnull
@CheckReturnValue
default RestAction<List<Command>> retrieveCommands() {
return retrieveCommands(false);
}
/**
* Retrieves the list of global commands.
* <br>This list does not include guild commands! Use {@link Guild#retrieveCommands()} for guild commands.
*
* @param withLocalizations
* {@code true} if the localization data (such as name and description) should be included
*
* @return {@link RestAction} - Type: {@link List} of {@link Command}
*/
@Nonnull
@CheckReturnValue
RestAction<List<Command>> retrieveCommands(boolean withLocalizations);
/**
* Retrieves the existing {@link Command} instance by id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param id
* The command id
*
* @throws IllegalArgumentException
* If the provided id is not a valid snowflake
*
* @return {@link RestAction} - Type: {@link Command}
*/
@Nonnull
@CheckReturnValue
RestAction<Command> retrieveCommandById(@Nonnull String id);
/**
* Retrieves the existing {@link Command} instance by id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param id
* The command id
*
* @return {@link RestAction} - Type: {@link Command}
*/
@Nonnull
@CheckReturnValue
default RestAction<Command> retrieveCommandById(long id)
{
return retrieveCommandById(Long.toUnsignedString(id));
}
/**
* Creates or updates a global command.
* <br>If a command with the same name exists, it will be replaced.
* This operation is idempotent.
* Commands will persist between restarts of your bot, you only have to create a command once.
*
* <p>To specify a complete list of all commands you can use {@link #updateCommands()} instead.
*
* <p>You need the OAuth2 scope {@code "applications.commands"} in order to add commands to a guild.
*
* @param command
* The {@link CommandData} for the command
*
* @throws IllegalArgumentException
* If null is provided
*
* @return {@link RestAction} - Type: {@link Command}
* <br>The RestAction used to create or update the command
*
* @see Commands#slash(String, String) Commands.slash(...)
* @see Commands#message(String) Commands.message(...)
* @see Commands#user(String) Commands.user(...)
* @see Guild#upsertCommand(CommandData) Guild.upsertCommand(...)
*/
@Nonnull
@CheckReturnValue
RestAction<Command> upsertCommand(@Nonnull CommandData command);
/**
* Creates or updates a global slash command.
* <br>If a command with the same name exists, it will be replaced.
* This operation is idempotent.
* Commands will persist between restarts of your bot, you only have to create a command once.
*
* <p>To specify a complete list of all commands you can use {@link #updateCommands()} instead.
*
* <p>You need the OAuth2 scope {@code "applications.commands"} in order to add commands to a guild.
*
* @param name
* The lowercase alphanumeric (with dash) name, 1-32 characters
* @param description
* The description for the command, 1-100 characters
*
* @throws IllegalArgumentException
* If null is provided or the name/description do not meet the requirements
*
* @return {@link CommandCreateAction}
*
* @see Guild#upsertCommand(String, String)
*/
@Nonnull
@CheckReturnValue
default CommandCreateAction upsertCommand(@Nonnull String name, @Nonnull String description)
{
return (CommandCreateAction) upsertCommand(new CommandDataImpl(name, description));
}
/**
* Configures the complete list of global commands.
* <br>This will replace the existing command list for this bot. You should only use this once on startup!
*
* <p>This operation is idempotent.
* Commands will persist between restarts of your bot, you only have to create a command once.
*
* <p>You need the OAuth2 scope {@code "applications.commands"} in order to add commands to a guild.
*
* <p><b>Examples</b>
*
* <p>Set list to 2 commands:
* <pre>{@code
* jda.updateCommands()
* .addCommands(Commands.slash("ping", "Gives the current ping"))
* .addCommands(Commands.slash("ban", "Ban the target user")
* .setGuildOnly(true)
* .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS))
* .addOption(OptionType.USER, "user", "The user to ban", true))
* .queue();
* }</pre>
*
* <p>Delete all commands:
* <pre>{@code
* jda.updateCommands().queue();
* }</pre>
*
* @return {@link CommandListUpdateAction}
*
* @see Guild#updateCommands()
*/
@Nonnull
@CheckReturnValue
CommandListUpdateAction updateCommands();
/**
* Edit an existing global command by id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param id
* The id of the command to edit
*
* @throws IllegalArgumentException
* If the provided id is not a valid snowflake
*
* @return {@link CommandEditAction} used to edit the command
*/
@Nonnull
@CheckReturnValue
CommandEditAction editCommandById(@Nonnull String id);
/**
* Edit an existing global command by id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param id
* The id of the command to edit
*
* @return {@link CommandEditAction} used to edit the command
*/
@Nonnull
@CheckReturnValue
default CommandEditAction editCommandById(long id)
{
return editCommandById(Long.toUnsignedString(id));
}
/**
* Delete the global command for this id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param commandId
* The id of the command that should be deleted
*
* @throws IllegalArgumentException
* If the provided id is not a valid snowflake
*
* @return {@link RestAction}
*/
@Nonnull
@CheckReturnValue
RestAction<Void> deleteCommandById(@Nonnull String commandId);
/**
* Delete the global command for this id.
*
* <p>If there is no command with the provided ID,
* this RestAction fails with {@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_COMMAND ErrorResponse.UNKNOWN_COMMAND}
*
* @param commandId
* The id of the command that should be deleted
*
* @return {@link RestAction}
*/
@Nonnull
@CheckReturnValue
default RestAction<Void> deleteCommandById(long commandId)
{
return deleteCommandById(Long.toUnsignedString(commandId));
}
/**
* Retrieves the currently configured {@link RoleConnectionMetadata} records for this application.
*
* @return {@link RestAction} - Type: {@link List} of {@link RoleConnectionMetadata}
*
* @see <a href="https://discord.com/developers/docs/tutorials/configuring-app-metadata-for-linked-roles" target="_blank">Configuring App Metadata for Linked Roles</a>
*/
@Nonnull
@CheckReturnValue
RestAction<List<RoleConnectionMetadata>> retrieveRoleConnectionMetadata();
/**
* Updates the currently configured {@link RoleConnectionMetadata} records for this application.
*
* <p>Returns the updated connection metadata records on success.
*
* @param records
* The new records to set
*
* @throws IllegalArgumentException
* If null is provided or more than {@value RoleConnectionMetadata#MAX_RECORDS} records are configured.
*
* @return {@link RestAction} - Type: {@link List} of {@link RoleConnectionMetadata}
*
* @see <a href="https://discord.com/developers/docs/tutorials/configuring-app-metadata-for-linked-roles" target="_blank">Configuring App Metadata for Linked Roles</a>
*/
@Nonnull
@CheckReturnValue
RestAction<List<RoleConnectionMetadata>> updateRoleConnectionMetadata(@Nonnull Collection<? extends RoleConnectionMetadata> records);
/**
* Constructs a new {@link Guild Guild} with the specified name
* <br>Use the returned {@link GuildAction GuildAction} to provide
* further details and settings for the resulting Guild!
*
* <p>This RestAction does not provide the resulting Guild!
* It will be in a following {@link net.dv8tion.jda.api.events.guild.GuildJoinEvent GuildJoinEvent}.
*
* @param name
* The name of the resulting guild
*
* @throws java.lang.IllegalStateException
* If the currently logged in account is in 10 or more guilds
* @throws java.lang.IllegalArgumentException
* If the provided name is empty, {@code null} or not between 2-100 characters
*
* @return {@link GuildAction GuildAction}
* <br>Allows for setting various details for the resulting Guild
*/
@Nonnull
@CheckReturnValue
GuildAction createGuild(@Nonnull String name);
/**
* Constructs a new {@link Guild Guild} from the specified template code.
*
* <p>This RestAction does not provide the resulting Guild!
* It will be in a following {@link net.dv8tion.jda.api.events.guild.GuildJoinEvent GuildJoinEvent}.
*
* <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_GUILD_TEMPLATE Unknown Guild Template}
* <br>The template doesn't exist.</li>
* </ul>
*
* @param code
* The template code to use to create a guild
* @param name
* The name of the resulting guild
* @param icon
* The {@link net.dv8tion.jda.api.entities.Icon Icon} to use, or null to use no icon
*
* @throws java.lang.IllegalStateException
* If the currently logged in account is in 10 or more guilds
* @throws java.lang.IllegalArgumentException
* If the provided name is empty, {@code null} or not between 2-100 characters
*
* @return {@link net.dv8tion.jda.api.requests.RestAction RestAction}
*/
@Nonnull
@CheckReturnValue
RestAction<Void> createGuildFromTemplate(@Nonnull String code, @Nonnull String name, @Nullable Icon icon);
/**
* {@link net.dv8tion.jda.api.utils.cache.CacheView CacheView} of
* all cached {@link net.dv8tion.jda.api.managers.AudioManager AudioManagers} created for this JDA instance.
* <br>AudioManagers are created when first retrieved via {@link Guild#getAudioManager() Guild.getAudioManager()}.
* <u>Using this will perform better than calling {@code Guild.getAudioManager()} iteratively as that would cause many useless audio managers to be created!</u>
*
* <p>AudioManagers are cross-session persistent!
*
* @return {@link net.dv8tion.jda.api.utils.cache.CacheView CacheView}
*/
@Nonnull
CacheView<AudioManager> getAudioManagerCache();
/**
* Immutable list of all created {@link net.dv8tion.jda.api.managers.AudioManager AudioManagers} for this JDA instance!
*
* @return Immutable list of all created AudioManager instances
*/
@Nonnull
@Unmodifiable
default List<AudioManager> getAudioManagers()
{
return getAudioManagerCache().asList();
}
/**
* {@link net.dv8tion.jda.api.utils.cache.SnowflakeCacheView SnowflakeCacheView} of
* all <b>cached</b> {@link net.dv8tion.jda.api.entities.User Users} visible to this JDA session.
*
* @return {@link net.dv8tion.jda.api.utils.cache.SnowflakeCacheView SnowflakeCacheView}
*/
@Nonnull
SnowflakeCacheView<User> getUserCache();
/**
* An immutable list of all {@link net.dv8tion.jda.api.entities.User Users} that share a
* {@link Guild Guild} with the currently logged in account.
* <br>This list will never contain duplicates and represents all
* {@link net.dv8tion.jda.api.entities.User Users} that JDA can currently see.
*
* <p><b>This will only check cached users!</b>
*
* <p>If the developer is sharding, then only users from guilds connected to the specifically logged in
* shard will be returned in the List.
*
* <p>This copies the backing store into a list. This means every call
* creates a new list with O(n) complexity. It is recommended to store this into
* a local variable or use {@link #getUserCache()} and use its more efficient
* versions of handling these values.
*
* @return Immutable list of all {@link net.dv8tion.jda.api.entities.User Users} that are visible to JDA.
*/
@Nonnull
@Unmodifiable
default List<User> getUsers()
{
return getUserCache().asList();
}
/**
* This returns the {@link net.dv8tion.jda.api.entities.User User} which has the same id as the one provided.
* <br>If there is no visible user with an id that matches the provided one, this returns {@code null}.
*
* <p><b>This will only check cached users!</b>
*
* @param id
* The id of the requested {@link net.dv8tion.jda.api.entities.User User}.
*
* @throws java.lang.NumberFormatException
* If the provided {@code id} cannot be parsed by {@link Long#parseLong(String)}
*
* @return Possibly-null {@link net.dv8tion.jda.api.entities.User User} with matching id.
*
* @see #retrieveUserById(String)
*/
@Nullable
default User getUserById(@Nonnull String id)
{
return getUserCache().getElementById(id);
}
/**
* This returns the {@link net.dv8tion.jda.api.entities.User User} which has the same id as the one provided.
* <br>If there is no visible user with an id that matches the provided one, this returns {@code null}.