Skip to content

Commit

Permalink
Update to v2.4.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooling0602 committed Dec 15, 2024
1 parent 70b7e2b commit 0cf5eed
Show file tree
Hide file tree
Showing 15 changed files with 138 additions and 150 deletions.
49 changes: 15 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
- 中文
- [English](https://github.com/Mooling0602/MatrixSync-MCDR/blob/main/README_en_us.md)
> 为避免合并入主分支后链接指向错误,URL一律使用主分支的地址。如果你正在访问其他分支,请注意自行定位链接跳转位置。
# MatrixSync-MCDR
一个MCDR(全称[MCDReforged](https://mcdreforged.com/))插件,用于同步Matrix群组和《我的世界》服务器的线上游戏之间的消息。
Expand All @@ -8,8 +9,6 @@

开发过程中用到的pypi项目:[matrix-nio](https://pypi.org/project/matrix-nio/)

当前分支版本:主分支@2.4.0

## 用法
从release下载最新版本,在MCDReforged的启动环境中安装好需要的Python依赖,然后扔到plugins文件夹里面即可。

Expand All @@ -19,32 +18,23 @@

若消息同步的过程中有任意方向的消息转发出现问题,也请按配置文件部分的内容检查配置是否正确。

### 使用 Git 从源码打包插件
> This part doesn't support English yet, please use translate tools at present.
>
> 依赖软件包`zip`
>
> 在终端上运行`git clone https://github.com/Mooling0602/MatrixSync-MCDR.git`,然后进入`MatrixSync-MCDR`目录下并运行`pack_plugin.sh`(记得给文件设置可执行权限)
>
> 若无法正常访问GitHub,可以运行`git clone https://mirror.ghproxy.com/https://github.com/Mooling0602/MatrixSync-MCDR.git`
>
> 懒人用命令:`git clone https://mirror.ghproxy.com/https://github.com/Mooling0602/MatrixSync-MCDR.git && cd MatrixSync-MCDR && chmod +x pack_plugin.sh && ./pack_plugin.sh`
>
> 打包脚本所用配置(config.ini)中的ci部分为主插件和配套子包的构建开关,设置为1即可打开,脚本运行后将生成打包好的插件,其中子包的构建在`subpack(rolling)/[MSync]*/内(如果开发完成),主插件的构建在主目录。
### 配置文件
#### config.json

| 配置项 | 配置内容 |
| - | - |
| **homeserver** | 机器人账号登录所使用的根服务器 |
| **homeserver** | 机器人账号所属的根服务器 |
| **user_id** | 机器人的账号ID,格式为@<用户名>:<根服务器>,如@mcchatbot:example.com |
| **password** | 机器人账号的密码,仅在初次登录使用 |
| **room_id** | 需要接收游戏消息的房间的ID |
| **password** | 机器人账号的密码,在初次登录和重新生成token时使用 |
| **room_id** | 需要接收游戏消息的房间的ID,使用管理员权限在房间设置中查看 |
| **room_name** | 需要转发消息到游戏内的房间的显示名称(必须准确无误,若发生更新也需要同步修改,否则你将看不到任何消息) |
| **device_id** | 登录用的设备名,一般无需修改,可自定义 |

> 目前只支持单账号和单聊天房间(相当于QQ群),计划在v3版本以后开放多配置接口支持。
> 只支持单账号和单聊天房间(相当于QQ群),计划在v3版本以后开发多配置管理。
>
> v2 LTS 即将推出,如果你不需要多账号、多房间管理,可以持续使用v2版本。
>
> v2 LTS 推送将于v2.5.x进行,届时会对当前的配置文件格式进行修改,可能和之前完全不兼容,请注意。
#### settings.json

Expand All @@ -66,31 +56,22 @@ from matrix_sync.reporter import send_matrix

def main():
message = "你要发送的消息"
clientStatus = matrix_sync.client.clientStatus
if clientStatus:
send_matrix(message)
send_matrix(message)

# 消息将在独立线程MatrixReporter中被发送到Matrix,不再可能会阻塞MCDR主线程
# 如果消息没有发送到Matrix,启用MCDR配置中的`debug.plugin`,会显示详情
```

## 热重载(reload)及消息互通控制
插件默认在游戏服务端启动完成时自动启动房间消息接收进程,在游戏服务端关闭后自动关闭房间消息接收进程。

要手动启动房间消息接收器(例如重载插件后的场景),请执行MCDR命令`!!msync start`,游戏内和控制台上都可以使用。

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

插件会自动在解析到游戏内的消息时尝试转发到配置好的Matrix房间内,暂时无法禁用,将于v2.4.0以后版本(v2.4.x)中通过和房间消息接收器同步开闭状态的方式解决。

该指令没有权限要求,但设置了进程锁(安全机制),重复执行会警告提示,不会影响插件功能的正常运行。
始终建议在运行环境稳定时,尽量不使用热重载。

请注意,该功能仍然是不稳定的,若发现任何错误请及时通过GitHub Issue向插件作者反馈。另外,重载插件前尽量先关闭房间消息接收器,否则可能无法清楚残留进程,导致只能重启整个MCDR解决!
现在Matrix消息的收发已经实现同步,使用`!!msync`查看帮助。

建议在运行环境稳定时,尽量不使用热重载。
服务器启动完成后,插件会自动启动Minecraft游戏服务器和Matrix之间的消息互通,暂时不能对消息的收发方向进行配置。(将于2.5.x继续改善)

## 注意
### 关于首次使用
首次加载插件的时候,插件将自动初始化配置并卸载自己。你需要正确修改默认的配置文件,并在settings.json中启用plugin_enabled配置项以启用插件,然后重启服务器或着重载插件以正常使用。若选择后一个方案,在插件重载后如果服务器已启动完毕,你可以使用`!!msync start`启动房间消息接收器,使Matrix的消息转发到游戏内。另外,只要插件成功加载没有出现问题,游戏内的消息将始终自动转发到Matrix的房间,将在v2.4.0以上版本中改为和房间消息接收器同步
首次加载插件的时候,插件将自动初始化配置并卸载自己。你需要正确修改默认的配置文件,并在settings.json中启用plugin_enabled配置项以启用插件,然后重载插件以正常使用

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

Expand Down
21 changes: 5 additions & 16 deletions README_en_us.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
- [中文](https://github.com/Mooling0602/MatrixSync-MCDR/blob/main/README.md)
- English
> To avoid incorrect links after merging into the main branch, all URLs should use the main branch's address. If you are accessing other branches, please make sure to manually adjust the link's target location.
# MatrixSync-MCDR
A MCDR (full name [MCDReforged](https://mcdreforged.com/)) plugin, use to sync messages between Matrix groups and online gaming in Minecraft servers.
Expand All @@ -10,8 +11,6 @@ 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: [email protected]

## 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 All @@ -26,7 +25,7 @@ If there is any issue with message forwarding in any direction during the messag

| Configuration Item | Content |
| - | - |
| **homeserver** | The home server used to log in to the bot account |
| **homeserver** | The homeserver address used to log in to the bot account |
| **user_id** | The bot account ID, formatted as @username:example.com |
| **password** | The password of the bot account, generally only used for the initial login |
| **room_id** | The ID of the room to receive game messages |
Expand All @@ -43,23 +42,13 @@ Multi-config is not supported, will add API support for developers from v3.
| sync_old_msg | Whether to sync old messages, enabled on default, disable to see old messages when plugin is just loaded |

## Interface (API)
See "接口(API)" [中文](https://github.com/Mooling0602/MatrixSync-MCDR/blob/README.md) README.
See the docs in [中文文档](https://github.com/Mooling0602/MatrixSync-MCDR/blob/docs.md) at present.

## Hot Reload (reload) & message sync control
By default, the plugin automatically starts the room message reception process when the game server starts and automatically stops the process when the game server shuts down.

To manually start the room message receiver (e.g., after reloading the plugin), execute the MCDR command !!msync start, which can be used both in-game and in the console.

To stop the room message receiver in advance, you can use !!msync stop in the console. The message receiver must be manually restarted with !!msync start before the next server startup.

The plugin will automatically attempt to forward in-game messages to the configured Matrix room when parsing them. This feature cannot be disabled at the moment but will be resolved in version 2.4.0 (v2.4.x) by syncing the open/close status with the room message receiver.

This command has no permission requirements but is protected by a process lock (security mechanism). Repeated execution will trigger a warning but will not affect the normal operation of the plugin.

Please note that this feature is still unstable. If any errors occur, please report them promptly via GitHub Issues to the plugin author. Additionally, before reloading the plugin, it's recommended to close the room message receiver, as failing to do so may leave residual processes that could only be cleared by restarting the entire MCDR.

It is advisable not to use hot reload in a stable environment.

Execute `!!msync` to see the usage.

## Note
### First-time Use
When loading the plugin for the first time, the plugin will automatically initialize the configuration and then unload itself. You need to correctly modify the default configuration file and enable the plugin_enabled option in settings.json to activate the plugin. Then, restart the server or reload the plugin for proper use. If you choose the latter, after reloading the plugin, if the server has finished starting, you can use !!msync start to start the room message receiver, enabling Matrix message forwarding to the game. Furthermore, as long as the plugin is successfully loaded without issues, in-game messages will always be automatically forwarded to the Matrix room. This will be synchronized with the room message receiver in versions above 2.4.0.
Expand Down
2 changes: 1 addition & 1 deletion config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ ver=3
[main]
ver=2.4.1
[release]
test=1
test=0
[ci]
plugin=1
File renamed without changes.
File renamed without changes.
18 changes: 5 additions & 13 deletions docs.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
- 中文
- English (Unsupported yet, please use translate tools.)
- English (Unsupported yet, please use translate tools at present.)

# MatrixSync-MCDR 文档
这里是MCDReforged插件MatrixSync的文档
这里是MCDReforged插件MatrixSync的API文档

插件配置部分仍保留在README。

Expand All @@ -23,20 +23,12 @@ def main():
message = "你要发送的消息"
send_matrix(message)
```
目前仍无法获取发送结果,但如果主插件在加载时没有成功初始化客户端,你可以通过以下方式获取到相关报错:
```python
import ...
from matrix_sync.reporter import sender
目前发送结果可以通过启用MCDR配置中的debug.plugin项获取。

def main():
response = send_matrix(message)
if response is not None:
print(response)
```
> 在MCDR中,常用`server.logger.info``psi.logger.info`代替`print`,以进行更标准化的日志格式输出。
### 旧版接口(v2.2-)
旧版接口含有较大缺陷(会阻塞MCDR主线程,消息发不出去等故障情况将导致MCDR卡死),且已不具备实用的应用场景,但仍然可用。
旧版接口具有体验问题和潜在错误(会阻塞MCDR主线程,消息发不出去等故障情况将导致MCDR卡死),且一般情况下已不具备实用的应用场景,但仍然可用。
```python
import ...
import asyncio
Expand All @@ -58,4 +50,4 @@ async def async_main():

任何情况下,都不要再尝试使用这个接口!

另外,建议停止使用v2.3.x版本
另外,建议马上停止使用v2.3.x版本,如果你正在使用!
16 changes: 9 additions & 7 deletions lang/en_us.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ matrix_sync:
config_path: Config path
need_edit_config: Please edit the default config.json to the correct configuration information, and then restart the plugin after enabling the plugin_enabled item in settings.json!
read_config: Applying precent config, please waiting...
hotload_tip: If reloading plugin needs to enable message sync manually, to transfer messages from matrix to the game, please execute `!!msync start`
user_mismatch: Detected wrong bot account with token cached, please delete token.json in config path of plugin, or use bot account match token cached!
do_unload: Plugin will be unloaded, please reload manually after you're done.
user_mismatch: Detected token cached mismatch present bot account (%user_id%), please delete token or use correct bot account!
do_unload: Plugin is unloading, please reload manually after you configured right.
on_console:
commands: Excute command
on_server_stop: Server stopped, stopping messages sync.
Expand Down Expand Up @@ -44,7 +43,10 @@ matrix_sync:
ac: Account
cs: Console
help_tips:
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.
message: "See command help page for §7!!msync§r "
title: "----- MatrixSync command help page -----"
root_command: "§7!!msync §rShow this help page"
start_command: "§7!!msync start §rStart message sync(Auto executes when server startup.)"
stop_command: "§7!!msync stop §rStop message sync(Auto stops when server exit.)"
send_command: "§7!!msync send §rSend a text message to the matrix room, can be quote by \"\" if spaces are included in the text."
status_command: "§7!!msync status §rSee the present status of message sync"
14 changes: 8 additions & 6 deletions lang/zh_cn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ matrix_sync:
config_path: 配置文件所在目录
need_edit_config: 请将默认配置config.json修改为正确的配置信息,然后启用settings.json中的plugin_enabled项后重启插件!
read_config: 正在应用当前配置,请稍等……
hotload_tip: 若重载插件需要手动开启消息同步,以将Matrix的消息转发到游戏中,请执行!!msync start
user_mismatch: 检测到当前配置的机器人账号和token缓存不符,请删除插件配置目录下的token.json或使用与token缓存相符的机器人账号!
user_mismatch: 检测到当前配置的机器人账号(%user_id%)与缓存的token不符,请删除当前token.json或使用正确的账号!
do_unload: 插件将卸载,请在处理完成后手动重载插件!
on_console:
commands: 执行命令
Expand Down Expand Up @@ -44,7 +43,10 @@ matrix_sync:
ac: 账户
cs: 控制台
help_tips:
title: "!!msync 指令帮助"
start_command: "!!msync start - 开始消息同步(服务器启动完成时会自动开始)"
stop_command: "!!msync stop - 关闭消息同步(服务端停止运行后会自动关闭)"
closetip_command: "!!msync closetip - 关闭消息同步开始后出现的大量提示,建议认真阅读理解后再关闭"
message: "查看指令 §7!!msync §r的帮助"
title: "----- MatrixSync 指令帮助 -----"
root_command: "§7!!msync §r显示此帮助页面"
start_command: "§7!!msync start §r开始消息同步(服务器启动完成时会自动开始)"
stop_command: "§7!!msync stop §r关闭消息同步(服务端停止运行后会自动关闭)"
send_command: "§7!!msync send §r向Matrix房间发送指定消息,若含有空格请使用\"\"括起来"
status_command: "§7!!msync status §r查看当前消息同步状态"
26 changes: 18 additions & 8 deletions matrix_sync/entry.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time

from typing import Optional
from .utils import tr
from .client import init
from .config import load_config, check_config
Expand All @@ -9,7 +10,7 @@
from mcdreforged.api.all import *


# Framwork ver: 2.4.1-3
# Framwork ver: 2.4.1
def on_load(server: PluginServerInterface, prev_module):
load_config()
from .config import load_tip
Expand All @@ -21,17 +22,22 @@ def on_load(server: PluginServerInterface, prev_module):
else:
init()
plugin_command(server)
server.logger.info(tr("init_tips.hotload_tip"))
if server.is_server_startup():
start_sync()

# Automatically run sync processes.
def on_server_startup(server: PluginServerInterface):
def start_sync(on_reload: Optional[bool] = True):
if not globals.tLock.locked():
message = tr("sync_tips.server_started")
start_room_msg()
time.sleep(1)
send_matrix(message)
if not on_reload:
time.sleep(1)
message = tr("sync_tips.server_started")
send_matrix(message)
else:
server.logger.info(tr("manual_sync.start_error"))
psi.logger.info(tr("manual_sync.start_error"))

def on_server_startup(server: PluginServerInterface):
start_sync(False)

# Game message reporter
def on_user_info(server: PluginServerInterface, info: Info):
Expand All @@ -48,7 +54,11 @@ def on_server_stop(server: PluginServerInterface, server_return_code: int):
server.logger.info(tr("on_server_crash"))
exit_message = tr("sync_tips.server_crashed")

send_matrix(exit_message)
# 鉴于有用户反馈关服时消息发送不到Matrix,这里卡一个协程用于发送
# 为了防止卡住MCDR主线程出现无响应提示影响用户体验,一般都在子线程中发送消息,但是直接用协程正常情况下也没啥问题
# 有bug的话应该会有人在issues提出,暂时先这么解决
from .reporter import sendMsg
asyncio.run(sendMsg(exit_message))

globals.cleaned = True

Expand Down
12 changes: 7 additions & 5 deletions matrix_sync/receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import matrix_sync.config

from .utils.token import getToken
from .utils import psi, plgSelf
from .utils import psi, plgSelf, tr
from mcdreforged.api.event import PluginEvent
from nio import AsyncClient, MatrixRoom, RoomMessageText, SyncError
from typing import Optional
Expand Down Expand Up @@ -50,9 +50,11 @@ async def getMsg() -> None:
user, token = await getToken()
client.access_token = token
if user != user_id:
psi.logger.error("检测到当前配置的机器人账号和token缓存不符,请删除插件配置目录下的token.json或使用与token缓存相符的机器人账号!")
psi.logger.info("插件将卸载,请在处理完成后手动重载插件!")
psi.unload_plugin(plgSelf.id)
if user is not None:
tip = tr("init_tips.user_mismatch")
psi.logger.error(tip.replace("%user_id%", user_id))
psi.logger.info(tr("init_tips.do_unload"))
psi.unload_plugin(plgSelf.id)
else:
client.user_id = user_id
client.device_id = device_id
Expand All @@ -69,7 +71,7 @@ async def getMsg() -> None:
await client.sync_forever(timeout=5)
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.")
psi.logger.info("Use §7!!msync start §rafter homeserver is running or your network restored.")
except Exception as e:
psi.logger.error(f"Sync error: {e}")
except asyncio.CancelledError:
Expand Down
3 changes: 2 additions & 1 deletion matrix_sync/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ async def sendMsg(message) -> None:
user, token = await getToken()
client.access_token = token
if user != user_id:
psi.logger.error(tr("init_tips.user_mismatch"))
tip = tr("init_tips.user_mismatch")
psi.logger.error(tip.replace("%user_id%", user_id))
psi.logger.info(tr("init_tips.do_unload"))
psi.unload_plugin(plgSelf.id)
else:
Expand Down
Loading

0 comments on commit 0cf5eed

Please sign in to comment.