Skip to content

Commit

Permalink
Update to v2.4.2 with lots of error fixed, no loner need config.room_…
Browse files Browse the repository at this point in the history
…name
  • Loading branch information
Mooling0602 committed Dec 17, 2024
1 parent ff202a7 commit 09a5916
Show file tree
Hide file tree
Showing 9 changed files with 33 additions and 25 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@
| **homeserver** | 机器人账号所属的根服务器 |
| **user_id** | 机器人的账号ID,格式为@<用户名>:<根服务器>,如@mcchatbot:example.com |
| **password** | 机器人账号的密码,在初次登录和重新生成token时使用 |
| **room_id** | 需要接收游戏消息的房间的ID,使用管理员权限在房间设置中查看 |
| **room_name** | 需要转发消息到游戏内的房间的显示名称(必须准确无误,若发生更新也需要同步修改,否则你将看不到任何消息) |
| **room_id** | 需要同步游戏消息的房间的ID,使用管理员权限在房间设置中查看 |
| **device_id** | 登录用的设备名,一般无需修改,可自定义 |

> 只支持单账号和单聊天房间(相当于QQ群),计划在v3版本以后开发多配置管理。
Expand Down
3 changes: 1 addition & 2 deletions README_en_us.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ If there is any issue with message forwarding in any direction during the messag
| **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 |
| **room_name** | The display name of the room to forward messages to the game (must be accurate, if updated, it also needs to be modified synchronously, otherwise you will not see any messages) |
| **room_id** | The ID of the room to sync game messages |
| **device_id** | The device name used for login, generally no need to modify, can be customized |

Multi-config is not supported, will add API support for developers from v3.
Expand Down
4 changes: 2 additions & 2 deletions config.ini
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Do not edit this file!
# 不要修改这个文件!
[framework]
ver=3
ver=1
[main]
ver=2.4.1
ver=2.4.2
[release]
test=0
[ci]
Expand Down
5 changes: 3 additions & 2 deletions matrix_sync/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@

from .utils import psi, plgSelf, tr
from .utils.token import getToken
from .utils.globals import clientStatus
from .reporter import sendMsg
from mcdreforged.api.decorator import new_thread
from nio import AsyncClient, LoginResponse


clientStatus = False

# Cache Token.
def cache_token(resp: LoginResponse):
from .config import TOKEN_FILE, user_id
Expand Down Expand Up @@ -58,11 +57,13 @@ async def init_client() -> None:
psi.logger.info(tr("init_tips.do_unload"))
psi.unload_plugin(plgSelf.id)
else:
psi.logger.info("MatrixClient inited.")
await test_client()

# Send test messages.
async def test_client():
global clientStatus
message = tr("sync_tips.reporter_status")
psi.logger.info("Reporting on_load tip to matrix...")
await sendMsg(message)
clientStatus = True
5 changes: 2 additions & 3 deletions matrix_sync/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"user_id": "@username:matrix.example.org",
"password": "your_password",
"room_id": "!your-room_id:matrix.example.org",
"room_name": "your-room-display-name",
"device_id": "mcdr"
}

Expand All @@ -24,14 +23,14 @@
}

def load_config():
global config, user_id, password, room_id, room_name, settings, use_token, DATA_FOLDR, TOKEN_FILE, device_id, homeserver, load_tip, sync_old_msg
global config, user_id, password, room_id, room_name, settings, use_token, DATA_FOLDR, TOKEN_FILE, device_id, homeserver, load_tip, sync_old_msg, allow_all_rooms_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"]
allow_all_rooms_msg = settings["allow_all_rooms_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
9 changes: 5 additions & 4 deletions matrix_sync/entry.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import time
import os

from typing import Optional
from .utils import tr
from .client import init, clientStatus
from .client import init
from .config import load_config, check_config
from .utils import psi, globals
from .utils.commands import *
from .reporter import send_matrix
from mcdreforged.api.all import *


# Framwork ver: 2.4.1
# Framwork ver: 2.4.2
def on_load(server: PluginServerInterface, prev_module):
load_config()
from .config import load_tip
Expand All @@ -22,15 +23,15 @@ def on_load(server: PluginServerInterface, prev_module):
else:
init()
plugin_command(server)
if server.is_server_startup() and clientStatus:
from .config import TOKEN_FILE
if server.is_server_startup() and os.path.exists(TOKEN_FILE):
start_sync()

# Automatically run sync processes.
def start_sync(on_reload: Optional[bool] = True):
if not globals.tLock.locked():
start_room_msg()
if not on_reload:
time.sleep(1)
message = tr("sync_tips.server_started")
send_matrix(message)
else:
Expand Down
24 changes: 16 additions & 8 deletions matrix_sync/receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
from .utils.token import getToken
from .utils import psi, plgSelf, tr
from mcdreforged.api.event import PluginEvent
from nio import AsyncClient, MatrixRoom, RoomMessageText, SyncError
from nio import AsyncClient, MatrixRoom, RoomMessageText, SyncError, RoomMessagesResponse
from typing import Optional


homeserver_online = True

def load_msg_filter(room_id: str):
msg_filter = {"room_id": room_id}
return msg_filter

class RoomMessageEvent(PluginEvent):
def __init__(self, message: str, sender: str, room: Optional[str] = None):
super().__init__('MatrixRoomMessage') # 使用固定的事件ID
Expand All @@ -20,18 +24,18 @@ def __init__(self, message: str, sender: str, room: Optional[str] = None):

async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None:
transfer = False
from .config import user_id, room_name, settings
from .config import user_id, settings
msg_format = settings["room_msg_format"]["multi_room"]
roomMsg = msg_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 == user_id:
# Apply settings config
if not matrix_sync.config.settings["allow_all_rooms_msg"]:
msg_format = matrix_sync.config.settings["room_msg_format"]["single_room"]
if not settings["allow_all_rooms_msg"]:
msg_format = settings["room_msg_format"]["single_room"]
roomMsg = msg_format.replace('%sender%', room.user_name(event.sender)).replace('%message%', event.body)
if room.display_name == room_name:
transfer = True
psi.dispatch_event(RoomMessageEvent(event.body, room.user_name(event.sender)), (event.body, room.user_name(event.sender)))
# if response.room_id == room_id:
transfer = True
psi.dispatch_event(RoomMessageEvent(event.body, room.user_name(event.sender)), (event.body, room.user_name(event.sender)))
else:
psi.dispatch_event(RoomMessageEvent(event.body, room.user_name(event.sender), room.display_name), (event.body, room.user_name(event.sender), room.display_name))
if transfer:
Expand All @@ -45,7 +49,8 @@ def on_sync_error(response: SyncError):

async def getMsg() -> None:
global next_batch, msg_callback
from .config import homeserver, device_id, user_id, sync_old_msg
from .config import homeserver, device_id, user_id, sync_old_msg, allow_all_rooms_msg
from .config import room_id as cfg_room_id
client = AsyncClient(f"{homeserver}")
user, token = await getToken()
client.access_token = token
Expand All @@ -63,6 +68,9 @@ async def getMsg() -> None:
client.user_id = user_id
client.device_id = device_id

if not allow_all_rooms_msg:
print("ok.")
await client.upload_filter(room={"rooms": [cfg_room_id]})
client.add_response_callback(on_sync_error, SyncError)

try:
Expand Down
3 changes: 2 additions & 1 deletion matrix_sync/utils/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
tLock = threading.Lock()
report_matrix = False
cleaned = False
sync_task = None
sync_task = None
clientStatus = None
2 changes: 1 addition & 1 deletion mcdreforged.plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"id": "matrix_sync",
"version": "2.4.1",
"version": "2.4.2",
"name": "MatrixSync",
"description": {
"en_us": "Sync messages between online game and Matrix groups.",
Expand Down

0 comments on commit 09a5916

Please sign in to comment.