YeetBot/src/main/kotlin/nl/voidcorp/yeetbot/Yeet.kt

110 lines
3.1 KiB
Kotlin

package nl.voidcorp.yeetbot
import com.github.salomonbrys.kotson.fromJson
import io.javalin.Javalin
import io.javalin.json.FromJsonMapper
import io.javalin.json.JavalinJson
import io.javalin.json.ToJsonMapper
import net.dv8tion.jda.core.AccountType
import net.dv8tion.jda.core.JDABuilder
import net.dv8tion.jda.core.OnlineStatus
import net.dv8tion.jda.core.entities.Game
import org.apache.logging.log4j.LogManager
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.util.*
import kotlin.concurrent.fixedRateTimer
import kotlin.concurrent.schedule
lateinit var config: Config
val logger = LogManager.getLogger("YeetBot")
fun main(args: Array<String>) {
config = if (File("conf.json").exists()) {
gson.fromJson(FileReader("conf.json"))
} else {
Config()
}
val token = if (args.isEmpty()) {
throw IllegalArgumentException("missing the token string my dude!")
} else {
args[0]
}
val jda = JDABuilder(AccountType.BOT).setToken(token).build()
jda.addEventListener(MessageListener())
jda.presence.setPresence(OnlineStatus.ONLINE, Game.playing("a banjo"))
fixedRateTimer("ConfigThread", period = 1000 * 60 * 5, initialDelay = 1000 * 10) {
logger.info("Writing config!")
try {
with(FileWriter("conf.json")) {
gson.toJson(config, this)
close()
}
} catch (e: Exception) {
logger.fatal("Could not write config!", e)
}
}
fixedRateTimer("StopTimer", period = 1000) {
if (File("new").exists()) {
File("new").delete()
var tick = false
val t = fixedRateTimer("ColorTick", period = 1000) {
if (tick) {
jda.presence.setPresence(OnlineStatus.DO_NOT_DISTURB, Game.watching("a restart timer!"))
} else {
jda.presence.setPresence(OnlineStatus.IDLE, Game.watching("a restart timer!"))
}
tick = !tick
}
Timer().schedule(1000 * 30) {
t.cancel()
jda.presence.setPresence(OnlineStatus.DO_NOT_DISTURB, Game.watching("myself restart!"))
logger.info("Writing config!")
try {
with(FileWriter("conf.json")) {
gson.toJson(config, this)
close()
}
} catch (e: Exception) {
logger.fatal("Could not write config!", e)
}
Timer().schedule(1000) {
Runtime.getRuntime().exec("sudo service jservice-yeetbot restart")
}
}
}
}
JavalinJson.toJsonMapper = object : ToJsonMapper {
override fun map(obj: Any): String = obj.toJson()
}
JavalinJson.fromJsonMapper = object : FromJsonMapper {
override fun <T> map(json: String, targetClass: Class<T>): T = gson.fromJson(json, targetClass)
}
val app = Javalin.create().start(config.httpPort)
app.get("/") {
it.result("memes!")
}
app.get("/test") {
it.json(config)
}
}