Refactor configuration class

Deprecate "minecraftMessageFormat" and "telegramMessageFormat" in favor of new options
This commit is contained in:
kraftwerk28 2021-07-03 19:22:13 +03:00
parent d819420811
commit 826c556ae9
8 changed files with 126 additions and 85 deletions

View File

@ -37,7 +37,7 @@ repositories {
val tgBotVersion = "6.0.4" val tgBotVersion = "6.0.4"
val retrofitVersion = "2.7.1" val retrofitVersion = "2.7.1"
val plugDir = "MinecraftServers/spigot_1.16.5/plugins/" val plugDir = "MinecraftServers/spigot_1.17/plugins/"
val homeDir = System.getProperty("user.home") val homeDir = System.getProperty("user.home")
tasks { tasks {

View File

@ -1,14 +1,14 @@
package org.kraftwerk28.spigot_tg_bridge package org.kraftwerk28.spigot_tg_bridge
import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.configuration.file.FileConfiguration
class Commands(yamlCfg: YamlConfiguration) { class Commands(cfg: FileConfiguration) {
val time: String? val time: String?
val online: String? val online: String?
val chatID: String? val chatID: String?
init { init {
yamlCfg.run { cfg.run {
time = getString("commands.time") time = getString("commands.time")
online = getString("commands.online") online = getString("commands.online")
chatID = getString("commands.chat_id") chatID = getString("commands.chat_id")

View File

@ -4,73 +4,96 @@ import org.bukkit.configuration.file.YamlConfiguration
import java.io.File import java.io.File
import org.kraftwerk28.spigot_tg_bridge.Constants as C import org.kraftwerk28.spigot_tg_bridge.Constants as C
class Configuration { class Configuration(plugin: Plugin) {
private lateinit var yamlCfg: YamlConfiguration val isEnabled: Boolean
val logFromMCtoTG: Boolean
var isEnabled: Boolean = false val telegramFormat: String
var logFromMCtoTG: Boolean = false val minecraftFormat: String
var telegramMessageFormat: String = "" val serverStartMessage: String?
var minecraftMessageFormat: String = "" val serverStopMessage: String?
var serverStartMessage: String? = null val logJoinLeave: Boolean
var serverStopMessage: String? = null val joinString: String
val leaveString: String
val logDeath: Boolean
val logPlayerAsleep: Boolean
val onlineString: String
val nobodyOnlineString: String
// Telegram bot stuff // Telegram bot stuff
var botToken: String = "" val botToken: String
var allowedChats: List<Long> = listOf() val allowedChats: List<Long>
var logFromTGtoMC: Boolean = false val logFromTGtoMC: Boolean
var allowWebhook: Boolean = false val allowWebhook: Boolean
var webhookConfig: Map<String, Any>? = null val webhookConfig: Map<String, Any>?
var logJoinLeave: Boolean = false var commands: Commands
var joinString: String? = null
var leaveString: String? = null
var logDeath: Boolean = false
var logPlayerAsleep: Boolean = false
var onlineString: String = ""
var nobodyOnlineString: String = ""
lateinit var commands: Commands init {
fun reload(plugin: Plugin) {
val cfgFile = File(plugin.dataFolder, C.configFilename); val cfgFile = File(plugin.dataFolder, C.configFilename);
if (!cfgFile.exists()) { if (!cfgFile.exists()) {
cfgFile.parentFile.mkdirs() cfgFile.parentFile.mkdirs()
plugin.saveResource(C.configFilename, false); plugin.saveDefaultConfig()
// plugin.saveResource(C.configFilename, false);
throw Exception(C.WARN.noConfigWarning) throw Exception(C.WARN.noConfigWarning)
} }
yamlCfg = YamlConfiguration() val pluginConfig = plugin.getConfig()
yamlCfg.load(cfgFile) pluginConfig.getString("minecraftMessageFormat")?.let {
plugin.logger.warning("""
yamlCfg.run { Config option "minecraftMessageFormat" is deprecated.
isEnabled = getBoolean("enable", true) Moved it to new key "telegramFormat"
logFromTGtoMC = getBoolean("logFromTGtoMC", true) """.trimIndent().replace('\n', ' '))
logFromMCtoTG = getBoolean("logFromMCtoTG", true) pluginConfig.set("telegramFormat", it)
telegramMessageFormat = getString("telegramMessageFormat", "<%username%>: %message%")!! pluginConfig.set("minecraftMessageFormat", null)
minecraftMessageFormat = getString("minecraftMessageFormat", "<i>%username%</i>: %message%")!! plugin.saveConfig()
allowedChats = getLongList("chats") }
serverStartMessage = getString("serverStartMessage") pluginConfig.getString("telegramMessageFormat")?.let {
serverStopMessage = getString("serverStopMessage") plugin.logger.warning("""
botToken = getString("botToken") ?: throw Exception(C.WARN.noToken) Config option "telegramMessageFormat" is deprecated.
allowWebhook = getBoolean("useWebhook", false) Moved it to new key "minecraftFormat"
val whCfg = get("webhookConfig") """.trimIndent().replace('\n', ' '))
if (whCfg is Map<*, *>) { pluginConfig.set("minecraftFormat", it)
@Suppress("UNCHECKED_CAST") pluginConfig.set("telegramMessageFormat", null)
webhookConfig = whCfg as Map<String, Any>? plugin.saveConfig()
}
logJoinLeave = getBoolean("logJoinLeave", false)
onlineString = getString("strings.online", "Online")!!
nobodyOnlineString = getString("strings.nobodyOnline", "Nobody online")!!
joinString = getString("strings.joined", "<i>%username%</i> joined.")
leaveString = getString("strings.left", "<i>%username%</i> left.")
logDeath = getBoolean("logPlayerDeath", false)
logPlayerAsleep = getBoolean("logPlayerAsleep", false)
} }
commands = Commands(yamlCfg) pluginConfig.run {
isEnabled = getBoolean("enable", true)
serverStartMessage = getString("serverStartMessage")
serverStopMessage = getString("serverStopMessage")
logFromTGtoMC = getBoolean("logFromTGtoMC", true)
logFromMCtoTG = getBoolean("logFromMCtoTG", true)
telegramFormat = getString(
"telegramFormat",
"<i>%username%</i>: %message%",
)!!
minecraftFormat = getString(
"minecraftFormat",
"<%username%>: %message%",
)!!
// isEnabled = getBoolean("enable", true)
allowedChats = getLongList("chats")
botToken = getString("botToken") ?: throw Exception(C.WARN.noToken)
allowWebhook = getBoolean("useWebhook", false)
@Suppress("unchecked_cast")
webhookConfig = get("webhookConfig") as Map<String, Any>?
logJoinLeave = getBoolean("logJoinLeave", false)
onlineString = getString("strings.online", "Online")!!
nobodyOnlineString = getString(
"strings.nobodyOnline",
"Nobody online",
)!!
joinString = getString(
"strings.joined",
"<i>%username%</i> joined.",
)!!
leaveString = getString("strings.left", "<i>%username%</i> left.")!!
logDeath = getBoolean("logPlayerDeath", false)
logPlayerAsleep = getBoolean("logPlayerAsleep", false)
commands = Commands(this)
}
} }
fun load(plugin: Plugin) = reload(plugin) companion object {
}
} }

View File

@ -19,6 +19,7 @@ object Constants {
} }
const val USERNAME_PLACEHOLDER = "%username%" const val USERNAME_PLACEHOLDER = "%username%"
const val MESSAGE_TEXT_PLACEHOLDER = "%message%" const val MESSAGE_TEXT_PLACEHOLDER = "%message%"
const val CHAT_TITLE_PLACEHOLDER = "%chat%"
object COMMANDS { object COMMANDS {
const val PLUGIN_RELOAD = "tgbridge_reload" const val PLUGIN_RELOAD = "tgbridge_reload"
} }

View File

@ -25,17 +25,17 @@ class EventHandler(
@EventHandler @EventHandler
fun onPlayerJoin(event: PlayerJoinEvent) { fun onPlayerJoin(event: PlayerJoinEvent) {
if (!config.logJoinLeave || config.joinString == null) return if (!config.logJoinLeave) return
val username = event.player.displayName.fullEscape() val username = event.player.displayName.fullEscape()
val text = config.joinString!!.replace("%username%", username) val text = config.joinString.replace("%username%", username)
tgBot.sendMessageToTelegram(text) tgBot.sendMessageToTelegram(text)
} }
@EventHandler @EventHandler
fun onPlayerLeave(event: PlayerQuitEvent) { fun onPlayerLeave(event: PlayerQuitEvent) {
if (!config.logJoinLeave || config.leaveString == null) return if (!config.logJoinLeave) return
val username = event.player.displayName.fullEscape() val username = event.player.displayName.fullEscape()
val text = config.leaveString!!.replace("%username%", username) val text = config.leaveString.replace("%username%", username)
tgBot.sendMessageToTelegram(text) tgBot.sendMessageToTelegram(text)
} }
@ -52,7 +52,8 @@ class EventHandler(
@EventHandler @EventHandler
fun onPlayerAsleep(event: PlayerBedEnterEvent) { fun onPlayerAsleep(event: PlayerBedEnterEvent) {
if (!config.logPlayerAsleep) return if (!config.logPlayerAsleep) return
if (event.bedEnterResult != PlayerBedEnterEvent.BedEnterResult.OK) return if (event.bedEnterResult != PlayerBedEnterEvent.BedEnterResult.OK)
return
val text = "<i>${event.player.displayName}</i> fell asleep." val text = "<i>${event.player.displayName}</i> fell asleep."
tgBot.sendMessageToTelegram(text) tgBot.sendMessageToTelegram(text)
} }

View File

@ -8,11 +8,11 @@ import org.kraftwerk28.spigot_tg_bridge.Constants as C
class Plugin : JavaPlugin() { class Plugin : JavaPlugin() {
var tgBot: TgBot? = null var tgBot: TgBot? = null
val config: Configuration = Configuration() lateinit var config: Configuration
override fun onEnable() { override fun onEnable() {
try { try {
config.load(this) config = Configuration(this)
} catch (e: Exception) { } catch (e: Exception) {
logger.warning(e.message) logger.warning(e.message)
return return
@ -42,26 +42,36 @@ class Plugin : JavaPlugin() {
} }
override fun onDisable() { override fun onDisable() {
if (!config.isEnabled) return if (!config.isEnabled)
return
config.serverStopMessage?.let { config.serverStopMessage?.let {
tgBot?.sendMessageToTelegram(it) tgBot?.sendMessageToTelegram(it)
} }
logger.info("Plugin stopped.") logger.info("Plugin stopped.")
} }
fun sendMessageToMinecraft(text: String, username: String? = null) = fun sendMessageToMinecraft(
config.telegramMessageFormat text: String,
username: String? = null,
chatTitle: String? = null,
) =
config.minecraftFormat
.replace(C.MESSAGE_TEXT_PLACEHOLDER, text.escapeEmoji()) .replace(C.MESSAGE_TEXT_PLACEHOLDER, text.escapeEmoji())
.run { .run {
username?.let { username -> username?.let {
replace(C.USERNAME_PLACEHOLDER, username.escapeEmoji()) replace(C.USERNAME_PLACEHOLDER, it.escapeEmoji())
} ?: this
}
.run {
chatTitle?.let {
replace(C.CHAT_TITLE_PLACEHOLDER, it)
} ?: this } ?: this
} }
.also { server.broadcastMessage(it) } .also { server.broadcastMessage(it) }
fun reload() { fun reload() {
logger.info(C.INFO.reloading) logger.info(C.INFO.reloading)
config.reload(this) config = Configuration(this)
loadBot() loadBot()
logger.info(C.INFO.reloadComplete) logger.info(C.INFO.reloadComplete)
} }

View File

@ -176,7 +176,9 @@ class TgBot(
} }
fun sendMessageToTelegram(text: String, username: String? = null) { fun sendMessageToTelegram(text: String, username: String? = null) {
val messageText = username?.let { formatMsgFromMinecraft(it, text) } ?: text val messageText = username?.let {
formatMsgFromMinecraft(it, text)
} ?: text
config.allowedChats.forEach { chatId -> config.allowedChats.forEach { chatId ->
scope.launch { scope.launch {
api.sendMessage(chatId, messageText) api.sendMessage(chatId, messageText)
@ -188,14 +190,18 @@ class TgBot(
val msg = update.message!! val msg = update.message!!
if (!config.logFromTGtoMC || msg.from == null) if (!config.logFromTGtoMC || msg.from == null)
return return
plugin.sendMessageToMinecraft(msg.text!!, msg.from.rawUserMention()) plugin.sendMessageToMinecraft(
text = msg.text!!,
username = msg.from.rawUserMention(),
chatTitle = msg.chat.title,
)
} }
private fun formatMsgFromMinecraft( private fun formatMsgFromMinecraft(
username: String, username: String,
text: String text: String
): String = ): String =
config.minecraftMessageFormat config.telegramFormat
.replace("%username%", username.fullEscape()) .replace(C.USERNAME_PLACEHOLDER, username.fullEscape())
.replace("%message%", text.escapeHtml()) .replace(C.MESSAGE_TEXT_PLACEHOLDER, text.escapeHtml())
} }

View File

@ -2,20 +2,20 @@ enable: true
botToken: abcdef123456789 botToken: abcdef123456789
chats: chats:
- -1234567890123 - -1234567890123
serverStartMessage: 'Server started.' serverStartMessage: "Server started."
serverStopMessage: 'Server stopped.' serverStopMessage: "Server stopped."
logJoinLeave: true logJoinLeave: true
logFromMCtoTG: true logFromMCtoTG: true
logFromTGtoMC: true logFromTGtoMC: true
logPlayerDeath: false logPlayerDeath: false
logPlayerAsleep: false logPlayerAsleep: false
telegramMessageFormat: '<%username%>: %message%' minecraftFormat: "<%username%>: %message%"
minecraftMessageFormat: '<i>%username%</i>: %message%' telegramFormat: "<i>%username%</i>: %message%"
strings: strings:
online: '<b>Online</b>' online: "<b>Online</b>"
nobodyOnline: '<b>Nobody online...</b>' nobodyOnline: "<b>Nobody online...</b>"
joined: '<i>%username%</i> joined.' joined: "<i>%username%</i> joined."
left: '<i>%username%</i> left.' left: "<i>%username%</i> left."
commands: commands:
time: 'time' time: 'time'
online: 'online' online: 'online'