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¶
onErrorResponse
- SeeawaitCatching
Result<Unit>.ignore
- Ignores and clears the specified error responsesResult<T>.handle
- Supplies a value when the specified error response is caught
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¶
MessageCreateData.toEditData
- Does what it says, the edit data will replace the content of the entire message-
MessageEditData.toCreateData
- Do I need to say anything? -
MessageCreateData.send
- Sends the message, this is useful for chaining MessageEditData.edit
- Edits with that message, this is useful for chaining-
InteractionHook.replaceWith
- Replaces this interaction's message with the following content -
RestAction<R>.deleteDelayed
- Deletes the message after the delay, the rest action itself is delayed, not the code execution
Entity retrieval¶
Those check the cache before doing a request.
Guild.retrieveMemberOrNull
- Returns null if the member does not existJDA.retrieveUserOrNull
- Returns null if the user does not existGuild.retrieveThreadChannelById
- Retrieves a thread by ID, from any thread container, archived or not.Guild.retrieveThreadChannelOrNull
- Same but returns null if it does not exist, if the bot doesn't have access to it, or if the channel isn't a thread.
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 typeenumSetOfAll
- Creates an enum set of the provided type, with all the entries in itenumMapOf
- Creates a map with an enum keytoImmutableList
- Creates an immutable copy of the listtoImmutableSet
- Creates an immutable copy of the settoImmutableMap
- Creates an immutable copy of the mapcontainsAny
- Checks if the collection contains any of the provided elements