Awesome Open Source
Awesome Open Source


Support Server Invite Maven Central Javadocs GitHub Workflow Status (branch)

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.

๐Ÿƒ Quick Example

In this example for v3.1, whenever a user sends a !ping message the bot will immediately respond with Pong!.

public final class ExampleBot {

  public static void main(final String[] args) {
    final String token = args[0];
    final DiscordClient client = DiscordClient.create(token);
    final GatewayDiscordClient gateway = client.login().block();

    gateway.on(MessageCreateEvent.class).subscribe(event -> {
      final Message message = event.getMessage();
      if ("!ping".equals(message.getContent())) {
        final MessageChannel channel = message.getChannel().block();


๐Ÿ”— Quick Links

๐Ÿ’Ž Benefits

  • ๐Ÿš€ Reactive - Discord4J follows the reactive-streams protocol to ensure Discord bots run smoothly and efficiently regardless of size.

  • ๐Ÿ“œ Official - Automatic rate limiting, automatic reconnection strategies, and consistent naming conventions are among the many features Discord4J offers to ensure your Discord bots run up to Discord's specifications and to provide the least amount of surprises when interacting with our library.

  • ๐Ÿ› ๏ธ Modular - Discord4J breaks itself into modules to allow advanced users to interact with our API at lower levels to build minimal and fast runtimes or even add their own abstractions.

  • โš”๏ธ Powerful - Discord4J can be used to develop any bot, big or small. We offer many tools for developing large-scale bots from custom distribution frameworks, off-heap caching, and its interaction with Reactor allows complete integration with frameworks such as Spring and Micronaut.

  • ๐Ÿซ Community - We pride ourselves on our inclusive community and are willing to help whenever challenges arise; or if you just want to chat! We offer help ranging from Discord4J specific problems, to general programming and web development help, and even Reactor-specific questions. Be sure to visit us on our Discord server!

๐Ÿ“ฆ Installation


repositories {

dependencies {
  implementation 'com.discord4j:discord4j-core:3.1.5'

Gradle Kotlin DSL

repositories {

dependencies {




libraryDependencies ++= Seq(
  "com.discord4j" % "discord4j-core" % "3.1.5"

๐Ÿ”€ Discord4J Versions

Discord4J 3.1.x introduces performance and API enhancements, a plethora of new features, and dependency upgrades. A Migration Guide is provided to aide users and ensure a smooth and readily available transition.

Discord4J Support Gateway/API Intents
v3.2.x In development v8 Mandatory, non-privileged default
v3.1.x Current v6 Optional, no intent default
v3.0.x Maintenance only v6 No intents support

See this wiki page for more details about compatibility.

๐ŸŽ‰ Sponsors

We would like to give a special thanks to all of our sponsors for providing us the funding to continue developing and hosting repository resources as well as driving forward initiatives for community programs. In particular, we would like to give a special shoutout to these wonderful individuals:

โ›ฐ๏ธ Large Bots

Here are some real-world examples of large bots using Discord4J:

  • Groovy - An easy to use music bot used by more than 4 million servers.
  • ZeroTwo - An anime multi-purpose bot used in more than 250K servers.
  • DisCal - Implements Google Calendar into Discord as seamlessly and comprehensively as possible; serving nearly 14K servers.
  • Shadbot - A configurable multipurpose bot with music, gambling mini-games, video game stats, and more; serving almost 12K servers.

Do you own a large bot using Discord4J? Ask an admin in our Discord or submit a pull request to add your bot to the list!

โš›๏ธ Reactive

Discord4J uses Project Reactor as the foundation for our asynchronous framework. Reactor provides a simple yet extremely powerful API that enables users to reduce resources and increase performance.

public final class ExampleBot {

  public static void main(final String[] args) {
    final String token = args[0];
    final DiscordClient client = DiscordClient.create(token);

    client.login().flatMapMany(gateway -> gateway.on(MessageCreateEvent.class))
      .filter(message -> "!ping".equals(message.getContent()))
      .flatMap(channel -> channel.createMessage("Pong!"))

Discord4J also provides several methods to aide in better reactive chain compositions, such as GatewayDiscordClient#withGateway and EventDispatcher#on with an error handling overload.

final String token = args[0];
final DiscordClient client = DiscordClient.create(token);

client.withGateway(gateway -> {
  final Publisher<?> pingPong = gateway.on(MessageCreateEvent.class, event ->
      .filter(message -> "!ping".equals(message.getContent()))
      .flatMap(channel -> channel.createMessage("Pong!")));
    final Publisher<?> onDisconnect = gateway.onDisconnect()
      .doOnTerminate(() -> System.out.println("Disconnected!"));

    return Mono.when(pingPong, onDisconnect);

๐Ÿงต Kotlin

By utilizing Reactor, Discord4J has native integration with Kotlin coroutines when paired with the kotlinx-coroutines-reactor library.

val token = args[0]
val client = DiscordClient.create(token)

client.withGateway {
  mono {
      .collect {
        val message = it.message
        if (message.content == "!ping") {
          val channel =

๐Ÿ“š Examples

๐Ÿ“‘ Message Embeds

// ANY_URL =
final MessageChannel channel = ...
channel.createEmbed(spec -> 
    .setAuthor("setAuthor", ANY_URL, IMAGE_URL)
    .setDescription("setDescription\n" +
      "big D: is setImage\n" +
      "small D: is setThumbnail\n" +
      "<-- setColor")
    .addField("addField", "inline = true", true)
    .addField("addFIeld", "inline = true", true)
    .addField("addFile", "inline = false", false)
    .setFooter("setFooter --> setTimestamp", IMAGE_URL)

๐Ÿท๏ธ Find Members by Role Name

Users typically prefer working with names instead of IDs. This example will demonstrate how to search for all members that have a role with a specific name.

final Guild guild = ...
final Set<Member> roleMembers = new HashSet<>();

for (final Member member : guild.getMembers().toIterable()) {
  for (final Role role : member.getRoles().toIterable()) {
    if ("Developers".equalsIgnoreCase(role.getName())) {

return roleMembers;

Alternatively, using Reactor:

final Guild guild = ...
return guild.getMembers()
  .filterWhen(member -> member.getRoles()

๐ŸŽต Voice and Music

Discord4J provides full support for voice connections and the ability to send audio to other users connected to the same channel. Discord4J can accept any Opus audio source with LavaPlayer being the preferred solution for downloading and encoding audio from YouTube, SoundCloud, and other providers.

To get started, you will first need to instantiate and configure an, conventionally global, AudioPlayerManager.

public static final AudioPlayerManager PLAYER_MANAGER;

static {
  PLAYER_MANAGER = new DefaultAudioPlayerManager();
  // This is an optimization strategy that Discord4J can utilize to minimize allocations

Next, we need to allow Discord4J to read from an AudioPlayer to an AudioProvider.

public final class LavaPlayerAudioProvider extends AudioProvider {

  private final AudioPlayer player;
  private final MutableAudioFrame frame;

  public LavaPlayerAudioProvider(final AudioPlayer player) {
    // Allocate a ByteBuffer for Discord4J's AudioProvider to hold audio data for Discord
    // Set LavaPlayer's AudioFrame to use the same buffer as Discord4J's
    frame = new MutableAudioFrame();
    this.player = player;

  public boolean provide() {
    // AudioPlayer writes audio data to the AudioFrame
    final boolean didProvide = player.provide(frame);

    if (didProvide) {

    return didProvide;

Typically, audio players will have queues or internal playlists for users to be able to automatically cycle through songs as they are finished or requested to be skipped over. We can manage this queue externally and pass it to other areas of our code to allow tracks to be viewed, queued, or skipped over by creating an AudioTrackScheduler.

public final class AudioTrackScheduler extends AudioEventAdapter {

  private final List<AudioTrack> queue;
  private final AudioPlayer player;

  public AudioTrackScheduler(final AudioPlayer player) {
    // The queue may be modifed by different threads so guarantee memory safety
    // This does not, however, remove several race conditions currently present
    queue = Collections.synchronizedList(new LinkedList<>());
    this.player = player;

  public List<AudioTrack> getQueue() {
    return queue;

  public boolean play(final AudioTrack track) {
    return play(track, false);

  public boolean play(final AudioTrack track, final boolean force) {
    final boolean playing = player.startTrack(track, !force);

    if (!playing) {

    return playing;

  public boolean skip() {
    return !queue.isEmpty() && play(queue.remove(0), true);

  public void onTrackEnd(final AudioPlayer player, final AudioTrack track, final AudioTrackEndReason endReason) {
    // Advance the player if the track completed naturally (FINISHED) or if the track cannot play (LOAD_FAILED)
    if (endReason.mayStartNext) {

Currently, Discord only allows 1 voice connection per server. Working within this limitation, it is logical to think of the 3 components we have worked with thus far (AudioPlayer, LavaPlayerAudioProvider, and AudioTrackScheduler) to be correlated to a specific Guild, naturally unique by some Snowflake. Logically, it makes sense to combine these objects into one, so that they can be put into a Map for easier retrieval when connecting to a voice channel or when working with commands.

public final class GuildAudioManager {

  private static final Map<Snowflake, GuildAudioManager> MANAGERS = new ConcurrentHashMap<>();

  public static GuildAudioManager of(final Snowflake id) {
    return MANAGERS.computeIfAbsent(id, ignored -> new GuildAudioManager());

  private final AudioPlayer player;
  private final AudioTrackScheduler scheduler;
  private final LavaPlayerAudioProvider provider;

  private GuildAudioManager() {
    player = PLAYER_MANAGER.createPlayer();
    scheduler = new AudioTrackScheduler(player);
    provider = new LavaPlayerAudioProvider(player);


  // getters

Finally, we need to connect to the voice channel. After connecting you are given a VoiceConnection object where you can utilize it later to disconnect from the voice channel by calling VoiceConnection#disconnect.

final VoiceChannel channel = ...
final GuildAudioManager manager = GuildAudioManager.of(channel.getGuildId());
final AudioProvider provider = manager.getProvider();
final VoiceConnection connection = channel.join(spec -> spec.setProvider(provider)).block();

// In the AudioLoadResultHandler, add AudioTrack instances to the AudioTrackScheduler (and send notifications to users)
PLAYER_MANAGER.loadItemOrdered(manager, "", new AudioLoadResultHandler() { /* overrides */ })

โŒ Disconnecting from a Voice Channel Automatically

Typically, after everyone has left a voice channel, the bot should disconnect automatically as users typically forget to disconnect the bot manually. This problem can be solved rather elegantly using a reactive approach over an imperative one as the example below demonstrates.

final VoiceChannel channel = ...
final Mono<Void> onDisconnect = channel.join(spec -> { /* TODO Initialize */ })
  .flatMap(connection -> {
    // The bot itself has a VoiceState; 1 VoiceState signals bot is alone
    final Publisher<Boolean> voiceStateCounter = channel.getVoiceStates()
      .map(count -> 1L == count);

    // After 10 seconds, check if the bot is alone. This is useful if
    // the bot joined alone, but no one else joined since connecting
    final Mono<Void> onDelay = Mono.delay(Duration.ofSeconds(10L))
      .filterWhen(ignored -> voiceStateCounter)

    // As people join and leave `channel`, check if the bot is alone.
    // Note the first filter is not strictly necessary, but it does prevent many unnecessary cache calls
    final Mono<Void> onEvent = channel.getClient().getEventDispatcher().on(VoiceStateUpdateEvent.class)
      .filter(event -> event.getOld().flatMap(VoiceState::getChannelId).map(channel.getId()::equals).orElse(false))
      .filterWhen(ignored -> voiceStateCounter)

    // Disconnect the bot if either onDelay or onEvent are completed!
    return Mono.first(onDelay, onEvent).then(connection.disconnect());

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
java (30,656)ย 
api (1,654)ย 
bot (728)ย 
rest-api (538)ย 
rest (480)ย 
websocket (458)ย 
discord (392)ย 
discord-bot (160)ย 
discord-api (58)ย 
reactor (34)ย 
bot-api (24)ย 
javadoc (16)ย 

Find Open Source By Browsing 7,000 Topics Across 59 Categories

Advertising ๐Ÿ“ฆย 10
All Projects
Application Programming Interfaces ๐Ÿ“ฆย 124
Applications ๐Ÿ“ฆย 192
Artificial Intelligence ๐Ÿ“ฆย 78
Blockchain ๐Ÿ“ฆย 73
Build Tools ๐Ÿ“ฆย 113
Cloud Computing ๐Ÿ“ฆย 80
Code Quality ๐Ÿ“ฆย 28
Collaboration ๐Ÿ“ฆย 32
Command Line Interface ๐Ÿ“ฆย 49
Community ๐Ÿ“ฆย 83
Companies ๐Ÿ“ฆย 60
Compilers ๐Ÿ“ฆย 63
Computer Science ๐Ÿ“ฆย 80
Configuration Management ๐Ÿ“ฆย 42
Content Management ๐Ÿ“ฆย 175
Control Flow ๐Ÿ“ฆย 213
Data Formats ๐Ÿ“ฆย 78
Data Processing ๐Ÿ“ฆย 276
Data Storage ๐Ÿ“ฆย 135
Economics ๐Ÿ“ฆย 64
Frameworks ๐Ÿ“ฆย 215
Games ๐Ÿ“ฆย 129
Graphics ๐Ÿ“ฆย 110
Hardware ๐Ÿ“ฆย 152
Integrated Development Environments ๐Ÿ“ฆย 49
Learning Resources ๐Ÿ“ฆย 166
Legal ๐Ÿ“ฆย 29
Libraries ๐Ÿ“ฆย 129
Lists Of Projects ๐Ÿ“ฆย 22
Machine Learning ๐Ÿ“ฆย 347
Mapping ๐Ÿ“ฆย 64
Marketing ๐Ÿ“ฆย 15
Mathematics ๐Ÿ“ฆย 55
Media ๐Ÿ“ฆย 239
Messaging ๐Ÿ“ฆย 98
Networking ๐Ÿ“ฆย 315
Operating Systems ๐Ÿ“ฆย 89
Operations ๐Ÿ“ฆย 121
Package Managers ๐Ÿ“ฆย 55
Programming Languages ๐Ÿ“ฆย 245
Runtime Environments ๐Ÿ“ฆย 100
Science ๐Ÿ“ฆย 42
Security ๐Ÿ“ฆย 396
Social Media ๐Ÿ“ฆย 27
Software Architecture ๐Ÿ“ฆย 72
Software Development ๐Ÿ“ฆย 72
Software Performance ๐Ÿ“ฆย 58
Software Quality ๐Ÿ“ฆย 133
Text Editors ๐Ÿ“ฆย 49
Text Processing ๐Ÿ“ฆย 136
User Interface ๐Ÿ“ฆย 330
User Interface Components ๐Ÿ“ฆย 514
Version Control ๐Ÿ“ฆย 30
Virtualization ๐Ÿ“ฆย 71
Web Browsers ๐Ÿ“ฆย 42
Web Servers ๐Ÿ“ฆย 26
Web User Interface ๐Ÿ“ฆย 210