Java Discord API - A comprehensive Java library for building Discord bots and applications
npx @tessl/cli install tessl/maven-net-dv8tion--jda@5.6.0JDA 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.
implementation("net.dv8tion:JDA:5.6.1")import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import java.util.EnumSet;
public class SimpleBot extends ListenerAdapter {
public static void main(String[] args) {
// Create JDA instance with basic configuration
JDA jda = JDABuilder.createLight("BOT_TOKEN",
EnumSet.of(GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT))
.addEventListeners(new SimpleBot())
.build();
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
// Respond to messages
if (event.getMessage().getContentRaw().equals("!ping")) {
event.getChannel().sendMessage("Pong!").queue();
}
}
}JDA is built around several key components:
JDA interface serves as the main registry and entry point for all API accessJDABuilder provides fluent configuration for creating JDA instancesPrimary interfaces for creating, configuring, and managing JDA instances and bot lifecycle.
// Main JDA interface - acts as registry for all API access
interface JDA {
Status getStatus();
EnumSet<GatewayIntent> getGatewayIntents();
JDA awaitReady() throws InterruptedException;
void shutdown();
void addEventListener(Object... listeners);
void removeEventListener(Object... listeners);
}
// Builder for creating JDA instances
class JDABuilder {
static JDABuilder createDefault(String token);
static JDABuilder createLight(String token);
JDABuilder enableIntents(GatewayIntent... intents);
JDABuilder addEventListeners(Object... listeners);
JDABuilder setStatus(OnlineStatus status);
JDABuilder setActivity(Activity activity);
JDA build();
}
// Connection status enumeration
enum Status {
INITIALIZING, INITIALIZED, LOGGING_IN, CONNECTING_TO_WEBSOCKET,
IDENTIFYING_SESSION, AWAITING_LOGIN_CONFIRMATION, LOADING_SUBSYSTEMS,
CONNECTED, READY, DISCONNECTED, RECONNECTING, SHUTTING_DOWN, SHUTDOWN,
FAILED_TO_LOGIN
}Comprehensive object model representing all Discord entities with full CRUD operations and relationship management.
// Core user representation
interface User {
String getName();
String getDiscriminator();
String getGlobalName();
String getAvatarUrl();
boolean isBot();
RestAction<PrivateChannel> openPrivateChannel();
}
// Guild member representation
interface Member {
User getUser();
String getNickname();
String getEffectiveName();
List<Role> getRoles();
EnumSet<Permission> getPermissions();
OffsetDateTime getTimeJoined();
AuditableRestAction<Void> kick();
}
// Guild (server) representation
interface Guild {
String getName();
Member getOwner();
List<Member> getMembers();
List<Role> getRoles();
List<GuildChannel> getChannels();
RoleAction createRole();
ChannelAction<TextChannel> createTextChannel(String name);
}Complete message handling including creation, editing, reactions, embeds, attachments, and rich message components.
// Message interface
interface Message {
String getContentRaw();
String getContentDisplay();
User getAuthor();
MessageChannel getChannel();
List<MessageEmbed> getEmbeds();
List<Message.Attachment> getAttachments();
RestAction<Void> delete();
MessageEditAction editMessage(String content);
RestAction<Void> addReaction(Emoji emoji);
}
// Message creation
interface MessageCreateAction extends RestAction<Message> {
MessageCreateAction setContent(String content);
MessageCreateAction setEmbeds(MessageEmbed... embeds);
MessageCreateAction setFiles(FileUpload... files);
MessageCreateAction setComponents(ActionRow... components);
}
// Embed builder
class EmbedBuilder {
EmbedBuilder setTitle(String title);
EmbedBuilder setDescription(String description);
EmbedBuilder addField(String name, String value, boolean inline);
EmbedBuilder setColor(Color color);
MessageEmbed build();
}Real-time event handling system for responding to Discord gateway events with comprehensive event types and flexible listener patterns.
// Base event interface
interface GenericEvent {
JDA getJDA();
long getResponseNumber();
}
// Event listener base class
abstract class ListenerAdapter {
void onMessageReceived(MessageReceivedEvent event);
void onSlashCommandInteraction(SlashCommandInteractionEvent event);
void onGuildMemberJoin(GuildMemberJoinEvent event);
void onGuildMemberRemove(GuildMemberRemoveEvent event);
// ... many more event handler methods
}
// Key event types
class MessageReceivedEvent extends GenericMessageEvent {
Message getMessage();
User getAuthor();
MessageChannel getChannel();
}Modern Discord interactions including slash commands, buttons, select menus, modals, and context menus with full builder pattern support.
// Slash command interactions
interface SlashCommandInteraction extends IReplyCallback {
String getName();
List<OptionMapping> getOptions();
OptionMapping getOption(String name);
String getSubcommandName();
}
// Command builders
class Commands {
static SlashCommandData slash(String name, String description);
static CommandData user(String name);
static CommandData message(String name);
}
// Reply callback interface
interface IReplyCallback {
ReplyCallbackAction reply(String content);
ReplyCallbackAction reply(MessageEmbed embed);
ReplyCallbackAction deferReply();
InteractionHook getHook();
}Powerful asynchronous request system with automatic rate-limit handling, chaining capabilities, error handling, and execution control.
// Core RestAction interface
interface RestAction<T> {
void queue();
void queue(Consumer<? super T> success);
void queue(Consumer<? super T> success, Consumer<? super Throwable> failure);
CompletableFuture<T> submit();
T complete();
RestAction<T> queueAfter(long delay, TimeUnit unit);
<U> RestAction<U> flatMap(Function<? super T, ? extends RestAction<U>> flatMapper);
<U> RestAction<U> map(Function<? super T, ? extends U> mapper);
}
// Auditable actions that appear in audit log
interface AuditableRestAction<T> extends RestAction<T> {
AuditableRestAction<T> reason(String reason);
}Voice channel connections with audio sending/receiving capabilities, including native audio processing and WebRTC support.
// Audio manager for voice connections
interface AudioManager {
void openAudioConnection(VoiceChannel channel);
void closeAudioConnection();
void setSendingHandler(AudioSendHandler handler);
void setReceivingHandler(AudioReceiveHandler handler);
boolean isConnected();
VoiceChannel getConnectedChannel();
}
// Audio send handler
interface AudioSendHandler {
boolean canProvide();
ByteBuffer provide20MsAudio();
boolean isOpus();
}
// Audio receive handler
interface AudioReceiveHandler {
boolean canReceiveUser();
void handleUserAudio(UserAudio userAudio);
void handleCombinedAudio(CombinedAudio combinedAudio);
}Multi-shard bot support for scaling beyond Discord's gateway limits with centralized management and cross-shard operations.
// Shard manager for large bots
interface ShardManager {
List<JDA> getShards();
JDA getShardById(int shardId);
void start(int shardId);
void restart(int shardId);
void shutdown();
void setStatus(OnlineStatus status);
SnowflakeCacheView<Guild> getGuildCache();
SnowflakeCacheView<User> getUserCache();
}
// Shard manager builder
class DefaultShardManagerBuilder {
static DefaultShardManagerBuilder createDefault(String token);
DefaultShardManagerBuilder setShardsTotal(int shardsTotal);
DefaultShardManagerBuilder setShards(int minShardId, int maxShardId);
DefaultShardManagerBuilder addEventListeners(Object... listeners);
ShardManager build();
}// Gateway intents for event filtering
enum GatewayIntent {
GUILDS, GUILD_MEMBERS, GUILD_MODERATION, GUILD_EMOJIS_AND_STICKERS,
GUILD_INTEGRATIONS, GUILD_WEBHOOKS, GUILD_INVITES, GUILD_VOICE_STATES,
GUILD_PRESENCES, GUILD_MESSAGES, GUILD_MESSAGE_REACTIONS, GUILD_MESSAGE_TYPING,
DIRECT_MESSAGES, DIRECT_MESSAGE_REACTIONS, DIRECT_MESSAGE_TYPING, MESSAGE_CONTENT,
GUILD_SCHEDULED_EVENTS, AUTO_MODERATION_CONFIGURATION, AUTO_MODERATION_EXECUTION;
EnumSet<GatewayIntent> DEFAULT = EnumSet.of(GUILDS, GUILD_MODERATION, GUILD_EMOJIS_AND_STICKERS,
GUILD_INTEGRATIONS, GUILD_WEBHOOKS, GUILD_INVITES, GUILD_VOICE_STATES, GUILD_MESSAGES,
GUILD_MESSAGE_REACTIONS, GUILD_MESSAGE_TYPING, DIRECT_MESSAGES, DIRECT_MESSAGE_REACTIONS,
DIRECT_MESSAGE_TYPING, GUILD_SCHEDULED_EVENTS, AUTO_MODERATION_CONFIGURATION, AUTO_MODERATION_EXECUTION);
}
// Discord permissions
enum Permission {
CREATE_INSTANT_INVITE, KICK_MEMBERS, BAN_MEMBERS, ADMINISTRATOR, MANAGE_CHANNELS,
MANAGE_SERVER, ADD_REACTIONS, VIEW_AUDIT_LOGS, PRIORITY_SPEAKER, STREAM,
VIEW_CHANNEL, SEND_MESSAGES, SEND_TTS_MESSAGES, MANAGE_MESSAGES, EMBED_LINKS,
ATTACH_FILES, READ_MESSAGE_HISTORY, MENTION_EVERYONE, USE_EXTERNAL_EMOJIS,
VIEW_GUILD_INSIGHTS, CONNECT, SPEAK, MUTE_MEMBERS, DEAFEN_MEMBERS, MOVE_MEMBERS,
USE_VAD, CHANGE_NICKNAME, MANAGE_NICKNAMES, MANAGE_ROLES, MANAGE_WEBHOOKS,
MANAGE_EMOJIS_AND_STICKERS, USE_APPLICATION_COMMANDS, REQUEST_TO_SPEAK,
MANAGE_EVENTS, MANAGE_THREADS, CREATE_PUBLIC_THREADS, CREATE_PRIVATE_THREADS,
USE_EXTERNAL_STICKERS, SEND_MESSAGES_IN_THREADS, USE_EMBEDDED_ACTIVITIES,
MODERATE_MEMBERS, VIEW_CREATOR_MONETIZATION_ANALYTICS, USE_SOUNDBOARD,
USE_EXTERNAL_SOUNDS, SEND_VOICE_MESSAGES
}
// Online status options
enum OnlineStatus {
ONLINE, IDLE, DO_NOT_DISTURB, INVISIBLE, OFFLINE, UNKNOWN
}
// Channel types
enum ChannelType {
TEXT, PRIVATE, VOICE, GROUP, CATEGORY, NEWS, STAGE, NEWS_THREAD,
PUBLIC_THREAD, PRIVATE_THREAD, FORUM, MEDIA, GUILD_DIRECTORY
}
// REST API ping information
class RestPing {
long getTime();
CompletableFuture<Long> submit();
}
// Bot application information
interface ApplicationInfo {
String getName();
String getDescription();
User getOwner();
String getIconId();
String getIconUrl();
List<String> getTags();
boolean isBotPublic();
boolean isBotRequireCodeGrant();
}
// Cache view interfaces
interface CacheView<T> {
long size();
boolean isEmpty();
List<T> asList();
Set<T> asSet();
Stream<T> stream();
}
interface SnowflakeCacheView<T> extends CacheView<T> {
T getElementById(long id);
T getElementById(String id);
List<T> getElementsByName(String name, boolean ignoreCase);
}
// Event management
interface IEventManager {
void register(Object listener);
void unregister(Object listener);
void handle(GenericEvent event);
List<Object> getRegisteredListeners();
}
// Presence management
interface Presence {
void setStatus(OnlineStatus status);
void setActivity(Activity activity);
void setIdle(boolean idle);
OnlineStatus getStatus();
Activity getActivity();
boolean isIdle();
}
// Activity representation
interface Activity {
String getName();
String getUrl();
ActivityType getType();
RichPresence asRichPresence();
static Activity playing(String name);
static Activity streaming(String name, String url);
static Activity listening(String name);
static Activity watching(String name);
static Activity competing(String name);
}
enum ActivityType {
PLAYING, STREAMING, LISTENING, WATCHING, COMPETING
}
// Direct audio controller
interface DirectAudioController {
void connect(VoiceChannel channel);
void disconnect();
boolean isConnected();
VoiceChannel getConnectedChannel();
}
// Cache flags for memory optimization
enum CacheFlag {
ACTIVITY, VOICE_STATE, EMOJI, STICKER, CLIENT_STATUS, MEMBER_OVERRIDES,
ROLE_TAGS, FORUM_TAGS, ONLINE_STATUS, SCHEDULED_EVENTS
}