add reload and langs reload, make ongoing thread warn can be before the thread register.

- change MornyLangs re-implements the methods of Translations so that it can be used like a Translations
  - changes its inner Translations implementation can be reloaded.
- MornyCoeur.dsl changes its `translations` from type Translations to MornyLangs in order to make reload works.
- add ensureCleansState to ThreadingManager and ThreadingManagerImpl to make the warn-before-register works
- cha /test implements message threads warn-before-register
This commit is contained in:
A.C.Sukazyo Eyre 2024-05-09 17:55:31 +08:00
parent aad79b9726
commit e2a1bc2e59
Signed by: Eyre_S
GPG Key ID: C17CE40291207874
7 changed files with 192 additions and 99 deletions

View File

@ -26,7 +26,7 @@ morny.command.info.sub_start.message
| (你可以随时通过 /info 重新获得这些信息) | (你可以随时通过 /info 重新获得这些信息)
morny.misc.command_test.message morny.misc.command_test.message
| <b>这只是一个 /test 测试命令。</b>测试 <i>id</i> 为 <code>1</code>。 | <b>这只是一个 /test 测试命令。</b>测试 <i>id</i> 为 <code>2</code>。
| 你可以回复一条消息来测试回复消息的功能。 | 你可以回复一条消息来测试回复消息的功能。
morny.misc.command_test.branch_normal.message morny.misc.command_test.branch_normal.message

View File

@ -15,7 +15,6 @@ import cc.sukazyo.cono.morny.util.time.WatchDog
import cc.sukazyo.cono.morny.util.GivenContext import cc.sukazyo.cono.morny.util.GivenContext
import cc.sukazyo.cono.morny.util.UseString.MString import cc.sukazyo.cono.morny.util.UseString.MString
import cc.sukazyo.cono.morny.util.UseThrowable.toLogString import cc.sukazyo.cono.morny.util.UseThrowable.toLogString
import cc.sukazyo.cono.morny.util.hytrans.Translations
import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.TelegramBot
import com.pengrad.telegrambot.request.GetMe import com.pengrad.telegrambot.request.GetMe
@ -212,10 +211,11 @@ class MornyCoeur (modules: List[MornyModule])(using val config: MornyConfig)(tes
$MornyHellos.Hello, $MornyHellos.Hello,
MornyInfoOnStart(), MornyInfoOnStart(),
$MornyManagers.SaveData,
$MornyInformation, $MornyInformation,
$MornyInformationOlds.Version, $MornyInformationOlds.Version,
$MornyInformationOlds.Runtime, $MornyInformationOlds.Runtime,
$MornyManagers.SaveData,
$MornyManagers.Reload,
$MornyManagers.Exit, $MornyManagers.Exit,
DirectMsgClear(), DirectMsgClear(),
@ -369,7 +369,7 @@ class MornyCoeur (modules: List[MornyModule])(using val config: MornyConfig)(tes
object dsl extends BotExtension { object dsl extends BotExtension {
given coeur: MornyCoeur = MornyCoeur.this given coeur: MornyCoeur = MornyCoeur.this
given account: TelegramBot = MornyCoeur.this.account given account: TelegramBot = MornyCoeur.this.account
given translations: Translations = MornyCoeur.this.lang.translations given translations: MornyLangs = MornyCoeur.this.lang
} }
def saveDataAll(): Unit = { def saveDataAll(): Unit = {
@ -377,6 +377,12 @@ class MornyCoeur (modules: List[MornyModule])(using val config: MornyConfig)(tes
logger `notice` "done all save action." logger `notice` "done all save action."
} }
def reload (): Unit = {
logger `info` "Reloading coeur data / config..."
lang.reload()
logger `info` "done reload coeur data / config."
}
private def exitCleanup (): Unit = { private def exitCleanup (): Unit = {
// Morny Exiting // Morny Exiting

View File

@ -1,25 +1,31 @@
package cc.sukazyo.cono.morny.core package cc.sukazyo.cono.morny.core
import cc.sukazyo.cono.morny.core.Log.logger import cc.sukazyo.cono.morny.core.Log.logger
import cc.sukazyo.cono.morny.core.MornyLangs.load
import cc.sukazyo.cono.morny.data.MornyAssets import cc.sukazyo.cono.morny.data.MornyAssets
import cc.sukazyo.cono.morny.util.hytrans.* import cc.sukazyo.cono.morny.util.hytrans.*
import cc.sukazyo.cono.morny.util.UseThrowable.toLogString import cc.sukazyo.cono.morny.util.UseThrowable.toLogString
import cc.sukazyo.cono.morny.util.var_text.{Var, VarText}
import java.io.IOException import java.io.IOException
import scala.collection.mutable import scala.collection.mutable
import scala.util.boundary import scala.util.boundary
import scala.util.boundary.break import scala.util.boundary.break
class MornyLangs { object MornyLangs {
private val (lang_index, lang_trans) = { private def load(): Translations = {
val (lang_index, lang_trans) = {
logger `info` s"Loading Morny's translation data." logger `info` s"Loading Morny's translation data."
val (lang_dir, lang_index_content) = try {( val (lang_dir, lang_index_content) = try {
(
MornyAssets.pack.getResDir("langs"), MornyAssets.pack.getResDir("langs"),
MornyAssets.pack.getResource("langs/_index.hyl").readAsString() MornyAssets.pack.getResource("langs/_index.hyl").readAsString()
)} catch case e: IOException => )
} catch case e: IOException =>
throw Exception("Cannot read Morny's translations file.", e) throw Exception("Cannot read Morny's translations file.", e)
val my_index = LanguageTree.parseTreeDocument(lang_index_content) val my_index = LanguageTree.parseTreeDocument(lang_index_content)
val indexed_langs: Set[String] = { val indexed_langs: Set[String] = {
@ -31,10 +37,11 @@ class MornyLangs {
val language_translations = mutable.HashMap.empty[String, Definitions] val language_translations = mutable.HashMap.empty[String, Definitions]
for (file <- lang_dir.listFiles().filter(_.isFile)) yield { boundary { for (file <- lang_dir.listFiles().filter(_.isFile)) yield {
boundary {
import file.getPath as raw_path import file.getPath as raw_path
if !(raw_path.endsWith(".hyt") || raw_path.endsWith(".hytrans")) then break() if !(raw_path.endsWith(".hyt") || raw_path.endsWith(".hytrans")) then break()
val file_name = file.getPath.reverse.takeWhile(c=>(c!='/')&&(c !='\\')).reverse val file_name = file.getPath.reverse.takeWhile(c => (c != '/') && (c != '\\')).reverse
val file_basename = file_name.dropRight( val file_basename = file_name.dropRight(
if file_name.endsWith(".hyt") then ".hyt".length if file_name.endsWith(".hyt") then ".hyt".length
else ".hytrans".length else ".hytrans".length
@ -57,12 +64,39 @@ class MornyLangs {
// TODO: merge // TODO: merge
logger `warn` s" language $normalized seems already loaded one yet, this will override the old one!" logger `warn` s" language $normalized seems already loaded one yet, this will override the old one!"
else language_translations += (normalized -> lang_def) else language_translations += (normalized -> lang_def)
}} }
}
(my_index, language_translations.toMap) (my_index, language_translations.toMap)
} }
val translations: Translations = Translations(lang_index, lang_trans) Translations(lang_index, lang_trans)
}
}
class MornyLangs {
private var translations: Translations = load()
def reload (): Unit =
translations = load()
def getRaw: Translations = translations
def traverse (using lang: String)(f: (LangTag, Definitions) => Unit): Unit =
getRaw.traverse(f)
def traverseWithKey (key: String)(using lang: String)(f: (LangTag, Option[String]) => Unit): Unit =
getRaw.traverseWithKey(key)(f)
def get (key: String)(using lang: String): Option[String] =
getRaw.get(key)
def trans (key: String)(using lang: String): VarText =
getRaw.trans(key)
def trans (key: String, args: Var*)(using lang: String): String =
getRaw.trans(key, args*)
def transAsVar (key: String, args: Var*)(using lang: String): Var =
getRaw.transAsVar(key, args*)
} }

View File

@ -39,6 +39,18 @@ trait ThreadingManager {
*/ */
def doAfter[P] (thread: MessageThread[P]): Unit def doAfter[P] (thread: MessageThread[P]): Unit
/** Ensure current context have no ongoing message thread so that you can create a new one
* safely.
*
* If there's already an ongoing message thread, it will be canceled. Also, depends on the
* implementation, it may throw an exception or log a warning etc.
*
* @see [[cancelThread]] the method that will be used to cancel the ongoing message thread.
*
* @param _cxt the current context you want to check.
*/
def ensureCleanState (using _cxt: MessagingContext.WithUserAndMessage): Unit
/** Try to continue run a message thread using the given message. /** Try to continue run a message thread using the given message.
* *
* @since 2.0.0 * @since 2.0.0

View File

@ -3,18 +3,61 @@ package cc.sukazyo.cono.morny.core.bot.command
import cc.sukazyo.cono.morny.core.bot.api.ICommandAlias.HiddenAlias import cc.sukazyo.cono.morny.core.bot.api.ICommandAlias.HiddenAlias
import cc.sukazyo.cono.morny.core.Log.logger import cc.sukazyo.cono.morny.core.Log.logger
import cc.sukazyo.cono.morny.core.MornyCoeur import cc.sukazyo.cono.morny.core.MornyCoeur
import cc.sukazyo.cono.morny.core.bot.api.{ICommandAlias, ITelegramCommand} import cc.sukazyo.cono.morny.core.bot.api.{messages, ICommandAlias, ISimpleCommand, ITelegramCommand}
import cc.sukazyo.cono.morny.core.bot.api.messages.MessagingContext
import cc.sukazyo.cono.morny.data.TelegramStickers import cc.sukazyo.cono.morny.data.TelegramStickers
import cc.sukazyo.cono.morny.reporter.MornyReport import cc.sukazyo.cono.morny.reporter.MornyReport
import cc.sukazyo.cono.morny.util.tgapi.InputCommand import cc.sukazyo.cono.morny.util.tgapi.InputCommand
import cc.sukazyo.cono.morny.util.tgapi.formatting.TelegramFormatter.* import cc.sukazyo.cono.morny.util.tgapi.formatting.TelegramFormatter.*
import cc.sukazyo.cono.morny.util.tgapi.TelegramExtensions.Requests.unsafeExecute import cc.sukazyo.cono.morny.util.tgapi.TelegramExtensions.Requests.unsafeExecute
import com.pengrad.telegrambot.model.Update import com.pengrad.telegrambot.model.Update
import com.pengrad.telegrambot.request.SendSticker import com.pengrad.telegrambot.request.{EditMessageText, SendMessage, SendSticker}
import com.pengrad.telegrambot.TelegramBot
class MornyManagers (using coeur: MornyCoeur) { class MornyManagers (using coeur: MornyCoeur) {
private given TelegramBot = coeur.account import coeur.dsl.{*, given}
private def verifyTrusted (command: ISimpleCommand)(using cxt: MessagingContext.WithUserAndMessage): Boolean = {
if !(coeur.trusted isTrust cxt.bind_user) then
SendSticker(
cxt.bind_chat.id,
TelegramStickers ID_403
).replyToMessageId(cxt.bind_message.messageId)
.unsafeExecute
logger `attention` s"403 ${command.name} caught from user ${cxt.bind_user toLogTag}"
coeur.externalContext.consume[MornyReport](_.unauthenticatedAction(s"/${command.name}", cxt.bind_user))
false
else true
}
object Reload extends ITelegramCommand {
override val name: String = "reload"
override val aliases: List[ICommandAlias] = Nil
override val paramRule: String = ""
override val description: String = "重新载入 Bot 资源文件 / 配置文件"
override def execute (using command: InputCommand, event: Update): Unit = {
given cxt: MessagingContext.WithUserAndMessage = MessagingContext.extract(using event.message)
if !verifyTrusted(this) then return
val statusMessage = SendMessage(
cxt.bind_chat.id,
"[ .... ] Coeur reload."
).replyToMessageId(cxt.bind_message.messageId)
.unsafeExecute
coeur.reload()
EditMessageText(
statusMessage.message.chat.id,
statusMessage.message.messageId,
"[ OK ] Coeur reload."
).unsafeExecute
}
}
object Exit extends ITelegramCommand { object Exit extends ITelegramCommand {
@ -24,30 +67,17 @@ class MornyManagers (using coeur: MornyCoeur) {
override val description: String = "关闭 Bot (仅可信成员)" override val description: String = "关闭 Bot (仅可信成员)"
override def execute (using command: InputCommand, event: Update): Unit = { override def execute (using command: InputCommand, event: Update): Unit = {
given cxt: MessagingContext.WithUserAndMessage = MessagingContext.extract(using event.message)
val user = event.message.from if !verifyTrusted(this) then return
if (coeur.trusted isTrust user) {
SendSticker( SendSticker(
event.message.chat.id, cxt.bind_chat.id,
TelegramStickers ID_EXIT TelegramStickers ID_EXIT
).replyToMessageId(event.message.messageId) ).replyToMessageId(cxt.bind_message.messageId)
.unsafeExecute .unsafeExecute
logger `attention` s"Morny exited by user ${user toLogTag}" logger `attention` s"Morny exited by user ${cxt.bind_user toLogTag}"
coeur.exit(0, user) coeur.exit(0, cxt.bind_user)
} else {
SendSticker(
event.message.chat.id,
TelegramStickers ID_403
).replyToMessageId(event.message.messageId)
.unsafeExecute
logger `attention` s"403 exit caught from user ${user toLogTag}"
coeur.externalContext.consume[MornyReport](_.unauthenticatedAction("/exit", user))
}
} }
@ -61,31 +91,18 @@ class MornyManagers (using coeur: MornyCoeur) {
override val description: String = "保存缓存数据到文件(仅可信成员)" override val description: String = "保存缓存数据到文件(仅可信成员)"
override def execute (using command: InputCommand, event: Update): Unit = { override def execute (using command: InputCommand, event: Update): Unit = {
given cxt: MessagingContext.WithUserAndMessage = MessagingContext.extract(using event.message)
val user = event.message.from if !verifyTrusted(this) then return
if (coeur.trusted isTrust user) { logger `attention` s"call save from command by ${cxt.bind_user toLogTag}"
logger `attention` s"call save from command by ${user toLogTag}"
coeur.saveDataAll() coeur.saveDataAll()
SendSticker( SendSticker(
event.message.chat.id, cxt.bind_chat.id,
TelegramStickers ID_SAVED TelegramStickers ID_SAVED
).replyToMessageId(event.message.messageId) ).replyToMessageId(cxt.bind_message.messageId)
.unsafeExecute .unsafeExecute
} else {
SendSticker(
event.message.chat.id,
TelegramStickers ID_403
).replyToMessageId(event.message.messageId)
.unsafeExecute
logger `attention` s"403 save caught from user ${user toLogTag}"
coeur.externalContext.consume[MornyReport](_.unauthenticatedAction("/save", user))
}
} }
} }

View File

@ -78,6 +78,28 @@ class ThreadingManagerImpl (using bot: TelegramBot) extends ThreadingManager {
threadMap.get(ThreadKey fromMessage message) threadMap.get(ThreadKey fromMessage message)
.exists(_.onExecuteIt(message)) .exists(_.onExecuteIt(message))
/** Ensure current context have no ongoing message thread so that you can create a new one
* safely.
*
* If there's already an ongoing message thread, it will be canceled, and will output a
* notice message to that context.
*
* @see [[cancelThread]] the method that will be used to cancel the ongoing message thread.
*
* @param _cxt the current context you want to check. This context will be converted to the
* [[ThreadKey]] in order to do the check, if needed, some message will also
* sent to this context.
*/
override def ensureCleanState (using _cxt: MessagingContext.WithUserAndMessage): Unit =
if cancelThread(ThreadKey fromContext _cxt) then
SendMessage(
_cxt.bind_chat.id,
"""There seems another message thread is waiting for future messages.
|That thread has been canceled automatically.
|""".stripMargin
).replyToMessageId(_cxt.bind_message.messageId)
.unsafeExecute
override def cancelThread (threadKey: ThreadKey): Boolean = override def cancelThread (threadKey: ThreadKey): Boolean =
threadMap.get(threadKey) threadMap.get(threadKey)
.exists(_.onCancelIt()) .exists(_.onCancelIt())

View File

@ -20,6 +20,8 @@ class Testing (using coeur: MornyCoeur) extends ISimpleCommand {
given context: MessagingContext.WithUserAndMessage = MessagingContext.extract(using event.message) given context: MessagingContext.WithUserAndMessage = MessagingContext.extract(using event.message)
given lang: String = context.bind_user.prefer_language given lang: String = context.bind_user.prefer_language
coeur.messageThreading.ensureCleanState
SendMessage( SendMessage(
event.message.chat.id, event.message.chat.id,
translations.trans("morny.misc.command_test.message") translations.trans("morny.misc.command_test.message")