Giter Site home page Giter Site logo

jda's Introduction

version jenkins license Discord FAQ

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.

This officially makes JDA-Client deprecated. Please do not continue using it, and instead switch to the promoted 3.x version listed further below.

Creating the JDA Object

Creating the JDA Object is done via the JDABuilder class by providing an AccountType (Bot/Client). After setting the token via setter, the JDA Object is then created by calling the .buildBlocking() or the .buildAsync() (non-blocking login) method.

Example:

JDA jda = new JDABuilder(AccountType.BOT).setToken("token").buildBlocking();

Note: It is important to set the correct AccountType because Bot-accounts require a token prefix to login.

Examples:

Using EventListener:

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

    @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, RateLimitedException, InterruptedException
    {
        JDA jda = new JDABuilder(AccountType.BOT).setToken("token").buildBlocking();
        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().getContent());
        }
        else
        {
            System.out.printf("[%s][%s] %s: %s\n", event.getGuild().getName(),
                        event.getTextChannel().getName(), event.getMember().getEffectiveName(),
                        event.getMessage().getContent());
        }
    }
}

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

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.

When using sharding it is also recommended to use a SessionReconnectQueue instance for all shards. This allows JDA to properly handle reconnecting multiple shards without violating Discord limitations (not using this might cause an IP ban on bad days).

Logins between shards must happen with a minimum of 5 SECONDS of backoff time. JDA will inform you if the backoff is too short with a log message:

Encountered IDENTIFY (OP 2) Rate Limit! Waiting 5 seconds before trying again!

Note: Failing to backoff properly will cause JDA to wait 5 seconds after failing to connect. Respect the 5 second login rate limit!

Example Sharding

public static void main(String[] args) throws Exception
{
    JDABuilder shardBuilder = new JDABuilder(AccountType.BOT).setToken(args[0]).setReconnectQueue(new SessionReconnectQueue());
    //register your listeners here using shardBuilder.addEventListener(...)
    for (int i = 0; i < 10; i++)
    {
        shardBuilder.useSharding(i, 10)
                    .buildAsync();
        Thread.sleep(5000); //sleep 5 seconds between each login
    }
}

More Examples

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

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

And many more!

Download

Latest Version: version

Be sure to replace the VERSION key below with the latest version 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>

Gradle

dependencies {
    compile 'net.dv8tion:JDA:VERSION'
}

repositories {
    jcenter()
}

The builds are distributed using JCenter through Bintray JDA JCenter Bintray

Documentation

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

Getting Help

If you need help, or just want to talk with the JDA or other Discord Devs, you can join the Unofficial Discord API Guild.

Once you joined, you can find JDA-specific help in the #java_jda channel
We have our own Discord Server here

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 MinnDevelopment
Kotlin-JDA provides several extensions allowing to easily use kotlin idioms with JDA.

Features include:

  • Groovy-style Builders
  • Coroutine RestActions

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 master branch (or a feature-branch) and create your PR into that same branch. We will be rejecting any PRs between 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

Dependencies:

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

Related Projects

See also: https://discordapp.com/developers/docs/topics/libraries

jda's People

Contributors

abalabahaha avatar almighty-alpaca avatar arsenarsen avatar avarel avatar barronpm avatar breadmoirai avatar din0s avatar dscalzi avatar dv8fromtheworld avatar fabricio20 avatar freyacodes avatar goldrenard avatar jagrosh avatar jbyoshi avatar kaaz avatar kantenkugel avatar minndevelopment avatar natanbc avatar pear0 avatar randomnetcat avatar scarsz avatar schnapster avatar scoreunder avatar shredder121 avatar tazzie02 avatar thvardhan avatar v0idst4r avatar walshydev avatar xetanai avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.