### Basic Javacord Discord Bot Example
Source: https://javacord.org/wiki/getting-started/setup/eclipse-maven
This Java code provides a minimal working example of a Javacord Discord bot. It initializes the `DiscordApi` with a provided token, sets up a message listener to respond with 'Pong!' when a user sends '!ping', and prints the bot's invite URL to the console for easy sharing.
```Java
package com.github.yourname.myfirstbot;
import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
public class Main {
public static void main(String[] args) {
// Insert your bot's token here
String token = "your token";
DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();
// Add a listener which answers with "Pong!" if someone writes "!ping"
api.addMessageCreateListener(event -> {
if (event.getMessageContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
// Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
}
}
```
--------------------------------
### Basic Javacord Discord Bot Example
Source: https://javacord.org/wiki/getting-started/setup/intellij-maven
This Java code demonstrates a simple Javacord bot that logs in using a provided token and responds with 'Pong!' when a user sends '!ping' in any channel the bot can see. It also prints the bot's invite URL to the console, allowing easy sharing and addition to Discord servers.
```Java
package com.github.yourname;
import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
public class Main {
public static void main(String[] args) {
// Insert your bot's token here
String token = "your token";
DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();
// Add a listener which answers with "Pong!" if someone writes "!ping"
api.addMessageCreateListener(event -> {
if (event.getMessageContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
// Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
}
}
```
--------------------------------
### Add Javacord Snapshot Dependency
Source: https://javacord.org/wiki/getting-started/download-installation
Instructions for integrating the latest development (snapshot) version of the Javacord library. This setup is useful for accessing new features or bug fixes before they are officially released, requiring the addition of a specific snapshot repository.
```Groovy
repositories {
maven {
url "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
dependencies {
implementation 'org.javacord:javacord:$latest-snapshot-version'
}
```
```XML
snapshots-repo
https://oss.sonatype.org/content/repositories/snapshots/
org.javacord
javacord
$latest-snapshot-version
pom
```
```Scala
resolvers += "snapshots-repo" at "https://oss.sonatype.org/content/repositories/snapshots/"
libraryDependencies ++= Seq("org.javacord" % "javacord" % "$latest-snapshot-version")
```
--------------------------------
### Ineffective Support Question Formats
Source: https://javacord.org/wiki/getting-started/faq
These examples demonstrate unhelpful ways to ask for technical support, lacking crucial context and details necessary for effective troubleshooting.
```Plaintext
Why is my code not working?
//Code
```
```Plaintext
Why am I getting Exception X?
```
--------------------------------
### Add Log4j Core Logging Dependency
Source: https://javacord.org/wiki/getting-started/download-installation
Provides code examples for declaring the Log4j Core dependency in different Java build systems. This dependency enables advanced logging features like custom log formats, diverse log targets (console, file), and granular log level control per class.
```Groovy
dependencies { runtimeOnly 'org.apache.logging.log4j:log4j-core:2.17.0' }
```
```XML
org.apache.logging.log4j
log4j-core
2.17.0
```
```Scala
libraryDependencies ++= Seq("org.apache.logging.log4j" % "log4j-core" % "2.17.0")
```
--------------------------------
### Respond to AutoComplete Interaction (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/responding
Provides an example of how to respond to an autocomplete interaction triggered by a slash command. It shows how to offer a list of predefined choices to the user as they type.
```Java
api.addAutocompleteCreateListener(event -> {
event.getAutocompleteInteraction()
.respondWithChoices(Arrays.asList(
SlashCommandOptionChoice.create("one", 1),
SlashCommandOptionChoice.create("two", 2))
);
});
```
--------------------------------
### Example Javacord Fallback Logger Output Format
Source: https://javacord.org/wiki/basic-tutorials/logger-config
Illustrates the standard format of a log line generated by Javacord's fallback logger, showing components like timestamp, log level, logger name, message, and thread context (e.g., shard number).
```Log Output
2018-08-03 20:00:06.080+0200 DEBUG org.javacord.core.util.gateway.DiscordWebSocketAdapter Received HELLO packet {shard=0}
```
--------------------------------
### Add Javacord Release Dependency
Source: https://javacord.org/wiki/getting-started/download-installation
Instructions for adding the stable Javacord library as a dependency to your project. This configuration fetches the latest official release from Maven Central, ensuring a stable and tested version of the library.
```Groovy
repositories { mavenCentral() }
dependencies { implementation 'org.javacord:javacord:$latest-version' }
```
```XML
org.javacord
javacord
$latest-version
pom
```
```Scala
libraryDependencies ++= Seq("org.javacord" % "javacord" % "$latest-version")
```
--------------------------------
### Create Discord Webhooks with Javacord
Source: https://javacord.org/wiki/basic-tutorials/creating-entities
This example illustrates how to create a webhook for a specific text channel using Javacord's `WebhookBuilder`. It covers setting the webhook's name and its avatar from a local file.
```Java
ServerTextChannel channel = ...;
Webhook webhook = new WebhookBuilder(channel)
.setName("Captain Hook")
.setAvatar(new File("C:/Users/Bastian/Pictures/puppy.jpg"))
.create().join();
```
--------------------------------
### Add Logback Classic and SLF4J Bridge Dependencies with Gradle
Source: https://javacord.org/wiki/basic-tutorials/logger-config
Provides the Gradle dependency configuration for integrating Logback Classic, along with the `log4j-to-slf4j` bridge, allowing Javacord to use SLF4J compatible logging frameworks.
```Gradle
dependencies {
runtimeOnly 'org.apache.logging.log44j:log4j-to-slf4j:2.17.0'
runtimeOnly 'ch.qos.logback:logback-classic:1.2.3'
}
```
--------------------------------
### Configure Javacord API with all available intents
Source: https://javacord.org/wiki/basic-tutorials/gateway-intents
This example demonstrates how to initialize the Javacord Discord API builder to enable all available intents, including privileged ones. This provides the bot with access to all possible Discord events and data.
```Java
DiscordApi api = new DiscordApiBuilder()
.setToken("topc secret")
.setAllIntents()
.login()
.join();
```
--------------------------------
### Add Javacord Maven Dependency
Source: https://javacord.org/wiki/getting-started/setup/intellij-maven
This XML snippet shows how to add the Javacord library as a dependency to a Maven project's `pom.xml` file. It specifies the `groupId`, `artifactId`, `version`, and `type` for the Javacord dependency, enabling Maven to download and include the library in the project.
```XML
4.0.0
your.package.name
myfirstbot
1.0-SNAPSHOT
org.javacord
javacord
$latest-version
pom
```
--------------------------------
### Retrieve Server-Specific Slash Commands (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/commands
This example demonstrates how to retrieve slash commands that are specific to a particular Discord server. It requires a `Server` object and uses `api.getServerSlashCommands(server)` to get a `Set` of `SlashCommand` objects for that server.
```Java
Server server = ...;
Set commands = api.getServerSlashCommands(server).join();
```
--------------------------------
### Configure Gradle Build for Standalone Application
Source: https://javacord.org/wiki/basic-tutorials/running
These Gradle build scripts configure a Java application for standalone deployment. They apply the 'application' plugin, set the Java source compatibility, define the main class, and include the Javacord dependency from Maven Central. Both Kotlin DSL and Groovy DSL examples are provided for flexibility.
```Kotlin
plugins {
application
}
version = "1.0.0"
java {
sourceCompatibility = JavaVersion.VERSION_1_8
}
application {
mainClass.set("com.github.yourname.BotMain")
// mainClassName.set("com.github.yourname.BotMain") // Gradle < 6.4
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.javacord:javacord:{{latestVersion}}")
}
```
```Groovy
plugins {
id 'application'
}
version '1.0.0'
java {
sourceCompatibility = JavaVersion.VERSION_1_8
}
application {
mainClass = 'com.github.yourname.BotMain'
// mainClassName = 'com.github.yourname.BotMain' // for Gradle versions < 6.4
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.javacord:javacord:{{latestVersion}}'
}
```
--------------------------------
### Create a Basic Javacord Discord Bot
Source: https://javacord.org/wiki/getting-started/setup/intellij-gradle
This Java code initializes a Discord bot using the Javacord library. It sets the bot's authentication token, adds a message listener to respond with 'Pong!' when a user sends '!ping', and prints the bot's invite URL to the console. Users must replace the placeholder 'your token' with their actual Discord bot token.
```Java
package com.github.yourname;
import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
public class Main {
public static void main(String[] args) {
// Insert your bot's token here
String token = "your token";
DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();
// Add a listener which answers with "Pong!" if someone writes "!ping"
api.addMessageCreateListener(event -> {
if (event.getMessageContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
// Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
}
}
```
--------------------------------
### Add Javacord Dependency to Gradle Build File
Source: https://javacord.org/wiki/getting-started/setup/intellij-gradle
This Gradle build script demonstrates how to configure a Java project, set the source compatibility, define Maven Central as a repository, and add the Javacord library as an implementation dependency. Users should replace '$latest-version' with the actual latest version of Javacord.
```Gradle
plugins {
id 'java'
}
group 'com.github.yourname'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation 'org.javacord:javacord:$latest-version'
}
```
--------------------------------
### Respond to Discord Interaction with a Modal (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/responding
Shows how to display a modal popup to a user in response to an interaction. The example creates a modal with a specified ID and title, containing a short text input field for user input.
```Java
api.addMessageComponentCreateListener(event -> {
event.getInteraction().respondWithModal("modalId","Modal Title",
ActionRow.of(TextInput.create(TextInputStyle.SHORT, "text_input_id", "This is a Text Input Field")));
});
```
--------------------------------
### Add Log4j 2 Core Dependency with Gradle
Source: https://javacord.org/wiki/basic-tutorials/logger-config
Shows the Gradle dependency declaration required to include Log4j 2 Core in a project, enabling its use as a proper logging framework.
```Gradle
dependencies { runtimeOnly 'org.apache.logging.log4j:log4j-core:2.17.0' }
```
--------------------------------
### General Lambda Expression Syntax with Multiple Parameters
Source: https://javacord.org/wiki/essential-knowledge/lambdas
This is a general example illustrating the syntax for a lambda expression when the functional interface method has more than one parameter. The parameters must be enclosed in parentheses when there are multiple.
```Java
(param1, param2) -> { ... }
```
--------------------------------
### Send Followup Messages to Discord Interaction (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/responding
Illustrates how to send multiple followup messages within 15 minutes after an initial command response. This example uses `createFollowupMessageBuilder()` on the `SlashCommandInteraction` object to send additional messages.
```Java
api.addSlashCommandCreateListener(event -> {
SlashCommandInteraction slashCommandInteraction = event.getSlashCommandInteraction();
slashCommandInteraction.respondLater().thenAccept(interactionOriginalResponseUpdater -> {
interactionOriginalResponseUpdater.setContent("You will receive the answer in a few minutes!").update();
// time < 15 minutes
slashCommandInteraction.createFollowupMessageBuilder()
.setContent("Thank you for your patience, it took a while but the answer to the universe is 42")
.send();
});
});
```
--------------------------------
### Bulk Overwrite Global Application Commands (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/commands
This example demonstrates how to perform a bulk overwrite of global application commands, which is efficient for updating or creating multiple commands simultaneously with a single API request. It involves creating a set of `SlashCommandBuilder` objects and then using `api.bulkOverwriteGlobalApplicationCommands()`.
```Java
DiscordApi api = ...;
Set builders = new HashSet<>();
builders.add(new SlashCommandBuilder().setName("server").setDescription("A command for the server"));
buiders.add(new SlashCommandBuilder().setName("permission").setDescription("A command for permissions"));
api.bulkOverwriteGlobalApplicationCommands(builders).join();
```
--------------------------------
### Add Javacord Maven Dependency
Source: https://javacord.org/wiki/getting-started/setup/eclipse-maven
This XML snippet demonstrates how to add the Javacord library as a dependency in a Maven `pom.xml` file. It includes the necessary `groupId`, `artifactId`, `version`, and `type` elements to correctly pull the Javacord library into your project.
```XML
4.0.0
your.package.name
myfirstbot
1.0-SNAPSHOT
org.javacord
javacord
$latest-version
pom
```
--------------------------------
### Retrieve Optional Value Using get() (Java)
Source: https://javacord.org/wiki/essential-knowledge/optionals
Shows how to retrieve the value from an `Optional` using the `get()` method. This method should only be used when absolutely certain that the Optional contains a value, as it throws `NoSuchElementException` otherwise. Careless use can lead to runtime errors.
```Java
TextChannel channel = api.getTextChannelById(123L).get();
channel.sendMessage("Hi");
```
--------------------------------
### Play YouTube Video Using Lavaplayer with Javacord
Source: https://javacord.org/wiki/advanced-topics/playing-audio
This Java example demonstrates the usage of the `LavaplayerAudioSource` to play a YouTube video. It initializes Lavaplayer's `AudioPlayerManager`, registers a `YoutubeAudioSourceManager`, creates an `AudioPlayer`, sets up the custom audio source for a Javacord audio connection, and loads/plays a YouTube item using an `AudioLoadResultHandler`.
```Java
// Create a player manager
AudioPlayerManager playerManager = new DefaultAudioPlayerManager();
playerManager.registerSourceManager(new YoutubeAudioSourceManager());
AudioPlayer player = playerManager.createPlayer();
// Create an audio source and add it to the audio connection's queue
AudioSource source = new LavaplayerAudioSource(api, player);
audioConnection.setAudioSource(source);
// You can now use the AudioPlayer like you would normally do with Lavaplayer, e.g.,
playerManager.loadItem("https://www.youtube.com/watch?v=NvS351QKFV4", new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
player.playTrack(track);
}
@Override
public void playlistLoaded(AudioPlaylist playlist) {
for (AudioTrack track : playlist.getTracks()) {
player.playTrack(track);
}
}
@Override
public void noMatches() {
// Notify the user that we've got nothing
}
@Override
public void loadFailed(FriendlyException throwable) {
// Notify the user that everything exploded
}
});
```
--------------------------------
### Configure Javacord API with only specified intents
Source: https://javacord.org/wiki/basic-tutorials/gateway-intents
This example demonstrates how to initialize the Javacord Discord API builder to enable only a specific set of intents, such as `Intent.GUILDS` and `Intent.DIRECT_MESSAGES`. This provides precise control over which events the bot receives.
```Java
DiscordApi api = new DiscordApiBuilder()
.setToken("topc secret")
.setIntents(Intent.GUILDS, Intent.DIRECT_MESSAGES)
.login()
.join();
```
--------------------------------
### Implement MessageCreateListener with Java Method Reference
Source: https://javacord.org/wiki/essential-knowledge/lambdas
This example shows how to replace a lambda expression with a method reference for even more concise code. Method references are particularly useful when the lambda simply calls an existing method, improving readability and brevity.
```Java
api.addMessageCreateListener(MessageEvent::pinMessage);
```
--------------------------------
### Configure Javacord API with all non-privileged intents (Default)
Source: https://javacord.org/wiki/basic-tutorials/gateway-intents
This example demonstrates how to initialize the Javacord Discord API builder to use all non-privileged intents, which is the default setting. This ensures the bot receives events for common Discord activities without requiring special permissions.
```Java
DiscordApi api = new DiscordApiBuilder()
.setToken("topc secret")
.setAllNonPrivilegedIntents()
.login()
.join();
```
--------------------------------
### Configure Javacord Fallback Logger Levels
Source: https://javacord.org/wiki/basic-tutorials/logger-config
Demonstrates how to programmatically enable debug and trace logging for Javacord's simple fallback logger. These settings should be applied early in the application lifecycle as they only affect newly created loggers.
```Java
// Enable debug logging
FallbackLoggerConfiguration.setDebug(true);
// Enable trace logging
FallbackLoggerConfiguration.setTrace(true);
```
--------------------------------
### Manually Construct Discord Bot Invite URL
Source: https://javacord.org/wiki/getting-started/creating-a-bot-account
This example shows the structure of a Discord bot invite URL. Users need to replace '123456789' with their bot's client ID and optionally adjust the 'permissions' parameter. The 'scope' parameter includes 'applications.commands' and 'bot'.
```URL
https://discord.com/api/oauth2/authorize?client_id=123456789&scope=applications.commands%20bot&permissions=0
```
--------------------------------
### Create Complex Global Slash Command with Subcommands and Options (Javacord)
Source: https://javacord.org/wiki/basic-tutorials/interactions/commands
This example illustrates the creation of a sophisticated global slash command named 'channel' with nested subcommands and options. It defines a subcommand group 'edit' containing a subcommand 'allow', which takes channel, user, and permission arguments. The permission argument uses predefined choices, showcasing advanced command structure capabilities.
```Java
SlashCommand command =
SlashCommand.with("channel", "A command dedicated to channels",
Arrays.asList(
SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND_GROUP, "edit", "Edits a channel",
Arrays.asList(
SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "allow", "Allows a permission to a user for a channel",
Arrays.asList(
SlashCommandOption.create(SlashCommandOptionType.CHANNEL, "channel", "The channel to modify", true),
SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user which permissions should be changed", true),
SlashCommandOption.createWithChoices(SlashCommandOptionType.DECIMAL, "permission", "The permission to allow", true,
Arrays.asList(
SlashCommandOptionChoice.create("manage", 0),
SlashCommandChoice.create("show", 1)))
```
--------------------------------
### Javacord: Login with Recommended Shard Count
Source: https://javacord.org/wiki/advanced-topics/sharding
Illustrates how to use Javacord's `setRecommendedTotalShards()` method to let Discord determine the optimal number of shards for the bot, then logs in all of them. This method automatically handles the API call to get the recommendation and ensures proper login sequencing.
```java
public class Main {
public static void main(String[] args) {
new DiscordApiBuilder()
.setToken("top secret")
.setRecommendedTotalShards().join()
.loginAllShards()
.forEach(shardFuture -> shardFuture
.thenAccept(Main::onShardLogin)
.exceptionally(ExceptionLogger.get())
);
}
private static void onShardLogin(DiscordApi api) {
// ...
}
}
```
--------------------------------
### Javacord EmbedBuilder setAuthor Method Example
Source: https://javacord.org/wiki/basic-tutorials/embeds
Illustrates the basic usage of the `setAuthor` method in Javacord's `EmbedBuilder` to define the author's name, an optional URL, and an optional icon URL for a Discord embed. This snippet shows the typical parameter order and types.
```Java
.setAuthor("Author Name", "http://google.com/", "https://cdn.discordapp.com/embed/avatars/0.png")
```
--------------------------------
### Constructing a Rich Discord Message with Javacord MessageBuilder
Source: https://javacord.org/wiki/basic-tutorials/message-builder
This Java code example demonstrates the comprehensive usage of Javacord's `MessageBuilder` to compose a multi-faceted Discord message. It illustrates how to append text with formatting (bold, underline), embed a code snippet, attach multiple local files, and include a rich embed with a title, description, and color, before sending the complete message to a specified channel.
```Java
new MessageBuilder()
.append("Look at these ")
.append("awesome", MessageDecoration.BOLD, MessageDecoration.UNDERLINE)
.append(" animal pictures! 😃")
.appendCode("java", "System.out.println(\"Sweet!\");")
.addAttachment(new File("C:/Users/Bastian/Pictures/kitten.jpg"))
.addAttachment(new File("C:/Users/Bastian/Pictures/puppy.jpg"))
.setEmbed(new EmbedBuilder()
.setTitle("WOW")
.setDescription("Really cool pictures!")
.setColor(Color.ORANGE))
.send(channel);
```
--------------------------------
### Chain CompletableFuture Operations with thenCompose (Java)
Source: https://javacord.org/wiki/essential-knowledge/completable-futures
Demonstrates chaining asynchronous operations using `thenCompose` in Java. This example creates a server text channel, sends a message, and adds a reaction, consolidating error handling with a single `exceptionally` call.
```java
new ServerTextChannelBuilder(server)
.setName("new-channel")
.create()
.thenCompose(channel -> channel.sendMessage("First!"))
.thenCompose(message -> message.addReaction("👍"))
.exceptionally(ExceptionLogger.get());
```
--------------------------------
### Demonstrate Javacord Ratelimit Handling for Sending Messages
Source: https://javacord.org/wiki/advanced-topics/ratelimits
This code snippet illustrates how Javacord automatically manages Discord's ratelimits when sending multiple messages to a channel. Despite the messages being sent consecutively in the code, Javacord introduces necessary delays to comply with Discord's '5 messages per 5 seconds' ratelimit per channel, preventing the bot from being rate-limited. The example sends 12 messages, which Javacord will deliver in batches with appropriate pauses.
```Java
// Who even needs loops?
channel.sendMessage("Ratelimit Example #1");
channel.sendMessage("Ratelimit Example #2");
channel.sendMessage("Ratelimit Example #3");
channel.sendMessage("Ratelimit Example #4");
channel.sendMessage("Ratelimit Example #5");
channel.sendMessage("Ratelimit Example #6");
channel.sendMessage("Ratelimit Example #7");
channel.sendMessage("Ratelimit Example #8");
channel.sendMessage("Ratelimit Example #9");
channel.sendMessage("Ratelimit Example #10");
channel.sendMessage("Ratelimit Example #11");
channel.sendMessage("Ratelimit Example #12");
```
--------------------------------
### Configure Gradle Shadow Plugin for Fat Jar
Source: https://javacord.org/wiki/basic-tutorials/running
This Gradle snippet demonstrates how to apply the 'shadow' plugin to your `build.gradle` file. This plugin is essential for creating a fat jar by shading dependencies. The specified version (7.1.2) ensures compatibility and access to the plugin's features.
```Gradle
plugins {
id 'java'
# ...
id 'com.github.johnrengelman.shadow' version '7.1.2'
}
```
--------------------------------
### Configure Maven Plugins for Application Distribution
Source: https://javacord.org/wiki/basic-tutorials/running
This XML snippet for `pom.xml` demonstrates how to integrate the Appassembler Maven Plugin and the Maven Assembly Plugin. The Appassembler plugin creates the runnable distribution with a specified main class, while the Assembly plugin packages it into an archive. Both are bound to the `package` lifecycle phase to automate the build process.
```XML
...
org.codehaus.mojo
appassembler-maven-plugin
1.10
org.javacord.examplebot.Main
examplebot
create-distribution
package
assemble
maven-assembly-plugin
3.3.0
src/assembly/distribution.xml
create-archive
package
single
```
--------------------------------
### Complete Javacord Bot Main Class Structure
Source: https://javacord.org/wiki/getting-started/writing-your-first-bot
Presents a full Java class structure for a Javacord bot, including the main method. It shows how to initialize the Discord API, set the bot token, add necessary intents (like MESSAGE_CONTENT), log in, and integrate a message create listener to handle commands.
```java
public class MyFirstBot {
public static void main(String[] args) {
// Log the bot in
DiscordApi api = new DiscordApiBuilder()
.setToken("")
.addIntents(Intent.MESSAGE_CONTENT)
.login().join();
// Add a listener which answers with "Pong!" if someone writes "!ping"
api.addMessageCreateListener(event -> {
if (event.getMessageContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
}
}
```
--------------------------------
### Recommended Structured Format for Support Questions
Source: https://javacord.org/wiki/getting-started/faq
This template outlines a comprehensive approach to asking for technical support, ensuring all relevant information—such as the issue, desired outcome, current behavior, code, and exception details—is provided for faster resolution.
```Plaintext
I have an issue with: YOUR_ISSUE
I want to do: WHAT_YOU_WANT_TO_DO
Currently this happens: WHAT_HAPPENS_NOW
//Code
//Exception
The exception is thrown in the following line:(not the number) CODE_LINE
```
--------------------------------
### Log in a Javacord Discord Bot
Source: https://javacord.org/wiki/getting-started/writing-your-first-bot
This Java code snippet demonstrates how to initialize and log in a Discord bot using the Javacord library. It utilizes the `DiscordApiBuilder` to set the bot's token and enable necessary gateway intents, such as `MESSAGE_CONTENT`, before logging in and blocking until the connection is established.
```Java
DiscordApi api = new DiscordApiBuilder()
.setToken("")
.addIntents(Intent.MESSAGE_CONTENT)
.login().join();
```
--------------------------------
### Define Custom Maven Assembly Descriptor
Source: https://javacord.org/wiki/basic-tutorials/running
This XML snippet defines a custom assembly descriptor (`distribution.xml`) used by the Maven Assembly Plugin. It specifies the desired archive formats (tar.gz, tar.bz2, zip) and includes various files like README, LICENSE, and NOTICE from the project's base directory, along with the output generated by the Appassembler plugin, into the final distribution archive.
```XML
distribution
tar.gz
tar.bz2
zip
${project.basedir}
/
README*
LICENSE*
NOTICE*
${project.build.directory}/appassembler
/
```
--------------------------------
### Check if Optional Contains Value with isPresent() in Java
Source: https://javacord.org/wiki/essential-knowledge/optionals
The `isPresent` method checks whether an `Optional` instance holds a non-null value. It's typically used before calling `get()` to ensure the presence of a value, preventing `NoSuchElementException`.
```Java
Optional channel = api.getTextChannelById(123L);
if (channel.isPresent()) {
// A text channel with the id 123 exists. It's safe to call #get() now
channel.get().sendMessage("Hi");
}
```
--------------------------------
### Add Reaction Add Listener to Message
Source: https://javacord.org/wiki/basic-tutorials/listeners
Demonstrates how to attach a listener directly to a message object to react to reactions. This example deletes the message if a '👎' reaction is added and automatically removes the listener after 30 minutes.
```Java
message.addReactionAddListener(event -> {
if (event.getEmoji().equalsEmoji("👎")) {
event.deleteMessage();
}
}).removeAfter(30, TimeUnit.MINUTES);
```
--------------------------------
### Create Discord Invites with Javacord
Source: https://javacord.org/wiki/basic-tutorials/creating-entities
This snippet shows how to generate an invite for a server channel using Javacord's `InviteBuilder`. It demonstrates how to configure the invite's maximum age and maximum uses.
```Java
ServerTextChannel channel = ...;
Invite invite = new InviteBuilder(channel)
.setMaxAgeInSeconds(60*60*24)
.setMaxUses(42)
.create().join();
```
--------------------------------
### Send Message with Custom Emoji
Source: https://javacord.org/wiki/basic-tutorials/emojis-and-reactions
Illustrates how to send messages containing custom Discord emojis using Javacord. It provides examples of embedding the custom emoji's mention tag directly or retrieving it programmatically from a CustomEmoji object.
```Java
channel.sendMessage("Hi! <:javacord:415465982715494402>");
```
```Java
CustomEmoji emoji = ...;
channel.sendMessage("Hi! " + emoji.getMentionTag());
```
--------------------------------
### Create Discord Voice Channels with Javacord
Source: https://javacord.org/wiki/basic-tutorials/creating-entities
This snippet demonstrates how to create a server voice channel using Javacord's `ServerVoiceChannelBuilder`. It shows how to set the channel's name and user limit before creating it.
```Java
Server server = ...;
ServerVoiceChannel channel = new ServerVoiceChannelBuilder(server)
.setName("example-channel")
.setUserlimit(10)
.create().join();
```
--------------------------------
### Javacord API Usage: Message Sending and Author Check
Source: https://javacord.org/wiki/getting-started/faq
Illustrates fundamental Javacord API calls for sending messages to a channel and verifying if a message's author is a user, highlighting its use of `CompletableFuture` for asynchronous operations and `Optional` for potentially null return types.
```Java
channel.sendMessage("Javacord")
```
```Java
message.getMessageAuthor().asUser().isPresent()
```
--------------------------------
### JDA API Usage: Message Sending and Author Check
Source: https://javacord.org/wiki/getting-started/faq
Demonstrates how to send messages and check message author status using JDA's API, noting its `queue()` method for request execution and direct `null` checks for absent values.
```Java
channel.sendMessage("JDA").queue()
```
```Java
message.getMember() != null
```
--------------------------------
### Javacord: Login with Fixed Shard Count
Source: https://javacord.org/wiki/advanced-topics/sharding
Demonstrates how to initialize a Discord bot using Javacord by explicitly setting a total number of shards and logging in all of them. It shows how to handle successful shard logins and register listeners for each shard.
```java
public class Main {
public static void main(String[] args) {
new DiscordApiBuilder()
.setToken("top secret")
.setTotalShards(10)
.loginAllShards()
.forEach(shardFuture -> shardFuture
.thenAcceptAsync(Main::onShardLogin)
.exceptionally(ExceptionLogger.get())
);
}
private static void onShardLogin(DiscordApi api) {
System.out.println("Shard " + api.getCurrentShard() + " logged in!");
// You can treat the shard like a normal bot account, e.g. registering listeners
api.addMessageCreateListener(event -> {
// ...
});
}
}
```
--------------------------------
### Javacord API: Sharding Methods
Source: https://javacord.org/wiki/advanced-topics/sharding
Documentation for key Javacord methods related to Discord bot sharding, including login procedures and shard recommendation. These methods facilitate the management of multiple bot instances across different Discord servers.
```APIDOC
DiscordApiBuilder:
setRecommendedTotalShards(): CompletableFuture
Description: Asks Discord to recommend a total amount of shards for the bot.
Returns: A CompletableFuture that completes with the DiscordApiBuilder instance after obtaining the recommended shard count.
DiscordApi:
loginAllShards(): Collection>
Description: Logs in all shards configured for the Discord bot. This method automatically obeys the > 5-second delay rule between shard logins.
Returns: A collection of CompletableFuture, where each future represents the login process for a single shard.
```
--------------------------------
### Configure Maven Shade Plugin for Fat Jar with Signature Exclusion
Source: https://javacord.org/wiki/basic-tutorials/running
This Maven plugin configuration shows how to integrate the `maven-shade-plugin` into your `pom.xml` to build a fat jar. It includes crucial settings for attaching the shaded artifact, specifying a classifier, and using a `ManifestResourceTransformer` to set the main class. Additionally, it demonstrates how to exclude security signatures (e.g., .SF, .DSA, .RSA) from dependencies, which is often required to prevent issues with signed JARs when creating a fat jar.
```Maven
...
org.apache.maven.plugins
maven-shade-plugin
3.2.3
true
fat
com.github.yourname.BotMain
*:*
META-INF/*.SF
META-INF/*.DSA
META-INF/*.RSA
package
shade
```
--------------------------------
### Registering Listeners During DiscordApiBuilder Initialization
Source: https://javacord.org/wiki/basic-tutorials/listeners
Illustrates how to register various types of listeners (inline, class instance, and constructor reference) directly within the `DiscordApiBuilder` chain before the API logs in. This allows listeners to be active from the very beginning of the bot's lifecycle, handling events like server availability.
```Java
DiscordApi api = new DiscordApiBuilder()
// An inline listener
.addMessageCreateListener(event -> {
Message message = event.getMessage();
if (message.getContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
})
.addServerBecomesAvailableListener(event -> {
System.out.println("Loaded " + event.getServer().getName());
})
// A listener in their own class
.addListener(new MyListener())
// Alternative syntax that can be used for classes that require a DiscordApi parameter in their constructor
.addListener(MyListener::new)
.setToken("top secret")
.setWaitForServersOnStartup(false)
.login()
.join();
```
--------------------------------
### Implement Reconnect-Resistant Message Listener in Javacord
Source: https://javacord.org/wiki/advanced-topics/bot-lifecycle
This Java example shows how to register a `MessageCreateListener` that is inherently resilient to bot reconnections. It demonstrates a simple '!ping' command handler, emphasizing that such event-driven logic remains functional even after a bot reconnects, though some messages during the disconnection period might be missed.
```Java
api.addMessageCreateListener(event -> {
if (event.getMessage().getContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
```