fix: Matrix连接改为非阻塞模式,修复服务启动阻塞问题

This commit is contained in:
2026-04-11 12:22:03 +08:00
parent fd583132d7
commit b05a03e198
7 changed files with 104 additions and 105 deletions

View File

@@ -45,12 +45,18 @@ class MatrixBot:
return False
try:
self.client = AsyncClient(self.homeserver, self.username)
# 创建客户端
self.client = AsyncClient(
self.homeserver,
self.username,
store_path="/tmp/matrix_store"
)
# 如果有access_token直接使用
# 如果有access_token直接设置
if self.access_token:
self.client.access_token = self.access_token
logger.info(f"Matrix连接成功(使用token): {self.username}")
self.client.user_id = self.username
logger.info(f"Matrix已设置access_token: {self.username}")
self.is_running = True
return True
@@ -71,6 +77,7 @@ class MatrixBot:
async def start_sync(self, message_handler: Callable = None):
"""开始同步消息"""
if not self.client:
logger.warning("Matrix客户端未初始化")
return
self.on_message_callback = message_handler
@@ -78,8 +85,27 @@ class MatrixBot:
# 注册消息处理器
self.client.add_event_callback(self._handle_room_message, RoomMessageText)
# 开始同步循环
await self.client.sync_forever(timeout=30000)
# 首先执行一次同步获取房间信息
try:
sync_response = await self.client.sync(timeout=10000)
logger.info(f"Matrix初始同步完成")
except Exception as e:
logger.warning(f"Matrix初始同步失败: {e}, 将尝试继续")
# 启动后台同步任务(不阻塞)
asyncio.create_task(self._sync_loop())
logger.info("Matrix同步任务已启动")
async def _sync_loop(self):
"""后台同步循环"""
while self.is_running:
try:
# 使用较短的超时,避免长时间阻塞
await self.client.sync(timeout=5000)
await asyncio.sleep(1) # 每秒同步一次
except Exception as e:
logger.warning(f"Matrix同步错误: {e}")
await asyncio.sleep(5) # 出错后等待5秒再重试
async def _handle_room_message(self, room: MatrixRoom, event: RoomMessageText):
"""处理收到的房间消息"""