ForcePilot/backend/package/yuxi/channel/routing/session_key.py
Kris bab30f2715
Some checks failed
Deploy VitePress site to Pages / build (push) Has been cancelled
Ruff Format Check / Ruff Format & Lint (push) Has been cancelled
Deploy VitePress site to Pages / Deploy (push) Has been cancelled
feat:0715
2026-07-15 12:30:58 +08:00

51 lines
1.5 KiB
Python

"""Session Key 构建器"""
from collections.abc import Callable
from typing import Any
SessionKeyExtension = Callable[..., str | None]
def build_session_key(
channel_type: str,
account_id: str,
chat_type: str,
peer_id: str,
thread_id: str | None = None,
*,
extension: SessionKeyExtension | None = None,
) -> str:
"""
按 `channel_type:account_id:chat_type:peer_id[:thread_id]` 格式拼接 session key。
插件可通过 `extension` 参数注入自定义拼接逻辑;若扩展返回非空值则直接使用,
否则按默认规则生成。
"""
if extension is not None:
custom = extension(
channel_type=channel_type,
account_id=account_id,
chat_type=chat_type,
peer_id=peer_id,
thread_id=thread_id,
)
if custom:
return custom
parts = [channel_type, account_id, chat_type, peer_id]
if thread_id:
parts.append(thread_id)
return ":".join(parts)
def parse_session_key_parts(session_key: str) -> dict[str, Any]:
"""将默认格式 session key 解析为结构化字段,方便路由匹配使用。"""
parts = session_key.split(":")
return {
"channel_type": parts[0] if len(parts) > 0 else None,
"account_id": parts[1] if len(parts) > 1 else None,
"chat_type": parts[2] if len(parts) > 2 else None,
"peer_id": parts[3] if len(parts) > 3 else None,
"thread_id": parts[4] if len(parts) > 4 else None,
}