diff --git a/MatrixSync-v2.3.1.mcdr b/MatrixSync-v2.3.1.mcdr new file mode 100644 index 0000000..050e805 Binary files /dev/null and b/MatrixSync-v2.3.1.mcdr differ diff --git a/README.md b/README.md index 9163e4e..401b812 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,7 @@ 开发过程中用到的pypi项目:[matrix-nio](https://pypi.org/project/matrix-nio/)。 -当前分支版本:主分支@2.3.0 - -请注意,插件在加载时会阻塞MCDR主线程,如果MCDR被阻塞并且无法继续正常启动,请检查强制结束所有进程并检查插件配置是否正确、Matrix根服务器是否在线等或禁用插件后重新启动。 +当前分支版本:主分支@2.3.1 ## 用法 从release下载最新版本,在MCDReforged的启动环境中安装好需要的Python依赖,然后扔到plugins文件夹里面即可。 @@ -52,9 +50,10 @@ | - | - | | plugin-enabled | 插件是否启用,请确保配置文件和所需设置修改无误后再开启 | | allow_all_rooms_msg | 是否允许来自所有房间的消息,若开启,则来自机器人账号所加入的房间的消息都会被转发到游戏中,并注明房间的显示名称,否则只转发已设置的房间的消息 | +| sync_old_msg | 是否同步旧的消息,默认开启,可在插件配置目录下的token.json文件中增加有效的`next_batch`项后关闭 | ## 接口(API) -插件提供了一个协程函数`sendMsg()`供其他开发者调用以实现向Matrix群组发送自定义内容,其回调参数为`message`下面是代码参考: +插件提供了一个协程函数`sendMsg()`供其他开发者调用以实现向Matrix群组发送自定义内容,其回调参数为`message`,下面是代码参考: ```python import asyncio import ... @@ -121,6 +120,22 @@ async def main(): server.logger.info("error") ``` +由于2.3.0版本新增了Matrix房间消息的分发事件,且2.3.1版本重构了这部分接口,所以该部分内容已过时。 + +这些过时的内容仍然持续有效,但其做法不再推荐,请等待后续更详细的文档更新。 + +重构后接口的简单用法: +```python +import matrix_sync.client + +def main(): + clientStatus = matrix_sync.client.clientStatus + if clientStatus: + sender(message) + +# 消息将在独立线程中被发送到Matrix,不再可能会阻塞MCDR主线程 +``` + ## 热重载(reload)及消息互通控制 插件默认在游戏服务端启动完成时才会自动启动房间消息接收进程,重新加载插件后,消息接收器并不会自动启动。 @@ -128,6 +143,8 @@ async def main(): 要关闭房间消息接收进程,可以在控制台使用`!!msync stop`,直到下次服务器启动完成前消息接收器都必须手动重启。 +要在详细阅读后关闭2.3.1版本新增的大量提示,可以使用`!!msync closetip`,目前想重新查看提示,只能在源码中查看语言文件,或自行修改token.json + 插件会自动在解析到游戏内的消息时尝试转发到配置好的Matrix房间内,暂时无法禁用。 该指令没有权限要求,但设置了进程锁(安全机制),重复执行会警告提示,不会影响插件功能的正常运行。 @@ -136,5 +153,7 @@ async def main(): ## 注意 - 首次加载插件的时候,插件将自动初始化配置并卸载自己。你需要正确修改默认的配置文件,并在settings.json中启用plugin_enabled配置项以启用插件,然后重启服务器或着重载插件以正常使用。 -- 不打算支持加密信息(EE2E),有需要可以二次开发修改插件,也欢迎PR。 + +- 不打算支持加密信息(EE2E),有需要可以二次开发修改插件,欢迎PR。 + - 多语言目前只支持中文(简体)和英语(用谷歌和ChatGPT从中文翻译),任何人都可以联系我帮助完善翻译,欢迎PR到/lang语言文件中。 diff --git a/README_en_us.md b/README_en_us.md index be788b0..87ef267 100644 --- a/README_en_us.md +++ b/README_en_us.md @@ -10,9 +10,7 @@ The following project is used in the development process: [matrix-nio](https://p Thanks for ChatGPT and Google Translate's help to translate the content from Chinese, if anything wrong, please issue to feedback or PR to `/lang`. -Present branch version: released@2.3.0 - -Please note that the plugin will block the MCDR main thread during loading. If MCDR is blocked and cannot continue its normal startup, please check by forcibly terminating all processes and verifying whether the plugin configuration is correct, whether the Matrix root server is online, etc., or restart after disabling the plugin. +Present branch version: released@2.3.1 ## Usage Download the latest version from the release, install the necessary Python dependencies in the MCDReforged startup environment, and then throw it into the plugins folder. @@ -41,6 +39,7 @@ If there is any issue with message forwarding in any direction during the messag | - | - | | plugin-enabled | Whether the plugin is enabled, please ensure the configuration file and necessary settings are modified correctly before enabling | | allow_all_rooms_msg | Whether to allow messages from all rooms, if enabled, messages from rooms joined by the bot account will be forwarded to the game, with the room display name specified, otherwise only messages from the configured room will be forwarded | +| sync_old_msg | Whether to sync old messages, enabled on default, can turn it off after vaild `next_batch` appeared in token.json in config path of the plugin | ## Interface (API) The plugin provides a coroutine function `sendMsg()` for other developers to call to send custom content to the Matrix group. Its callback parameter is `message`. Here is the code reference: @@ -69,6 +68,8 @@ Add the main plugin (MatrixSync) to the dependencies of MCDR, and include its Py Please note that support for this interface is experimental, and it cannot be guaranteed that the message forwarding functionality of the main plugin (MatrixSync) will work when calling this interface (there may be situations where the bot is not properly configured, or existing login information and tokens cannot be used). If you want to call this interface, please ensure that the user has installed and configured the main plugin (MatrixSync). +Outdated after version 2.3.1, please wait new document finished. + ## Hot Reload (reload) & message sync control By default, the plugin will only start the room message receive process after the game server has finished starting up. After reloading the plugin, the MatrixReceiver sub thread will not start automatically. diff --git a/config.ini b/config.ini index 04272cd..83b64f4 100644 --- a/config.ini +++ b/config.ini @@ -3,6 +3,6 @@ [framework] ver=1 [main] -ver=2.3.0 +ver=2.3.1 [release] -test=0 +test=1 diff --git a/lang/en_us.yml b/lang/en_us.yml index dc9efab..939fd98 100644 --- a/lang/en_us.yml +++ b/lang/en_us.yml @@ -9,6 +9,12 @@ matrix_sync: on_server_stop: Server stopped, stopping messages sync. on_server_crash: Server crashed or not stopped normally, stopping messages sync, unknown errors may happen. on_unload: Unloading plugin, waiting for message sync process to exit... + old_msg_sync: If there are no errors, you can now modify the "sync_old_msg" item in the settings.json file in the plugin configuration directory to false, which will prevent the plugin from syncing old messages that have already been sent. + old_msg_sync2: Please note that messages sent in the chat room when message synchronization is not running will not be sent out anymore. + old_msg_sync3: This is an experimental feature. If there are any issues, please report them via GitHub Issues. + old_msg_sync4: If there are any errors, please first change the "sync_old_msg" item to true, and once the message receiver is functioning correctly, check if the token.json file in the plugin configuration directory contains a valid "next_batch" item. If it does, you can follow the steps mentioned above to retry. + old_msg_sync5: This prompt text is quite lengthy. If you have read and understood it, you can use !!msync closetip to close this prompt. + on_tip_read: Tips closed, you can see these in GitHub page after. run_tips: failed: Failed to login! first_time_login: First login, continuing with password... @@ -17,6 +23,7 @@ matrix_sync: error: Please check your account, password and network conditions, you can issue in GitHub for any help. manual_sync: start_sync: Room message receiver (as sub thread 'MatrixReceiver') started! + start_tip: Room message receiver reloaded with possible history messages reprinting. stop_sync: Room message receiver stopped! Before next time server startup, it needs to be started manually. start_error: Room message receiver is already running, do not restart it in cases not special such as non-reloading or after stopped! stop_error: Unknown errors happened when stop room message receiver! @@ -38,3 +45,4 @@ matrix_sync: title: "!!msync Command Help" start_command: "!!msync start - Start message sync process. (will automatically start when server startup) " stop_command: "!!msync stop - Stop message sync process. (will automatically stop when server stopped)" + closetip_command: Use !!msync closetip to close the numerous prompts that appear after starting message sync. It is recommended to read and understand them carefully before closing. diff --git a/lang/zh_cn.yml b/lang/zh_cn.yml index 5c4173a..856afdc 100644 --- a/lang/zh_cn.yml +++ b/lang/zh_cn.yml @@ -9,6 +9,12 @@ matrix_sync: on_server_stop: 服务器已关闭,停止消息同步。 on_server_crash: 服务器崩溃或者非正常退出,已停止消息同步,可能出现未知报错。 on_unload: 正在卸载插件,等待消息同步进程退出…… + old_msg_sync: 如果没有报错,现在你可以修改插件配置目录下的settings.json中的"sync_old_msg"项为false,让插件不再同步发送过的旧消息 + old_msg_sync2: 请注意,在消息同步未运行时房间内的聊天消息,不会再发送出来 + old_msg_sync3: 这是一项实验性功能,如果有问题请通过GitHub Issues反馈 + old_msg_sync4: 若有报错,请先修改"sync_old_msg"项为true,待消息接收器正常工作后检查插件配置目录下的token.json是否存在含有有效数据的“next_batch”项,若是则按上面的步骤重新操作即可 + old_msg_sync5: 此提示文本内容较多,若你已经阅读并理解完毕,可以使用!!msync closetip关闭此提示 + on_tip_read: 已关闭提示,后续可在GitHub页面重新查看! run_tips: failed: 登录失败! first_time_login: 首次登录,将使用密码继续…… @@ -17,6 +23,7 @@ matrix_sync: error: 请检查你的账号密码以及网络情况,你可以在GitHub提出issue以获取任何帮助。 manual_sync: start_sync: 已开始接收房间消息!(启动子线程MatrixReceiver) + start_tip: 房间消息接收器开始重载,已发送的历史消息可能会重新输出! stop_sync: 已停止接收房间消息,到下次服务器启动完成前都只能手动重启! start_error: 已在接收房间消息,非重载等特殊情况或手动停止后,不要再次尝试启动! stop_error: 关闭房间消息接收器时发生未知错误! @@ -38,3 +45,4 @@ matrix_sync: title: "!!msync 指令帮助" start_command: "使用!!msync start开始消息同步(服务器启动完成时会自动开始)" stop_command: "使用!!msync stop关闭消息同步(服务端停止运行后会自动关闭)" + closetip_command: "使用!!msync closetip关闭消息同步开始后出现的大量提示,建议认真阅读理解后再关闭" diff --git a/matrix_sync/client.py b/matrix_sync/client.py index f2233eb..bb0e00e 100644 --- a/matrix_sync/client.py +++ b/matrix_sync/client.py @@ -1,3 +1,4 @@ +import asyncio import json import os import sys @@ -22,6 +23,13 @@ def cache_token(resp: LoginResponse): ) # Init Matrix bot. +@new_thread('MatrixInitClient') +def init(): + asyncio.run(init_task()) + +async def init_task(): + await init_client() + async def init_client() -> None: TOKEN_FILE = matrix_sync.config.TOKEN_FILE homeserver = matrix_sync.config.homeserver diff --git a/matrix_sync/config.py b/matrix_sync/config.py index b1e86b5..2587a7d 100644 --- a/matrix_sync/config.py +++ b/matrix_sync/config.py @@ -16,17 +16,19 @@ # Bot manage config. bot_config = { "plugin_enabled": False, - "allow_all_rooms_msg": False + "allow_all_rooms_msg": False, + "sync_old_msg": True } def load_config(): - global config, user_id, password, room_id, room_name, settings, use_token, DATA_FOLDR, TOKEN_FILE, device_id, homeserver, load_tip + global config, user_id, password, room_id, room_name, settings, use_token, DATA_FOLDR, TOKEN_FILE, device_id, homeserver, load_tip, sync_old_msg config = psi.load_config_simple("config.json", account_config) user_id = config["user_id"] password = config["password"] room_id = config["room_id"] room_name = config["room_name"] settings = psi.load_config_simple("settings.json", bot_config) + sync_old_msg = settings["sync_old_msg"] DATA_FOLDER = psi.get_data_folder() tip_path = psi.rtr("matrix_sync.init_tips.config_path") load_tip = f"{tip_path}: {DATA_FOLDER}" diff --git a/matrix_sync/entry.py b/matrix_sync/entry.py index 3164b00..177a261 100644 --- a/matrix_sync/entry.py +++ b/matrix_sync/entry.py @@ -1,14 +1,16 @@ import asyncio import threading +import json import matrix_sync.config import matrix_sync.client import matrix_sync.receiver import matrix_sync.reporter -from matrix_sync.client import init_client +from matrix_sync.client import init from matrix_sync.config import load_config, check_config from matrix_sync.receiver import getMsg -from matrix_sync.reporter import gameMsgFormater, sendMsg +from matrix_sync.reporter import sender +from matrix_sync.token import get_tip_read from mcdreforged.api.all import * # Framwork ver: 2.3.0-1 @@ -26,7 +28,7 @@ def on_load(server: PluginServerInterface, old): if do_unload: server.unload_plugin("matrix_sync") else: - asyncio.run(init_client()) + init() server.register_command( Literal('!!msync') .runs( @@ -38,16 +40,22 @@ def on_load(server: PluginServerInterface, old): lambda src: src.reply(manualSync()) ) ) + # .then( + # Literal('restart') + # .runs( + # lambda src: src.reply(restartSync()) + # ) + # ) .then( - Literal('restart') + Literal('stop') .runs( - lambda src: src.reply(restartSync()) + lambda src: src.reply(stopSync(src)) ) ) .then( - Literal('stop') + Literal('closetip') .runs( - lambda src: src.reply(stopSync(src)) + lambda src: src.reply(closeTip()) ) ) ) @@ -58,14 +66,27 @@ def help() -> RTextList: return RTextList( psi.rtr("matrix_sync.help_tips.title") + "\n", psi.rtr("matrix_sync.help_tips.start_command") + "\n", - psi.rtr("matrix_sync.help_tips.stop_command") + "\n" + psi.rtr("matrix_sync.help_tips.stop_command") + "\n", + psi.rtr("matrix_sync.help_tips.closetip_command") + "\n" ) # Manually run sync processes. def manualSync(): if not tLock.locked(): start_room_msg() - return psi.rtr("matrix_sync.manual_sync.start_sync") + psi.say(psi.rtr("matrix_sync.manual_sync.start_tip")) + read = asyncio.run(get_tip_read()) + if not read: + return RTextList( + psi.rtr("matrix_sync.manual_sync.start_sync") + "\n", + psi.rtr("matrix_sync.old_msg_sync") + "\n", + psi.rtr("matrix_sync.old_msg_sync2") + "\n", + psi.rtr("matrix_sync.old_msg_sync3") + "\n", + psi.rtr("matrix_sync.old_msg_sync4") + "\n", + psi.rtr("matrix_sync.old_msg_sync5") + "\n" + ) + else: + return psi.rtr("matrix_sync.manual_sync.start_sync") else: return psi.rtr("matrix_sync.manual_sync.start_error") @@ -84,10 +105,19 @@ def stopSync(src): else: return psi.rtr("matrix_sync.manual_sync.stop_denied") -# Restart room message receiver, not recommend -def restartSync(): - stopSync() - manualSync() +def closeTip(): + TOKEN_FILE = matrix_sync.config.TOKEN_FILE + with open(TOKEN_FILE, "r") as f: + existing_data = json.load(f) + existing_data["tip_read"] = True + with open(TOKEN_FILE, "w") as f: + json.dump(existing_data, f) + return psi.rtr("matrix_sync.on_tip_read") + +# Restart room message receiver, not recommend. +# def restartSync(src): +# stopSync(src) +# manualSync() # Automatically run sync processes. def on_server_startup(server: PluginServerInterface): @@ -95,7 +125,7 @@ def on_server_startup(server: PluginServerInterface): if not tLock.locked(): if clientStatus: message = psi.rtr("matrix_sync.sync_tips.server_started") - asyncio.run(sendMsg(message)) + sender(message) start_room_msg() else: server.logger.info(server.rtr("matrix_sync.manual_sync.start_error")) @@ -116,11 +146,12 @@ async def on_room_msg(): # Game message reporter def on_user_info(server: PluginServerInterface, info: Info): - gameMsgFormater(server, info) - report = matrix_sync.reporter.report - if report: - gameMsg = matrix_sync.reporter.gameMsg - asyncio.run(sendMsg(gameMsg)) + # formater(server, info) + if info.player is not None and not info.content.startswith("!!"): + playerMsg = f"<{info.player}> {info.content}" + clientStatus = matrix_sync.client.clientStatus + if clientStatus: + sender(playerMsg) # Exit sync process when server stop. def on_server_stop(server: PluginServerInterface, server_return_code: int): @@ -130,13 +161,13 @@ def on_server_stop(server: PluginServerInterface, server_return_code: int): clientStatus = matrix_sync.client.clientStatus stopTip = server.rtr("matrix_sync.sync_tips.server_stopped") if clientStatus: - asyncio.run(sendMsg(stopTip)) + sender(stopTip) else: server.logger.info(server.rtr("matrix_sync.on_server_crash")) crashTip = server.rtr("matrix_sync.sync_tips.server_crashed") clientStatus = matrix_sync.client.clientStatus if clientStatus: - asyncio.run(sendMsg(crashTip)) + sender(crashTip) if sync_task is not None: sync_task.cancel() diff --git a/matrix_sync/receiver.py b/matrix_sync/receiver.py index 95d6ba8..a2d8b49 100644 --- a/matrix_sync/receiver.py +++ b/matrix_sync/receiver.py @@ -1,13 +1,17 @@ # Codes sub thread MatrixReceiver running. import asyncio +import json import matrix_sync.config -from matrix_sync.token import getToken +from matrix_sync.token import getToken, get_next_batch from mcdreforged.api.all import * from nio import AsyncClient, MatrixRoom, RoomMessageText, SyncResponse, SyncError from typing import Optional psi = ServerInterface.psi() +homeserver_online = True +refresh = True +next_batch = None client = None class RoomMessageEvent(PluginEvent): @@ -37,19 +41,34 @@ async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None: if transfer: psi.broadcast(f"{roomMsg}") +def sync_cache(data): + TOKEN_FILE = matrix_sync.config.TOKEN_FILE + with open(TOKEN_FILE, "r") as f: + existing_data = json.load(f) + existing_data["next_batch"] = data + with open(TOKEN_FILE, "w") as f: + json.dump(existing_data, f) + def on_sync_response(response: SyncResponse): - global server_is_online - server_is_online = True + global refresh + if refresh: + next_batch = response.next_batch + sync_cache(next_batch) + refresh = False + else: + pass def on_sync_error(response: SyncError): - global server_is_online + global homeserver_online + psi.logger.error(f"Sync error: {response.status_code}") if response.status_code >= 500: - server_is_online = False + homeserver_online = False async def getMsg() -> None: homeserver = matrix_sync.config.homeserver device_id = matrix_sync.config.device_id user_id = matrix_sync.config.user_id + sync_old_msg = matrix_sync.config.sync_old_msg global client client = AsyncClient(f"{homeserver}") client.access_token = await getToken() @@ -61,7 +80,17 @@ async def getMsg() -> None: client.add_event_callback(message_callback, RoomMessageText) try: - await client.sync_forever(timeout=5) + if homeserver_online: + if sync_old_msg is True: + await client.sync_forever(timeout=5) + else: + next_batch = await get_next_batch() + await client.sync_forever(timeout=5, since=next_batch) + else: + psi.logger.error("Sync failed: homeserver is down or your network disconnected with it.") + psi.logger.info("Use !!msync start after homeserver is running or your network restored.") + except Exception as e: + psi.logger.error(f"Sync error: {e}") except asyncio.CancelledError: await client.close() finally: diff --git a/matrix_sync/reporter.py b/matrix_sync/reporter.py index e31c38d..b96555e 100644 --- a/matrix_sync/reporter.py +++ b/matrix_sync/reporter.py @@ -1,7 +1,4 @@ -import aiofiles -import json -import re -import os +import asyncio import matrix_sync.client import matrix_sync.config @@ -10,34 +7,15 @@ from matrix_sync.token import getToken psi = ServerInterface.psi() -report = False - -def gameMsgFormater(server: PluginServerInterface, info: Info): - # psi.logger.info(psi.rtr("matrix_sync.sync_tips.test")) - # Debug code: Uncomment the above to determine whether game messages have been started to be reported. - TOKEN_FILE = matrix_sync.config.TOKEN_FILE - global gameMsg, report - console_tr = psi.rtr("matrix_sync.tr.cs") - gameMsg = f"<{info.player}> {info.content}" - if info.player is None: - if re.fullmatch(r'say \S*', info.content): - msg_content = '{}'.format(info.content.rsplit(' ', 1)[1]) - gameMsg = f"<{console_tr}> {msg_content}" - else: - option = psi.rtr("matrix_sync.on_console.commands") - gameMsg = f"[!] {console_tr} {option} -> {info.content}" - if info.content == "stop": - gameMsg = psi.rtr("matrix_sync.sync_tips.server_stopping") - else: - if info.content.startswith("!!"): - option = psi.rtr("matrix_sync.on_console.commands") - gameMsg = f"[!] {info.player} {option} -> {info.content}" - report = False - clientStatus = matrix_sync.client.clientStatus - if clientStatus: - report = True # Game Message reporter. +@new_thread('MatrixReporter') +def sender(message): + asyncio.run(send(message)) + +async def send(message): + await sendMsg(message) + async def sendMsg(message) -> None: homeserver = matrix_sync.config.homeserver user_id = matrix_sync.config.user_id @@ -48,10 +26,13 @@ async def sendMsg(message) -> None: client.user_id = user_id client.device_id = device_id - await client.room_send( - room_id, - message_type="m.room.message", - content={"msgtype": "m.text", "body": f"{message}"}, - ) + try: + await client.room_send( + room_id, + message_type="m.room.message", + content={"msgtype": "m.text", "body": f"{message}"}, + ) - await client.close() + await client.close() + except Exception as e: + psi.logger.error(f"Send to matrix error: {e}") diff --git a/matrix_sync/token.py b/matrix_sync/token.py index 113a295..7e7185e 100644 --- a/matrix_sync/token.py +++ b/matrix_sync/token.py @@ -7,4 +7,21 @@ async def getToken(): async with aiofiles.open(TOKEN_FILE, "r") as f: contents = await f.read() cache = json.loads(contents) - return cache["token"] \ No newline at end of file + return cache["token"] + +async def get_next_batch(): + TOKEN_FILE = matrix_sync.config.TOKEN_FILE + async with aiofiles.open(TOKEN_FILE, "r") as f: + contents = await f.read() + cache = json.loads(contents) + return cache["next_batch"] + +async def get_tip_read(): + TOKEN_FILE = matrix_sync.config.TOKEN_FILE + async with aiofiles.open(TOKEN_FILE, "r") as f: + contents = await f.read() + cache = json.loads(contents) + try: + return cache["tip_read"] + except KeyError: + return False diff --git a/mcdreforged.plugin.json b/mcdreforged.plugin.json index 6724f5c..c259145 100644 --- a/mcdreforged.plugin.json +++ b/mcdreforged.plugin.json @@ -1,6 +1,6 @@ { "id": "matrix_sync", - "version": "2.3.0", + "version": "2.3.1", "name": "MatrixSync", "description": { "en_us": "Sync messages between online game and Matrix groups.", diff --git a/subpacks(rolling)/[MSync]AutoReply/mcdreforged.plugin.json b/subpacks(rolling)/[MSync]AutoReply/mcdreforged.plugin.json new file mode 100644 index 0000000..6c3d31e --- /dev/null +++ b/subpacks(rolling)/[MSync]AutoReply/mcdreforged.plugin.json @@ -0,0 +1,15 @@ +{ + "id": "msync_auto_reply", + "version": "0.0.1", + "name": "[MSync]AutoReply", + "description": { + "en_us": "A subpack of MatrixSync, automatically reply messages from room.", + "zh_cn": "MatrixSync的子包,自动回复房间内消息" + }, + "dependencies": { + "mcdreforged": ">=2.1.0", + "matrix_sync": ">=2.3.1" + }, + "author": "Mooling0602", + "link": "https://github.com/Mooling0602/MatrixSync-MCDR" +} \ No newline at end of file diff --git a/subpacks(rolling)/[MSync]AutoReply/msync_auto_reply/__init__.py b/subpacks(rolling)/[MSync]AutoReply/msync_auto_reply/__init__.py new file mode 100644 index 0000000..d3cd5d7 --- /dev/null +++ b/subpacks(rolling)/[MSync]AutoReply/msync_auto_reply/__init__.py @@ -0,0 +1,18 @@ +import matrix_sync.config +import matrix_sync.client + +from mcdreforged.api.all import * +from matrix_sync.reporter import sender + +def on_load(server: PluginServerInterface, old): + server.logger.info("[MSync]AutoReply loaded.") + server.register_event_listener('MatrixRoomMessage', main) + +def main(server: PluginServerInterface, message: str, sender: str): + user_id = matrix_sync.config.user_id + if not sender == user_id: + if message == "服务器连接信息": + clientStatus = matrix_sync.client.clientStatus + if clientStatus: + sender("服务器名称:星块服务器\n地址:play.staringplanet.top\n* 已进行SRV解析,Java版无需添加端口\n端口:21152") + server.logger.info("解析到指定内容,已自动发送回复") diff --git a/subpacks(rolling)/[MSync]MoreMessages/MSync.MoreMessages.mcdr b/subpacks(rolling)/[MSync]MoreMessages/MSync.MoreMessages.mcdr new file mode 100644 index 0000000..f660268 Binary files /dev/null and b/subpacks(rolling)/[MSync]MoreMessages/MSync.MoreMessages.mcdr differ diff --git a/subpacks(rolling)/[MSync]MoreMessages/mcdreforged.plugin.json b/subpacks(rolling)/[MSync]MoreMessages/mcdreforged.plugin.json new file mode 100644 index 0000000..9dbffdd --- /dev/null +++ b/subpacks(rolling)/[MSync]MoreMessages/mcdreforged.plugin.json @@ -0,0 +1,15 @@ +{ + "id": "msync_more_msg", + "version": "0.0.1", + "name": "[MSync]MoreMessages", + "description": { + "en_us": "A subpack of MatrixSync, transfer more kinds of messages from the game.", + "zh_cn": "MatrixSync的子包,转发更多类型的游戏消息。" + }, + "dependencies": { + "mcdreforged": ">=2.1.0", + "matrix_sync": ">=2.3.1" + }, + "author": "Mooling0602", + "link": "https://github.com/Mooling0602/MatrixSync-MCDR" +} \ No newline at end of file diff --git a/subpacks(rolling)/[MSync]MoreMessages/msync_more_msg/__init__.py b/subpacks(rolling)/[MSync]MoreMessages/msync_more_msg/__init__.py new file mode 100644 index 0000000..a359dc7 --- /dev/null +++ b/subpacks(rolling)/[MSync]MoreMessages/msync_more_msg/__init__.py @@ -0,0 +1,34 @@ +import re + +from matrix_sync.reporter import sender +from mcdreforged.api.all import * + +psi = ServerInterface.psi() + +def on_load(server: PluginServerInterface, old): + server.logger.info("Subpack of MatrixSync: [Msync]MoreMessages loaded.") + +def on_user_info(server: PluginServerInterface, info: Info): + formatter(info) + if gameMsg is not None: + sender(gameMsg) + + +def formatter(info: Info): + global gameMsg + console_tr = psi.rtr("matrix_sync.tr.cs") + if info.player is None: + if re.fullmatch(r'say \S*', info.content): + msg_content = '{}'.format(info.content.rsplit(' ', 1)[1]) + gameMsg = f"<{console_tr}> {msg_content}" + else: + option = psi.rtr("matrix_sync.on_console.commands") + gameMsg = f"[!] {console_tr} {option} -> {info.content}" + if info.content == "stop": + gameMsg = psi.rtr("matrix_sync.sync_tips.server_stopping") + else: + if info.content.startswith("!!"): + option = psi.rtr("matrix_sync.on_console.commands") + gameMsg = f"[!] {info.player} {option} -> {info.content}" + else: + return None \ No newline at end of file diff --git a/subpacks(rolling)/[MSync]PlayingTips/MSync.PlayingTips.mcdr b/subpacks(rolling)/[MSync]PlayingTips/MSync.PlayingTips.mcdr new file mode 100644 index 0000000..e0d3a9b Binary files /dev/null and b/subpacks(rolling)/[MSync]PlayingTips/MSync.PlayingTips.mcdr differ diff --git a/subpacks(rolling)/[MSync]PlayingTips/mcdreforged.plugin.json b/subpacks(rolling)/[MSync]PlayingTips/mcdreforged.plugin.json index 97b62ae..9c30315 100644 --- a/subpacks(rolling)/[MSync]PlayingTips/mcdreforged.plugin.json +++ b/subpacks(rolling)/[MSync]PlayingTips/mcdreforged.plugin.json @@ -8,7 +8,7 @@ }, "dependencies": { "mcdreforged": ">=2.1.0", - "matrix_sync": ">=2.0.2" + "matrix_sync": ">=2.3.1" }, "author": "Mooling0602", "link": "https://github.com/Mooling0602/MatrixSync-MCDR" diff --git a/subpacks(rolling)/[MSync]PlayingTips/msync_playing_tips/__init__.py b/subpacks(rolling)/[MSync]PlayingTips/msync_playing_tips/__init__.py index 537df00..d29986e 100644 --- a/subpacks(rolling)/[MSync]PlayingTips/msync_playing_tips/__init__.py +++ b/subpacks(rolling)/[MSync]PlayingTips/msync_playing_tips/__init__.py @@ -1,17 +1,28 @@ import matrix_sync.client -import asyncio -from matrix_sync.reporter import sendMsg +import re +from matrix_sync.reporter import sender from mcdreforged.api.all import * def on_load(server: PluginServerInterface, old): - server.logger.info("Subpack of MatrixSync: playing_tips loaded.") + server.logger.info("Subpack of MatrixSync: [MSync]PlayingTips loaded.") def on_player_joined(server: PluginServerInterface, player: str, info: Info): tip = f"[+]{player}" if matrix_sync.client.clientStatus: - asyncio.run(sendMsg(tip)) + sender(tip) def on_player_left(server: PluginServerInterface, player: str): tip = f"[-]{player}" if matrix_sync.client.clientStatus: - asyncio.run(sendMsg(tip)) \ No newline at end of file + sender(tip) + +def on_info(server: PluginServerInterface, info: Info): + if info.is_from_server and re.fullmatch(r'(.+) issued server command: (.+)', info.content): + match = re.fullmatch(r'(.+) issued server command: (.+)', info.content) + if match: + player = match.group(1) + command = match.group(2) + server.say(f"* {player} 执行游戏指令 -> {command}") + clientStatus = matrix_sync.client.clientStatus + if clientStatus: + sender(f"* {player} 执行游戏指令 -> {command}")