Convert Figma logo to code with AI

discord-jda logoJDA

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

4,281
736
4,281
43

Top Related Projects

4,280

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

Discord4J is a fast, powerful, unopinionated, reactive library to enable quick and easy development of Discord bots for Java, Kotlin, and other JVM languages using the official Discord Bot API.

An API wrapper for Discord written in Python.

An unofficial .Net wrapper for the Discord API (https://discord.com/)

Quick Overview

JDA (Java Discord API) is a powerful and feature-rich Java wrapper for the Discord API. It provides an easy-to-use interface for creating Discord bots and applications, allowing developers to interact with Discord's features programmatically.

Pros

  • Comprehensive and well-documented API
  • Active development and community support
  • Efficient and performant, with built-in caching mechanisms
  • Supports both synchronous and asynchronous programming models

Cons

  • Steep learning curve for beginners
  • Large dependency size
  • Occasional breaking changes between major versions
  • Limited support for some newer Discord features compared to official libraries

Code Examples

  1. Creating a simple bot and responding to messages:
public class MyBot extends ListenerAdapter {
    public static void main(String[] args) throws LoginException {
        JDA jda = JDABuilder.createDefault("YOUR_BOT_TOKEN")
            .addEventListeners(new MyBot())
            .build();
    }

    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        if (event.getAuthor().isBot()) return;
        if (event.getMessage().getContentRaw().equals("!ping")) {
            event.getChannel().sendMessage("Pong!").queue();
        }
    }
}
  1. Sending an embed message:
EmbedBuilder embed = new EmbedBuilder();
embed.setTitle("Hello, Embed!")
     .setDescription("This is a sample embed message.")
     .setColor(Color.RED)
     .addField("Field 1", "Value 1", true)
     .addField("Field 2", "Value 2", true);

event.getChannel().sendMessageEmbeds(embed.build()).queue();
  1. Adding a reaction to a message:
Message message = event.getMessage();
message.addReaction(Emoji.fromUnicode("U+1F44D")).queue(); // Thumbs up emoji

Getting Started

To start using JDA in your project, add the following dependency to your build.gradle file:

repositories {
    mavenCentral()
}

dependencies {
    implementation 'net.dv8tion:JDA:5.0.0-beta.8'
}

For Maven, add this to your pom.xml:

<dependency>
    <groupId>net.dv8tion</groupId>
    <artifactId>JDA</artifactId>
    <version>5.0.0-beta.8</version>
</dependency>

Then, create a new bot instance using your bot token:

JDA jda = JDABuilder.createDefault("YOUR_BOT_TOKEN").build();

Remember to replace "YOUR_BOT_TOKEN" with your actual bot token from the Discord Developer Portal.

Competitor Comparisons

4,280

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

Pros of JDA

  • Actively maintained with frequent updates
  • Large and supportive community
  • Extensive documentation and examples

Cons of JDA

  • Steeper learning curve for beginners
  • Higher memory usage for large-scale applications

Code Comparison

JDA:

JDA jda = JDABuilder.createDefault("token")
    .enableIntents(GatewayIntent.MESSAGE_CONTENT)
    .addEventListeners(new MyListener())
    .build();

JDA>:

JDA jda = JDABuilder.createDefault("token")
    .setActivity(Activity.playing("with JDA>"))
    .build();

Both JDA and JDA> are essentially the same project, with JDA> being a fork of the original JDA repository. The differences between them are minimal, as JDA> primarily exists to maintain compatibility with older versions of JDA and provide a transition path for users who haven't updated to the latest JDA release.

In practice, most users should opt for the main JDA repository, as it receives more frequent updates and has broader community support. JDA> serves as a fallback option for those who need to maintain compatibility with older code or dependencies.

Discord4J is a fast, powerful, unopinionated, reactive library to enable quick and easy development of Discord bots for Java, Kotlin, and other JVM languages using the official Discord Bot API.

Pros of Discord4J

  • Built on Project Reactor, offering better support for reactive programming
  • More idiomatic Java 8+ API design
  • Supports both blocking and non-blocking operations

Cons of Discord4J

  • Smaller community and less documentation compared to JDA
  • Steeper learning curve, especially for developers new to reactive programming
  • Less frequent updates and potentially slower bug fixes

Code Comparison

Discord4J:

client.getEventDispatcher().on(MessageCreateEvent.class)
    .map(MessageCreateEvent::getMessage)
    .filter(message -> message.getContent().equalsIgnoreCase("!ping"))
    .flatMap(Message::getChannel)
    .flatMap(channel -> channel.createMessage("Pong!"))
    .subscribe();

JDA:

@Override
public void onMessageReceived(MessageReceivedEvent event) {
    if (event.getMessage().getContentRaw().equalsIgnoreCase("!ping")) {
        event.getChannel().sendMessage("Pong!").queue();
    }
}

Both Discord4J and JDA are popular Java libraries for Discord bot development. Discord4J offers a more modern, reactive approach, which can be beneficial for complex applications but may have a steeper learning curve. JDA, on the other hand, has a larger community, more extensive documentation, and a simpler API, making it easier for beginners to get started. The choice between the two depends on the developer's familiarity with reactive programming and the specific requirements of the project.

An API wrapper for Discord written in Python.

Pros of discord.py

  • Written in Python, which is known for its simplicity and readability
  • Extensive documentation and a large, active community
  • Supports both synchronous and asynchronous programming paradigms

Cons of discord.py

  • Generally slower performance compared to JDA due to Python's interpreted nature
  • Limited to Python ecosystem, which may have fewer enterprise-grade libraries
  • Requires more boilerplate code for certain tasks

Code Comparison

discord.py:

@bot.command()
async def hello(ctx):
    await ctx.send('Hello, World!')

JDA:

public class HelloCommand extends ListenerAdapter {
    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        if (event.getMessage().getContentRaw().equals("!hello")) {
            event.getChannel().sendMessage("Hello, World!").queue();
        }
    }
}

Summary

discord.py offers simplicity and ease of use, making it ideal for rapid development and smaller projects. It benefits from Python's extensive ecosystem and readability. However, JDA provides better performance and is more suitable for large-scale applications, leveraging Java's strong typing and robust enterprise capabilities. The choice between the two largely depends on the project requirements, team expertise, and performance needs.

An unofficial .Net wrapper for the Discord API (https://discord.com/)

Pros of Discord.Net

  • Written in C#, offering strong typing and integration with .NET ecosystem
  • Supports both synchronous and asynchronous programming models
  • Extensive documentation and active community support

Cons of Discord.Net

  • Limited to .NET platform, reducing cross-platform compatibility
  • May have a steeper learning curve for developers not familiar with C#
  • Potentially slower performance compared to JDA's Java implementation

Code Comparison

Discord.Net:

var client = new DiscordSocketClient();
await client.LoginAsync(TokenType.Bot, "token");
await client.StartAsync();

client.MessageReceived += async (message) =>
{
    if (message.Content == "!ping")
        await message.Channel.SendMessageAsync("Pong!");
};

JDA:

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

jda.addEventListener(new ListenerAdapter() {
    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        if (event.getMessage().getContentRaw().equals("!ping"))
            event.getChannel().sendMessage("Pong!").queue();
    }
});

Both libraries offer similar functionality for creating Discord bots, but with syntax and patterns specific to their respective languages. Discord.Net leverages C#'s async/await pattern, while JDA uses Java's event-driven approach.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

maven-central jitpack jenkins-shield license-shield

discord-shield faq-shield docs-shield troubleshooting-shield migration-shield

JDA (Java Discord API)

This open source library is intended for implementing bots on Discord using the real-time gateway and REST API. It provides event based functionality to implement bots of any kind, allowing for effective and scalable applications.

📖 Overview

The core concepts of JDA have been developed to make building scalable apps easy:

  1. Event System
    Providing simplified events from the gateway API, to respond to any platform events in real-time without much hassle.
  2. Rest Actions
    Easy to use and scalable implementation of REST API functionality, letting you choose between callbacks with combinators, futures, and blocking. The library also handles rate-limits imposed by Discord automatically, while still offering ways to replace the default implementation.
  3. Customizable Cache
    Trading memory usage for better performance where necessary, with sane default presets to choose from and customize.

You can learn more by visiting our wiki or referencing our Javadocs.

🔬 Installation

maven-central jitpack

This library is available on maven central. The latest version is always shown in the GitHub Release.

The minimum java version supported by JDA is Java SE 8. JDA also uses JSR 305 to support solid interoperability with Kotlin out of the box.

Gradle

repositories {
    mavenCentral()
}

dependencies {
    implementation("net.dv8tion:JDA:$version") { // replace $version with the latest version
      // Optionally disable audio natives to reduce jar size by excluding `opus-java`
      // Gradle DSL:
      // exclude module: 'opus-java'
      // Kotlin DSL:
      // exclude(module="opus-java")
    }
}

Maven

<dependency>
    <groupId>net.dv8tion</groupId>
    <artifactId>JDA</artifactId>
    <version>$version</version> <!-- replace $version with the latest version -->
    <!-- Optionally disable audio natives to reduce jar size by excluding `opus-java`
    <exclusions>
        <exclusion>
            <groupId>club.minnced</groupId>
            <artifactId>opus-java</artifactId>
        </exclusion>
    </exclusions>
    -->
</dependency>

🤖 Creating a Bot

To use this library, you have to create an Application in the Discord Application Dashboard and grab your bot token. You can find a step-by-step guide for this in our wiki page Creating a Discord Bot.

🏃‍♂️ Getting Started

We provide a number of examples to introduce you to JDA. You can also take a look at our official Wiki, Documentation, and FAQ.

Every bot implemented by JDA starts out using the JDABuilder or DefaultShardManagerBuilder. Both builders provide a set of default presets for cache usage and events it wants to receive:

  • createDefault - Enables cache for users who are active in voice channels and all cache flags
  • createLight - Disables all user cache and cache flags
  • create - Enables member chunking, caches all users, and enables all cache flags

We recommend reading the guide on caching and intents to get a feel for configuring your bot properly. Here are some possible use-cases:

Example: Message Logging

[!NOTE] The following example makes use of the privileged intent GatewayIntent.MESSAGE_CONTENT, which must be explicitly enabled in your application dashboard. You can find out more about intents in our wiki guide.

Simply logging messages to the console. Making use of JDABuilder, the intended entry point for smaller bots that don't intend to grow to thousands of guilds.

Starting your bot and attaching an event listener, using the right intents:

public static void main(String[] args) {
  JDABuilder.createLight(token, EnumSet.of(GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT))
      .addEventListener(new MessageReceiveListener())
      .build();
}

Your event listener could look like this:

public class MessageReceiveListener extends ListenerAdapter {
  @Override
  public void onMessageReceived(MessageReceivedEvent event) {
    System.out.printf("[%s] %#s: %s\n",
      event.getChannel(),
      event.getAuthor(),
      event.getMessage().getContentDisplay());
  }
}

You can find a more thorough example with the MessageLoggerExample class.

Example: Slash Command Bot

This is a bot that makes use of interactions to respond to user commands. Unlike the message logging bot, this bot can work without any enabled intents, since interactions are always available.

public static void main(String[] args) {
  JDA jda = JDABuilder.createLight(token, Collections.emptyList())
      .addEventListener(new SlashCommandListener())
      .build();

  // Register your commands to make them visible globally on Discord:

  CommandListUpdateAction commands = jda.updateCommands();

  // Add all your commands on this action instance
  commands.addCommands(
    Commands.slash("say", "Makes the bot say what you tell it to")
      .addOption(STRING, "content", "What the bot should say", true), // Accepting a user input
    Commands.slash("leave", "Makes the bot leave the server")
      .setGuildOnly(true) // this doesn't make sense in DMs
      .setDefaultPermissions(DefaultMemberPermissions.DISABLED) // only admins should be able to use this command.
  );

  // Then finally send your commands to discord using the API
  commands.queue();
}

An event listener that responds to commands could look like this:

public class SlashCommandListener extends ListenerAdapter {
  @Override
  public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
    switch (event.getName()) {
      case "say" -> {
        String content = event.getOption("content", OptionMapping::getAsString);
        event.reply(content).queue();
      };
      case "leave" -> {
        event.reply("I'm leaving the server now!")
          .setEphemeral(true) // this message is only visible to the command user
          .flatMap(m -> event.getGuild().leave()) // append a follow-up action using flatMap
          .queue(); // enqueue both actions to run in sequence (send message -> leave guild)
      };
      default -> return;
    }
  }
}

You can find a more thorough example with the SlashBotExample class.

🚀 RestAction

In this library, the RestAction interface is used as a request builder for all API endpoints. This interface represents a lazy request builder, as shown in this simple example:

channel.sendMessage("Hello Friend!")
  .addFiles(FileUpload.fromData(greetImage)) // Chain builder methods to configure the request
  .queue() // Send the request asynchronously

[!IMPORTANT] The final call to queue() sends the request. You can also send the request synchronously or using futures, check out our extended guide in the RestAction Wiki.

The RestAction interface also supports a number of operators to avoid callback hell:

  • map
    Convert the result of the RestAction to a different value
  • flatMap
    Chain another RestAction on the result
  • delay
    Delay the element of the previous step

As well as combinators like:

  • and
    Require another RestAction to complete successfully, running in parallel
  • allOf
    Accumulate a list of many actions into one (see also mapToResult)
  • zip
    Similar to and, but combines the results into a list

And configurators like:

  • timeout and deadline
    Configure how long the action is allowed to be in queue, cancelling if it takes too long
  • setCheck
    Running some checks right before the request is sent, this can be helpful when it is in queue for a while
  • reason
    The audit log reason for an action

Example:

public RestAction<Void> selfDestruct(MessageChannel channel, String content) {
    return channel.sendMessage("The following message will destroy itself in 1 minute!")
        .addActionRow(Button.danger("delete", "Delete now")) // further amend message before sending
        .delay(10, SECONDS, scheduler) // after sending, wait 10 seconds
        .flatMap((it) -> it.editMessage(content)) // then edit the message
        .delay(1, MINUTES, scheduler) // wait another minute
        .flatMap(Message::delete); // then delete
}

This could then be used in code:

selfDestruct(channel, "Hello friend, this is my secret message").queue();

🧩 Extensions

jda-ktx

Created and maintained by MinnDevelopment.
Provides Kotlin extensions for RestAction and events that provide a more idiomatic Kotlin experience.

fun main() {
    val jda = light(BOT_TOKEN)
    
    jda.onCommand("ping") { event ->
        val time = measureTime {
            event.reply("Pong!").await() // suspending
        }.inWholeMilliseconds

        event.hook.editOriginal("Pong: $time ms").queue()
    }
}

There are a number of examples available in the README.

Lavaplayer

Created by sedmelluq and now maintained by the lavalink community
Lavaplayer is the most popular library used by Music Bots created in Java. It is highly compatible with JDA and Discord4J and allows playing 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. We recommend to also use udpqueue in addition to lavaplayer, to avoid stuttering issues caused by GC pauses.

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/lavalink-devs/lavaplayer/tree/master/demo-jda

udpqueue (an extension of jda-nas)

Created and maintained by sedmelluq and extended by MinnDevelopment
Provides a native implementation for the JDA Audio Send-System to avoid GC pauses potentially causing problems with continuous audio playback.

Note that this send-system creates an extra UDP-Client which causes audio receive to no longer function properly, since Discord identifies the sending UDP-Client as the receiver.

JDABuilder builder = JDABuilder.createDefault(BOT_TOKEN)
    .setAudioSendFactory(new NativeAudioSendFactory());

Lavalink

Created by Freya Arbjerg and now maintained by the lavalink community.

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 directly as it is easier.

Lavalink-Client is the official Lavalink client for JDA.

🛠️ 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.

Please follow our Contributing Guidelines.

Do not expect your pull request to get immediate attention, sometimes it will take a long time to get a response. You can join our discord server and ask in #lib-dev before starting to work on a new PR, to get more immediate feedback from our community members.

🚨 Breaking Changes

Due to the nature of the Discord API, the library will regularly introduce breaking changes to allow for a quick adoption of newer features. We try to keep these breaking changes minimal, but cannot avoid them entirely.

Most breaking changes will result in a minor version bump (5.1.2 → 5.2.0).