实现了 Teams 机器人所需的全功能组件,包括: - 基础命令解析与帮助卡片生成 - 租户验证与访问控制 - 自定义 UA 与媒体工具 - 消息分块、批注处理与会话管理 - 防抖、缓存与配置路由能力 - 投票、配对、审计与运行时状态管理 - TTS 语音合成与卡片构建工具 - 群组管理与权限控制逻辑
77 lines
1.7 KiB
Python
77 lines
1.7 KiB
Python
"""Microsoft Teams 出站批注增强。
|
||
|
||
解析 `@[Name](id)` 格式 → `<at>` entities,
|
||
支持 ID 格式验证 (Bot ID/AAD UUID)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import uuid
|
||
from typing import Any
|
||
|
||
BOT_ID_PREFIX = "28:"
|
||
AT_REGEX = re.compile(r"@\[([^\]]+)]\(([^)]+)\)")
|
||
|
||
|
||
def parse_outbound_mentions(text: str) -> tuple[str, list[dict[str, Any]]]:
|
||
entities: list[dict[str, Any]] = []
|
||
processed_text = text
|
||
|
||
for match in AT_REGEX.finditer(text):
|
||
name = match.group(1)
|
||
user_id = match.group(2).strip()
|
||
mention_id = user_id
|
||
|
||
if not _validate_mention_id(user_id):
|
||
continue
|
||
|
||
at_text = f"<at>{name}</at>"
|
||
entities.append(
|
||
{
|
||
"type": "mention",
|
||
"mentioned": {"id": mention_id, "name": name},
|
||
"text": at_text,
|
||
}
|
||
)
|
||
|
||
return processed_text, entities
|
||
|
||
|
||
def _validate_mention_id(user_id: str) -> bool:
|
||
if not user_id:
|
||
return False
|
||
if user_id.startswith(BOT_ID_PREFIX):
|
||
return len(user_id) > len(BOT_ID_PREFIX)
|
||
try:
|
||
uuid.UUID(user_id)
|
||
return True
|
||
except ValueError:
|
||
pass
|
||
if "@" in user_id:
|
||
return True
|
||
return len(user_id) > 8
|
||
|
||
|
||
def build_mention_entity(
|
||
name: str,
|
||
user_id: str,
|
||
at_text: str | None = None,
|
||
) -> dict[str, Any]:
|
||
at = at_text or f"<at>{name}</at>"
|
||
return {
|
||
"type": "mention",
|
||
"mentioned": {"id": user_id, "name": name},
|
||
"text": at,
|
||
}
|
||
|
||
|
||
def apply_mentions_to_activity(
|
||
activity: dict[str, Any],
|
||
mentions: list[dict[str, Any]],
|
||
) -> dict[str, Any]:
|
||
entities: list[dict] = activity.setdefault("entities", [])
|
||
for m in mentions:
|
||
entities.append(m)
|
||
return activity
|