### Intent Configuration Examples Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Examples showing how to add and remove gateway intents. ```kotlin light("token") { // Add intents intents += GatewayIntent.GUILD_MEMBERS intents += listOf(GatewayIntent.MESSAGE_CONTENT, GatewayIntent.GUILD_PRESENCES) // Remove intents (automatically disables related cache flags) intents -= GatewayIntent.GUILD_MESSAGE_TYPING } ``` -------------------------------- ### Cache Configuration Examples Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Examples demonstrating how to enable and disable specific cache flags. ```kotlin default("token") { // Enable cache cache += CacheFlag.VOICE_STATE cache += listOf(CacheFlag.ACTIVITIES, CacheFlag.CLIENT_STATUS) // Disable cache cache -= CacheFlag.ROLE_TAGS } ``` -------------------------------- ### Mentions Configuration Examples Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Examples demonstrating different configurations for mention parsing, from allowing all to disabling all. ```kotlin // Allow everything val permissive = Mentions(parseEveryone = true) // Disable all mentions val safe = Mentions(parseUsers = false, parseRoles = false) // Only @everyone val everyone = Mentions(parseUsers = false, parseRoles = false, parseEveryone = true) MessageCreate( content = "@everyone important update", mentions = everyone ) ``` -------------------------------- ### Full JDA-KTX Bot Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md A comprehensive example showcasing bot initialization, command registration and handling, message listeners, and awaiting ready state. ```kotlin import dev.minn.jda.ktx.jdabuilder.light import dev.minn.jda.ktx.events.* import dev.minn.jda.ktx.coroutines.await import dev.minn.jda.ktx.messages.* import dev.minn.jda.ktx.interactions.commands.* import dev.minn.jda.ktx.interactions.components.* import net.dv8tion.jda.api.requests.GatewayIntent import net.dv8tion.jda.api.Permission import kotlin.time.Duration.Companion.minutes fun main() { val jda = light("TOKEN") { intents += listOf( GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT ) } // Register command jda.upsertCommand("ban", "Ban a user") { restrict(guild = true, Permission.BAN_MEMBERS) option("user", "User to ban", required = true) }.queue() // Handle command jda.onCommand("ban", timeout = 2.minutes) { event -> val user = event.getOption("user")!! val confirm = danger("ban", "Confirm") event.reply_( "Ban **${user.asTag}**?", components = listOf(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.editOriginal("User banned").queue() } ?: event.hook.editOriginal("Timed out").queue() } // Message listener jda.listener { event -> if (event.message.contentRaw.startsWith("!hello")) { val message = MessageCreate { content = "Hello ${event.author.asTag}!" embeds += Embed { title = "Greeting" color = 0x00FF00 } } event.channel.sendMessage(message).await() } } jda.awaitReady() println("Bot ready!") } ``` -------------------------------- ### SendDefaults Usage Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example demonstrating how to set global defaults for ephemeral replies and content, and how to override them for a specific message. ```kotlin // Make all interaction replies ephemeral by default SendDefaults.ephemeral = true SendDefaults.content = "Operation completed" jda.onCommand("test") { event -> event.reply_().queue() // Uses defaults: "Operation completed", ephemeral=true } // Override for specific call event.reply_("Custom message", ephemeral = false).queue() ``` -------------------------------- ### ButtonDefaults Usage Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example of setting default button styles and expiration times, and then creating a button that overrides these defaults. ```kotlin // Configure defaults ButtonDefaults.STYLE = ButtonStyle.PRIMARY ButtonDefaults.EXPIRATION = 5.minutes // Now all buttons use these defaults val button = button("id", label = "Click me") // Uses PRIMARY style, 5m expiration // Override for specific button val customButton = button("id2", label = "Custom", style = ButtonStyle.DANGER) ``` -------------------------------- ### Example: Replying to Commands and Interactions Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Shows how to use the `reply_` extension function to send a simple text reply to a command and a more complex reply with components and ephemeral settings. ```kotlin jda.onCommand("ping") { event -> event.reply_("Pong!").queue() } jda.onCommand("ban") { event -> event.reply_( "Are you sure?", components = listOf(danger("ban", "Yes").into()), ephemeral = true ).queue() ``` -------------------------------- ### Create JDA Instance with Default Configuration Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Use the `default()` function to create a JDA instance with standard configurations. This is a common starting point for bots. ```kotlin val jda = JDA.default() ``` -------------------------------- ### Pagination with Flow Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/coroutines.md Process large amounts of data efficiently by converting a PaginationAction to a Flow and collecting its items. ```kotlin suspend fun logAllMessages(channel: TextChannel) { channel.getHistory().asFlow().collect { println("[${it.timeCreated}] ${it.author.asTag}: ${it.contentRaw}") } } ``` -------------------------------- ### Basic Bot Setup with Coroutines Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Sets up a basic JDA bot using the light DSL and enables coroutines for asynchronous event handling. It configures necessary intents and includes a simple message listener. ```kotlin import dev.minn.jda.ktx.jdabuilder.light import dev.minn.jda.ktx.events.listener import dev.minn.jda.ktx.events.onCommand import net.dv8tion.jda.api.requests.GatewayIntent import net.dv8tion.jda.api.events.message.MessageReceivedEvent fun main() { val jda = light("TOKEN", enableCoroutines = true) { intents += listOf( GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT ) } jda.listener { event -> if (event.message.contentRaw.startsWith("!")) { event.channel.sendMessage("Command detected!").await() } } } ``` -------------------------------- ### Coroutine Event Listener Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/packages.md Demonstrates setting up JDA with coroutines and registering a message event listener that uses suspending functions. ```kotlin val jda = light(token, enableCoroutines=true) jda.listener { event -> if (event.message.contentRaw.startsWith("!hello")) { event.channel.sendTyping().await() // <- suspending function event.channel.send("Hello!").queue() } } ``` -------------------------------- ### Example: Constructing and Sending a Message Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Demonstrates how to use the MessageCreate builder to construct a message with content, embeds, and components, then send it to a channel. Note the use of `Embed` and `row` for builder configuration. ```kotlin import dev.minn.jda.ktx.messages.* val message = MessageCreate( content = "Hello!", embeds = listOf(Embed { title = "Title" description = "Description" }) ) { embeds += Embed("Another embed") components += row(primary("click", "Click me")) } channel.sendMessage(message).queue() ``` -------------------------------- ### JDA-KTX Error Handling Examples Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Demonstrates how to handle potential errors and timeouts using try-catch blocks, withTimeoutOrNull, and exception handling within listeners. ```kotlin // In listener try { val user = jda.retrieveUserById(123).await() } catch (e: ErrorResponseException) { println("User not found: ${e.errorCode}") } ``` ```kotlin // With timeout val result = withTimeoutOrNull(5.seconds) { channel.sendMessage("Hi").await() } if (result == null) { println("Message send timed out") } ``` ```kotlin // In button handler jda.onButton("test") { event -> try { event.guild!!.ban(event.user, 0).await() event.reply_("Banned").queue() } catch (e: Exception) { event.reply_("Error: ${e.message}").queue() } } ``` -------------------------------- ### Example: Create a Detailed Embed Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Constructs a user profile embed with a title, description, a non-inline field, color, and timestamp. This demonstrates the flexibility of the embed builder. ```kotlin val embed = Embed(title = "User Profile", description = "Information about a user") { field { name = "Join Date" value = user.timeCreated.toString() inline = false } color = 0xFF0000 timestamp = Instant.now() } ``` -------------------------------- ### MessageEditDefaults Usage Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Demonstrates the difference between merging and replacing message fields during edits using MessageEditDefaults.replace. ```kotlin MessageEditDefaults.replace = false message.editMessage_("New content").queue() // Only content is updated; embeds and components remain unchanged MessageEditDefaults.replace = true message.editMessage_("New content").queue() // Everything except content is cleared ``` -------------------------------- ### Create JDA Instance Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a JDA instance with full configuration, including coroutines and custom intents. Use this for a complete setup. ```kotlin inline fun createJDA( token: String, enableCoroutines: Boolean = true, timeout: Duration = Duration.INFINITE, intent: GatewayIntent, vararg intents: GatewayIntent, builder: JDABuilder.() -> Unit = {} ): JDA ``` -------------------------------- ### Custom CoroutineEventManager Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example of creating a custom CoroutineEventManager with a specific scope and timeout, then applying it to a JDABuilder. ```kotlin val customScope = getDefaultScope( pool = Executors.newFixedThreadPool(4), job = SupervisorJob(), errorHandler = CoroutineExceptionHandler { _, throwable -> logger.error("Event error", throwable) } ) val manager = CoroutineEventManager( scope = customScope, timeout = 5.minutes ) JDABuilder.createDefault("token") .setEventManager(manager) .build() ``` -------------------------------- ### Create Default JDA Instance with Default Intents Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a JDA instance with default cache flags and default intents. This is the simplest way to get a standard JDA instance running. ```kotlin inline fun default( token: String, enableCoroutines: Boolean = true, timeout: Duration = Duration.INFINITE, builder: JDABuilder.() -> Unit = {} ): JDA ``` -------------------------------- ### Example: Edit Message Content Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Demonstrates how to edit the content of a message after it has been sent. The `.queue()` method asynchronously sends the edit request. ```kotlin val message = channel.sendMessage("Old content").complete() message.editMessage_("New content").queue() ``` -------------------------------- ### Create Default JDA Instance with Intents Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a JDA instance with default cache flags enabled. Use this when you need the standard JDA setup with specific intents. ```kotlin inline fun default( token: String, enableCoroutines: Boolean = true, timeout: Duration = Duration.INFINITE, intent: GatewayIntent, vararg intents: GatewayIntent, builder: JDABuilder.() -> Unit = {} ): JDA ``` -------------------------------- ### CoroutineEventManager Listener Example Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/coroutines.md Demonstrates how to use await() within a CoroutineEventManager listener, where listener functions are suspending by default. The event manager automatically launches each listener in its own coroutine. ```kotlin jda.listener { // Suspend within the listener val guild = event.guild val newRole = guild.createRole().await() event.channel.sendMessage("Created role: ${newRole.name}").await() } ``` -------------------------------- ### ShardManager.scope Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Gets the coroutine scope used by the CoroutineEventManager, or the default scope, for launching coroutines. ```APIDOC ## ShardManager.scope ### Description Gets the coroutine scope used by the CoroutineEventManager, or the default scope. ### Property Signature ```kotlin val ShardManager.scope: CoroutineScope ``` ### Returns The CoroutineScope for launching coroutines ``` -------------------------------- ### JDA.scope Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Gets the coroutine scope used by the CoroutineEventManager, or the default scope, for launching coroutines. ```APIDOC ## JDA.scope ### Description Gets the coroutine scope used by the CoroutineEventManager, or the default scope. ### Property Signature ```kotlin val JDA.scope: CoroutineScope ``` ### Returns The CoroutineScope for launching coroutines ### Example ```kotlin val jda = light("token") jda.scope.launch { // Coroutine code here } ``` ``` -------------------------------- ### Create Simple Slash Command Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Define a basic slash command with a name and description. Options can be added to accept user input. ```kotlin jda.upsertCommand("ping", "Ping pong") { option("message", "Optional message") }.queue() ``` -------------------------------- ### ContextInteraction.targetMember Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Gets the member instance for a user context interaction target in a guild. ```APIDOC ## ContextInteraction.targetMember ### Description Gets the member instance for a user context interaction target in a guild. ### Method Extension Property ### Signature ```kotlin val ContextInteraction.targetMember: Member? ``` ### Returns Member if in a guild, null otherwise ### Example ```kotlin jda.onContext("Profile") { event -> val member = event.targetMember // Safe access println("Member: ${member?.user?.asTag}") } ``` ``` -------------------------------- ### Create String Select Menus Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Implement string select menus with options, descriptions, and emojis. Each option has a unique value. ```kotlin StringSelectMenu("menu") { option("Option 1", "opt1") option("Option 2", "opt2", description = "A choice") option("Option 3", "opt3", emoji = "🎉".toEmoji()) } ``` -------------------------------- ### Create Simple Embed Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Instantiate an embed with a title and description. ```kotlin // Simple Embed("My Title", "Description") ``` -------------------------------- ### Get Context Interaction Target Member Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/module-index.md Extension property to retrieve the target Member from a ContextInteraction targeting a User. ```kotlin val ContextInteraction.targetMember: Member? ``` -------------------------------- ### Type-Safe DSL Builders for Commands Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Demonstrates how to create a slash command using the jda-ktx DSL, including specifying options and restrictions. ```kotlin // Create a command Command("ban", "Ban a user") { restrict(guild = true, Permission.BAN_MEMBERS) option("user", "User to ban", required = true) option("reason", "Ban reason") } ``` -------------------------------- ### Custom Error Handling for Coroutine Scope Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example of creating a coroutine scope with a custom exception handler to manage uncaught exceptions. ```kotlin val scope = getDefaultScope( errorHandler = CoroutineExceptionHandler { ctx, exception -> when (exception) { is CancellationException -> {} is TimeoutCancellationException -> { logger.warn("Event listener timeout") } else -> { logger.error("Event error", exception) sentryClient.captureException(exception) } } } ) ``` -------------------------------- ### light() - Primary Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a lightweight JDA instance without default cache flags. Provides multiple overloads for different intent configurations. ```APIDOC ## light() - Primary ### Description Creates a lightweight JDA instance without default cache flags. Provides multiple overloads for different intent configurations. ### Method `light` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **token** (String) - Required - The bot token - **enableCoroutines** (Boolean) - Optional - true - Whether to use CoroutineEventManager - **timeout** (Duration) - Optional - Duration.INFINITE - Timeout for event listeners - **intent** (GatewayIntent) - Required - Primary gateway intent - **intents** (vararg GatewayIntent) - Optional - Additional gateway intents - **builder** (JDABuilder.() -> Unit) - Optional - {} - Configuration lambda ### Response #### Success Response - **JDA instance** ### Example ```kotlin import dev.minn.jda.ktx.jdabuilder.light import net.dv8tion.jda.api.requests.GatewayIntent val jda = light("token", enableCoroutines = true) { intents += GatewayIntent.GUILD_MEMBERS intents += GatewayIntent.MESSAGE_CONTENT } ``` ``` -------------------------------- ### EventTimeout Configuration Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Configures listener timeouts using EventTimeout.Limit for a specific duration. This example shows setting a 2-minute timeout for a ButtonInteractionEvent listener. ```kotlin val timeout = EventTimeout.Limit(2.minutes) val listener = listener(timeout = 2.minutes) { // This listener will timeout after 2 minutes } ``` -------------------------------- ### Create JDA Instance with Light Configuration Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Utilize the `light()` function for a minimal JDA instance, suitable for scenarios where full JDA features are not required. This can reduce memory footprint. ```kotlin val jda = JDA.light() ``` -------------------------------- ### Create Embed with DSL Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Build a rich embed using a DSL, configuring title, description, color, fields, thumbnail, image, footer, and timestamp. ```kotlin // With DSL Embed { title = "Title" description = "Description" color = 0xFF0000 field("Field", "Value") field("Inline", "Yes", inline = true) thumbnail = "https://example.com/img.png" image = "https://example.com/big.png" footer("Footer text") timestamp = Instant.now() } ``` -------------------------------- ### Example: Message with @everyone Mention Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Creates a message that explicitly allows the `@everyone` mention by configuring the `Mentions` object. This is useful for important announcements. ```kotlin MessageCreate( content = "@everyone check this out", mentions = Mentions(parseEveryone = true) ) ``` -------------------------------- ### Custom Parent Job for Coroutine Scope Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example of creating a coroutine scope with a custom SupervisorJob, allowing for graceful cancellation of all event handlers. ```kotlin val supervisorJob = SupervisorJob() val scope = getDefaultScope(job = supervisorJob) // Later, cancel all event handlers gracefully supervisorJob.cancel() ``` -------------------------------- ### Create a String Select Menu Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Build a `StringSelectMenu` for users to select one or more options from a list. This is useful for choices or filtering. ```kotlin val menu = StringSelectMenu("choose_option") { placeholder = "Select an option" SelectOption("Option 1", "value1") SelectOption("Option 2", "value2") } ``` -------------------------------- ### Custom Thread Pool for Coroutine Scope Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Example of creating a custom coroutine scope using a fixed thread pool for event handling. ```kotlin val customScope = getDefaultScope( pool = Executors.newFixedThreadPool(8, ThreadFactory { Thread(it, "JDA-Event-${threadCounter++}").apply { isDaemon = true priority = Thread.NORM_PRIORITY } }) ) val manager = CoroutineEventManager(scope = customScope) ``` -------------------------------- ### Get Generic Channel by Type Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt The `getChannel()` utility function allows retrieving a channel from a `Guild` or `ChannelManager` by casting it to a specific channel type. ```kotlin val textChannel = guild.getChannel(channelId) ``` -------------------------------- ### Create Slash Command with Choices Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Provide predefined choices for a slash command option, allowing users to select from a list of valid inputs. ```kotlin jda.upsertCommand("choice", "Pick one") { option("pick", "Your choice", required = true) { choice("Option A", "a") choice("Option B", "b") choice("Option C", "c") } }.queue() ``` -------------------------------- ### light() - Collection Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a lightweight JDA instance using a collection of intents. ```APIDOC ## light() - Collection ### Description Creates a lightweight JDA instance using a collection of intents. ### Method `light` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **token** (String) - Required - The bot token - **enableCoroutines** (Boolean) - Optional - true - Whether to use CoroutineEventManager - **timeout** (Duration) - Optional - Duration.INFINITE - Timeout for event listeners - **intents** (Collection) - Required - Gateway intents - **builder** (JDABuilder.() -> Unit) - Optional - {} - Configuration lambda ### Response #### Success Response - **JDA instance** ### Example ```kotlin val intents = listOf(GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT) val jda = light("token", intents = intents) ``` ``` -------------------------------- ### Initialize SLF4J Logger by Type Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/utilities.md Initializes an SLF4J Logger using the reified type parameter. This is a concise way to get a logger for the current class. ```kotlin class MyService { private val log by SLF4J() } ``` -------------------------------- ### light() - Defaults Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a lightweight JDA instance using default intents. ```APIDOC ## light() - Defaults ### Description Creates a lightweight JDA instance using default intents. ### Method `light` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **token** (String) - Required - The bot token - **enableCoroutines** (Boolean) - Optional - true - Whether to use CoroutineEventManager - **timeout** (Duration) - Optional - Duration.INFINITE - Timeout for event listeners - **builder** (JDABuilder.() -> Unit) - Optional - {} - Configuration lambda ### Response #### Success Response - **JDA instance** ``` -------------------------------- ### Component Creation Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/module-index.md DSL builders for creating interactive components like buttons and select menus. ```APIDOC ## Component Creation ### `button() / primary() / danger()` **Description:** Builders for creating various types of buttons. ### `StringSelectMenu()` **Description:** Builder for creating string select menus. ### `EntitySelectMenu()` **Description:** Builder for creating entity select menus. ### `row()` **Description:** Builder for creating an action row to hold components. ### `container()` **Description:** Builder for creating Component V2 containers. ``` -------------------------------- ### Get Coroutine Scope from JDA Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Retrieves the coroutine scope associated with the CoroutineEventManager for a JDA instance. Use this scope for launching coroutines related to JDA events. ```kotlin val jda = light("token") jda.scope.launch { // Coroutine code here } ``` -------------------------------- ### Create a String Select Menu Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Build a string select menu with a custom ID, placeholder, value range, and options. Supports custom builders for configuration. ```kotlin inline fun StringSelectMenu( customId: String, uniqueId: Int = -1, placeholder: String? = null, valueRange: IntRange = 1..1, disabled: Boolean = false, options: Collection = emptyList(), builder: StringSelectMenu.Builder.() -> Unit = {} ): StringSelectMenu ``` ```kotlin val menu = StringSelectMenu("class") { option("Warrior", "warrior", emoji = Emoji.fromUnicode("⚔️")) option("Mage", "mage", emoji = Emoji.fromUnicode("✨")) option("Rogue", "rogue", emoji = Emoji.fromUnicode("🗡️")) } ``` -------------------------------- ### Create a Slash Command Definition Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Define slash commands using the `Command` builder. This allows you to specify the command name, description, and options. ```kotlin val command = Command("ping", "Check bot latency") { // Options and subcommands can be added here } ``` -------------------------------- ### Example: Set Default Ephemeral Replies Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/messages.md Sets the default ephemeral status for all subsequent reply operations to true. This ensures that commands marked as ephemeral will be private by default. ```kotlin SendDefaults.ephemeral = true // All reply_ calls default to ephemeral jda.onCommand("test") { event -> event.reply_("This is ephemeral by default").queue() } ``` -------------------------------- ### Create Lightweight JDA Instance with Default Intents Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a lightweight JDA instance using default intents. Use this when you don't need to specify individual intents. ```kotlin inline fun light( token: String, enableCoroutines: Boolean = true, timeout: Duration = Duration.INFINITE, builder: JDABuilder.() -> Unit = {} ): JDA ``` -------------------------------- ### Create Slash Command with Subcommands Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Organize complex commands into subcommands for better structure and user experience. This allows for multiple related actions under a single command. ```kotlin jda.updateCommands { slash("admin", "Admin commands") { subcommand("ban", "Ban a user") { option("user", "User", required = true) } subcommand("kick", "Kick a user") { option("user", "User", required = true) } } }.queue() ``` -------------------------------- ### Register Command Event Listener Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Set up a listener for slash commands, responding to a specific command name like 'ping'. ```kotlin // Command jda.onCommand("ping") { event -> event.reply_("Pong!").queue() } ``` -------------------------------- ### Get Target Member from Context Interaction Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Retrieves the Member object associated with a user context interaction target within a guild. Returns null if the interaction is not in a guild. ```kotlin val ContextInteraction.targetMember: Member? ``` ```kotlin jda.onContext("Profile") { val member = event.targetMember // Safe access println("Member: ${member?.user?.asTag}") } ``` -------------------------------- ### SelectOption Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Creates a select menu option with a label, value, and optional description and emoji. ```APIDOC ## SelectOption() ### Description Creates a select menu option with description and emoji. ### Signature ```kotlin fun SelectOption( label: String, value: String, description: String? = null, emoji: Emoji? = null, default: Boolean = false ): SelectOption ``` ### Parameters #### Path Parameters - **label** (String) - Required - The text displayed to the user for this option. - **value** (String) - Required - The custom value that will be sent to your application when this option is selected. - **description** (String?) - Optional - A description for this option, max 100 characters. - **emoji** (Emoji?) - Optional - An emoji for this option. - **default** (Boolean) - Optional - Whether this option is pre-selected. Default: false ``` -------------------------------- ### Get Coroutine Scope from ShardManager Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Retrieves the coroutine scope associated with the CoroutineEventManager for a ShardManager instance. This scope is used for launching coroutines within the shard manager context. ```kotlin val ShardManager.scope: CoroutineScope ``` -------------------------------- ### Configure Intents and Cache Flags Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Configure gateway intents and cache flags using the JDABuilder DSL accumulators. ```kotlin light("token") { intents += GatewayIntent.GUILD_MEMBERS intents += GatewayIntent.MESSAGE_CONTENT cache += CacheFlag.VOICE_STATE cache -= CacheFlag.EMOJI } ``` -------------------------------- ### Bot Creation Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/module-index.md Functions for creating bot instances with different configurations. ```APIDOC ## Bot Creation ### `light()` **Description:** Creates a bot instance with minimal configuration. ### `default()` **Description:** Creates a bot instance with default caching enabled. ### `jda.scope` **Description:** Accesses the coroutine scope associated with the JDA instance. ``` -------------------------------- ### Migrate Message Construction from JDA to jda-ktx Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Shows how to construct messages using jda-ktx's builder pattern, which is more concise and maintainable than JDA's traditional `MessageBuilder` and `EmbedBuilder`. ```kotlin MessageBuilder() .setContent("Hello") .addEmbeds(EmbedBuilder() .setTitle("Title") .build()) .build() ``` ```kotlin MessageCreate("Hello") { embeds += Embed(title = "Title") } ``` -------------------------------- ### Handle Button Clicks Source: https://github.com/minndevelopment/jda-ktx/blob/master/packages.md Listens for a button with the custom ID 'hello' and replies with a simple greeting. ```kotlin jda.onButton("hello") { // Button that says hello it.reply_("Hello :)").queue() } ``` -------------------------------- ### Create Default JDA Instance with Intent Collection Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/jda-builder.md Creates a JDA instance with default cache flags enabled, using a collection of intents. This is suitable for standard JDA setup with pre-defined intent collections. ```kotlin inline fun default( token: String, enableCoroutines: Boolean = true, timeout: Duration = Duration.INFINITE, intents: Collection, builder: JDABuilder.() -> Unit = {} ): JDA ``` -------------------------------- ### Create a Primary Button Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Build interactive buttons using the `button` DSL. Specify the button style (e.g., `primary`) and its label. ```kotlin val button = Button("Click Me", ButtonStyle.PRIMARY) { /* action */ } ``` -------------------------------- ### Create an Entity Select Menu Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Construct an `EntitySelectMenu` to allow users to select Discord entities like users, channels, or roles. This requires specifying the entity type. ```kotlin val userMenu = EntitySelectMenu.user("select_user") { /* options */ } ``` -------------------------------- ### Get Entity Reference Delegate Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Entity reference delegates (e.g., `User.ref`, `Member.ref`) provide a convenient way to obtain references to entities without fetching them immediately. This is useful for passing entity IDs around. ```kotlin val userRef = User.ref(userId) val memberRef = Member.ref(guildId, userId) ``` -------------------------------- ### Type-Safe DSL Builders for Buttons Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Illustrates the creation of styled buttons using jda-ktx DSL functions. ```kotlin // Create buttons val approve = success("approve", "Approve") val deny = danger("deny", "Deny") ``` -------------------------------- ### Create SlashCommandData with DSL Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Use the Command builder for creating slash command data with a Domain Specific Language (DSL) syntax. This is useful for defining the structure and options of your slash commands. ```kotlin inline fun Command( name: String, description: String, builder: SlashCommandData.() -> Unit = {} ): SlashCommandData ``` ```kotlin import dev.minn.jda.ktx.interactions.commands.* Command("ban", "Ban a user") { restrict(guild = true, Permission.BAN_MEMBERS) option("user", "The user to ban", required = true) option("reason", "Ban reason") } ``` -------------------------------- ### Automatic Entity Caching Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Demonstrates how to use jda-ktx's `ref()` extension for automatic entity caching, ensuring safe references to Discord entities. ```kotlin class ModLog(channel: TextChannel) { // Automatically refreshes from cache on each access val channel: TextChannel by channel.ref() fun log(message: String) { channel.sendMessage(message).queue() } } ``` -------------------------------- ### Register Simple Slash Command Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Registers a simple slash command with an optional string option and sets up a listener for command execution. ```kotlin jda.upsertCommand("ping", "Pong!") { option("message", "Optional message") }.queue() jda.onCommand("ping") { event -> val msg = event.getOption("message") ?: "Pong!" event.reply_(msg).queue() } ``` -------------------------------- ### Create JDA Instance with Full Configuration Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/module-index.md Provides a fully configurable JDA instance creation function, including coroutine support and custom timeouts. ```kotlin fun createJDA(token: String, enableCoroutines: Boolean = false, timeout: Long = 3000, vararg intents: Intent, builder: JDABuilder.() -> Unit = {}): JDA ``` -------------------------------- ### button() Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Creates a Button with keyword arguments and style options. This function is a versatile way to construct buttons for user interaction. ```APIDOC ## button() ### Description Creates a Button with keyword arguments and style options. ### Method ```kotlin fun button( customId: String, label: String? = ButtonDefaults.LABEL, emoji: Emoji? = ButtonDefaults.EMOJI, uniqueId: Int = -1, style: ButtonStyle = ButtonDefaults.STYLE, disabled: Boolean = ButtonDefaults.DISABLED ): Button ``` ### Parameters #### Path Parameters - **customId** (String) - Required - Button custom ID - **label** (String?) - Optional - Button text label - **emoji** (Emoji?) - Optional - Button emoji - **uniqueId** (Int) - Optional - Unique ID for client-side generation - **style** (ButtonStyle) - Optional - Button visual style - **disabled** (Boolean) - Optional - Disabled state ### Returns Button instance ### Request Example ```kotlin val button = button("confirm", label = "Confirm", style = ButtonStyle.SUCCESS) ``` ``` -------------------------------- ### Command Creation Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/module-index.md Utilities for defining and configuring slash commands. ```APIDOC ## Command Creation ### `Command()` **Description:** Builder for creating slash commands. ### `Subcommand()` **Description:** Builder for creating subcommands. ### `Option()` **Description:** Defines a typed option for a command. ### `SlashCommandData.restrict()` **Description:** Restricts command usage based on permissions. ``` -------------------------------- ### Create Select Menu Option Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Creates a select menu option with a label, value, and optional description, emoji, or default status. ```kotlin fun SelectOption( label: String, value: String, description: String? = null, emoji: Emoji? = null, default: Boolean = false ): SelectOption ``` ```kotlin SelectOption("Frost Mage", "mage-frost", description = "Ice damage", emoji = FROST_EMOJI, default = true) ``` -------------------------------- ### Logging in Event Listeners with SLF4J Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/utilities.md Shows how to use the SLF4J delegate for logging within event listeners, providing a concise way to log information like member joins. ```kotlin object EventLogger : ListenerAdapter() { private val log by SLF4J override fun onGuildMemberJoin(event: GuildMemberJoinEvent) { log.info("Member joined: {}", event.user.asTag) } } ``` -------------------------------- ### Type-Safe DSL Builders for Messages Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Shows how to construct a message with embeds and components using the jda-ktx DSL. ```kotlin // Create a message MessageCreate(content = "Hello") { embeds += Embed { title = "Welcome" description = "Welcome to the server" } components += row(primary("id", "Click me")) } ``` -------------------------------- ### Create Entity Select Menus Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Create select menus for specific Discord entities like users, roles, or channels. You can specify the target types and a placeholder. ```kotlin EntitySelectMenu( "users", setOf(SelectTarget.USER), placeholder = "Select a user", valueRange = 1..5 ) EntitySelectMenu("roles", setOf(SelectTarget.ROLE)) EntitySelectMenu("channels", setOf(SelectTarget.CHANNEL)) ``` -------------------------------- ### Command() Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Creates a SlashCommandData with DSL syntax. Use this to define top-level slash commands. ```APIDOC ## Command() ### Description Creates a SlashCommandData with DSL syntax. ### Method Signature ```kotlin inline fun Command( name: String, description: String, builder: SlashCommandData.() -> Unit = {} ): SlashCommandData ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | String | Yes | Command name (1-32 chars, lowercase alphanumeric) | | description | String | Yes | Command description (1-100 chars) | | builder | lambda | No | Configuration DSL | ### Returns SlashCommandData configured via DSL ### Example ```kotlin import dev.minn.jda.ktx.interactions.commands.* Command("ban", "Ban a user") { restrict(guild = true, Permission.BAN_MEMBERS) option("user", "The user to ban", required = true) option("reason", "Ban reason") } ``` ``` -------------------------------- ### Command with User Interaction and Timeout Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/overview.md Handles a slash command with user confirmation using buttons and includes a timeout mechanism for the interaction. It demonstrates awaiting button presses and replying to the user. ```kotlin jda.onCommand("ban", timeout = 2.minutes) { event -> val user = event.getOption("user")!! val confirm = danger("${user.id}:ban", "Confirm") event.reply_( "Ban **${user.asTag}**?", components = listOf(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.editOriginal("Timed out").queue() ``` -------------------------------- ### Safe Entity Caching with `ref()` Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/utilities.md Demonstrates using the `ref()` delegate for safe entity caching, ensuring properties like usernames are always up-to-date from the cache. ```kotlin class UserProfile(user: User) { private val user: User by user.ref() fun getUsername() = user.asTag // Always up-to-date from cache } ``` -------------------------------- ### Create a Success Button Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Construct a button with the `success` style, typically used for confirmation actions. The `success` function is a shortcut for `Button(style = ButtonStyle.SUCCESS)`. ```kotlin val confirmButton = Button.success("Confirm") { /* action */ } ``` -------------------------------- ### Create Basic Buttons Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Use the `button` function for simple buttons with an ID and label. Various styles and options like emojis and disabled states are available. ```kotlin button("id", label = "Click me") // With style primary("id", "Primary") success("id", "Success") danger("id", "Danger") secondary("id", "Secondary") // With emoji button("id", label = "React", emoji = "👍".toEmoji()) // Disabled button("id", label = "Disabled", disabled = true) ``` -------------------------------- ### JDA-KTX Selection Menu Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Create and handle a selection menu for users to choose from a list of options. This is useful for role selection or other choices. ```kotlin val menu = StringSelectMenu("role") { option("Admin", "admin") option("Mod", "mod") option("User", "user") } event.reply_("Select a role:", components = listOf(row(menu))).queue() jda.onStringSelect("role") { event -> val role = when (event.values[0]) { "admin" -> guild.getRoleByName("Admin", true) "mod" -> guild.getRoleByName("Mod", true) else -> guild.getRoleByName("User", true) } event.guild!!.addRoleToMember(event.member!!, role!!).await() event.reply_("Role assigned").queue() } ``` -------------------------------- ### JDA.onContext() Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Creates a listener for context menu commands, filtering by name and target type. Supports an optional timeout. ```APIDOC ## JDA.onContext() ### Description Creates a listener for context menu commands, filtering by name and target type. Supports an optional timeout. ### Method `inline fun JDA.onContext(...)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **T** (Target type) - Required - Message or User - **name** (String) - Required - Context command name - **timeout** (Duration?) - Optional - Optional timeout - **consumer** (suspend lambda) - Required - The handler ### Request Example ```kotlin jda.onContext("Pin Message") { event -> event.target.pin().await() event.reply("Message pinned!").queue() } ``` ### Response #### Success Response - **CoroutineEventListener** - Represents the registered listener ``` -------------------------------- ### Configure Defaults at Startup Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/configuration.md Set global defaults for components like ephemeral messages and button styles/expiration before creating the JDA instance. This ensures consistent behavior across your application. ```kotlin fun main() { // Configure defaults once at startup SendDefaults.ephemeral = false ButtonDefaults.STYLE = ButtonStyle.PRIMARY ButtonDefaults.EXPIRATION = 10.minutes // Create JDA with configured defaults val jda = light("token") { intents += GatewayIntent.MESSAGE_CONTENT } // Register listeners... } ``` -------------------------------- ### Create Command Autocomplete Listener Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Creates a listener for command autocomplete interactions. Use this to provide suggestions for command options. ```kotlin fun JDA.onCommandAutocomplete( name: String, option: String? = null, timeout: Duration? = null, consumer: suspend CoroutineEventListener.(CommandAutoCompleteInteractionEvent) -> Unit ): CoroutineEventListener ``` ```kotlin jda.onCommandAutocomplete("play", "track") { event -> event.replyChoiceStrings(youtube.search(event.focusedOption.value)).queue() } ``` -------------------------------- ### Handle Command with Permission Check and Button Confirmation Source: https://github.com/minndevelopment/jda-ktx/blob/master/README.md Implements a ban command that first checks for ban permissions. If the user lacks permission, it sends an ephemeral reply. Otherwise, it prompts for confirmation using a button and awaits the user's interaction before proceeding with the ban. ```kotlin 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() } ``` -------------------------------- ### Create Context Menu Command Listener Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/events.md Creates a listener for context menu commands, identified by name and target type. This is used for handling user or message context menu interactions. ```kotlin inline fun JDA.onContext( name: String, timeout: Duration? = null, crossinline consumer: suspend CoroutineEventListener.(GenericContextInteractionEvent) -> Unit ): CoroutineEventListener ``` ```kotlin jda.onContext("Pin Message") { event.target.pin().await() event.reply("Message pinned!").queue() } ``` -------------------------------- ### Use SLF4J Logger Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/quick-reference.md Integrate SLF4J for logging within your JDA-KTX listeners. This provides a standard way to log events and debug your bot. ```kotlin class MyListener : ListenerAdapter() { private val log by SLF4J override fun onMessageReceived(event: MessageReceivedEvent) { log.info("Message: {}", event.message.contentRaw) } } ``` -------------------------------- ### JDA Builder Functions Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt This section details the functions available for building and configuring a JDA instance using JDA-KTX. It includes factory functions like `light()`, `default()`, and `createJDA()`, along with builder extensions for intents and cache, and property extensions for coroutine scopes. ```APIDOC ## JDA Builder Functions ### Description Functions for creating and configuring JDA instances with coroutine support. ### Functions - `light()`: Creates a JDA instance with minimal configuration. - `default()`: Creates a JDA instance with default configurations. - `createJDA()`: A factory function for creating JDA instances with custom configurations. ### Extensions - **Intents**: Builder extensions for configuring JDA intents. - **Cache**: Builder extensions for configuring JDA cache flags. - **Scope**: Property extensions for customizing the coroutine scope. ### Helper Classes - `IntentAccumulator`: Assists in accumulating JDA intents. - `CacheFlagAccumulator`: Assists in accumulating JDA cache flags. ``` -------------------------------- ### Create a Secondary Button Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/INDEX.txt Build a button with the `secondary` style for less prominent actions. This is the default style if none is specified. ```kotlin val infoButton = Button.secondary("More Info") { /* action */ } ``` -------------------------------- ### Create SubcommandData with DSL Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/interactions.md Use the Subcommand builder for creating subcommand data with DSL syntax. This allows for nested command structures within a parent slash command. ```kotlin inline fun Subcommand( name: String, description: String, builder: SubcommandData.() -> Unit = {} ): SubcommandData ``` ```kotlin slash("mod", "Moderation commands") { subcommand("ban", "Ban a user") { option("user", "The user to ban", required = true) } subcommand("kick", "Kick a user") { option("user", "The user to kick", required = true) } } ``` -------------------------------- ### SLF4J Logger Initialization Source: https://github.com/minndevelopment/jda-ktx/blob/master/_autodocs/api-reference/utilities.md Provides property delegates for SLF4J Logger initialization, supporting initialization by property delegation, by name, or by type. ```APIDOC ## SLF4J Logger Initialization ### Description Property delegate for SLF4J Logger initialization. ### Method Object with operator functions for delegation. ### Usage Patterns 1. **Delegate Property:** ```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) } } ``` 2. **By Name:** ```kotlin class MyService { private val log by SLF4J("myservice") } ``` 3. **By Type:** ```kotlin class MyService { private val log by SLF4J() } ``` ```