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¶
RestAction<*>.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()
}
RestAction<R>.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()
}
RestAction<R>.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¶
RestResult<T>.onErrorResponse
— Runs code if the specified error response was returned, seeawaitCatching
aboveRestResult<T>.ignore
— Ignores and clears the specified error responsesRestResult<T>.handle
— Replaced the specified error response with the calculated value
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 (unless you useawait
)
Entity retrieval¶
Those check the cache before doing a request.
Members¶
Guild.retrieveMemberOrNull
— Returns null if the member does not existGuild.retrieveMemberByIdOrNull
— Returns null if the member does not exist
Users¶
JDA.retrieveUserOrNull
— Returns null if the user does not existJDA.retrieveUserByIdOrNull
— Returns null if the user does not exist
Stickers¶
JDA.retrieveStickerOrNull
— Returns null if the sticker does not exist
Entitlements¶
JDA.retrieveEntitlementByIdOrNull
— Returns null if the entitlement does not exist
Webhooks¶
JDA.retrieveWebhookByIdOrNull
— Returns null if the webhook does not exist
Threads (unofficial support)¶
Guild.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 keyList<T>.toImmutableList
— Creates an immutable copy of the listSet<T>.toImmutableSet
— Creates an immutable copy of the setMap<K, V>.toImmutableMap
— Creates an immutable copy of the mapIterable<T>.containsAny
— Checks if the collection contains any of the provided elements
Emojis¶
Emoji.asUnicodeEmoji
— Converts a JEmoji'sEmoji
into a JDAUnicodeEmoji
lazyUnicodeEmoji
— Lazily fetches the Unicode from the given shortcode