Skip to content

Kotlin extensions

In addition to what JDA-KTX offers, Kotlin users have access to top-level functions and extensions in various categories:

JDA

REST actions

awaitUnit - Awaits completion and returns Unit, particularly useful to reply + return
fun onSlashCommand(event: GuildSlashEvent, inputUser: InputUser)
    val member = inputUser.member
        ?: return event.reply_("The user needs to be a member of this server!", ephemeral = true).awaitUnit()
}
awaitOrNullOn - Awaits completion, returns null if the action failed with the expected error response
fun onSlashBanInfo(event: GuildSlashEvent, user: User)
    val ban = event.guild.retrieveBan(user).awaitOrNullOn(ErrorResponse.UNKNOWN_BAN)
        ?: return event.reply_("This user is not banned", ephemeral = true).awaitUnit()
}
awaitCatching - Awaits completion and returns a Result with the wrapped value/failure
fun onSlashBanInfo(event: GuildSlashEvent, user: User)
    val ban = event.guild.retrieveBan(user).awaitCatching()
        .onErrorResponse(ErrorResponse.UNKNOWN_BAN) {
            return event.reply_("This user is not banned", ephemeral = true).awaitUnit()
        }
        .getOrThrow()
}

Error response handling

runIgnoringResponse - Runs the block and ignores the following error responses, throws other exceptions
runIgnoringResponse(ErrorResponse.CANNOT_SEND_TO_USER) {
    channel.sendMessage(msg).await()
}
runIgnoringResponseOrNull - Runs the block and returns null on the following error responses, throws other exceptions
suspend fun Guild.retrieveBanOrNull(user: UserSnowflake): Ban? = runIgnoringResponseOrNull(ErrorResponse.UNKNOWN_BAN) {
    retrieveBan(user).await() // Can also use awaitOrNullOn, removing runIgnoringResponseOrNull
}

Messages

Entity retrieval

Those check the cache before doing a request.

Misc

suppressContentWarning - Runs the block and suppresses warnings emitted by JDA when reading message content, this is mostly useful in message context commands
val contentRaw = suppressContentWarning { message.contentRaw }
  • getMissingPermissions - Gets the missing permissions from the required permissions, for the given entity, in the specified channel

Any method accepting a Java Duration should also have an extension using Kotlin's Duration

Resolvers

enumResolver - Creates a parameter resolver which transforms arguments into an enum entry, compatible with most handlers
enum class MyEnum {
    FIRST,
    SECOND,
    THIRD
}

@BConfiguration
class MyEnumResolverProvider {
    // Creates an enum resolver for all values
    // you can also customize what values can be used, per-guild,
    // and also change how they are displayed
    @Resolver
    fun myEnumResolver() = enumResolver<MyEnum>()
}
resolverFactory - Creates a factory for parameter resolvers, useful to avoid the boilerplate of using TypedParameterResolverFactory

See example on the docs

I/O

readResource - Gets an InputStream of a resource from the classpath
readResource("/file.txt").use { contentStream ->
    // ...
}
readResourceAsString - Gets a resource from the classpath as a String
val content = readResourceAsString("/file.txt")
withResource - Uses an InputStream of a resource from the classpath
withResource("/file.txt") { contentStream ->
    // ...
}

Coroutines

namedDefaultScope - Creates a CoroutineScope with a thread name and a fixed thread pool
// 1 thread named "[feature] timeout"
// You can also configure other CoroutineScope characteristics
private val timeoutScope = namedDefaultScope("[feature] timeout", corePoolSize = 1)

// ...

timeoutScope.launch {
    // Async task
}

Logging

KotlinLogging.loggerOf - Creates a logger targeting the specified class
private val logger = KotlinLogging.loggerOf<MyService>()

@BService
class MyServiceImpl : MyService {
    // ...
}

Collections

  • enumSetOf - Creates an enum set of the provided type
  • enumSetOfAll - Creates an enum set of the provided type, with all the entries in it
  • enumMapOf - Creates a map with an enum key
  • toImmutableList - Creates an immutable copy of the list
  • toImmutableSet - Creates an immutable copy of the set
  • toImmutableMap - Creates an immutable copy of the map
  • containsAny - Checks if the collection contains any of the provided elements