Java Discord API - A comprehensive Java library for building Discord bots and applications
npx @tessl/cli install tessl/maven-net-dv8tion--jda@5.6.00
# JDA (Java Discord API)
1
2
JDA is a comprehensive Java library that provides a complete wrapper around Discord's REST and Gateway APIs for building Discord bots and applications. It features an event-driven architecture with real-time gateway event handling, a powerful RestAction system for asynchronous API interactions, configurable caching policies, full support for Discord interactions including slash commands, voice and audio capabilities, and built-in sharding support for large-scale applications.
3
4
## Package Information
5
6
- **Package Name**: net.dv8tion:JDA
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Minimum Java Version**: Java SE 8
10
- **Installation**: `implementation("net.dv8tion:JDA:5.6.1")`
11
12
## Core Imports
13
14
```java
15
import net.dv8tion.jda.api.JDA;
16
import net.dv8tion.jda.api.JDABuilder;
17
import net.dv8tion.jda.api.entities.*;
18
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
19
import net.dv8tion.jda.api.hooks.ListenerAdapter;
20
import net.dv8tion.jda.api.requests.GatewayIntent;
21
```
22
23
## Basic Usage
24
25
```java
26
import net.dv8tion.jda.api.JDABuilder;
27
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
28
import net.dv8tion.jda.api.hooks.ListenerAdapter;
29
import net.dv8tion.jda.api.requests.GatewayIntent;
30
import java.util.EnumSet;
31
32
public class SimpleBot extends ListenerAdapter {
33
public static void main(String[] args) {
34
// Create JDA instance with basic configuration
35
JDA jda = JDABuilder.createLight("BOT_TOKEN",
36
EnumSet.of(GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT))
37
.addEventListeners(new SimpleBot())
38
.build();
39
}
40
41
@Override
42
public void onMessageReceived(MessageReceivedEvent event) {
43
// Respond to messages
44
if (event.getMessage().getContentRaw().equals("!ping")) {
45
event.getChannel().sendMessage("Pong!").queue();
46
}
47
}
48
}
49
```
50
51
## Architecture
52
53
JDA is built around several key components:
54
55
- **Core System**: `JDA` interface serves as the main registry and entry point for all API access
56
- **Builder Pattern**: `JDABuilder` provides fluent configuration for creating JDA instances
57
- **Entity System**: Rich object model representing Discord entities (guilds, channels, users, messages, roles)
58
- **Event System**: Real-time event handling via gateway connection with customizable event managers
59
- **RestAction System**: Asynchronous request handling with rate-limit management and chaining support
60
- **Interaction System**: Full support for slash commands, buttons, select menus, and modals
61
- **Caching System**: Configurable entity caching with memory/performance trade-offs
62
- **Audio System**: Voice channel connections with send/receive audio capabilities
63
- **Sharding System**: Multi-shard support for large-scale bot deployments
64
65
## Capabilities
66
67
### Core JDA Management
68
69
Primary interfaces for creating, configuring, and managing JDA instances and bot lifecycle.
70
71
```java { .api }
72
// Main JDA interface - acts as registry for all API access
73
interface JDA {
74
Status getStatus();
75
EnumSet<GatewayIntent> getGatewayIntents();
76
JDA awaitReady() throws InterruptedException;
77
void shutdown();
78
void addEventListener(Object... listeners);
79
void removeEventListener(Object... listeners);
80
}
81
82
// Builder for creating JDA instances
83
class JDABuilder {
84
static JDABuilder createDefault(String token);
85
static JDABuilder createLight(String token);
86
JDABuilder enableIntents(GatewayIntent... intents);
87
JDABuilder addEventListeners(Object... listeners);
88
JDABuilder setStatus(OnlineStatus status);
89
JDABuilder setActivity(Activity activity);
90
JDA build();
91
}
92
93
// Connection status enumeration
94
enum Status {
95
INITIALIZING, INITIALIZED, LOGGING_IN, CONNECTING_TO_WEBSOCKET,
96
IDENTIFYING_SESSION, AWAITING_LOGIN_CONFIRMATION, LOADING_SUBSYSTEMS,
97
CONNECTED, READY, DISCONNECTED, RECONNECTING, SHUTTING_DOWN, SHUTDOWN,
98
FAILED_TO_LOGIN
99
}
100
```
101
102
[Core JDA Management](./core-management.md)
103
104
### Discord Entities
105
106
Comprehensive object model representing all Discord entities with full CRUD operations and relationship management.
107
108
```java { .api }
109
// Core user representation
110
interface User {
111
String getName();
112
String getDiscriminator();
113
String getGlobalName();
114
String getAvatarUrl();
115
boolean isBot();
116
RestAction<PrivateChannel> openPrivateChannel();
117
}
118
119
// Guild member representation
120
interface Member {
121
User getUser();
122
String getNickname();
123
String getEffectiveName();
124
List<Role> getRoles();
125
EnumSet<Permission> getPermissions();
126
OffsetDateTime getTimeJoined();
127
AuditableRestAction<Void> kick();
128
}
129
130
// Guild (server) representation
131
interface Guild {
132
String getName();
133
Member getOwner();
134
List<Member> getMembers();
135
List<Role> getRoles();
136
List<GuildChannel> getChannels();
137
RoleAction createRole();
138
ChannelAction<TextChannel> createTextChannel(String name);
139
}
140
```
141
142
[Discord Entities](./entities.md)
143
144
### Messaging System
145
146
Complete message handling including creation, editing, reactions, embeds, attachments, and rich message components.
147
148
```java { .api }
149
// Message interface
150
interface Message {
151
String getContentRaw();
152
String getContentDisplay();
153
User getAuthor();
154
MessageChannel getChannel();
155
List<MessageEmbed> getEmbeds();
156
List<Message.Attachment> getAttachments();
157
RestAction<Void> delete();
158
MessageEditAction editMessage(String content);
159
RestAction<Void> addReaction(Emoji emoji);
160
}
161
162
// Message creation
163
interface MessageCreateAction extends RestAction<Message> {
164
MessageCreateAction setContent(String content);
165
MessageCreateAction setEmbeds(MessageEmbed... embeds);
166
MessageCreateAction setFiles(FileUpload... files);
167
MessageCreateAction setComponents(ActionRow... components);
168
}
169
170
// Embed builder
171
class EmbedBuilder {
172
EmbedBuilder setTitle(String title);
173
EmbedBuilder setDescription(String description);
174
EmbedBuilder addField(String name, String value, boolean inline);
175
EmbedBuilder setColor(Color color);
176
MessageEmbed build();
177
}
178
```
179
180
[Messaging System](./messaging.md)
181
182
### Event System
183
184
Real-time event handling system for responding to Discord gateway events with comprehensive event types and flexible listener patterns.
185
186
```java { .api }
187
// Base event interface
188
interface GenericEvent {
189
JDA getJDA();
190
long getResponseNumber();
191
}
192
193
// Event listener base class
194
abstract class ListenerAdapter {
195
void onMessageReceived(MessageReceivedEvent event);
196
void onSlashCommandInteraction(SlashCommandInteractionEvent event);
197
void onGuildMemberJoin(GuildMemberJoinEvent event);
198
void onGuildMemberRemove(GuildMemberRemoveEvent event);
199
// ... many more event handler methods
200
}
201
202
// Key event types
203
class MessageReceivedEvent extends GenericMessageEvent {
204
Message getMessage();
205
User getAuthor();
206
MessageChannel getChannel();
207
}
208
```
209
210
[Event System](./events.md)
211
212
### Interaction System
213
214
Modern Discord interactions including slash commands, buttons, select menus, modals, and context menus with full builder pattern support.
215
216
```java { .api }
217
// Slash command interactions
218
interface SlashCommandInteraction extends IReplyCallback {
219
String getName();
220
List<OptionMapping> getOptions();
221
OptionMapping getOption(String name);
222
String getSubcommandName();
223
}
224
225
// Command builders
226
class Commands {
227
static SlashCommandData slash(String name, String description);
228
static CommandData user(String name);
229
static CommandData message(String name);
230
}
231
232
// Reply callback interface
233
interface IReplyCallback {
234
ReplyCallbackAction reply(String content);
235
ReplyCallbackAction reply(MessageEmbed embed);
236
ReplyCallbackAction deferReply();
237
InteractionHook getHook();
238
}
239
```
240
241
[Interaction System](./interactions.md)
242
243
### RestAction System
244
245
Powerful asynchronous request system with automatic rate-limit handling, chaining capabilities, error handling, and execution control.
246
247
```java { .api }
248
// Core RestAction interface
249
interface RestAction<T> {
250
void queue();
251
void queue(Consumer<? super T> success);
252
void queue(Consumer<? super T> success, Consumer<? super Throwable> failure);
253
CompletableFuture<T> submit();
254
T complete();
255
RestAction<T> queueAfter(long delay, TimeUnit unit);
256
<U> RestAction<U> flatMap(Function<? super T, ? extends RestAction<U>> flatMapper);
257
<U> RestAction<U> map(Function<? super T, ? extends U> mapper);
258
}
259
260
// Auditable actions that appear in audit log
261
interface AuditableRestAction<T> extends RestAction<T> {
262
AuditableRestAction<T> reason(String reason);
263
}
264
```
265
266
[RestAction System](./restactions.md)
267
268
### Audio System
269
270
Voice channel connections with audio sending/receiving capabilities, including native audio processing and WebRTC support.
271
272
```java { .api }
273
// Audio manager for voice connections
274
interface AudioManager {
275
void openAudioConnection(VoiceChannel channel);
276
void closeAudioConnection();
277
void setSendingHandler(AudioSendHandler handler);
278
void setReceivingHandler(AudioReceiveHandler handler);
279
boolean isConnected();
280
VoiceChannel getConnectedChannel();
281
}
282
283
// Audio send handler
284
interface AudioSendHandler {
285
boolean canProvide();
286
ByteBuffer provide20MsAudio();
287
boolean isOpus();
288
}
289
290
// Audio receive handler
291
interface AudioReceiveHandler {
292
boolean canReceiveUser();
293
void handleUserAudio(UserAudio userAudio);
294
void handleCombinedAudio(CombinedAudio combinedAudio);
295
}
296
```
297
298
[Audio System](./audio.md)
299
300
### Sharding System
301
302
Multi-shard bot support for scaling beyond Discord's gateway limits with centralized management and cross-shard operations.
303
304
```java { .api }
305
// Shard manager for large bots
306
interface ShardManager {
307
List<JDA> getShards();
308
JDA getShardById(int shardId);
309
void start(int shardId);
310
void restart(int shardId);
311
void shutdown();
312
void setStatus(OnlineStatus status);
313
SnowflakeCacheView<Guild> getGuildCache();
314
SnowflakeCacheView<User> getUserCache();
315
}
316
317
// Shard manager builder
318
class DefaultShardManagerBuilder {
319
static DefaultShardManagerBuilder createDefault(String token);
320
DefaultShardManagerBuilder setShardsTotal(int shardsTotal);
321
DefaultShardManagerBuilder setShards(int minShardId, int maxShardId);
322
DefaultShardManagerBuilder addEventListeners(Object... listeners);
323
ShardManager build();
324
}
325
```
326
327
[Sharding System](./sharding.md)
328
329
## Types
330
331
```java { .api }
332
// Gateway intents for event filtering
333
enum GatewayIntent {
334
GUILDS, GUILD_MEMBERS, GUILD_MODERATION, GUILD_EMOJIS_AND_STICKERS,
335
GUILD_INTEGRATIONS, GUILD_WEBHOOKS, GUILD_INVITES, GUILD_VOICE_STATES,
336
GUILD_PRESENCES, GUILD_MESSAGES, GUILD_MESSAGE_REACTIONS, GUILD_MESSAGE_TYPING,
337
DIRECT_MESSAGES, DIRECT_MESSAGE_REACTIONS, DIRECT_MESSAGE_TYPING, MESSAGE_CONTENT,
338
GUILD_SCHEDULED_EVENTS, AUTO_MODERATION_CONFIGURATION, AUTO_MODERATION_EXECUTION;
339
340
EnumSet<GatewayIntent> DEFAULT = EnumSet.of(GUILDS, GUILD_MODERATION, GUILD_EMOJIS_AND_STICKERS,
341
GUILD_INTEGRATIONS, GUILD_WEBHOOKS, GUILD_INVITES, GUILD_VOICE_STATES, GUILD_MESSAGES,
342
GUILD_MESSAGE_REACTIONS, GUILD_MESSAGE_TYPING, DIRECT_MESSAGES, DIRECT_MESSAGE_REACTIONS,
343
DIRECT_MESSAGE_TYPING, GUILD_SCHEDULED_EVENTS, AUTO_MODERATION_CONFIGURATION, AUTO_MODERATION_EXECUTION);
344
}
345
346
// Discord permissions
347
enum Permission {
348
CREATE_INSTANT_INVITE, KICK_MEMBERS, BAN_MEMBERS, ADMINISTRATOR, MANAGE_CHANNELS,
349
MANAGE_SERVER, ADD_REACTIONS, VIEW_AUDIT_LOGS, PRIORITY_SPEAKER, STREAM,
350
VIEW_CHANNEL, SEND_MESSAGES, SEND_TTS_MESSAGES, MANAGE_MESSAGES, EMBED_LINKS,
351
ATTACH_FILES, READ_MESSAGE_HISTORY, MENTION_EVERYONE, USE_EXTERNAL_EMOJIS,
352
VIEW_GUILD_INSIGHTS, CONNECT, SPEAK, MUTE_MEMBERS, DEAFEN_MEMBERS, MOVE_MEMBERS,
353
USE_VAD, CHANGE_NICKNAME, MANAGE_NICKNAMES, MANAGE_ROLES, MANAGE_WEBHOOKS,
354
MANAGE_EMOJIS_AND_STICKERS, USE_APPLICATION_COMMANDS, REQUEST_TO_SPEAK,
355
MANAGE_EVENTS, MANAGE_THREADS, CREATE_PUBLIC_THREADS, CREATE_PRIVATE_THREADS,
356
USE_EXTERNAL_STICKERS, SEND_MESSAGES_IN_THREADS, USE_EMBEDDED_ACTIVITIES,
357
MODERATE_MEMBERS, VIEW_CREATOR_MONETIZATION_ANALYTICS, USE_SOUNDBOARD,
358
USE_EXTERNAL_SOUNDS, SEND_VOICE_MESSAGES
359
}
360
361
// Online status options
362
enum OnlineStatus {
363
ONLINE, IDLE, DO_NOT_DISTURB, INVISIBLE, OFFLINE, UNKNOWN
364
}
365
366
// Channel types
367
enum ChannelType {
368
TEXT, PRIVATE, VOICE, GROUP, CATEGORY, NEWS, STAGE, NEWS_THREAD,
369
PUBLIC_THREAD, PRIVATE_THREAD, FORUM, MEDIA, GUILD_DIRECTORY
370
}
371
372
// REST API ping information
373
class RestPing {
374
long getTime();
375
CompletableFuture<Long> submit();
376
}
377
378
// Bot application information
379
interface ApplicationInfo {
380
String getName();
381
String getDescription();
382
User getOwner();
383
String getIconId();
384
String getIconUrl();
385
List<String> getTags();
386
boolean isBotPublic();
387
boolean isBotRequireCodeGrant();
388
}
389
390
// Cache view interfaces
391
interface CacheView<T> {
392
long size();
393
boolean isEmpty();
394
List<T> asList();
395
Set<T> asSet();
396
Stream<T> stream();
397
}
398
399
interface SnowflakeCacheView<T> extends CacheView<T> {
400
T getElementById(long id);
401
T getElementById(String id);
402
List<T> getElementsByName(String name, boolean ignoreCase);
403
}
404
405
// Event management
406
interface IEventManager {
407
void register(Object listener);
408
void unregister(Object listener);
409
void handle(GenericEvent event);
410
List<Object> getRegisteredListeners();
411
}
412
413
// Presence management
414
interface Presence {
415
void setStatus(OnlineStatus status);
416
void setActivity(Activity activity);
417
void setIdle(boolean idle);
418
OnlineStatus getStatus();
419
Activity getActivity();
420
boolean isIdle();
421
}
422
423
// Activity representation
424
interface Activity {
425
String getName();
426
String getUrl();
427
ActivityType getType();
428
RichPresence asRichPresence();
429
430
static Activity playing(String name);
431
static Activity streaming(String name, String url);
432
static Activity listening(String name);
433
static Activity watching(String name);
434
static Activity competing(String name);
435
}
436
437
enum ActivityType {
438
PLAYING, STREAMING, LISTENING, WATCHING, COMPETING
439
}
440
441
// Direct audio controller
442
interface DirectAudioController {
443
void connect(VoiceChannel channel);
444
void disconnect();
445
boolean isConnected();
446
VoiceChannel getConnectedChannel();
447
}
448
449
// Cache flags for memory optimization
450
enum CacheFlag {
451
ACTIVITY, VOICE_STATE, EMOJI, STICKER, CLIENT_STATUS, MEMBER_OVERRIDES,
452
ROLE_TAGS, FORUM_TAGS, ONLINE_STATUS, SCHEDULED_EVENTS
453
}
454
```