Skip to content

Commit

Permalink
Update to v2.5.3, still developing
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooling0602 committed Jan 24, 2025
1 parent 042a1a0 commit d9246f2
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 45 deletions.
1 change: 1 addition & 0 deletions lang/en_us.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ matrix_sync:
failed: Failed to login your bot
success: Login by password successfully!
save_token: Saving token for the bot account...
no_permission: Permission level is too low!
on_receiver_cancelled: Receiver task was cancelled.
on_send_command:
sending: Message is sending to matrix...
Expand Down
5 changes: 3 additions & 2 deletions lang/zh_cn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ matrix_sync:
failed: 无法登录你的机器人
success: 成功使用密码完成登录!
save_token: 正在为机器人账号保存Token...
no_permission: 权限等级过低!
on_receiver_cancelled: 接收器任务已经取消。
on_send_command:
sending: 消息正在发送到Matrix...
Expand All @@ -30,6 +31,6 @@ matrix_sync:
settings_comp_check:
failed: "兼容性检查失败!旧有的设置项将备份为\"settings.json.bak\""
sync_status:
running: "[MSync] 消息同步正在运行..."
not_running: "[MSync] 消息同步未在运行!"
running: "消息同步正在运行..."
not_running: "消息同步未在运行!"
token_mismatch: Token和现有的账号不匹配!同步任务将不会继续进行。
4 changes: 2 additions & 2 deletions matrix_sync/client/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
import aiofiles
from matrix_sync.commands import start_sync
import matrix_sync.logger.get_logger as get_logger
from ..logger.get_logger import console_logger
import matrix_sync.plg_globals as plg_globals

from . import *
Expand All @@ -21,7 +21,7 @@ async def cache_token(resp: LoginResponse):
}))

async def login_by_password():
logger = get_logger()
logger = console_logger()
client = AsyncClient(
get_homeserver(plg_globals.config["homeserver"]),
plg_globals.config["user_id"],
Expand Down
6 changes: 3 additions & 3 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.logger.get_logger as get_logger
from ..logger.get_logger import console_logger
import matrix_sync.plg_globals as plg_globals

from . import *
Expand All @@ -21,14 +21,14 @@ async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None:
event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room_info)

def on_sync_error(response: SyncError):
logger = get_logger()
logger = console_logger()
global homeserver_online
logger.error(f"Sync error: {response.status_code}", "Receiver")
if response.status_code >= 500:
homeserver_online = False

async def get_messages() -> None:
logger = get_logger()
logger = console_logger()
global receiver
resp = None
client = AsyncClient(homeserver=get_homeserver(plg_globals.config["homeserver"]))
Expand Down
95 changes: 70 additions & 25 deletions matrix_sync/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import asyncio
import threading
import matrix_sync.logger.get_logger as get_logger
from ..logger.get_logger import console_logger, reply_logger
import matrix_sync.plg_globals as plg_globals

from mcdreforged.api.all import *
from ..logger.get_logger import reply_logger
from ..client.reporter import send_to_matrix
from ..client.receiver import get_messages, stop_sync
from ..client import *
Expand All @@ -16,15 +17,15 @@
plg_globals.tLock = threading.Lock()

def start_sync():
logger = get_logger()
logger = console_logger()
if not plg_globals.tLock.locked():
run_sync_task()
else:
logger.warning(tr("on_sync_running"))

@new_thread('MatrixReceiver')
def run_sync_task():
logger = get_logger()
logger = console_logger()
plg_globals.sync = True
if plg_globals.token_vaild:
with plg_globals.tLock:
Expand Down Expand Up @@ -52,42 +53,86 @@ def command_register(server: PluginServerInterface):
builder.register(server)

@builder.command("!!msync start")
def on_command_start():
start_sync()
def on_command_start(src: CommandSource):
if src.has_permission_higher_than(2):
start_sync()
else:
src.reply(tr("no_permission"))

@builder.command("!!msync stop")
async def on_command_stop():
await stop_sync()
async def on_command_stop(src: CommandSource):
if src.has_permission_higher_than(2):
await stop_sync()
else:
src.reply(tr("no_permission"))

@builder.command("!!msync status")
def show_status():
logger = get_logger()
logger.info(f"Receiver: {plg_globals.sync}")
if plg_globals.sync:
logger.info(tr("sync_status.running"))
else:
logger.info(tr("sync_status.not_running"))
def show_status(src: CommandSource):
logger = console_logger()
def return_result():
if plg_globals.sync:
logger.info(tr("sync_status.running"))
else:
logger.info(tr("sync_status.not_running"))
if src.is_console:
logger = console_logger()
logger.info(f"Receiver: {plg_globals.sync}")
return_result()
if src.is_player:
try:
from rc_api import cmdReply
reply = cmdReply()
reply.log(src, f"Receiver: {plg_globals.sync}", logger)
if plg_globals.sync:
reply.log(src, tr("sync_status.running"), logger)
else:
reply.log(src, tr("sync_status.not_running"), logger)
except ModuleNotFoundError:
reply = reply_logger()
reply(src, f"Receiver: {plg_globals.sync}")
if plg_globals.sync:
reply(src, tr("sync_status.running"))
else:
reply(src, tr("sync_status.not_running"))

@builder.command("!!msync send <message>")
def on_command_send(src: CommandSource, ctx: CommandContext):
if plg_globals.token_vaild:
matrix_reporter(ctx["message"])
src.reply(tr("on_send_command.sending"))
if src.has_permission_higher_than(2):
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"))
else:
src.reply(tr("on_send_command.failed") + ": " + tr("token_mismatch"))
src.reply(tr("no_permission"))

@builder.command("!!msync reload")
def on_command_reload():
psi.reload_plugin(plgSelf.id)
def on_command_reload(src: CommandSource):
if src.has_permission_higher_than(2):
psi.reload_plugin(plgSelf.id)
else:
try:
from rc_api import cmdReply
reply = cmdReply()
logger = console_logger()
reply.log(src, tr("no_permission"), logger)
# reply.log(src, tr("no_permission")) if you don't use any modified logger instance.
except ModuleNotFoundError:
src.reply(tr("no_permission"))

@builder.command("!!msync reload <pack_name>")
def on_command_reload_subpack(src: CommandSource, ctx: CommandContext):
plugin_list = psi.get_plugin_list()
subpack_id = "msync_" + ctx["pack_name"]
if subpack_id in plugin_list:
psi.reload_plugin(subpack_id)
if src.has_permission_higher_than(2):
plugin_list = psi.get_plugin_list()
subpack_id = ctx["pack_name"]
if not subpack_id.startswith("msync_"):
subpack_id = "msync_" + ctx["pack_name"]
if subpack_id in plugin_list:
psi.reload_plugin(subpack_id)
else:
src.reply("Reload subpack error: Invaild name or target subpack is not loaded!")
else:
src.reply("Reload subpack error: Invaild name!")
src.reply(tr("no_permission"))

@builder.command("!!msync")
@builder.command("!!msync help")
Expand Down
13 changes: 10 additions & 3 deletions matrix_sync/entry.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import matrix_sync.logger.get_logger as get_logger
import logging
import matrix_sync.plg_globals as plg_globals

from .logger.get_logger import console_logger
from .utils import tr, configDir
from .client.reporter import send_to_matrix
from .client.receiver import stop_sync
Expand All @@ -10,10 +12,15 @@
from mcdreforged.api.all import *


# Framwork ver: 2.5.1-3
# Globally hide useless log outputs.
# logging.getLogger('nio').setLevel(logging.WARNING)

# Framwork ver: 2.5.3-1
def on_load(server: PluginServerInterface, prev_module):
load_config(server)
command_register(server)
if plg_globals.settings["log_style"]["debug"] is False:
logging.getLogger('nio').setLevel(logging.WARNING)
if not os.path.exists(f"{configDir}/token.json"):
from .client.init import first_login
first_login()
Expand Down Expand Up @@ -46,6 +53,6 @@ async def on_server_stop(server: PluginServerInterface, server_return_code: int)

# Wait for receiver sync exited, then unload plugin.
async def on_unload(server: PluginServerInterface):
logger = get_logger()
logger = console_logger()
logger.info(tr("on_unload"))
await stop_sync()
5 changes: 2 additions & 3 deletions matrix_sync/event/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import matrix_sync.logger.get_logger as get_logger

from ..logger.get_logger import console_logger
from mcdreforged.api.all import *
from ..utils import psi

Expand All @@ -16,7 +15,7 @@ def __init__(self, message: str, sender: str, room_info):
self.room_info = room_info

def event_dispatcher(event: type[PluginEvent], *args, **kwargs):
logger = get_logger()
logger = console_logger()
event_instance = event(*args, **kwargs)
psi.dispatch_event(event_instance, args)
logger.debug("Event dispatched to MCDR!")
4 changes: 2 additions & 2 deletions matrix_sync/event/receiver.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import matrix_sync.logger.get_logger as get_logger
from ..logger.get_logger import console_logger
import matrix_sync.plg_globals as plg_globals

from mcdreforged.api.types import PluginServerInterface
Expand All @@ -8,7 +8,7 @@ def listen_message(server: PluginServerInterface):
server.register_event_listener("MatrixRoomMessage", on_matrix_message)

def on_matrix_message(server, message: str, sender: str, room_info):
logger = get_logger()
logger = console_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_info.display_name).replace('%sender%', sender).replace('%message%', message)
Expand Down
28 changes: 23 additions & 5 deletions matrix_sync/logger/get_logger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import matrix_sync.plg_globals as plg_globals

from mcdreforged.api.types import CommandSource
from ..utils import psi
from . import info_logger, debug_logger

Expand All @@ -15,10 +16,24 @@ def warning(self, *args):
def error(self, *args):
psi.logger.error(args[0])

def critical(self, *args):
psi.logger.critical(args[0])

def debug(self, *args):
psi.logger.debug(args[0])

def get_logger():
class srcReply:
def __call__(self, src: CommandSource, *args):
src.reply(args[0])

class plgReply:
def __call__(self, src: CommandSource, *args):
if src.player is not None:
psi.tell(src.player, args[0])
else:
raise ValueError

def console_logger():
if plg_globals.settings["log_style"]["mcdr"]:
logger = psiLogger()
return logger
Expand All @@ -29,7 +44,10 @@ def get_logger():
logger = info_logger
return logger


__all__ = ["get_logger"]
import sys
sys.modules[__name__] = get_logger
def reply_logger():
if plg_globals.settings["log_style"]["mcdr"]:
logger = srcReply()
return logger
else:
logger = plgReply()
return logger

0 comments on commit d9246f2

Please sign in to comment.