51 lines
1.5 KiB
Python
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,
|
|
}
|