XUtils

JDA

Wrapping of the Discord REST API and its WebSocket events.


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.

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][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][GatewayIntent]:

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.

🧩 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.

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());

🚨 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).


Articles

  • coming soon...