- Notifications
You must be signed in to change notification settings - Fork0
Java wrapper for the popular chat & VOIP service: Discordhttps://discord.com
License
ishwi/JDA
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
JDA strives to provide a clean and full wrapping of the Discord REST api and its Websocket-Events for Java.This library is a helpful tool that provides the functionality to create a discord bot in java.
Due to official statements made by the Discord developers we will no longer support unofficial features. These featuresare undocumented API endpoints or protocols that are not available to bot-accounts.
Please see theDiscord docs for more information about bot accounts.
- Introduction
- Sharding
- Entity Lifetimes
- Download
- Documentation
- Support
- Extensions And Plugins
- Contributing
- Dependencies
- Other Libraries
Discord is currently prohibiting creation and usage of automated client accounts (AccountType.CLIENT).We have officially dropped support for client login as of version4.2.0!Note that JDA is not a good tool to build a custom discord client as it loads all servers/guilds on startup unlikea client which does this via lazy loading instead.If you need a bot, use a bot account from theApplication Dashboard.
Creating the JDA Object is done via the JDABuilder class. After setting the token and other options via setters,the JDA Object is then created by calling thebuild()
method. Whenbuild()
returns,JDA might not have finished starting up. However, you can useawaitReady()
on the JDA object to ensure that the entire cache is loaded before proceeding.Note that this method is blocking and will cause the thread to sleep until startup has completed.
Example:
JDAjda =JDABuilder.createDefault("token").build();
Both theJDABuilder
and theDefaultShardManagerBuilder
allow a set of configurations to improve the experience.
Example:
publicstaticvoidmain(String[]args) {JDABuilderbuilder =JDABuilder.createDefault(args[0]);// Disable parts of the cachebuilder.disableCache(CacheFlag.MEMBER_OVERRIDES,CacheFlag.VOICE_STATE);// Enable the bulk delete eventbuilder.setBulkDeleteSplittingEnabled(false);// Disable compression (not recommended)builder.setCompression(Compression.NONE);// Set activity (like "playing Something")builder.setActivity(Activity.watching("TV"));builder.build();}
You can configure the memory usage by changing enabledCacheFlags
on theJDABuilder
.Additionally, you can change the handling of member/user cache by setting either aChunkingFilter
, disablingintents, or changing themember cache policy.
publicvoidconfigureMemoryUsage(JDABuilderbuilder) {// Disable cache for member activities (streaming/games/spotify)builder.disableCache(CacheFlag.ACTIVITY);// Only cache members who are either in a voice channel or owner of the guildbuilder.setMemberCachePolicy(MemberCachePolicy.VOICE.or(MemberCachePolicy.OWNER));// Disable member chunking on startupbuilder.setChunkingFilter(ChunkingFilter.NONE);// Disable presence updates and typing eventsbuilder.disableIntents(GatewayIntent.GUILD_PRESENCE,GatewayIntent.GUILD_MESSAGE_TYPING);// Consider guilds with more than 50 members as "large".// Large guilds will only provide online members in their setup and thus reduce bandwidth if chunking is disabled.builder.setLargeThreshold(50);}
The event system in JDA is configured through a hierarchy of classes/interfaces.We offer two implementations for theIEventManager
:
- InterfacedEventManager which uses an
EventListener
interface and theListenerAdapter
abstract class - AnnotatedEventManager which uses the
@SubscribeEvent
annotation that can be applied to methods
By default theInterfacedEventManager is used.Since you can create your own implementation ofIEventManager
this is a very versatile and configurable system.If the aforementioned implementations don't suit your use-case you can simply create a custom implementation andconfigure it on theJDABuilder
withsetEventManager(...)
.
Using EventListener:
publicclassReadyListenerimplementsEventListener{publicstaticvoidmain(String[]args)throwsLoginException,InterruptedException {// Note: It is important to register your ReadyListener before buildingJDAjda =JDABuilder.createDefault("token") .addEventListeners(newReadyListener()) .build();// optionally block until JDA is readyjda.awaitReady(); }@OverridepublicvoidonEvent(GenericEventevent) {if (eventinstanceofReadyEvent)System.out.println("API is ready!"); }}
Using ListenerAdapter:
publicclassMessageListenerextendsListenerAdapter{publicstaticvoidmain(String[]args)throwsLoginException {JDAjda =JDABuilder.createDefault("token").build();//You can also add event listeners to the already built JDA instance// Note that some events may not be received if the listener is added after calling build()// This includes events such as the ReadyEventjda.addEventListener(newMessageListener()); }@OverridepublicvoidonMessageReceived(MessageReceivedEventevent) {if (event.isFromType(ChannelType.PRIVATE)) {System.out.printf("[PM] %s: %s\n",event.getAuthor().getName(),event.getMessage().getContentDisplay()); }else {System.out.printf("[%s][%s] %s: %s\n",event.getGuild().getName(),event.getTextChannel().getName(),event.getMember().getEffectiveName(),event.getMessage().getContentDisplay()); } }}
Ping-Pong Bot:
publicclassBotextendsListenerAdapter{publicstaticvoidmain(String[]args)throwsLoginException {if (args.length <1) {System.out.println("You have to provide a token as first argument!");System.exit(1); }// args[0] should be the token// We only need 2 intents in this bot. We only respond to messages in guilds and private channels.// All other events will be disabled.JDABuilder.createLight(args[0],GatewayIntent.GUILD_MESSAGES,GatewayIntent.DIRECT_MESSAGES) .addEventListeners(newBot()) .setActivity(Activity.playing("Type !ping")) .build(); }@OverridepublicvoidonMessageReceived(MessageReceivedEventevent) {Messagemsg =event.getMessage();if (msg.getContentRaw().equals("!ping")) {MessageChannelchannel =event.getChannel();longtime =System.currentTimeMillis();channel.sendMessage("Pong!")/* => RestAction<Message> */ .queue(response/* => Message */ -> {response.editMessageFormat("Pong: %d ms",System.currentTimeMillis() -time).queue(); }); } }}
Slash-Commands:
publicclassBotextendsListenerAdapter{publicstaticvoidmain(String[]args)throwsLoginException {if (args.length <1) {System.out.println("You have to provide a token as first argument!");System.exit(1); }// args[0] should be the token// We don't need any intents for this bot. Slash commands work without any intents!JDAjda =JDABuilder.createLight(args[0],Collections.emptyList()) .addEventListeners(newBot()) .setActivity(Activity.playing("Type /ping")) .build();jda.upsertCommand("ping","Calculate ping of the bot").queue();// This can take up to 1 hour to show up in the client }@OverridepublicvoidonSlashCommand(SlashCommandEventevent) {if (!event.getName().equals("ping"))return;// make sure we handle the right commandlongtime =System.currentTimeMillis();event.reply("Pong!").setEphemeral(true)// reply or acknowledge .flatMap(v ->event.getHook().editOriginalFormat("Pong: %d ms",System.currentTimeMillis() -time)// then edit original ).queue();// Queue both reply and edit }}
ThroughRestAction we provide request handling with
and it is up to the user to decide which pattern to utilize.It can be combined with reactive libraries such asreactor-core due to being lazy.
The RestAction interface also supports a number of operators to avoid callback hell:
map
Convert the result of theRestAction
to a different valueflatMap
Chain anotherRestAction
on the resultdelay
Delay the element of the previous step
Example:
publicRestAction<Void>selfDestruct(MessageChannelchannel,Stringcontent) {returnchannel.sendMessage("The following message will destroy itself in 1 minute!") .delay(10,SECONDS,scheduler)// edit 10 seconds later .flatMap((it) ->it.editMessage(content)) .delay(1,MINUTES,scheduler)// delete 1 minute later .flatMap(Message::delete);}
We provide a small set of Examples in theExample Directory.
Discord allows Bot-accounts to share load across sessions by limiting them to a fraction of the total connected Guilds/Servers of the bot.
This can be done usingsharding which will limit JDA to only a certain amount of Guilds/Servers including events and entities.Sharding will limit the amount of Guilds/Channels/Users visible to the JDA session so it is recommended to have some kind of elevated management toaccess information of other shards.
To use sharding in JDA you will need to useJDABuilder.useSharding(int shardId, int shardTotal)
. TheshardId is 0-based which means the first shardhas the ID 0. TheshardTotal is the total amount of shards (not 0-based) which can be seen similar to the length of an array, the last shard has the ID ofshardTotal - 1
.
TheSessionController
is a tool of the JDABuilderthat allows to control state and behaviour between shards (sessions). When using multiple builders to build shards you have to create one instanceof this controller and add the same instance to each builder:builder.setSessionController(controller)
Since version3.4.0 JDA provides aShardManager
which automates this building process.
publicstaticvoidmain(String[]args)throwsException{JDABuildershardBuilder =JDABuilder.createDefault(args[0]);//register your listeners here using shardBuilder.addEventListeners(...)shardBuilder.addEventListeners(newMessageListener());for (inti =0;i <10;i++) {shardBuilder.useSharding(i,10) .build(); }}
When the
useSharding
method is invoked for the first time, the builder automatically sets a SessionController internally (if none is present)
publicstaticvoidmain(String[]args)throwsException{DefaultShardManagerBuilderbuilder =DefaultShardManagerBuilder.createDefault(args[0]);builder.addEventListeners(newMessageListener());builder.build();}
AnEntity is the term used to describe types such asGuildChannel/Message/User and other entities that Discord provides.Instances of these entities are created and deleted by JDA when Discord instructs it. This means the lifetime depends on signals provided by the Discord API which are used to create/update/delete entities.This is done through Gateway Events known as "dispatches" that are handled by the JDA WebSocket handlers.When Discord instructs JDA to delete entities, they are simply removed from the JDA cache and lose their references.Once that happens, nothing in JDA interacts or updates the instances of those entities, and they become useless.Discord may instruct to delete these entities randomly for cache synchronization with the API.
It is not recommended to storeany of these entities for a longer period of time!Instead of keeping (e.g.) aUser
instance in some field, an ID should be used. With the ID of a user,you can usegetUserById(id)
to get and keep the user reference in a local variable (see below).
When an entity is updated through its manager, they will send a request to the Discord API which will update the stateof the entity. The success of this requestdoes not imply the entity has been updated yet. All entities are updatedby the aforementionedGateway Events which means you cannot rely on the cache being updated yet once theexecution of a RestAction has completed. Some requests rely on the cache being updated to correctly update the entity.An example of this is updating roles of a member which overrides all roles of the member by sending a list of thenew set of roles. This is done by first checking the current cache, the roles the member has right now, and appendingor removing the requested roles. If the cache has not yet been updated by an event, this will result in unexpected behavior.
Discord may request that a client (the JDA session) invalidates its entire cache. When this happens, JDA willremove all of its current entities and reconnect the session. This is signaled through theReconnectEvent
.When entities are removed from the JDA cache, they lose access to the encapsulating entities. For instance,a channel loses access to its guild. Once that happens, they are unable to make any API requests through RestActionand instead throw anIllegalStateException
. It ishighly recommended to only keep references to entitiesby storing theirid and using the respectiveget...ById(id)
method when needed.
publicclassUserLoggerextendsListenerAdapter {privatefinallonguserId;publicUserLogger(Useruser) {this.userId =user.getIdLong(); }@OverridepublicvoidonMessageReceived(MessageReceivedEventevent) {Userauthor =event.getAuthor();Messagemessage =event.getMessage();if (author.getIdLong() ==userId) {// Print the message of the userSystem.out.println(author.getAsTag() +": " +message.getContentDisplay()); } }@OverridepublicvoidonGuildJoin(GuildJoinEventevent) {JDAapi =event.getJDA();Useruser =api.getUserById(userId);// Acquire a reference to the User instance through the iduser.openPrivateChannel().queue((channel) -> {// Send a private message to the userchannel.sendMessageFormat("I have joined a new guild: **%s**",event.getGuild().getName()).queue(); }); }}
Latest Stable Version:GitHub ReleaseLatest Version:
Be sure to replace theVERSION key below with the one of the versions shown above!
Maven
<dependency> <groupId>net.dv8tion</groupId> <artifactId>JDA</artifactId> <version>VERSION</version></dependency>
<repository> <id>dv8tion</id> <name>m2-dv8tion</name> <url>https://m2.dv8tion.net/releases</url></repository>
Maven without Audio
<dependency> <groupId>net.dv8tion</groupId> <artifactId>JDA</artifactId> <version>VERSION</version> <exclusions> <exclusion> <groupId>club.minnced</groupId> <artifactId>opus-java</artifactId> </exclusion> </exclusions></dependency>
Gradle
dependencies {//Change 'implementation' to 'compile' in old Gradle versions implementation("net.dv8tion:JDA:VERSION")}repositories { mavenCentral()// for transitive dependencies maven { name'm2-dv8tion' url'https://m2.dv8tion.net/releases' }}
Gradle without Audio
dependencies {//Change 'implementation' to 'compile' in old Gradle versions implementation("net.dv8tion:JDA:VERSION") { excludemodule:'opus-java' }}
The builds are distributed using a custom S3 instance.
If you do not need any opus de-/encoding done by JDA (voice receive/send with PCM) you can excludeopus-java
entirely.This can be done if you only send audio with anAudioSendHandler
which only sends opus (isOpus() = true
). (Seelavaplayer)
If you want to use a custom opus library you can provide the absolute path toOpusLibrary.loadFrom(String)
before usingthe audio api of JDA. This works withoutopus-java-natives
as it only requiresopus-java-api
.
For this setup you should only excludeopus-java-natives
asopus-java-api
is a requirement for en-/decoding.
Seeopus-java
JDA is usingSLF4J to log its messages.
That means you should add some SLF4J implementation to your build path in addition to JDA.If no implementation is found, following message will be printed to the console on startup:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
JDA currently provides a fallback Logger in case that no SLF4J implementation is present.We strongly recommend to use one though, as that can improve speed and allows you to customize the Logger as well as log to files
The most popular implementations areLog4j 2 andLogback
Docs can be found on theJenkins or directlyhere
A simple Wiki can also be found in this repository'sWiki section
We use a number of annotations to indicate future plans for implemented functionality such as new features ofthe Discord API.
- Incubating
This annotation is used to indicate that functionality may change in the future. Often used when a new feature is added. - ReplaceWith
Paired with@Deprecated
this is used to inform you how the new code-fragment is supposed to look once the hereby annotated functionality is removed. - ForRemoval
Paired with@Deprecated
this indicates that we plan to entirely remove the hereby annotated functionality in the future. - DeprecatedSince
Paired with@Deprecated
this specifies when a feature was marked as deprecated.
For general troubleshooting you can visit our wikiTroubleshooting andFAQ.
If you need help, or just want to talk with the JDA or other Devs, you can join theOfficial JDA Discord Guild.
Alternatively you can also join theUnofficial Discord API Guild.Once you joined, you can find JDA-specific help in the#java_jda
channel.
For guides and setup help you can also take a look at thewiki
Especially interesting are theGetting StartedandSetup Pages.
Created and maintained bysedmelluq
LavaPlayer is the most popular library used by Music Bots created in Java.It is highly compatible with JDA and Discord4J and allows to play audio fromYoutube, Soundcloud, Twitch, Bandcamp andmore providers.
The library can easily be expanded to more services by implementing your own AudioSourceManager and registering it.
It is recommended to read theUsage section of LavaPlayerto understand a proper implementation.
Sedmelluq provided a demo in his repository which presents an example implementation for JDA:https://github.com/sedmelluq/lavaplayer/tree/master/demo-jda
Maintained byFreya Arbjerg.
Lavalink is a popular standalone audio sending node based on Lavaplayer. Lavalink was built with scalability in mind,and allows streaming music via many servers. It supports most of Lavaplayer's features.
Lavalink is used by many large bots, as well as bot developers who can not use a Java library like Lavaplayer.If you plan on serving music on a smaller scale with JDA it is often preferable to just use Lavaplayer directlyas it is easier.
Lavalink-Client is the official Lavalink client for JDA.
Created and maintained bysedmelluq
Provides a native implementation for the JDA Audio Send-System to avoid GC pauses.
Note that this send system creates an extra UDP-Client which causes audio receive to no longer function properlysince discord identifies the sending UDP-Client as the receiver.
JDABuilderbuilder =JDABuilder.createDefault(BOT_TOKEN) .setAudioSendFactory(newNativeAudioSendFactory());
Created and maintained byMinnDevelopment.
ProvidesKotlin extensions forRestAction and events that provide a more idiomatic Kotlin experience.
funmain() {val jda=JDABuilder.createDefault(BOT_TOKEN) .injectKTX() .build() jda.onCommand("ping") { event->val time= measureTime { event.reply("Pong!").await() }.inWholeMilliseconds event.hook.editOriginal("Pong:$time ms").queue() }}
There is a number of examples available in theREADME.
More can be found in our github organization:JDA-Applications
If you want to contribute to JDA, make sure to base your branch off of ourdevelopment branch (or a feature-branch)and create your PR into thatsame branch.We will be rejecting any PRs between branches or into release branches!It is very possible that your change might already be in development or you missed something.
More information can be found at the wiki pageContributing
When a feature is introduced to replace or enhance existing functionality we might deprecate old functionality.
A deprecated method/class usually has a replacement mentioned in its documentation which should be switched to. Deprecatedfunctionality might or might not exist in the next minor release. (Hint: The minor version is theMM
ofXX.MM.RR_BB
in our version format)
It is possible that some features are deprecated without replacement, in this case the functionality is no longer supported by either the JDA structuredue to fundamental changes (for example automation of a feature) or due to discord API changes that cause it to be removed.
We highly recommend to discontinue usage of deprecated functionality and update by going through each minor release instead of jumping.For instance, when updating from version 3.3.0 to version 3.5.1 you should do the following:
- Update to
3.4.RR_BB
and check for deprecation, replace - Update to
3.5.1_BB
and check for deprecation, replace
TheBB
indicates the build number specified in the release details.
TheRR
in version3.4.RR
should be replaced by the latest version that was published for3.4
, you can find out which the latestversion was by looking at therelease page
This project requiresJava 8+.
All dependencies are managed automatically by Gradle.
- NV Websocket Client
- Version:2.14
- Github
- OkHttp
- Version:3.13.0
- Github
- Apache Commons Collections4
- Version:4.1
- Website
- jackson
- Version:2.10.1
- Github
- Trove4j
- Version:3.0.3
- BitBucket
- slf4j-api
- Version:1.7.25
- Website
- opus-java (optional)
- Version:1.1.0
- GitHub
See also:https://discord.com/developers/docs/topics/community-resources#libraries
About
Java wrapper for the popular chat & VOIP service: Discordhttps://discord.com
Resources
License
Stars
Watchers
Forks
Packages0
Languages
- Java99.8%
- Kotlin0.2%