ForcePilot/backend/package/yuxi/channels/adapters/matrix/directory.py
Kris 2063145ce1 feat(matrix): 新增完整的Matrix适配器工具集
新增了20+个Matrix相关工具模块,包含线程处理、自动加入、消息去重、配置管理、安全策略、媒体处理、命令解析等功能,完善Matrix适配器基础能力
2026-05-12 00:45:54 +08:00

100 lines
3.0 KiB
Python

from __future__ import annotations
from typing import TYPE_CHECKING, Any
from yuxi.utils.logging_config import logger
if TYPE_CHECKING:
from nio import AsyncClient
async def search_users(
client: AsyncClient,
query: str,
limit: int = 20,
) -> list[dict[str, Any]]:
try:
resp = await client.search_user_directory(query, limit=limit)
results = getattr(resp, "results", [])
return [
{
"user_id": r.user_id,
"display_name": getattr(r, "display_name", ""),
"avatar_url": getattr(r, "avatar_url", ""),
}
for r in results
]
except Exception as e:
logger.debug(f"Matrix user directory search failed: {e}")
return []
async def search_groups(
client: AsyncClient,
query: str,
server: str | None = None,
) -> list[dict[str, Any]]:
try:
full_query = query if server else query
resp = await client.room_directory_search(full_query, server=server)
results = getattr(resp, "results", [])
return [
{
"room_id": getattr(r, "room_id", ""),
"name": getattr(r, "name", ""),
"alias": getattr(r, "canonical_alias", ""),
"topic": getattr(r, "topic", ""),
"num_joined_members": getattr(r, "num_joined_members", 0),
"world_readable": getattr(r, "world_readable", False),
"guest_can_join": getattr(r, "guest_can_join", False),
}
for r in results
]
except Exception as e:
logger.debug(f"Matrix group directory search failed: {e}")
return []
async def resolve_room_alias(
client: AsyncClient,
alias: str,
) -> dict[str, Any] | None:
try:
resp = await client.room_resolve_alias(alias)
return {
"room_id": resp.room_id if hasattr(resp, "room_id") else "",
"servers": getattr(resp, "servers", []),
}
except Exception as e:
logger.debug(f"Matrix room alias resolution failed for {alias}: {e}")
return None
async def list_public_rooms(
client: AsyncClient,
server: str | None = None,
limit: int = 50,
since: str | None = None,
) -> list[dict[str, Any]]:
try:
resp = await client.public_rooms(
server=server,
limit=limit,
since=since,
)
chunks = getattr(resp, "chunk", [])
return [
{
"room_id": getattr(r, "room_id", ""),
"name": getattr(r, "name", ""),
"alias": getattr(r, "canonical_alias", ""),
"topic": getattr(r, "topic", ""),
"num_joined_members": getattr(r, "num_joined_members", 0),
"world_readable": getattr(r, "world_readable", False),
}
for r in chunks
]
except Exception as e:
logger.debug(f"Matrix public rooms listing failed: {e}")
return []