ottobot-v3/src/main/kotlin/nl/voidcorp/ottobot/commands/fun/XKCDComicCommand.kt

62 lines
2.0 KiB
Kotlin

package nl.voidcorp.ottobot.commands.`fun`
import io.ktor.client.HttpClient
import io.ktor.client.engine.apache.Apache
import io.ktor.client.features.json.JacksonSerializer
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import net.dv8tion.jda.api.EmbedBuilder
import nl.voidcorp.ottobot.command.Command
import nl.voidcorp.ottobot.command.CommandGroup
import nl.voidcorp.ottobot.command.CommandMessage
import nl.voidcorp.ottobot.command.CommandResult
import nl.voidcorp.ottobot.external.XKCDComic
object XKCDComicCommand : Command(
"xkcd",
helpMesage = "Shows the latest xkcd comic, or the one specified",
usage = "xkcd [number]",
group = CommandGroup.FUN,
allowAnywhere = true
) {
val client = HttpClient(Apache) {
install(JsonFeature) {
serializer = JacksonSerializer()
}
}
override fun handle(event: CommandMessage): CommandResult {
val comic: XKCDComic? = if (event.params.drop(1).isEmpty()) {
runBlocking {
client.get("https://xkcd.com/info.0.json")
}
} else {
val id = event.params.drop(1).first()
if (!id.matches("\\d+".toRegex())) {
event.reply("$id is not a number...")
return CommandResult.SUCCESS
}
try {
runBlocking {
client.get("https://xkcd.com/$id/info.0.json")
}
} catch (e: Exception) {
event.reply("It seems I can't find that comic?")
return CommandResult.SUCCESS
}
}
if (comic != null) {
val builder = EmbedBuilder().setTitle(comic.title, "https://xkcd.com/${comic.num}")
.setImage(comic.img).setFooter(comic.alt).build()
event.reply(builder)
} else {
return CommandResult.ERROR
}
return CommandResult.SUCCESS
}
}