ForcePilot/backend/package/yuxi/channels/adapters/slack/normalizer.py
Kris df1a7c7bca refactor(slack-adapter): 整理导入顺序并修复格式问题
本次提交包含多个Slack适配器相关的代码优化:
1. 统一多个文件中datetime和UTC的导入顺序
2. 调整collection.abc导入的参数顺序
3. 修复normalizer.py的文件末尾空行问题
4. 重新排序blocks.py中的函数导入
5. 调整directory_config.py中的函数顺序
6. 重构http_handler中的channel_manager调用方式
7. 新增Slack原生流探测逻辑和相关状态管理
8. 扩展消息动作分类和默认配置
9. 新增大量Slack消息块构建工具函数
10. 大幅重构__init__.py的导出内容,整理导入顺序
11. 为adapter新增熔断机制、缓存持久化和更多API方法
12. 新增多种系统事件处理逻辑
2026-05-13 16:14:38 +08:00

59 lines
1.7 KiB
Python

from __future__ import annotations
import re
SLACK_MENTION_STRIP_PATTERN = re.compile(r"<@[^>\s]+>")
SLACK_CHANNEL_PATTERN = re.compile(r"<#([A-Z0-9]+)(?:\|([^>]+))?>")
SLACK_URL_PATTERN = re.compile(r"<(https?://[^|>]+)(?:\|([^>]+))?>")
SLACK_SUBTEAM_PATTERN = re.compile(r"<!subteam\^([A-Z0-9]+)(?:\|([^>]+))?>")
SLACK_SPECIAL_MENTION_PATTERN = re.compile(r"<!([^>]+)>")
SLACK_HTML_ENTITY_PATTERN = re.compile(r"&(amp|lt|gt|quot);")
_HTML_ENTITIES = {"amp": "&", "lt": "<", "gt": ">", "quot": '"'}
def strip_mentions(text: str) -> str:
return SLACK_MENTION_STRIP_PATTERN.sub("", text).strip()
def extract_mentions(text: str) -> list[str]:
return re.findall(r"<@([A-Z0-9]+)>", text)
def normalize_channel_refs(text: str) -> str:
def repl(m: re.Match) -> str:
name = m.group(2)
return f"#{name}" if name else f"#{m.group(1)}"
return SLACK_CHANNEL_PATTERN.sub(repl, text)
def normalize_urls(text: str) -> str:
def repl(m: re.Match) -> str:
url = m.group(1)
label = m.group(2)
if label and label != url:
return f"{label} ({url})"
return url
return SLACK_URL_PATTERN.sub(repl, text)
def normalize_special_mentions(text: str) -> str:
return SLACK_SPECIAL_MENTION_PATTERN.sub(r"@\1", text)
def unescape_html_entities(text: str) -> str:
def repl(m: re.Match) -> str:
return _HTML_ENTITIES.get(m.group(1), m.group(0))
return SLACK_HTML_ENTITY_PATTERN.sub(repl, text)
def normalize_slack_text(text: str) -> str:
text = normalize_channel_refs(text)
text = normalize_urls(text)
text = normalize_special_mentions(text)
text = unescape_html_entities(text)
return text.strip()