Discord4J 是一款快速、强大、无偏见的、反应性库,可让 Java、Kotlin 和其他 JVM 语言的开发者快速、轻松地开发 Discord 机器人。
Discord4J 是一款快速、强大、无偏见的、反应性库,可让 Java、Kotlin 和其他 JVM 语言的开发者快速、轻松地开发 Discord 机器人。
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.
In this example for v3.3, whenever a user sends a !ping message the bot will immediately respond with Pong!.
Make sure your bot has the Message Content intent enabled in your developer portal.
…
For a full project example, check out our example projects repository here.
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!
repositories {
mavenCentral()
}
dependencies {
implementation 'com.discord4j:discord4j-core:3.3.0'
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.discord4j:discord4j-core:3.3.0")
}
<dependencies>
<dependency>
<groupId>com.discord4j</groupId>
<artifactId>discord4j-core</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
libraryDependencies ++= Seq(
"com.discord4j" % "discord4j-core" % "3.3.0"
)
Discord4J 3.3.x includes simpler and more powerful APIs to build requests, a new entity cache and performance improvements from dependency upgrades. Check our Migration Guide for more details.
Discord4J Support Gateway/API Intents Interactions v3.3.x Current v10 Mandatory, non-privileged default Fully supported v3.2.x Maintenance only v8 Mandatory, non-privileged default Fully supported v3.1.x Unsupported v6 Optional, no intent default Maintenance onlySee our docs for more details about compatibility.
We would like to give 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:
Here are some real-world examples of large bots using Discord4J:
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!
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 class ExampleBot {
public static void main(String[] args) {
String token = args[0];
DiscordClient client = DiscordClient.create(token);
client.login().flatMapMany(gateway -> gateway.on(MessageCreateEvent.class))
.map(MessageCreateEvent::getMessage)
.filter(message -> "!ping".equals(message.getContent()))
.flatMap(Message::getChannel)
.flatMap(channel -> channel.createMessage("Pong!"))
.blockLast();
}
}
Discord4J also provides several methods to aid in better reactive chain compositions, such as
GatewayDiscordClient#withGateway and EventDispatcher#on with
an error handling overload.
…
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 {
it.on(MessageCreateEvent::class.java)
.asFlow()
.collect {
val message = it.message
if (message.content == "!ping") {
val channel = message.channel.awaitSingle()
channel.createMessage("Pong!").awaitSingle()
}
}
}
}
.block()
Starting from September 1, 2022, Discord requires bots to enable the "MESSAGE_CONTENT" intent to access the content of messages. To enable the intent, go to the Discord Developer Portal and select your bot. Then, go to the "Bot" tab and enable the "Message Content" intent. Then, add the intent to your bot when creating the DiscordClient:
GatewayDiscordClient client = DiscordClient.create(token)
.gateway()
.setEnabledIntents(IntentSet.nonPrivileged().or(IntentSet.of(Intent.MESSAGE_CONTENT)))
.login()
.block();
…
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.
Guild guild = ...
Set<Member> roleMembers = new HashSet<>();
for (Member member : guild.getMembers().toIterable()) {
for (Role role : member.getRoles().toIterable()) {
if ("Developers".equalsIgnoreCase(role.getName())) {
roleMembers.add(member);
break;
}
}
}
return roleMembers;
Alternatively, using Reactor:
Guild guild = ...
return guild.getMembers()
.filterWhen(member -> member.getRoles()
.map(Role::getName)
.any("Developers"::equalsIgnoreCase));
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.
[!WARNING]
The original LavaPlayer is no longer maintained. A new maintained version can be found here. If you need Java 8 support, you can use Walkyst's LavaPlayer fork, but it is also no longer maintained!
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
PLAYER_MANAGER.getConfiguration().setFrameBufferFactory(NonAllocatingAudioFrameBuffer::new);
AudioSourceManagers.registerRemoteSources(PLAYER_MANAGER);
AudioSourceManagers.registerLocalSource(PLAYER_MANAGER);
}
Next, we need to allow Discord4J to read from an AudioPlayer to an AudioProvider.
…
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.
…
Currently, Discord only allows 1 voice connection per server. Working within this limitation, it is logical to think of
the three 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.
…
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.
VoiceChannel channel = ...
AudioProvider provider = GuildAudioManager.of(channel.getGuildId()).
暂无开放 Issues,或尚未同步最近议题。