PlaguBot/bot/src/main/kotlin/dev/inmo/plagubot/App.kt

52 lines
1.7 KiB
Kotlin
Raw Normal View History

2020-11-08 13:23:01 +00:00
package dev.inmo.plagubot
2020-11-08 13:04:44 +00:00
2020-11-11 17:05:21 +00:00
import dev.inmo.micro_utils.coroutines.safelyWithoutExceptions
2020-11-12 05:52:09 +00:00
import dev.inmo.plagubot.config.Config
import dev.inmo.plagubot.config.configSerialFormat
2021-01-10 09:04:45 +00:00
import dev.inmo.tgbotapi.bot.Ktor.telegramBot
2020-11-11 17:05:21 +00:00
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
2021-01-10 09:04:45 +00:00
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.longPolling
2020-11-11 17:05:21 +00:00
import dev.inmo.tgbotapi.types.botCommandsLimit
import kotlinx.coroutines.*
2020-11-12 05:52:09 +00:00
import kotlinx.serialization.InternalSerializationApi
2020-11-11 17:05:21 +00:00
import java.io.File
2020-11-08 13:04:44 +00:00
2020-11-13 05:25:04 +00:00
suspend inline fun initPlaguBot(
config: Config,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default)
) {
2020-11-11 17:05:21 +00:00
val bot = telegramBot(config.botToken)
2021-01-10 09:04:45 +00:00
bot.longPolling(scope = scope) {
2020-11-11 17:05:21 +00:00
val commands = config.plugins.flatMap {
it.invoke(bot, config.database.database, this, scope)
it.getCommands()
}.let {
val futureUnavailable = it.drop(botCommandsLimit.last)
if (futureUnavailable.isNotEmpty()) {
println("Next commands are out of range in setting command request and will be unavailable from autocompleting: ${futureUnavailable}")
}
it.take(botCommandsLimit.last)
}
scope.launch {
safelyWithoutExceptions {
bot.setMyCommands(commands)
}
}
}
2020-11-13 05:25:04 +00:00
}
2020-11-12 06:20:18 +00:00
2020-11-13 05:25:04 +00:00
/**
* This method by default expects one argument in [args] field: path to config
*/
@InternalSerializationApi
suspend fun main(args: Array<String>) {
val (configPath) = args
val file = File(configPath)
val config = configSerialFormat.decodeFromString(Config.serializer(), file.readText())
val scope = CoroutineScope(Dispatchers.Default)
initPlaguBot(config, scope)
2020-11-12 06:20:18 +00:00
scope.coroutineContext.job.join()
2020-11-08 13:04:44 +00:00
}