Skip to content

Commit

Permalink
Update to 2.5.0-3, improved i18n
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooling0602 committed Dec 22, 2024
1 parent 4633c67 commit 10e2d7e
Show file tree
Hide file tree
Showing 17 changed files with 140 additions and 131 deletions.
2 changes: 1 addition & 1 deletion README_en_us.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ About [Matrix](https://matrix.org/): an open decentralized network communication

The following project is used in the development process: [matrix-nio](https://pypi.org/project/matrix-nio/).

v2.5.0+ need new translations, but not prepared yet, you can use translation tools to read "中文" README at present. I would be grateful if you could help translation by commit PRs.
README v2.5.0+ need new translations, but not prepared yet, you can use translation tools to read "中文" README at present. I would be grateful if you could help translation by commit PRs.
5 changes: 2 additions & 3 deletions config.ini
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Do not edit this file!
# 不要修改这个文件!
# Ci configuration for GitHub Actions.
[framework]
ver=2
ver=3
[main]
ver=2.5.0
[release]
Expand Down
45 changes: 3 additions & 42 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,8 @@
插件配置部分仍保留在README。

## 接口(API)
这里介绍插件提供的内部接口
这里介绍插件提供的接口

### 新版接口(v2.4.0)
2.4.0版本以后,插件完善了已有的消息上报器(MC -> Matrix)接口。
从v2.5.0起,插件重构了内部所有的API,并且不再支持MCDReforged未达到v2.14的版本。

简单用法:
```python
import ...
from matrix_sync.reporter import send_matrix

def main():
# 若message为MCDR.ServerInterface.rtr(),你需要将其转换为str类型,或改用MCDR.ServerInterface.tr(),否则会发生错误。
# 该问题的产生原因未知,暂时无法解决。
message = "你要发送的消息"
send_matrix(message)
```
目前发送结果可以通过启用MCDR配置中的debug.plugin项获取。

> 在MCDR中,常用`server.logger.info``psi.logger.info`代替`print`,以进行更标准化的日志格式输出。
### 旧版接口(v2.2-)
旧版接口具有体验问题和潜在错误(会阻塞MCDR主线程,消息发不出去等故障情况将导致MCDR卡死),且一般情况下已不具备实用的应用场景,但仍然可用。
```python
import ...
import asyncio
from matrix_sync.reporter import sendMsg

def main():
message = "你要发送的消息"
asyncio.run(sendMsg(message))

# 或者使用协程,如果你的插件会用到的话
async def async_main():
message = "你要发送的消息"
await sendMsg(message)
```
如果你的插件会使用独立的线程运行相关任务,则旧版接口仍然稳定有效。

### 废弃接口(v2.3.x)
即新版接口中这一部分:`from matrix_sync.reporter import send_matrix`,v2.3.x时曾为`sender()`,后发现和派发的Matrix消息事件中的`sender`(Matrix消息发送者)冲突,因此无法兼容,故废弃。

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

另外,建议马上停止使用v2.3.x版本,如果你正在使用!
> 待插件进入LTS推送阶段后,将完善文档内容。目前尚处于开发阶段,暂停更新。
19 changes: 19 additions & 0 deletions lang/en_us.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
matrix_sync:
check_config: Please recheck your config, if you confirm it's correct, issue this in GitHub.
login:
failed: Failed to login your bot
success: Login by password successfully!
save_token: Saving token for the bot account...
on_receiver_cancelled: Receiver task was cancelled.
on_sync_running: Already running message sync!
on_sync_start: Starting message sync...
on_unload: Unloading MatrixSync...
server_status:
starting: MC server is starting...
on_startup: MC server started!
on_stop: MC server stopped.
on_crash: MC server crashed!
sync_status:
running: MSync is running...
not_running: MSync is not running.
token_mismatch: The token mismatches present bot account! Sync tasks will not continue.
19 changes: 19 additions & 0 deletions lang/zh_cn.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
matrix_sync:
check_config: 请重新检查你的配置,如果你确信其准确无误,请前往GitHub Issues页面反馈相关问题!
login:
failed: 无法登录你的机器人
success: 成功使用密码完成登录!
save_token: 正在为机器人账号保存Token...
on_receiver_cancelled: 接收器任务已经取消。
on_sync_running: 消息同步已在运行!
on_sync_start: 开始消息同步...
on_unload: 正在卸载 MatrixSync...
server_status:
starting: MC服务器启动中...
on_startup: MC服务器启动完成!
on_stop: MC服务器已关闭
on_crash: MC服务器发生崩溃!
sync_status:
running: "[MSync] 消息同步正在运行..."
not_running: "[MSync] 消息同步未在运行!"
token_mismatch: Token和现有的账号不匹配!同步任务将不会继续进行。
8 changes: 4 additions & 4 deletions matrix_sync/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ def get_homeserver(url: str):
return correct_url

async def get_client_instance():
import matrix_sync.globals as globals
homeserver = get_homeserver(globals.config["homeserver"])
user = globals.config["user_id"]
device_id = globals.config["device_id"]
import matrix_sync.plg_globals as plg_globals
homeserver = get_homeserver(plg_globals.config["homeserver"])
user = plg_globals.config["user_id"]
device_id = plg_globals.config["device_id"]
client_instance = AsyncClient(homeserver, user, device_id)
user, token = await getToken()
client_instance.access_token = token
Expand Down
28 changes: 14 additions & 14 deletions matrix_sync/client/init.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import sys
import aiofiles
import matrix_sync.globals as globals
import matrix_sync.plg_globals as plg_globals

from . import *
from ..utils.logger import *
Expand All @@ -12,32 +12,32 @@
async def cache_token(resp: LoginResponse):
async with aiofiles.open(f"{configDir}/token.json", "w") as f:
await f.write(json.dumps({
"user_id": globals.config["user_id"],
"user_id": plg_globals.config["user_id"],
"token": resp.access_token
}))

async def login_by_password():
client = AsyncClient(
get_homeserver(globals.config["homeserver"]),
globals.config["user_id"],
globals.config["device_id"]
get_homeserver(plg_globals.config["homeserver"]),
plg_globals.config["user_id"],
plg_globals.config["device_id"]
)
resp = await client.login(globals.config["password"], device_name=globals.config["device_id"])
resp = await client.login(plg_globals.config["password"], device_name=plg_globals.config["device_id"])
if isinstance(resp, LoginResponse):
log_info("Login by password successfully!")
log_info(tr("login.success"))
await cache_token(resp)
log_info("Saving token of the bot account.")
log_info(tr("login.save_token"))
else:
log_error(f"Failed to login your bot: {resp}")
homeserver = get_homeserver(globals.config["homeserver"])
log_info(f'homeserver: "{homeserver}", bot: "{globals.config["user_id"]}"')
log_error("Please check your config, if you confirm it's correct, issue this in GitHub.")
log_error(f"{tr("login.failed")}: {resp}")
homeserver = get_homeserver(plg_globals.config["homeserver"])
log_info(f'homeserver: "{homeserver}", bot: "{plg_globals.config["user_id"]}"')
log_error(tr("check_config"))
sys.exit(1)

async def check_token() -> bool:
user, token = await getToken()
if user != globals.config["user_id"]:
log_error("The token mismatches present bot account!")
if user != plg_globals.config["user_id"]:
log_error(tr("token_mismatch"))
return False
else:
return True
45 changes: 26 additions & 19 deletions matrix_sync/client/receiver.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# thread MatrixReceiver
import asyncio
import matrix_sync.globals as globals
import matrix_sync.plg_globals as plg_globals

from . import *
from .init import check_token
Expand All @@ -16,15 +16,15 @@
receiver = None

async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None:
message_format = globals.settings["message_format"]["all_room"]
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 == globals.config["user_id"]:
if not event.sender == plg_globals.config["user_id"]:
# Apply settings config
if not globals.settings["sync"]["all_rooms"]:
message_format = globals.settings["message_format"]["single_room"]
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.display_name)
event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room.room_id)
log_info(room_message, "Message")
psi.say(room_message)

Expand All @@ -36,40 +36,46 @@ def on_sync_error(response: SyncError):

async def get_messages() -> None:
global receiver
client = AsyncClient(homeserver=get_homeserver(globals.config["homeserver"]))
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 = globals.config["user_id"]
client.user_id = plg_globals.config["user_id"]
client.access_token = token
client.device_id = globals.config["device_id"]
client.device_id = plg_globals.config["device_id"]

if not globals.settings["sync"]["all_rooms"]:
if not plg_globals.settings["listen"]["all_rooms"]:
log_info("ok.")
cfg_room_id = globals.config["room_id"]
log_info(cfg_room_id)
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)

client.add_response_callback(on_sync_error, SyncError)

if homeserver_online:
if globals.settings["sync"]["old_messages"] is True:
receiver = asyncio.create_task(client.sync_forever(timeout=5, sync_filter=resp.filter_id))
if plg_globals.settings["listen"]["old_messages"] is True:
receiver = asyncio.create_task(client.sync_forever(timeout=5))
else:
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))
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:
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.")

try:
await receiver
except asyncio.CancelledError:
log_warning("Receiver task was cancelled.")
log_warning(tr("on_receiver_cancelled"))
except Exception as e:
log_error(f"Receiver sync error: {e}")
receiver.cancel()
Expand All @@ -85,4 +91,5 @@ async def get_messages() -> None:

async def stop_sync():
if isinstance(receiver, asyncio.Task):
receiver.cancel()
receiver.cancel()
plg_globals.sync = False
10 changes: 5 additions & 5 deletions matrix_sync/client/reporter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Send messages to matrix room by configured room_id.
import re
import matrix_sync.globals as globals
import matrix_sync.plg_globals as plg_globals

from . import get_homeserver
from .init import check_token
Expand All @@ -11,21 +11,21 @@


async def send_to_matrix(message) -> None:
client = AsyncClient(get_homeserver(globals.config["homeserver"]))
client = AsyncClient(get_homeserver(plg_globals.config["homeserver"]))
token_vaild = await check_token()
if token_vaild:
user, token = await getToken()

client.user_id = globals.config["user_id"]
client.user_id = plg_globals.config["user_id"]
client.access_token = token
client.device_id = globals.config["device_id"]
client.device_id = plg_globals.config["device_id"]

# Remove formatting code of mc for colorful text not supported yet.
pattern = re.compile(r'§[0-9a-v]')
message_to_send = re.sub(pattern, '', message)

await client.room_send(
globals.config["room_id"],
plg_globals.config["room_id"],
message_type="m.room.message",
content={"msgtype": "m.text", "body": message_to_send},
)
Expand Down
28 changes: 16 additions & 12 deletions matrix_sync/commands.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import asyncio
import threading
import matrix_sync.globals as globals
import matrix_sync.plg_globals as plg_globals

from typing import Optional
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 .event import SendToMatrixEvent, event_dispatcher


builder = SimpleCommandBuilder()

globals.tLock = threading.Lock()
plg_globals.tLock = threading.Lock()

def start_sync(on_reload: Optional[bool] = True):
if not globals.tLock.locked():
if not on_reload:
matrix_reporter("MC server startup!")
def start_sync():
if not plg_globals.tLock.locked():
run_sync_task()
log_info("Starting receiver sync...")
log_info(tr("on_sync_start"))
else:
log_warning("Already running receiver sync.")
log_warning(tr("on_sync_running"))

@new_thread('MatrixReceiver')
def run_sync_task():
globals.sync = True
with globals.tLock:
plg_globals.sync = True
with plg_globals.tLock:
asyncio.run(add_sync_task())

async def add_sync_task():
Expand All @@ -35,6 +34,7 @@ async def add_sync_task():
@new_thread('MatrixReporter')
def matrix_reporter(message: str):
asyncio.run(add_report_task(message))
event_dispatcher(SendToMatrixEvent, user_id=plg_globals.config["user_id"], room_id=plg_globals.config["room_id"])

async def add_report_task(message: str):
report_task = asyncio.create_task(send_to_matrix(message))
Expand All @@ -53,4 +53,8 @@ async def on_command_stop():

@builder.command("!!msync status")
def show_status():
log_info(f"Receiver: {globals.sync}")
log_info(f"Receiver: {plg_globals.sync}")
if plg_globals.sync:
log_info(tr("sync_status.running"))
else:
log_info(tr("sync_status.not_running"))
10 changes: 5 additions & 5 deletions matrix_sync/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import matrix_sync.globals as globals
import matrix_sync.plg_globals as plg_globals

from .default import *
from ..utils import *


async def load_config(server: PluginServerInterface):
globals.config = server.load_config_simple('config.json', account_config)
if globals.config == account_config:
plg_globals.config = server.load_config_simple('config.json', account_config)
if plg_globals.config == account_config:
server.unload_plugin(plgSelf.id)
globals.settings = server.load_config_simple('settings.json', default_settings)
if not globals.settings["log_style"]["mcdr"]:
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.")
Loading

0 comments on commit 10e2d7e

Please sign in to comment.