Aquazus / JDA

Java wrapper for the popular chat & VOIP service: Discord https://discordapp.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

version jenkins license Discord FAQ Troubleshooting

JDA (Java Discord API)

JDA strives to provide a clean and full wrapping of the Discord REST api and its Websocket-Events for Java.

JDA 3.x

JDA will be continued with version 3.x and will support Bot-features (for bot-accounts) and Client-features (for user-accounts). Please see the Discord docs for more information about bot accounts.

  1. Examples
  2. Sharding
  3. Download
  4. Documentation
  5. Support
  6. Extensions And Plugins
  7. Contributing
  8. Dependencies
  9. Other Libraries

UserBots and SelfBots

Discord is currently prohibiting creation and usage of automated client accounts (AccountType.CLIENT). We however still have support to login with these accounts due to legacy support. That does not mean it is allowed or welcome to use. Note that JDA is not a good tool to build a custom discord client as it loads all servers/guilds on startup unlike a client which does this via lazy loading instead. If you need a bot, use a bot account from the Application Dashboard.

Read More

Creating the JDA Object

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 the build() method. When build() returns, JDA might not have finished starting up. However, you can use awaitReady() 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:

JDA jda = new JDABuilder("token").build();

Note: By default this will use the AccountType.BOT as that is the recommended type of account. You can change this to use AccountType.CLIENT, however you will be risking account termination. Use new JDABuilder(AccountType) to change to a different account type.

Examples:

Using EventListener:

public class ReadyListener implements EventListener
{
    public static void main(String[] args)
            throws LoginException, InterruptedException
    {
        // Note: It is important to register your ReadyListener before building
        JDA jda = new JDABuilder("token")
            .addEventListener(new ReadyListener())
            .build();

        // optionally block until JDA is ready
        jda.awaitReady();
    }

    @Override
    public void onEvent(Event event)
    {
        if (event instanceof ReadyEvent)
            System.out.println("API is ready!");
    }
}

Using ListenerAdapter:

public class MessageListener extends ListenerAdapter
{
    public static void main(String[] args)
            throws LoginException
    {
        JDA jda = new JDABuilder("token").build();
        jda.addEventListener(new MessageListener());
    }

    @Override
    public void onMessageReceived(MessageReceivedEvent event)
    {
        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());
        }
    }
}

More Examples

We provide a small set of Examples in the Example Directory.

Note: In these examples we override methods from the inheriting class ListenerAdapter.
The usage of the @Override annotation is recommended to validate methods.

In addition, you can look at the many Discord Bots that were implemented using JDA:

And many more!

Sharding a Bot

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 using sharding 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 to access information of other shards.

To use sharding in JDA you will need to use JDABuilder.useSharding(int shardId, int shardTotal). The shardId is 0-based which means the first shard has the ID 0. The shardTotal 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 of shardTotal - 1.

The SessionController is a tool of the JDABuilder that allows to control state and behaviour between shards (sessions). When using multiple builders to build shards you have to create one instance of this controller and add the same instance to each builder: builder.setSessionController(controller)

Since version 3.4.0 JDA provides a ShardManager which automates this building process.

Example Sharding - Using JDABuilder

public static void main(String[] args) throws Exception
{
    JDABuilder shardBuilder = new JDABuilder(args[0]);
    //register your listeners here using shardBuilder.addEventListener(...)
    shardBuilder.addEventListener(new MessageListener());
    for (int i = 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)

Example Sharding - Using DefaultShardManager

public static void main(String[] args) throws Exception
{
    DefaultShardManagerBuilder builder = new DefaultShardManagerBuilder();
    builder.setToken(args[0]);
    builder.addEventListener(new MessageListener());
    builder.build();
}

Download

Latest Stable Version: GitHub Release
Latest Version: version

Be sure to replace the VERSION 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>jcenter</id>
    <name>jcenter-bintray</name>
    <url>http://jcenter.bintray.com</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 {
    compile 'net.dv8tion:JDA:VERSION'
}

repositories {
    jcenter()
}

Gradle without Audio

dependencies {
    compile ('net.dv8tion:JDA:VERSION') {
        exclude module: 'opus-java'
    }
}

The builds are distributed using JCenter through Bintray JDA JCenter Bintray

If you do not need any opus de-/encoding done by JDA (voice receive/send with PCM) you can exclude opus-java entirely. This can be done if you only send audio with an AudioSendHandler which only sends opus (isOpus() = true). (See lavaplayer)

If you want to use a custom opus library you can provide the absolute path to OpusLibrary.loadFrom(String) before using the audio api of JDA. This works without opus-java-natives as it only requires opus-java-api.
For this setup you should only exclude opus-java-natives as opus-java-api is a requirement for en-/decoding.

See opus-java

Logging Framework - SLF4J

JDA is using SLF4J 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 implementation
SLF4J: 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 are Log4j 2 and Logback

Documentation

Docs can be found on the Jenkins or directly here
A simple Wiki can also be found in this repository's Wiki section

Annotations

We use a number of annotations to indicate future plans for implemented functionality such as new features of the 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.

Sources

Getting Help

For general troubleshooting you can visit our wiki Troubleshooting and FAQ.
If you need help, or just want to talk with the JDA or other Devs, you can join the Official JDA Discord Guild.

Alternatively you can also join the Unofficial 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 the wiki
Especially interesting are the Getting Started and Setup Pages.

Third Party Recommendations

Created and maintained by sedmelluq
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 from Youtube, Soundcloud, Twitch, Bandcamp and more providers.
The library can easily be expanded to more services by implementing your own AudioSourceManager and registering it.

It is recommended to read the Usage section of LavaPlayer to 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

Created and maintained by jagrosh.
JDA-Utilities provides a Command-Extension and several utilities to make using JDA very simple.

Features include:

  • Paginated Message using Reactions
  • EventWaiter allowing to wait for a response and other events

Created and maintained by sedmelluq
JDAction is a Gradle plugin which makes sure that the return values of all methods which return a RestAction are used. Since it is a common mistake to forget to .queue()/.complete()/.submit() RestActions, and it is often only discovered after noticing that something doesn't work, this plugin will help catch those cases quickly as it will cause a build failure in such case.

More info about RestAction: Wiki


More can be found in our github organization: JDA-Applications

Contributing to JDA

If you want to contribute to JDA, make sure to base your branch off of our development branch (or a feature-branch) and create your PR into that same branch. We will be rejecting any PRs between branches or into release branches!

It is also highly recommended to get in touch with the Devs before opening Pull Requests (either through an issue or the Discord servers mentioned above).
It is very possible that your change might already be in development or you missed something.

More information can be found at the wiki page Contributing

Deprecation Policy

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. Deprecated functionality might or might not exist in the next minor release. (Hint: The minor version is the MM of XX.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 structure due 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

The BB indicates the build number specified in the release details.

The RR in version 3.4.RR should be replaced by the latest version that was published for 3.4, you can find out which the latest version was by looking at the release page

Dependencies:

This project requires Java 8.
All dependencies are managed automatically by Gradle.

Related Projects

See also: https://discordapp.com/developers/docs/topics/community-resources#libraries

About

Java wrapper for the popular chat & VOIP service: Discord https://discordapp.com

License:Apache License 2.0


Languages

Language:Java 100.0%