### Example Bot Usage with Kord Source: https://github.com/kordlib/kord/blob/main/core/README.md Demonstrates how to set up a Kord bot to respond to messages. Includes both a flow-style event handling and a simplified event listener. Requires privileged intents for message content access. ```kotlin suspend fun main() { val kord = Kord("your bot token") // Flow style kord.events .filterIsInstance() .map { it.message } .filter { it.author?.isBot == false } .filter { it.content == "!ping" } .onEach { it.channel.createMessage("pong") } .launchIn(kord) // Simplified style kord.on { if (message.author?.isBot == true) return@on if (message.content == "!ping") message.channel.createMessage("pong") } kord.login { @OptIn(PrivilegedIntent::class) intents += Intent.MessageContent } } ``` -------------------------------- ### Start a Kord Bot Application Source: https://github.com/kordlib/kord/wiki/Getting-Started This is the minimal code required to get your bot online. Ensure you replace 'your bot token' with your actual bot token. The `login()` function keeps the bot running until it's logged out or the program stops. ```kotlin suspend fun main() { val kord = Kord("your bot token") kord.login() } ``` -------------------------------- ### Play Audio from YouTube with LavaPlayer Source: https://github.com/kordlib/kord/blob/main/voice/README.md This example demonstrates how to play audio from YouTube using a user-provided query and LavaPlayer. It requires a bot token as a command-line argument. Ensure LavaPlayer is configured to use remote sources like YouTube. ```kotlin suspend fun main(args: Array) { val token = args.firstOrNull() ?: error("token required") val kord = Kord(token) val lavaplayerManager = DefaultAudioPlayerManager() // to use YouTube, we tell LavaPlayer to use remote sources, like YouTube. AudioSourceManagers.registerRemoteSources(lavaplayerManager) // here we keep track of active voice connections val connections: MutableMap = mutableMapOf() kord.on { if (message.content.startsWith("!play")) { val channel = member?.getVoiceState()?.getChannelOrNull() ?: return@on // lets close the old connection if there is one if (connections.contains(guildId)) { connections.remove(guildId)!!.shutdown() } // our lavaplayer audio player which will provide frames of audio val player = lavaplayerManager.createPlayer() // lavaplayer uses ytsearch: as an identifier to search for YouTube val query = "ytsearch: ${message.content.removePrefix("!play")}" val track = lavaplayerManager.playTrack(query, player) // here we actually connect to the voice channel val connection = channel.connect { // the audio provider should provide frames of audio audioProvider { AudioFrame.fromData(player.provide()?.data) } } connections[guildId!!] = connection message.reply { content = "playing track: ${track.info.title}" } } else if (message.content == "!stop") { if (guildId == null) return@on connections.remove(guildId)?.shutdown() } } kord.login() } // lavaplayer isn't super kotlin-friendly, so we'll make it nicer to work with suspend fun DefaultAudioPlayerManager.playTrack(query: String, player: AudioPlayer): AudioTrack { val track = suspendCoroutine { this.loadItem(query, object : AudioLoadResultHandler { override fun trackLoaded(track: AudioTrack) { it.resume(track) } override fun playlistLoaded(playlist: AudioPlaylist) { it.resume(playlist.tracks.first()) } override fun noMatches() { TODO() } override fun loadFailed(exception: FriendlyException?) { TODO() } }) } player.playTrack(track) return track } ``` -------------------------------- ### Respond to a message using stateless channel behavior Source: https://github.com/kordlib/kord/wiki/Entities This example demonstrates how to respond to a message using the stateless `message.channel` behavior, which avoids fetching the full channel object and potential IO operations. ```kotlin kord.on { if(message.content == "!ping") return@on //get the behavior of a channel for free, happy! message.channel.createMessage("pong!") } ``` -------------------------------- ### Example Kord Gateway Usage Source: https://github.com/kordlib/kord/blob/main/gateway/README.md Demonstrates how to connect to Discord's gateway, handle events like message creation, and control gateway actions such as stopping, detaching, and editing presence. Requires a bot token as a command-line argument. Privileged intents like MessageContent need to be explicitly enabled. ```kotlin suspend fun main(args: Array) { val token = args.firstOrNull() ?: error("token required") val gateway = DefaultGateway { // optional builder for custom configuration client = HttpClient { install(WebSockets) } reconnectRetry = LinearRetry(2.seconds, 20.seconds, 10) sendRateLimiter = IntervalRateLimiter(120, 60.seconds) dispatcher = Dispatchers.Default } gateway.events.filterIsInstance().onEach { val words = it.message.content.split(' ') when (words.firstOrNull()) { "!close" -> gateway.stop() "!detach" -> gateway.detach() "!status" -> when (words.getOrNull(1)) { "playing" -> gateway.editPresence { status = PresenceStatus.Online afk = false playing("Kord") } } } }.launchIn(gateway) gateway.start(token) { @OptIn(PrivilegedIntent::class) intents += Intent.MessageContent } } ``` -------------------------------- ### Respond to a message by fetching channel state (less efficient) Source: https://github.com/kordlib/kord/wiki/Entities This example shows a less efficient way to respond to a message by first fetching the full channel object using `message.getChannel()`, which may incur IO operations if the channel is not cached. ```kotlin kord.on { if(message.content == "!ping") return@on //get a channel just to create a message, sad! message.getChannel().createMessage("pong!") } ``` -------------------------------- ### Listen to Reactions on a Specific Message with Live Entity Source: https://github.com/kordlib/kord/wiki/Entities Use `live()` on an entity to create a `Live[Entity]` which emits events filtered for that entity. This example shows how to listen for `ReactionAddEvent` on a specific message. Ensure the entity has events available. ```kotlin val liveMessage = message.live() liveMessage.on { println("this will only report reactions added to the message") } ``` -------------------------------- ### Enable Privileged Gateway Intents in Kord Source: https://github.com/kordlib/kord/wiki/Intents To use privileged intents like GuildPresences, you must opt-in using the @OptIn annotation and enable them in the Discord Developer Portal. This example shows how to add GuildPresences to the default non-privileged intents. ```kotlin Kord(token) { @OptIn(PrivilegedIntent::class) intents = Intents.nonPrivileged + Intent.GuildPresences } ``` -------------------------------- ### Initialize Kord REST Client Source: https://github.com/kordlib/kord/blob/main/rest/README.md Demonstrates how to initialize and use the Kord REST client to fetch the current user's username. Requires a Discord token as a command-line argument. ```kotlin suspend fun main(args: Array) { val token = args.firstOrNull() ?: error("token required") val rest = RestClient(KtorRequestHandler(token)) val username = rest.user.getCurrentUser().username println("using $username's token") } ``` -------------------------------- ### Initialize Kord with Default Cache Configuration Source: https://github.com/kordlib/kord/wiki/Caching This snippet shows the basic structure for creating a Kord instance with the cache configuration block. The cache will use default settings unless further specified. ```kotlin val kord = Kord("token"){ cache { } } ``` -------------------------------- ### Implement a Ping-Pong Bot with Message Handling Source: https://github.com/kordlib/kord/wiki/Getting-Started This snippet demonstrates how to create a bot that responds to a '!ping' command with 'pong!'. It requires enabling the Message Content Intent and should have event listeners added before calling `login()`. ```kotlin suspend fun main() { val kord = Kord("your bot token") kord.on { // runs every time a message is created that our bot can read // ignore other bots, even ourselves. We only serve humans here! if (message.author?.isBot != false) return@on // check if our command is being invoked if (message.content != "!ping") return@on // all clear, give them the pong! message.channel.createMessage("pong!") } kord.login { // we need to specify this to receive the content of messages @OptIn(PrivilegedIntent::class) intents += Intent.MessageContent } } ``` -------------------------------- ### Configure Audio Provider for Sending Audio Source: https://github.com/kordlib/kord/blob/main/voice/README.md Configure the audio provider within the `VoiceConnectionBuilder` to send audio frames to Discord. The audio provider should supply `AudioFrame` objects when requested by Kord. ```kotlin voiceChannel.connect { // audio provider wants a AudioFrame each time its called by Kord audioProvider { AudioFrame.fromData( /* an opus audio frame, you can use something like lavaplayer to do this for you*/ ) } } ``` -------------------------------- ### Configure Individual Entity Caching Policies Source: https://github.com/kordlib/kord/wiki/Caching Demonstrates how to set specific caching policies for different entity types like users, messages, and members. This allows fine-grained control over cache behavior, such as setting a maximum size for message caches or disabling member caching. ```kotlin val kord = Kord("token"){ cache { users { cache, description -> MapEntryCache(cache, description, MapLikeCollection.concurrentHashMap()) } messages { cache, description -> MapEntryCache(cache, description, MapLikeCollection.lruLinkedHashMap(maxSize = 100)) } members { cache, description -> MapEntryCache(cache, description, MapLikeCollection.none()) } } } ``` -------------------------------- ### Add SLF4J Simple Implementation Dependency Source: https://github.com/kordlib/kord/wiki/Logging Add the `slf4j-simple` dependency to your project's build file to provide an SLF4J implementation. Ensure you are using a recent version. ```kotlin repository { mavenCentral() } dependencies { implementation("org.slf4j:slf4j-simple:${version}") } ``` -------------------------------- ### Add Kord REST Dependency (Maven) Source: https://github.com/kordlib/kord/blob/main/rest/README.md Instructions for adding the Kord REST client dependency to a project using Maven. ```xml dev.kord kord-rest-jvm {version} ``` -------------------------------- ### SLF4J SimpleLogger Configuration Properties Source: https://github.com/kordlib/kord/wiki/Logging Configure the behavior of SLF4J's SimpleLogger by creating a `simplelogger.properties` file. Uncomment and set properties to customize logging levels, date/time display, and more. ```properties # SLF4J's SimpleLogger configuration file # Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err. # Default logging detail level for all instances of SimpleLogger. # Must be one of ("trace", "debug", "info", "warn", or "error"). # If not specified, defaults to "info". #org.slf4j.simpleLogger.defaultLogLevel=info # Logging detail level for a SimpleLogger instance named "xxxxx". # Must be one of ("trace", "debug", "info", "warn", or "error"). # If not specified, the default logging detail level is used. #org.slf4j.simpleLogger.log.xxxxx= # Set to true if you want the current date and time to be included in output messages. # Default is false, and will output the number of milliseconds elapsed since startup. #org.slf4j.simpleLogger.showDateTime=false # The date and time format to be used in the output messages. # The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. # If the format is not specified or is invalid, the default format is used. # The default format is yyyy-MM-dd HH:mm:ss:SSS Z. #org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z # Set to true if you want to output the current thread name. # Defaults to true. #org.slf4j.simpleLogger.showThreadName=true # Set to true if you want the Logger instance name to be included in output messages. # Defaults to true. #org.slf4j.simpleLogger.showLogName=true # Set to true if you want the last component of the name to be included in output messages. # Defaults to false. #org.slf4j.simpleLogger.showShortLogName=false ``` -------------------------------- ### Register Guild User Command Source: https://github.com/kordlib/kord/wiki/Interactions Registers a user command on a specific guild. This command will appear in the user context menu. ```kotlin kord.createGuildUserCommand(guildId, "show id") ``` -------------------------------- ### Enable Incoming Audio Reception Source: https://github.com/kordlib/kord/blob/main/voice/README.md Enable the reception of incoming audio packets from Discord by setting `receiveVoice = true` in the `VoiceConnectionBuilder`. This flag activates the `Streams` implementation for processing incoming audio. ```kotlin voiceChannel.connect { receiveVoice = true } ``` -------------------------------- ### Add Kord REST Dependency (Gradle Kotlin) Source: https://github.com/kordlib/kord/blob/main/rest/README.md Instructions for adding the Kord REST client dependency to a Kotlin project using Gradle. ```kotlin dependencies { implementation("dev.kord:kord-rest:{version}") } ``` -------------------------------- ### Add Kord Voice Dependency (Maven) Source: https://github.com/kordlib/kord/blob/main/voice/README.md Add the kord-voice dependency to your project using Maven. ```xml dev.kord kord-voice {version} ``` -------------------------------- ### Register Guild Chat Input Command with Choices Source: https://github.com/kordlib/kord/wiki/Interactions Registers a chat input command with predefined choices for its arguments. This limits user input to a specific set of values. ```kotlin val kord = Kord(System.getenv("TOKEN")) kord.createGuildChatInputCommand( Snowflake(556525343595298817), "sum", "A slash command that sums two numbers" ) { integer("first_number", "The first operand") { required = true for(i in 0L..9L) { choice("$i", i) } } integer("second_number", "The second operand") { required = true for(i in 0L..9L) { choice("$i", i) } } } ``` -------------------------------- ### Gradle Groovy Dependencies Source: https://github.com/kordlib/kord/blob/main/README.md Add Kord core library to your project using Gradle with Groovy DSL. Ensure you have mavenCentral and snapshots.kord.dev repositories configured. ```groovy repositories { mavenCentral() maven { url "https://snapshots.kord.dev/" } } dependencies { implementation("dev.kord:kord-core:{version}") } ``` -------------------------------- ### Listen to Guild Chat Input Interaction Source: https://github.com/kordlib/kord/wiki/Interactions Handles interactions for a guild-specific chat input command. It defers the response, retrieves arguments, and edits the response with the calculated sum. ```kotlin kord.on { val response = interaction.deferPublicResponse() val command = interaction.command val first = command.integers["first_number"]!! // it's required so it's never null val second = command.integers["second_number"]!! response.edit.respond { content = "$first + $second = ${first + second}" } } ``` -------------------------------- ### Maven Kord Snapshot Repository Source: https://github.com/kordlib/kord/blob/main/README.md Configure your Maven project to use the Kord snapshot repository. This is necessary for fetching snapshot versions of the library. ```xml snapshots-repo https://snapshots.kord.dev false true ``` -------------------------------- ### Maven Dependency Source: https://github.com/kordlib/kord/blob/main/gateway/README.md Include the kord-gateway-jvm artifact in your Maven project. ```xml dev.kord kord-gateway-jvm {version} ``` -------------------------------- ### Gradle Kotlin Dependencies Source: https://github.com/kordlib/kord/blob/main/README.md Add Kord core library to your project using Gradle with Kotlin DSL. Ensure you have mavenCentral and snapshots.kord.dev repositories configured. ```kotlin repositories { mavenCentral() maven("https://snapshots.kord.dev") } dependencies { implementation("dev.kord:kord-core:{version}") } ``` -------------------------------- ### Register Guild Chat Input Command Source: https://github.com/kordlib/kord/wiki/Interactions Registers a chat input command on a specific guild. Use this for guild-specific features or testing. ```kotlin val kord = Kord(System.getenv("TOKEN")) kord.createGuildChatInputCommand( Snowflake(556525343595298817), "sum", "A slash command that sums two numbers" ) { integer("first_number", "The first operand") { required = true } integer("second_number", "The second operand") { required = true } } ``` -------------------------------- ### Listen to Guild User Command Interaction Source: https://github.com/kordlib/kord/wiki/Interactions Handles interactions for a guild user command. It defers the response and edits it with the ID of the target user. ```kotlin kord.on { val response = interaction.deferPublicResponse() val user = interaction.target response.edit.respond { content = "${user.id}" } } ``` -------------------------------- ### Register Guild Message Command Source: https://github.com/kordlib/kord/wiki/Interactions Registers a message command on a specific guild. This command will appear in the message context menu. ```kotlin kord.createGuildMessageCommand(guildId, "show id") ``` -------------------------------- ### Process Incoming Audio Frames Source: https://github.com/kordlib/kord/blob/main/voice/README.md Access and process incoming audio frames from the `connection.streams.incomingAudioFrames` flow. This allows you to handle audio data received from Discord. ```kotlin val connection = voiceChannel.connect { receiveVoice = true } // processIncomingAudio is anything you want to do with the flow of `AudioFrame`s in a `Stream`. processIncomingAudio(connection.streams.incomingAudioFrames) ``` -------------------------------- ### Configure Non-Privileged Gateway Intents in Kord Source: https://github.com/kordlib/kord/wiki/Intents Set specific non-privileged intents when creating a new Kord instance. This allows you to control the events your bot receives. ```kotlin Kord(token){ intents = Intents(Intent.Guilds, Intent.DirectMessages, Intent.GuildMessages) } ``` -------------------------------- ### Gradle Kotlin Dependency Source: https://github.com/kordlib/kord/blob/main/gateway/README.md Add the kord-gateway dependency to your Kotlin project using Gradle. ```kotlin dependencies { implementation("dev.kord:kord-gateway:{version}") } ``` -------------------------------- ### Add Kord Voice Dependency (Gradle Kotlin) Source: https://github.com/kordlib/kord/blob/main/voice/README.md Add the kord-voice dependency to your project using Gradle with Kotlin DSL. ```kotlin dependencies { implementation("dev.kord:kord-voice:{version}") } ``` -------------------------------- ### Listen to Guild Message Command Interaction Source: https://github.com/kordlib/kord/wiki/Interactions Handles interactions for a guild message command. It defers the response and edits it with the ID of the target message. ```kotlin kord.on { val response = interaction.deferPublicResponse() val message = interaction.target response.edit.respond { content = "${message.id}" } } ``` -------------------------------- ### Gradle Kotlin Dependency for Kord Source: https://github.com/kordlib/kord/blob/main/core/README.md Add this dependency to your Kotlin project's build.gradle file to include Kord Core. ```gradle dependencies { implementation("dev.kord:kord-core:{version}") } ``` -------------------------------- ### Maven Dependency for Kord Source: https://github.com/kordlib/kord/blob/main/core/README.md Include this dependency in your Maven project's pom.xml to use Kord Core. ```xml dev.kord kord-core-jvm {version} ``` -------------------------------- ### Defer Public Interaction Source: https://github.com/kordlib/kord/wiki/Interactions Deferring an interaction publicly tells Discord that a response will be provided. This must be done within 3 seconds of receiving the interaction. ```kotlin kord.on { val response = interaction.deferPublicResponse() //... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.