feat(src): init matrix client module

This commit is contained in:
2025-06-23 14:29:23 +08:00
parent 7faba5e18f
commit 9966e7a73f
3 changed files with 90 additions and 1 deletions

View File

@@ -0,0 +1,71 @@
from typing import Optional
from logging import Logger
from nio import (
AsyncClient,
SyncResponse,
SyncError,
MatrixRoom,
RoomMessageText,
)
class MatrixClient:
def __init__(
self,
homeserver: str,
user_id: str,
token: str,
device_id: Optional[str] = "mcdr",
logger: Optional[Logger, callable] = print,
):
self.connected: bool = False
self.client = AsyncClient(homeserver=homeserver)
self.client.user_id = user_id
self.client.access_token = token
self.client.device_id = device_id
self.logger = logger
self.network_status: bool = True
async def connect(self) -> None:
if self.connected:
if self.logger:
message = (
"You have connected the matrix client, "
"please disconnect it before reconnect!"
)
if hasattr(self.logger, "info"):
self.logger.info(message)
else:
self.logger(message)
return
async def receive_messages() -> None:
client = self.client
async def on_sync_response(response: SyncResponse):
if hasattr(self.logger, "debug"):
self.logger.debug(f"MatrixClient response: {response}")
def on_sync_error(response: SyncError):
self.network_status = False
message = (
"Sync error with matrix homeserver: "
f"{response.status_code}"
)
RED = "\033[31m"
RESET = "\033[0m"
if not self.logger:
print(RED + message + RESET)
if hasattr(self.logger, "error"):
self.logger.error(message)
else:
self.logger(RED + message + RESET)
client.add_response_callback(on_sync_response, SyncResponse)
client.add_response_callback(on_sync_error, SyncError)
async def message_callback(
room: MatrixRoom, event: RoomMessageText
) -> None:
raise NotImplementedError()

View File

@@ -1,4 +1,4 @@
from mcdreforged.api.all import * # Type checking will be not happy, but the simplest way to import MCDR documented APIs. Relax anyway, this will be improved later.
from mcdreforged.api.all import PluginServerInterface
def on_load(server: PluginServerInterface, _prev_module):

18
mcdreforged.plugin.json Normal file
View File

@@ -0,0 +1,18 @@
{
"id": "matrix_py_bridge",
"version": "0.0.1",
"name": "MatrixPyBridge",
"description": {
"en_us": "A python plugin to sync messages between Minecraft server and matrix chat rooms.",
"zh_cn": "一个用于在 Minecraft 服务器和 Matrix 聊天室之间同步消息的 Python 插件。"
},
"author": "Mooling0602",
"link": "https://github.com/Mooling0602/MatrixPyBridge-MCDR",
"dependencies": {
"mcdreforged": ">=2.14.1"
},
"entrypoint": "matrix_py_bridge.mcdr.entry",
"resources": [
"lang"
]
}