### Coroutine Event Listener Example Source: https://github.com/freya022/jda-ktx/blob/master/packages.md A concise example demonstrating the usage of the `listener` extension function with `CoroutineEventManager`. It shows how to create a JDA instance with coroutines enabled and attach a listener for message events that uses suspending functions. ```kotlin val jda = light(token, enableCoroutines=true) jda.listener { event -> if (event.message.contentRaw.startsWith("!hello")) { event.channel.sendTyping().await() event.channel.send("Hello!").queue() } } ``` -------------------------------- ### Kotlin Coroutine Event Handling with JDA Source: https://github.com/freya022/jda-ktx/blob/master/packages.md Demonstrates how to enable coroutines in JDA using jda-ktx's CoroutineEventManager. It shows how to handle message events, including sending typing indicators, awaiting user mentions, and replying with embeds. Also includes an example of handling slash commands with timeouts and button interactions. ```kotlin val jda = light("token", enableCoroutines=true) { intents += listOf(GatewayIntent.GUILD_MEMBERS, GatewayIntent.MESSAGE_CONTENT) } jda.listener { val guild = it.guild val channel = it.channel val message = it.message val content = message.contentRaw if (content.startsWith("!profile")) { channel.sendTyping().await() val user = message.mentionedUsers.firstOrNull() ?: run { val matches = guild.retrieveMembersByPrefix(content.substringAfter("!profile "), 1).await() matches.firstOrNull() } if (user == null) channel.send("${it.author.asMention}, I cannot find a user for your query!").queue() else channel.send("${it.author.asMention}, here is the user profile:", embeds=profile(user).into()).queue() } } jda.onCommand("ban", timeout=2.minutes) { event -> val user = event.getOption("user")!! val confirm = danger("${user.id}:ban", "Confirm") event.reply_( "Are you sure you want to ban **${user.asTag}**?", components=confirm.into(), ephemeral=true ).queue() withTimeoutOrNull(1.minutes) { val pressed = event.user.awaitButton(confirm) pressed.deferEdit().queue() event.guild.ban(user, 0).queue() } ?: event.hook.editMessage(/*id="@original" is default */content="Timed out.", components=emptyList()).queue() } jda.onButton("hello") { it.reply_("Hello :)").queue() } ``` -------------------------------- ### Command and SelectMenu Builders Source: https://github.com/freya022/jda-ktx/blob/master/README.md Demonstrates how to build slash commands, subcommands, and select menus using a fluent Kotlin DSL. This includes setting command options, restrictions, and choices. ```kotlin jda.updateCommands { slash("ban", "Ban a user") { restrict(guild=true, Permission.BAN_MEMBERS) // guild only and requires ban permission option("user", "The user to ban", true) option("reason", "Why to ban this user") option("duration", "For how long to ban this user") { choice("1 day", 1) choice("1 week", 7) choice("1 month", 31) } } slash("mod", "Moderation commands") { restrict(guild=true, Permission.MODERATE_MEMBERS) // you cannot apply this on subcommands due to discord's design! subcommand("ban", "Ban a user") { option("user", "The user to ban", true) option("reason", "Why to ban this user") option("duration", "For how long to ban this user") { choice("1 day", 1) choice("1 week", 7) choice("1 month", 31) } } subcommand("prune", "Prune messages") { option("amount", "The amount to delete from 2-100, default 50") } } }.queue() ``` ```kotlin jda.upsertCommand("prune", "Prune messages") { restrict(guild=true, Permission.MESSAGE_MANAGE) // guild only and requires message manage perms option("amount", "The amount to delete from 2-100, default 50") }.queue() ``` ```kotlin val menu = StringSelectMenu("menu:class") { option("Frost Mage", "mage-frost", emoji=FROST_SPEC, default=true) option("Fire Mage", "mage-fire", emoji=FIRE_SPEC) option("Arcane Mage", "mage-arcane", emoji=ARCANE_SPEC) } ``` -------------------------------- ### Gradle Dependencies for JDA and jda-ktx Source: https://github.com/freya022/jda-ktx/blob/master/README.md Shows how to add JDA and jda-ktx libraries to a Gradle project by specifying repositories and dependencies. ```gradle repositories { mavenCentral() } dependencies { implementation("net.dv8tion:JDA:${JDA_VERSION}") implementation("club.minnced:jda-ktx:${VERSION}") } ``` -------------------------------- ### Button Interactions Source: https://github.com/freya022/jda-ktx/blob/master/README.md Illustrates how to create and handle button interactions in JDA using Kotlin. This includes defining buttons with labels, styles, and associated actions, and responding to button clicks. ```kotlin jda.upsertCommand("ban", "ban a user") { option("member", "The member to ban", true) option("reason", "The ban reason") }.queue() ``` ```kotlin jda.onCommand("ban") { event -> if (event.user.asTag != "Minn#6688") return@onCommand val guild = event.guild!! val member = event.getOption("member")!! val reason = event.getOption("reason") // Buttons will timeout after 15 minutes by default val accept = jda.button(label = "Accept", style = SUCCESS, user = event.user) { guild.ban(member, 0, reason).queue() it.editMessage("${event.user.asTag} banned ${member.asTag}") .setActionRows() // remove buttons from message .queue() } val deny = jda.button(label = "Deny", style = DANGER, user = event.user) { it.hook.deleteOriginal().queue() // automatically acknowledged if callback does not do it } event.reply_("Are you sure?") .addActionRow(accept, deny) // send your buttons .queue() } ``` ```kotlin // or a global listener jda.onButton("accept") { event -> event.reply("You accepted :)").queue() } ``` -------------------------------- ### Logback Webhook Appender Configuration Source: https://github.com/freya022/jda-ktx/blob/master/packages.md Configures the WebhookAppender for Logback to send log messages to a Discord webhook. Requires discord-webhooks and logback libraries. Specifies logging level, timeout, webhook URL, and logging pattern. ```xml warn 10000 https://discord.com/api/webhooks/:id/:token %boldWhite(%d{HH:mm:ss.SSS}) %boldCyan(%thread) %boldGreen(%logger{0}) %highlight(%level)\n%msg%n ``` -------------------------------- ### SLF4J Delegate for Logging Source: https://github.com/freya022/jda-ktx/blob/master/README.md Shows how to use the SLF4J delegate to initialize loggers within a Kotlin object. This is useful for logging events in a JDA listener. ```kotlin object Listener : ListenerAdapter() { private val log by SLF4J override fun onMessageReceived(event: MessageReceivedEvent) { log.info("[{}] {}: {}", event.channel.name, event.author.asTag, event.message.contentDisplay) } } ``` -------------------------------- ### Maven Dependencies for JDA and jda-ktx Source: https://github.com/freya022/jda-ktx/blob/master/README.md Provides the XML configuration for including JDA and jda-ktx libraries as dependencies in a Maven project. ```xml net.dv8tion JDA $JDA_VERSION club.minnced jda-ktx $VERSION ``` -------------------------------- ### Gradle Dependencies for jda-ktx Source: https://github.com/freya022/jda-ktx/blob/master/packages.md Provides the necessary Gradle dependencies to include JDA and jda-ktx in your Kotlin project. It specifies the repositories and the implementation dependencies for both libraries. ```gradle repositories { mavenCentral() } dependencies { implementation("net.dv8tion:JDA:${JDA_VERSION}") implementation("club.minnced:jda-ktx:${VERSION}") } ``` -------------------------------- ### Delegate Properties for JDA Entities Source: https://github.com/freya022/jda-ktx/blob/master/README.md Demonstrates the use of delegate properties to safely keep references of JDA entities like users and channels. These delegates can be used with the `ref()` extension function. ```kotlin class Foo(guild: Guild) { val guild : Guild by guild.ref() } ``` -------------------------------- ### Maven Dependencies for jda-ktx Source: https://github.com/freya022/jda-ktx/blob/master/packages.md Provides the Maven XML configuration for adding JDA and jda-ktx as dependencies to your project. This includes the groupId, artifactId, and version for both libraries. ```xml net.dv8tion JDA $JDA_VERSION club.minnced jda-ktx $VERSION ``` -------------------------------- ### Embed and Message Builders Source: https://github.com/freya022/jda-ktx/blob/master/README.md Provides builder alternatives for JDA's `MessageBuilder` and `EmbedBuilder`. These builders simplify the creation of embeds and messages. ```kotlin val embed = Embed(title="Hello Friend", description="Goodbye Friend") ``` ```kotlin val embed = Embed { // Builds a MessageEmbed title = "Hello Friend" description = "Goodbye Friend" field { name = "How good is this example?" value = "5 :star:" inline = false } timestamp = Instant.now() color = 0xFF0000 } ``` ```kotlin val message = MessageCreate { // Builds MessageCreateData embeds += Embed("Ban Confirmation") components += row( success(id="approve:ban:$userId", label="Approve"), danger(id="deny:ban:$userId", label="Deny") ) } ``` -------------------------------- ### Kotlin Message Sending/Editing Extensions Source: https://github.com/freya022/jda-ktx/blob/master/README.md Demonstrates using jda-ktx extensions for sending and editing messages with named parameters and default values. Includes setting defaults for ephemeral messages and handling button interactions. ```kotlin SendDefaults.ephemeral = true // <- all reply_ calls set ephemeral=true by default MessageEditDefaults.replace = false // <- only apply explicitly set parameters (default behavior) jda.onCommand("ban") { event -> if (!event.member.hasPermission(Permission.BAN_MEMBERS)) return@onCommand event.reply_("You can't do that!").queue() event.reply_("Are you sure?", components=danger("ban", "Yes!").into()) val interaction = event.user.awaitButton("ban") val user = event.getOption("target")!! event.guild!!.ban(user, 0).queue() interaction.editMessage_("Successfully banned user", components=emptyList()).queue() } ``` -------------------------------- ### Coroutine Event Handling with JDA Source: https://github.com/freya022/jda-ktx/blob/master/README.md Demonstrates how to enable and use Kotlin coroutines for event handling in JDA. It shows how to set up a CoroutineEventManager and use suspending functions within event listeners for asynchronous operations like sending messages and awaiting user interactions. ```kotlin val jda = light("token", enableCoroutines=true) { intents += listOf(GatewayIntent.GUILD_MEMBERS, GatewayIntent.MESSAGE_CONTENT) } jda.listener { val guild = it.guild val channel = it.channel val message = it.message val content = message.contentRaw if (content.startsWith("!profile")) { // Send typing indicator and wait for it to arrive channel.sendTyping().await() val user = message.mentionedUsers.firstOrNull() ?: run { // Try loading user through prefix loading val matches = guild.retrieveMembersByPrefix(content.substringAfter("!profile "), 1).await() // Take first result, or null matches.firstOrNull() } if (user == null) // unknown user for name channel.send("${it.author.asMention}, I cannot find a user for your query!").queue() else // load profile and send it as embed channel.send("${it.author.asMention}, here is the user profile:", embeds=profile(user).into()).queue() } } jda.onCommand("ban", timeout=2.minutes) { event -> // 2 minute timeout listener val user = event.getOption("user")!! val confirm = danger("${user.id}:ban", "Confirm") event.reply_( "Are you sure you want to ban **${user.asTag}**?", components=confirm.into(), ephemeral=true ).queue() withTimeoutOrNull(1.minutes) { // 1 minute scoped timeout val pressed = event.user.awaitButton(confirm) // await for user to click button pressed.deferEdit().queue() // Acknowledge the button press event.guild.ban(user, 0).queue() // the button is pressed -> execute action } ?: event.hook.editMessage(/*id="@original" is default */content="Timed out.", components=emptyList()).queue() } jda.onButton("hello") { // Button that says hello it.reply_("Hello :)").queue() } ``` -------------------------------- ### JDA Coroutine Extensions for Async Operations Source: https://github.com/freya022/jda-ktx/blob/master/README.md Provides suspending extension functions for common JDA components, enabling asynchronous operations without explicitly requiring the CoroutineEventManager. These functions simplify waiting for RestAction results, Task completions, and specific events. ```kotlin /* Async Operations */ // Await RestAction result suspend fun RestAction.await() // Await Task result (retrieveMembersByPrefix) suspend fun Task.await() /* Event Waiter */ // Await specific event suspend fun JDA.await(filter: (T) -> Boolean = { true }) // Await specific event suspend fun ShardManager.await(filter: (T) -> Boolean = { true }) // Await message from specific channel (filter by user and/or filter function) suspend fun MessageChannel.awaitMessage(author: User? = null, filter: (Message) -> Boolean = { true }): Message // Flow representation for PaginationAction fun > M.asFlow(): Flow ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.