ForcePilot/backend/package/yuxi/channel/extensions/slack/pairing.py
Kris bfc7755137 feat(channel): 添加 Slack 渠道扩展
新增 Slack 渠道扩展,支持在 Yuxi 平台中集成 Slack 团队协作平台。

包含以下功能模块:
- config: 渠道配置管理
- gateway: SSE/WebSocket 网关接入
- outbound: 外发消息管理
- streaming: 流式消息处理
- pairing: 用户配对与绑定
- security: 安全校验
- monitor: 渠道状态监控
- status: 会话状态管理
- actions: 交互动作处理
- interactive: 交互式消息
- commands: 斜杠指令
- threading: 线程管理
- mentions: @提及
- constants: 常量定义
- types: 类型定义
2026-05-21 11:43:23 +08:00

63 lines
2.4 KiB
Python

import secrets
import time
import logging
logger = logging.getLogger(__name__)
_PAIRING_CODES: dict[str, tuple[str, float]] = {}
_CODE_TTL_SECONDS = 300
class SlackPairing:
id_label = "slackSenderId"
async def generate_code(self, peer_id: str) -> str:
code = f"{secrets.randbelow(1_000_000):06d}"
_PAIRING_CODES[peer_id] = (code, time.monotonic())
logger.info("Slack pairing code generated for peer %s", peer_id)
return code
async def verify_code(self, peer_id: str, code: str) -> bool:
stored = _PAIRING_CODES.get(peer_id)
if stored is None:
return False
stored_code, created_at = stored
if time.monotonic() - created_at > _CODE_TTL_SECONDS:
_PAIRING_CODES.pop(peer_id, None)
logger.info("Slack pairing code expired for peer %s", peer_id)
return False
if not secrets.compare_digest(stored_code, code):
return False
_PAIRING_CODES.pop(peer_id, None)
logger.info("Slack pairing code verified for peer %s", peer_id)
return True
def normalize_allow_entry(self, entry: str) -> str:
stripped = entry.strip()
for prefix in ("slack:", "user:"):
if stripped.lower().startswith(prefix):
stripped = stripped[len(prefix) :].strip()
return stripped.upper()
async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None:
logger.info("Slack pairing approved for peer %s (account=%s)", peer_id, account_id or "default")
try:
from yuxi.channel.extensions.slack.config import SlackConfigAdapter
adapter = SlackConfigAdapter()
account = await adapter.resolve_account(account_id or "default", config)
bot_token = account.get("bot_token", "")
if not bot_token:
logger.warning("Cannot notify approval: no bot_token for account %s", account_id)
return
from slack_sdk.web.async_client import AsyncWebClient
client = AsyncWebClient(token=bot_token)
await client.chat_postMessage(
channel=peer_id,
text=":white_check_mark: 您的 DM 访问请求已被批准。现在可以直接向我发送消息了!",
)
except Exception:
logger.warning("Failed to send approval notification to peer %s", peer_id, exc_info=True)