Refine code

This commit is contained in:
kraftwerk28 2021-06-29 19:04:23 +03:00
parent 41fbe85f7f
commit 399c43480f
2 changed files with 42 additions and 43 deletions

View File

@ -1,12 +1,7 @@
package org.kraftwerk28.spigot_tg_bridge package org.kraftwerk28.spigot_tg_bridge
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.OkHttpClient
import com.google.gson.annotations.SerializedName as Name import com.google.gson.annotations.SerializedName as Name
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.* import retrofit2.http.*
import java.time.Duration
import retrofit2.Retrofit
interface TgApiService { interface TgApiService {
data class TgResponse<T>(val ok: Boolean, val result: T?, val description: String?) data class TgResponse<T>(val ok: Boolean, val result: T?, val description: String?)
@ -74,23 +69,4 @@ interface TgApiService {
suspend fun setMyCommands( suspend fun setMyCommands(
@Body commands: SetMyCommands, @Body commands: SetMyCommands,
): TgResponse<Boolean> ): TgResponse<Boolean>
companion object {
fun create(token: String): TgApiService {
val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.NONE;
}
val client = OkHttpClient
.Builder()
.addInterceptor(interceptor)
.readTimeout(Duration.ZERO)
.build();
val r = Retrofit.Builder()
.baseUrl("https://api.telegram.org/bot$token/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
return r.create(TgApiService::class.java)
}
}
} }

View File

@ -3,6 +3,11 @@ package org.kraftwerk28.spigot_tg_bridge
import org.kraftwerk28.spigot_tg_bridge.Constants as C import org.kraftwerk28.spigot_tg_bridge.Constants as C
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.channels.* import kotlinx.coroutines.channels.*
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.time.Duration
class TgBot( class TgBot(
private val plugin: Plugin, private val plugin: Plugin,
@ -10,14 +15,15 @@ class TgBot(
private val pollTimeout: Int = 30, private val pollTimeout: Int = 30,
) { ) {
private val api: TgApiService private val api: TgApiService
val updateChan = Channel<TgApiService.Update>() private val client: OkHttpClient
val scope = CoroutineScope(Dispatchers.Default) private val updateChan = Channel<TgApiService.Update>()
val pollJob: Job private val scope = CoroutineScope(Dispatchers.Default)
val handlerJob: Job private val pollJob: Job
var currentOffset: Long = -1 private val handlerJob: Job
var me: TgApiService.User private var currentOffset: Long = -1
var commandRegex: Regex private var me: TgApiService.User
val commandMap = config.commands.run { private var commandRegex: Regex
private val commandMap = config.commands.run {
mapOf( mapOf(
online to ::onlineHandler, online to ::onlineHandler,
time to ::timeHandler, time to ::timeHandler,
@ -26,14 +32,28 @@ class TgBot(
} }
init { init {
api = TgApiService.create(config.botToken) val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.NONE;
}
client = OkHttpClient
.Builder()
.addInterceptor(interceptor)
.readTimeout(Duration.ZERO)
.build();
api = Retrofit.Builder()
.baseUrl("https://api.telegram.org/bot${config.botToken}/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TgApiService::class.java)
runBlocking { runBlocking {
me = api.getMe().result!! me = api.getMe().result!!
// I don't put optional @username in regex since bot is // I intentionally don't put optional @username in regex
// only used in group chats // since bot is only used in group chats
commandRegex = """^\/(\w+)(?:@${me.username})$""".toRegex() commandRegex = """^\/(\w+)(?:@${me.username})$""".toRegex()
val commands = config.commands.run { listOf(time, online, chatID) } val commands = config.commands.run { listOf(time, online, chatID) }
.zip(C.COMMAND_DESC.run { .zip(C.COMMAND_DESC.run {
listOf(timeDesc, onlineDesc, chatIDDesc) listOf(timeDesc, onlineDesc, chatIDDesc)
@ -41,8 +61,10 @@ class TgBot(
.map { TgApiService.BotCommand(it.first!!, it.second) } .map { TgApiService.BotCommand(it.first!!, it.second) }
.let { TgApiService.SetMyCommands(it) } .let { TgApiService.SetMyCommands(it) }
api.deleteWebhook(true)
api.setMyCommands(commands) api.setMyCommands(commands)
} }
pollJob = scope.launch { pollJob = scope.launch {
try { try {
while (true) { while (true) {
@ -54,6 +76,7 @@ class TgBot(
} }
} catch (e: CancellationException) {} } catch (e: CancellationException) {}
} }
handlerJob = scope.launch { handlerJob = scope.launch {
try { try {
while (true) { while (true) {
@ -63,7 +86,7 @@ class TgBot(
} }
} }
suspend fun pollUpdates() { private suspend fun pollUpdates() {
val updatesResponse = api val updatesResponse = api
.getUpdates(offset = currentOffset, timeout = pollTimeout) .getUpdates(offset = currentOffset, timeout = pollTimeout)
updatesResponse.result?.let { updates -> updatesResponse.result?.let { updates ->
@ -74,7 +97,7 @@ class TgBot(
} }
} }
suspend fun handleUpdate() { private suspend fun handleUpdate() {
val update = updateChan.receive() val update = updateChan.receive()
update.message?.text?.let { update.message?.text?.let {
println("Text: $it") println("Text: $it")
@ -85,6 +108,10 @@ class TgBot(
} }
fun stop() { fun stop() {
client.run {
dispatcher.executorService.shutdown()
connectionPool.evictAll()
}
runBlocking { runBlocking {
pollJob.cancelAndJoin() pollJob.cancelAndJoin()
handlerJob.cancelAndJoin() handlerJob.cancelAndJoin()
@ -96,7 +123,6 @@ class TgBot(
if (!config.allowedChats.contains(msg.chat.id)) { if (!config.allowedChats.contains(msg.chat.id)) {
return return
} }
if (plugin.server.worlds.isEmpty()) { if (plugin.server.worlds.isEmpty()) {
api.sendMessage( api.sendMessage(
msg.chat.id, msg.chat.id,
@ -105,7 +131,6 @@ class TgBot(
) )
return return
} }
// TODO: handle multiple worlds // TODO: handle multiple worlds
val time = plugin.server.worlds.first().time val time = plugin.server.worlds.first().time
val text = C.TIMES_OF_DAY.run { val text = C.TIMES_OF_DAY.run {
@ -117,7 +142,6 @@ class TgBot(
else -> "" else -> ""
} }
} + " ($time)" } + " ($time)"
api.sendMessage(msg.chat.id, text, replyToMessageId = msg.messageId) api.sendMessage(msg.chat.id, text, replyToMessageId = msg.messageId)
} }
@ -126,7 +150,6 @@ class TgBot(
if (!config.allowedChats.contains(msg.chat.id)) { if (!config.allowedChats.contains(msg.chat.id)) {
return return
} }
val playerList = plugin.server.onlinePlayers val playerList = plugin.server.onlinePlayers
val playerStr = plugin.server val playerStr = plugin.server
.onlinePlayers .onlinePlayers