diff --git a/config.ini b/config.ini index 64914ad..c5b823a 100644 --- a/config.ini +++ b/config.ini @@ -1,8 +1,8 @@ # Ci configuration for GitHub Actions. [framework] -ver=4 +ver=3 [main] -ver=2.5.0 +ver=2.5.1 [release] test=0 [ci] diff --git a/lang/en_us.yml b/lang/en_us.yml index 531695e..c4d3be7 100644 --- a/lang/en_us.yml +++ b/lang/en_us.yml @@ -16,7 +16,9 @@ matrix_sync: success: Login by password successfully! save_token: Saving token for the bot account... on_receiver_cancelled: Receiver task was cancelled. - on_send_command: Message is sending to matrix... + on_send_command: + sending: Message is sending to matrix... + failed: Error when sending message on_sync_running: Already running message sync! on_sync_start: Starting message sync... on_unload: Unloading MatrixSync... @@ -25,6 +27,8 @@ matrix_sync: on_startup: MC server started! on_stop: MC server stopped. on_crash: MC server crashed! + settings_comp_check: + failed: "Compatibility check failed! Backup old settings as \"settings.json.bak\"." sync_status: running: MSync is running... not_running: MSync is not running. diff --git a/lang/zh_cn.yml b/lang/zh_cn.yml index c917fa0..cc35e49 100644 --- a/lang/zh_cn.yml +++ b/lang/zh_cn.yml @@ -16,7 +16,9 @@ matrix_sync: success: 成功使用密码完成登录! save_token: 正在为机器人账号保存Token... on_receiver_cancelled: 接收器任务已经取消。 - on_send_command: 消息正在发送到Matrix... + on_send_command: + sending: 消息正在发送到Matrix... + failed: 发送消息时发生错误 on_sync_running: 消息同步已在运行! on_sync_start: 开始消息同步... on_unload: 正在卸载 MatrixSync... @@ -25,6 +27,8 @@ matrix_sync: on_startup: MC服务器启动完成! on_stop: MC服务器已关闭 on_crash: MC服务器发生崩溃! + settings_comp_check: + failed: "兼容性检查失败!旧有的设置项将备份为\"settings.json.bak\"。" sync_status: running: "[MSync] 消息同步正在运行..." not_running: "[MSync] 消息同步未在运行!" diff --git a/matrix_sync/client/init.py b/matrix_sync/client/init.py index 42d3a59..df205c7 100644 --- a/matrix_sync/client/init.py +++ b/matrix_sync/client/init.py @@ -1,10 +1,11 @@ import json import sys import aiofiles +import matrix_sync.logger.get_logger as get_logger import matrix_sync.plg_globals as plg_globals from . import * -from ..utils.logger import * +from ..utils import configDir, tr from ..utils.token import getToken from nio import LoginResponse @@ -17,6 +18,7 @@ async def cache_token(resp: LoginResponse): })) async def login_by_password(): + logger = get_logger() client = AsyncClient( get_homeserver(plg_globals.config["homeserver"]), plg_globals.config["user_id"], @@ -24,21 +26,21 @@ async def login_by_password(): ) resp = await client.login(plg_globals.config["password"], device_name=plg_globals.config["device_id"]) if isinstance(resp, LoginResponse): - log_info(tr("login.success")) + logger.info(tr("login.success"), "FirstLogin") await cache_token(resp) - log_info(tr("login.save_token")) + plg_globals.token_vaild = True + logger.info(tr("login.save_token"), "FirstLogin") else: tip = tr("login.failed") - log_error(f"{tip}: {resp}") + logger.error(f"{tip}: {resp}", "FirstLogin") homeserver = get_homeserver(plg_globals.config["homeserver"]) - log_info(f'homeserver: "{homeserver}", bot: "{plg_globals.config["user_id"]}"') - log_error(tr("check_config")) + logger.info(f'homeserver: "{homeserver}", bot: "{plg_globals.config["user_id"]}"', "FirstLogin") + logger.error(tr("check_config"), "FirstLogin") sys.exit(1) async def check_token() -> bool: user, token = await getToken() if user != plg_globals.config["user_id"]: - log_error(tr("token_mismatch")) return False else: return True \ No newline at end of file diff --git a/matrix_sync/client/receiver.py b/matrix_sync/client/receiver.py index 0996e8b..7294c4a 100644 --- a/matrix_sync/client/receiver.py +++ b/matrix_sync/client/receiver.py @@ -1,10 +1,9 @@ # thread MatrixReceiver import asyncio +import matrix_sync.logger.get_logger as get_logger import matrix_sync.plg_globals as plg_globals from . import * -from .init import check_token -from ..utils.logger import * from ..utils.token import getToken from ..utils import tr from ..event import * @@ -16,77 +15,66 @@ receiver = None async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None: - message_format = plg_globals.settings["message_format"]["all_room"] - room_message = message_format.replace('%room_display_name%', room.display_name).replace('%sender%', room.user_name(event.sender)).replace('%message%', event.body) - # Avoid echo messages. - if not event.sender == plg_globals.config["user_id"]: - # Apply settings config - if not plg_globals.settings["listen"]["all_rooms"]: - message_format = plg_globals.settings["message_format"]["single_room"] - room_message = message_format.replace('%sender%', room.user_name(event.sender)).replace('%message%', event.body) - event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room.room_id) - log_info(room_message, "Message") - psi.say(room_message) + room_info.id = room.room_id + room_info.display_name= room.display_name + if event.sender != plg_globals.config["user_id"]: + event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room) def on_sync_error(response: SyncError): + logger = get_logger() global homeserver_online - log_error(f"Sync error: {response.status_code}") + logger.error(f"Sync error: {response.status_code}") if response.status_code >= 500: homeserver_online = False async def get_messages() -> None: + logger = get_logger() global receiver resp = None client = AsyncClient(homeserver=get_homeserver(plg_globals.config["homeserver"])) - token_vaild = await check_token() - if token_vaild: - user, token = await getToken() - client.user_id = plg_globals.config["user_id"] - client.access_token = token - client.device_id = plg_globals.config["device_id"] + client.user_id = plg_globals.config["user_id"] + user, token = await getToken() + client.access_token = token + client.device_id = plg_globals.config["device_id"] - if not plg_globals.settings["listen"]["all_rooms"]: - log_info("ok.") - cfg_room_id = plg_globals.config["room_id"] - log_info(f"Listening: {cfg_room_id}") - resp = await client.upload_filter(room={"rooms": [cfg_room_id]}) - if isinstance(resp, UploadFilterError): - log_error(resp) + if not plg_globals.settings["listen"]["all_rooms"]: + logger.info("ok.", "Receiver") + cfg_room_id = plg_globals.config["room_id"] + logger.info(f"Listening: {cfg_room_id}", "Receiver") + resp = await client.upload_filter(room={"rooms": [cfg_room_id]}) + if isinstance(resp, UploadFilterError): + logger.error(resp, "Receiver") - client.add_response_callback(on_sync_error, SyncError) + client.add_response_callback(on_sync_error, SyncError) - if homeserver_online: - if plg_globals.settings["listen"]["old_messages"] is True: - receiver = asyncio.create_task(client.sync_forever(timeout=5)) - else: - if resp is not None: - await client.sync(timeout=5, sync_filter=resp.filter_id) - client.add_event_callback(message_callback, RoomMessageText) - receiver = asyncio.create_task(client.sync_forever(timeout=5, sync_filter=resp.filter_id)) - else: - await client.sync(timeout=5) - client.add_event_callback(message_callback, RoomMessageText) - receiver = asyncio.create_task(client.sync_forever(timeout=5)) + if homeserver_online: + if plg_globals.settings["listen"]["old_messages"] is True: + receiver = asyncio.create_task(client.sync_forever(timeout=5)) else: - log_error("Sync failed: homeserver is down or your network disconnected with it.") - log_info("Use !!msync start after homeserver is running or your network restored.") + if resp is not None: + await client.sync(timeout=5, sync_filter=resp.filter_id) + client.add_event_callback(message_callback, RoomMessageText) + receiver = asyncio.create_task(client.sync_forever(timeout=5, sync_filter=resp.filter_id)) + else: + await client.sync(timeout=5) + client.add_event_callback(message_callback, RoomMessageText) + receiver = asyncio.create_task(client.sync_forever(timeout=5)) + else: + logger.error("Sync failed: homeserver is down or your network disconnected with it.", "Receiver") + logger.info("Use !!msync start after homeserver is running or your network restored.", "Receiver") - try: - await receiver - except asyncio.CancelledError: - log_warning(tr("on_receiver_cancelled")) - except Exception as e: - log_error(f"Receiver sync error: {e}") + try: + await receiver + except asyncio.CancelledError: + logger.warning(tr("on_receiver_cancelled"), "Receiver") + except Exception as e: + logger.error(f"Receiver sync error: {e}", "Receiver") + receiver.cancel() + finally: + if receiver: receiver.cancel() - finally: - if receiver: - receiver.cancel() - try: - await receiver - except asyncio.CancelledError: - pass - client.stop_sync_forever() + if client is not None: await client.close() async def stop_sync(): diff --git a/matrix_sync/client/reporter.py b/matrix_sync/client/reporter.py index 022d08d..08981d0 100644 --- a/matrix_sync/client/reporter.py +++ b/matrix_sync/client/reporter.py @@ -3,17 +3,14 @@ import matrix_sync.plg_globals as plg_globals from . import get_homeserver -from .init import check_token from ..utils import * -from ..utils.logger import * from ..utils.token import getToken from nio import AsyncClient async def send_to_matrix(message) -> None: client = AsyncClient(get_homeserver(plg_globals.config["homeserver"])) - token_vaild = await check_token() - if token_vaild: + if plg_globals.token_vaild: user, token = await getToken() client.user_id = plg_globals.config["user_id"] diff --git a/matrix_sync/commands/__init__.py b/matrix_sync/commands/__init__.py index 01006f9..7dd736b 100644 --- a/matrix_sync/commands/__init__.py +++ b/matrix_sync/commands/__init__.py @@ -1,13 +1,13 @@ import asyncio import threading +import matrix_sync.logger.get_logger as get_logger import matrix_sync.plg_globals as plg_globals from mcdreforged.api.all import * from ..client.reporter import send_to_matrix from ..client.receiver import get_messages, stop_sync from ..client import * -from ..utils import tr -from ..utils.logger import * +from ..utils import * from .help import * @@ -16,17 +16,23 @@ plg_globals.tLock = threading.Lock() def start_sync(): + logger = get_logger() if not plg_globals.tLock.locked(): run_sync_task() - log_info(tr("on_sync_start")) else: - log_warning(tr("on_sync_running")) + logger.warning(tr("on_sync_running")) @new_thread('MatrixReceiver') def run_sync_task(): + logger = get_logger() plg_globals.sync = True - with plg_globals.tLock: - asyncio.run(add_sync_task()) + if plg_globals.token_vaild: + with plg_globals.tLock: + logger.info(tr("on_sync_start")) + asyncio.run(add_sync_task()) + else: + logger.error(tr("token_mismatch")) + plg_globals.sync = False async def add_sync_task(): await get_messages() @@ -55,16 +61,20 @@ async def on_command_stop(): @builder.command("!!msync status") def show_status(): - log_info(f"Receiver: {plg_globals.sync}") + logger = get_logger() + logger.info(f"Receiver: {plg_globals.sync}") if plg_globals.sync: - log_info(tr("sync_status.running")) + logger.info(tr("sync_status.running")) else: - log_info(tr("sync_status.not_running")) + logger.info(tr("sync_status.not_running")) @builder.command("!!msync send ") def on_command_send(src: CommandSource, ctx: CommandContext): - matrix_reporter(ctx["message"]) - src.reply(tr("on_send_command")) + if plg_globals.token_vaild: + matrix_reporter(ctx["message"]) + src.reply(tr("on_send_command.sending")) + else: + src.reply(tr("on_send_command.failed") + ": " + tr("token_mismatch")) @builder.command("!!msync reload") def on_command_reload(): diff --git a/matrix_sync/config/__init__.py b/matrix_sync/config/__init__.py index 0874bef..7db9d16 100644 --- a/matrix_sync/config/__init__.py +++ b/matrix_sync/config/__init__.py @@ -1,7 +1,11 @@ +import os +import matrix_sync.utils.tr as tr import matrix_sync.plg_globals as plg_globals from .default import * from ..utils import * +from ..client.init import check_token +from mcdreforged.api.types import PluginServerInterface async def load_config(server: PluginServerInterface): @@ -9,5 +13,12 @@ async def load_config(server: PluginServerInterface): if plg_globals.config == account_config: server.unload_plugin(plgSelf.id) plg_globals.settings = server.load_config_simple('settings.json', default_settings) + if plg_globals.settings["ver"] != "2.5.1": + plg_globals.settings = None + psi.logger.info(tr("settings_comp_check.failed")) + os.rename(f"{configDir}/settings.json", f"{configDir}/settings.json.bak") + plg_globals.settings = server.load_config_simple('settings.json', default_settings) if not plg_globals.settings["log_style"]["mcdr"]: - psi.logger.info("Plugin MatrixSync will use its logger, with different format to MCDR.") \ No newline at end of file + psi.logger.info("Plugin MatrixSync will use its logger, different with MCDR.") + if os.path.exists(f"{configDir}/token.json"): + plg_globals.token_vaild = await check_token() \ No newline at end of file diff --git a/matrix_sync/config/default.py b/matrix_sync/config/default.py index edda737..e86f4a3 100644 --- a/matrix_sync/config/default.py +++ b/matrix_sync/config/default.py @@ -19,7 +19,8 @@ }, "log_style": { "mcdr": False, - "debug": False + "debug": False, + "show_time": False }, - "ver": "2.5.0" + "ver": "2.5.1" } \ No newline at end of file diff --git a/matrix_sync/entry.py b/matrix_sync/entry.py index 092cd1f..2fc0b7e 100644 --- a/matrix_sync/entry.py +++ b/matrix_sync/entry.py @@ -1,21 +1,24 @@ import os +import matrix_sync.logger.get_logger as get_logger -from .utils import tr -from .utils.logger import * -from .client.init import login_by_password +from .utils import tr, configDir from .client.reporter import send_to_matrix from .client.receiver import stop_sync from .config import load_config from .commands import * +from .event.receiver import listen_message from mcdreforged.api.all import * -# Framwork ver: 2.5.0-4 +# Framwork ver: 2.5.1-3 async def on_load(server: PluginServerInterface, prev_module): await load_config(server) + # await check_settings(server) command_register(server) if not os.path.exists(f"{configDir}/token.json"): + from .client.init import login_by_password await login_by_password() + listen_message(server) start_sync() def on_server_start(server: PluginServerInterface): @@ -25,21 +28,24 @@ def on_server_startup(server: PluginServerInterface): start_sync() matrix_reporter(tr("server_status.on_startup")) +# Built-in game message reporter. def on_user_info(server: PluginServerInterface, info: Info): if info.player is not None and not info.content.startswith("!!"): player_message = f"[MC] <{info.player}> {info.content}" if plg_globals.sync: matrix_reporter(player_message) -# Exit sync process when server stop. +# Send a message about the status of server to matrix when server stop. async def on_server_stop(server: PluginServerInterface, server_return_code: int): if server_return_code == 0: exit_message = tr("server_status.on_stop") else: exit_message = tr("server_status.on_crash") - + await send_to_matrix(exit_message) +# Wait for receiver sync exited, then unload plugin. async def on_unload(server: PluginServerInterface): - log_info(tr("on_unload")) + logger = get_logger() + logger.info(tr("on_unload")) await stop_sync() \ No newline at end of file diff --git a/matrix_sync/event/__init__.py b/matrix_sync/event/__init__.py index 8165e1b..b633b4f 100644 --- a/matrix_sync/event/__init__.py +++ b/matrix_sync/event/__init__.py @@ -1,15 +1,22 @@ +import matrix_sync.logger.get_logger as get_logger + from mcdreforged.api.all import * from ..utils import psi +class room_info(Serializable): + id: str + display_name: str + class MatrixMessageEvent(PluginEvent): - def __init__(self, message: str, sender: str, room_id: str): + def __init__(self, message: str, sender: str, room_info): super().__init__('MatrixRoomMessage') self.message = message self.sender = sender - self.room_id = room_id + self.room_info = room_info def event_dispatcher(event: type[PluginEvent], *args, **kwargs): + logger = get_logger() event_instance = event(*args, **kwargs) psi.dispatch_event(event_instance, args) - psi.logger.debug("Event dispatched to MCDR!") \ No newline at end of file + logger.debug("Event dispatched to MCDR!") \ No newline at end of file diff --git a/matrix_sync/event/receiver.py b/matrix_sync/event/receiver.py new file mode 100644 index 0000000..1831138 --- /dev/null +++ b/matrix_sync/event/receiver.py @@ -0,0 +1,19 @@ +import matrix_sync.logger.get_logger as get_logger +import matrix_sync.plg_globals as plg_globals + +from mcdreforged.api.types import PluginServerInterface + + +def listen_message(server: PluginServerInterface): + server.register_event_listener("MatrixRoomMessage", on_matrix_message) + +def on_matrix_message(server, message: str, sender: str, room): + logger = get_logger() + if plg_globals.settings["listen"]["all_rooms"]: + message_format = plg_globals.settings["message_format"]["all_room"] + room_message = message_format.replace('%room_display_name%', room.display_name).replace('%sender%', sender).replace('%message%', message) + else: + message_format = plg_globals.settings["message_format"]["single_room"] + room_message = message_format.replace('%sender%', sender).replace('%message%', message) + logger.info(room_message, "Message") + server.say(room_message) \ No newline at end of file diff --git a/matrix_sync/logger/__init__.py b/matrix_sync/logger/__init__.py new file mode 100644 index 0000000..fa5e773 --- /dev/null +++ b/matrix_sync/logger/__init__.py @@ -0,0 +1,59 @@ +import datetime + +from typing import Optional +from mcdreforged.api.rtext import * +from .text import * + + +class SimpleLogger: + def __init__(self, level="INFO"): + self.level = level + self.levels = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40} + self.colors = { + "DEBUG": RColor.dark_blue, + "INFO": RColor.green, + "WARNING": RColorRGB.from_rgb(255, 165, 0), + "ERROR": RColor.red, + "RESET": RColor.reset + } + + def log(self, level, message: str, module: Optional[str]=None): + if self.levels[level] >= self.levels[self.level]: + timestamp = datetime.datetime.now().strftime("%H:%M:%S") + color = self.colors.get(level, self.colors["RESET"]) + colored_level = RText(level, color).to_colored_text() + if pattern.search(message): + message = mc_to_ansi(message) + if module is not None: + print(f"[MSync - {module}] [{timestamp} {colored_level}] {message}") + else: + print(f"[MSync - {timestamp} {colored_level}] {message}") + + def debug(self, message, module: Optional[str]=None): + if module is None: + self.log("DEBUG", message) + else: + self.log("DEBUG", message, module) + + def info(self, message, module: Optional[str]=None): + if module is None: + self.log("INFO", message) + else: + self.log("INFO", message, module) + + def warning(self, message, module: Optional[str]=None): + if module is None: + self.log("WARNING", message) + else: + self.log("WARNING", message, module) + + def error(self, message, module: Optional[str]=None): + if module is None: + self.log("ERROR", message) + else: + self.log("ERROR", message, module) + +info_logger = SimpleLogger(level="INFO") +debug_logger = SimpleLogger(level="DEBUG") +# info_logger.error("Error", "Main") +# debug_logger.debug("Debug", "Main") \ No newline at end of file diff --git a/matrix_sync/logger/get_logger.py b/matrix_sync/logger/get_logger.py new file mode 100644 index 0000000..5c45674 --- /dev/null +++ b/matrix_sync/logger/get_logger.py @@ -0,0 +1,32 @@ +import matrix_sync.plg_globals as plg_globals + +from ..utils import psi +from . import info_logger, debug_logger + + +class psiLogger: + + def info(self, *args): + psi.logger.info(args[0]) + + def warning(self, *args): + psi.logger.warning(args[0]) + + def error(self, *args): + psi.logger.error(args[0]) + +def get_logger(): + if plg_globals.settings["log_style"]["mcdr"]: + logger = psiLogger() + return logger + else: + if plg_globals.settings["log_style"]["debug"]: + logger = debug_logger + else: + logger = info_logger + return logger + + +__all__ = ["get_logger"] +import sys +sys.modules[__name__] = get_logger \ No newline at end of file diff --git a/matrix_sync/logger/text.py b/matrix_sync/logger/text.py new file mode 100644 index 0000000..2fb0dfe --- /dev/null +++ b/matrix_sync/logger/text.py @@ -0,0 +1,26 @@ +import re + +from mcdreforged.minecraft.rtext.style import * + + +pattern = re.compile(r'(§[0-9a-fklmnor])') + +def mc_to_ansi(text: str) -> str: + + mc_to_console_map = { + color.mc_code: color.console_code + for color in RColor + if isinstance(color, RColorClassic) + } + mc_to_console_map.update({ + style.mc_code: style.console_code + for style in RStyle + if isinstance(style, RStyleClassic) + }) + mc_to_console_map['§r'] = Style.RESET_ALL + + def replace_code(match): + code = match.group(1) + return mc_to_console_map.get(code, '') + + return pattern.sub(replace_code, text) \ No newline at end of file diff --git a/matrix_sync/plg_globals.py b/matrix_sync/plg_globals.py index 0b50e7b..bcc4f14 100644 --- a/matrix_sync/plg_globals.py +++ b/matrix_sync/plg_globals.py @@ -1,4 +1,5 @@ config = None settings = None tLock = None -sync = None \ No newline at end of file +sync = None +token_vaild = None \ No newline at end of file diff --git a/matrix_sync/utils/__init__.py b/matrix_sync/utils/__init__.py index eedfa2d..43cee01 100644 --- a/matrix_sync/utils/__init__.py +++ b/matrix_sync/utils/__init__.py @@ -1,35 +1,8 @@ -from typing import Optional -from mcdreforged.api.all import * +from mcdreforged.api.types import ServerInterface + psi = ServerInterface.psi() MCDRConfig = psi.get_mcdr_config() plgSelf = psi.get_self_metadata() serverDir = MCDRConfig["working_directory"] -configDir = psi.get_data_folder() - - -def tr(tr_key: str, return_str: Optional[bool] = True): - ''' - 对`PluginServerInterface.rtr()`进行优化,提高翻译效率。 - - 参数: - tr_key (str): 原始或简化后的翻译键名称 - return_str (可选[bool]): 是否尝试转换成字符串减少出错 - - 返回: - translation: RTextMCDRTranslation组件 - 或tr_to_str: 字符串 - ''' - if tr_key.startswith(f"{plgSelf.id}"): - translation = psi.rtr(f"{tr_key}") - else: - # 使用此前缀代表非本插件的翻译键,则翻译时不会附加本插件的ID,避免错误。 - if tr_key.startswith("#"): - translation = psi.rtr(tr_key.replace("#", "")) - else: - translation = psi.rtr(f"{plgSelf.id}.{tr_key}") - if return_str: - tr_to_str: str = str(translation) - return tr_to_str - else: - return translation \ No newline at end of file +configDir = psi.get_data_folder() \ No newline at end of file diff --git a/matrix_sync/utils/logger.py b/matrix_sync/utils/logger.py deleted file mode 100644 index 71c28d4..0000000 --- a/matrix_sync/utils/logger.py +++ /dev/null @@ -1,31 +0,0 @@ -import matrix_sync.plg_globals as plg_globals - -from . import * - - -def log_tool(log_text: str, color: RColor, pfx: str, prefix: Optional[str] = None): - if plg_globals.settings["log_style"]["mcdr"]: - if pfx == "Info": - if prefix == "Message": - log_text = "[MSync] " + log_text - psi.logger.info(log_text) - elif pfx == "Warning": - psi.logger.warning(log_text) - elif pfx == "Error": - psi.logger.error(log_text) - else: - psi.logger.info(log_text) - else: - pfx_with_color = RText(pfx, color).to_colored_text() - if prefix is not None: - pfx_with_color = f"{prefix}/" + pfx_with_color - print(f"[MSync - {pfx_with_color}] {log_text}") - -def log_info(log_text: str, prefix: Optional[str] = None): - log_tool(log_text, RColor.green, "Info", prefix) - -def log_warning(log_text: str, prefix: Optional[str] = None): - log_tool(log_text, RColorRGB.from_rgb(255, 165, 0), "Warning", prefix) - -def log_error(log_text: str, prefix: Optional[str] = None): - log_tool(log_text, RColor.red, "Error", prefix) \ No newline at end of file diff --git a/matrix_sync/utils/tr.py b/matrix_sync/utils/tr.py new file mode 100644 index 0000000..0efe67b --- /dev/null +++ b/matrix_sync/utils/tr.py @@ -0,0 +1,33 @@ +from . import * +from typing import Optional + + +def tr(tr_key: str, return_str: Optional[bool] = True): + ''' + 对`PluginServerInterface.rtr()`进行优化,提高翻译效率。 + + 参数: + tr_key (str): 原始或简化后的翻译键名称 + return_str (可选[bool]): 是否尝试转换成字符串减少出错 + + 返回: + translation: RTextMCDRTranslation组件 + 或tr_to_str: 字符串 + ''' + if tr_key.startswith(f"{plgSelf.id}"): + translation = psi.rtr(f"{tr_key}") + else: + # 使用此前缀代表非本插件的翻译键,则翻译时不会附加本插件的ID,避免错误。 + if tr_key.startswith("#"): + translation = psi.rtr(tr_key.replace("#", "")) + else: + translation = psi.rtr(f"{plgSelf.id}.{tr_key}") + if return_str: + tr_to_str: str = str(translation) + return tr_to_str + else: + return translation + +__all__ = ["tr"] +import sys +sys.modules[__name__] = tr diff --git a/mcdreforged.plugin.json b/mcdreforged.plugin.json index 85aff82..31e80ea 100644 --- a/mcdreforged.plugin.json +++ b/mcdreforged.plugin.json @@ -1,6 +1,6 @@ { "id": "matrix_sync", - "version": "2.5.0", + "version": "2.5.1", "name": "MatrixSync", "description": { "en_us": "Sync messages between online game and Matrix groups.",