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 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")
tasks {

View File

@ -1,14 +1,14 @@
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 online: String?
val chatID: String?
init {
yamlCfg.run {
cfg.run {
time = getString("commands.time")
online = getString("commands.online")
chatID = getString("commands.chat_id")

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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