1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package com.chameth.hexbot
-
- import com.chameth.hexbot.modules.Hue
- import com.chameth.hexbot.modules.Module
- import com.dmdirc.ktirc.IrcClient
- import com.dmdirc.ktirc.events.IrcEvent
- import com.dmdirc.ktirc.events.ServerDisconnected
- import com.dmdirc.ktirc.events.ServerReady
- import com.dmdirc.ktirc.messages.sendJoin
- import com.ufoscout.properlty.Properlty
- import com.ufoscout.properlty.reader.EnvironmentVariablesReader
- import com.ufoscout.properlty.reader.PropertiesResourceReader
- import kotlinx.coroutines.Dispatchers
- import kotlinx.coroutines.GlobalScope
- import kotlinx.coroutines.launch
- import kotlinx.coroutines.runBlocking
- import org.jetbrains.exposed.sql.Database
- import java.util.logging.Level
- import java.util.logging.LogManager
-
- class HexBot(private val config: Properlty, availableModules: List<Module>) {
-
- private var client: IrcClient? = null
-
- private val channels
- get() = config.getArray("irc.channels")
-
- private val modules = availableModules.filter { it.init(config) }
-
- fun connect() {
- with (IrcClient {
- server {
- host = config["irc.server"].orElseThrow { IllegalStateException("irc.server not configured") }
- port = config.getInt("irc.port").orElseThrow { IllegalStateException("irc.port not configured") }
- useTls = config.getBoolean("irc.tls", false)
- password = config["irc.password", null]
- }
-
- profile {
- nickname = config["irc.nickname", "Hex"]
- realName = config["irc.realname", "+++Divide By Cucumber Error+++"]
- username = config["irc.ident", "hexbot"]
- }
-
- sasl {
- username = config["irc.nickserv.user", null]
- password = config["irc.nickserv.password", null]
- }
- }) {
- client = this
- onEvent {
- handleEvent(this, it)
- }
- connect()
- }
- }
-
- private fun handleEvent(client: IrcClient, event: IrcEvent) {
- when (event) {
- is ServerReady -> joinChannels()
- is ServerDisconnected -> client.connect()
- }
- for (module in modules) {
- GlobalScope.launch(Dispatchers.IO) {
- module.processEvent(client, event)
- }
- }
- }
-
- private fun joinChannels() {
- channels.forEach { client?.sendJoin(it) }
- }
-
- }
-
- internal fun loadConfig(): Properlty = Properlty
- .builder()
- .caseSensitive(false)
- .add(PropertiesResourceReader.build("./hexbot.properties").ignoreNotFound(true))
- .add(EnvironmentVariablesReader().replace("HEXBOT_", "").replace("_", "."))
- .build()
-
- fun main() = runBlocking<Unit> {
- val rootLogger = LogManager.getLogManager().getLogger("")
- rootLogger.level = Level.FINEST
- for (h in rootLogger.handlers) {
- h.level = Level.FINEST
- }
-
- Database.connect("jdbc:sqlite:data.db", "org.sqlite.JDBC")
-
- val bot = HexBot(loadConfig(), listOf(Hue()))
- bot.connect()
- readLine()
- }
|