Skip to content

Commit

Permalink
Merge pull request #9 from Mooling0602/2.3.1
Browse files Browse the repository at this point in the history
Update to v2.3.1
  • Loading branch information
Mooling0602 authored Oct 18, 2024
2 parents 28fbd43 + 8f3d40e commit 9196e9e
Show file tree
Hide file tree
Showing 21 changed files with 280 additions and 83 deletions.
Binary file added MatrixSync-v2.3.1.mcdr
Binary file not shown.
29 changes: 24 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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文件夹里面即可。
Expand Down Expand Up @@ -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 ...
Expand Down Expand Up @@ -121,13 +120,31 @@ 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)及消息互通控制
插件默认在游戏服务端启动完成时才会自动启动房间消息接收进程,重新加载插件后,消息接收器并不会自动启动。

要手动启动房间消息接收进程,请执行MCDR命令`!!msync start`,游戏内和控制台上都可以使用。

要关闭房间消息接收进程,可以在控制台使用`!!msync stop`,直到下次服务器启动完成前消息接收器都必须手动重启。

要在详细阅读后关闭2.3.1版本新增的大量提示,可以使用`!!msync closetip`,目前想重新查看提示,只能在源码中查看语言文件,或自行修改token.json

插件会自动在解析到游戏内的消息时尝试转发到配置好的Matrix房间内,暂时无法禁用。

该指令没有权限要求,但设置了进程锁(安全机制),重复执行会警告提示,不会影响插件功能的正常运行。
Expand All @@ -136,5 +153,7 @@ async def main():

## 注意
- 首次加载插件的时候,插件将自动初始化配置并卸载自己。你需要正确修改默认的配置文件,并在settings.json中启用plugin_enabled配置项以启用插件,然后重启服务器或着重载插件以正常使用。
- 不打算支持加密信息(EE2E),有需要可以二次开发修改插件,也欢迎PR。

- 不打算支持加密信息(EE2E),有需要可以二次开发修改插件,欢迎PR。

- 多语言目前只支持中文(简体)和英语(用谷歌和ChatGPT从中文翻译),任何人都可以联系我帮助完善翻译,欢迎PR到/lang语言文件中。
7 changes: 4 additions & 3 deletions README_en_us.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
[framework]
ver=1
[main]
ver=2.3.0
ver=2.3.1
[release]
test=0
test=1
8 changes: 8 additions & 0 deletions lang/en_us.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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...
Expand All @@ -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!
Expand All @@ -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.
8 changes: 8 additions & 0 deletions lang/zh_cn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: 首次登录,将使用密码继续……
Expand All @@ -17,6 +23,7 @@ matrix_sync:
error: 请检查你的账号密码以及网络情况,你可以在GitHub提出issue以获取任何帮助。
manual_sync:
start_sync: 已开始接收房间消息!(启动子线程MatrixReceiver)
start_tip: 房间消息接收器开始重载,已发送的历史消息可能会重新输出!
stop_sync: 已停止接收房间消息,到下次服务器启动完成前都只能手动重启!
start_error: 已在接收房间消息,非重载等特殊情况或手动停止后,不要再次尝试启动!
stop_error: 关闭房间消息接收器时发生未知错误!
Expand All @@ -38,3 +45,4 @@ matrix_sync:
title: "!!msync 指令帮助"
start_command: "使用!!msync start开始消息同步(服务器启动完成时会自动开始)"
stop_command: "使用!!msync stop关闭消息同步(服务端停止运行后会自动关闭)"
closetip_command: "使用!!msync closetip关闭消息同步开始后出现的大量提示,建议认真阅读理解后再关闭"
8 changes: 8 additions & 0 deletions matrix_sync/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import json
import os
import sys
Expand All @@ -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
Expand Down
6 changes: 4 additions & 2 deletions matrix_sync/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
73 changes: 52 additions & 21 deletions matrix_sync/entry.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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(
Expand All @@ -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())
)
)
)
Expand All @@ -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")

Expand All @@ -84,18 +105,27 @@ 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):
clientStatus = matrix_sync.client.clientStatus
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"))
Expand All @@ -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):
Expand All @@ -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()
Expand Down
Loading

0 comments on commit 9196e9e

Please sign in to comment.