ForcePilot/backend/package/yuxi/channel/extensions/telegram/pairing.py
Kris 8a3601250e feat(channel): 添加 Telegram 渠道扩展
新增 Telegram 渠道扩展,支持在 Yuxi 平台中集成 Telegram 即时通讯渠道。

包含以下功能模块:
- config: 渠道配置管理
- gateway: SSE/WebSocket 网关接入
- webhook: Webhook 事件处理
- polling: 长轮询模式
- outbound: 外发消息管理
- streaming: 流式消息处理
- pairing: 用户配对与绑定
- security: 安全校验
- dedupe: 消息去重
- monitor: 渠道状态监控
- status: 会话状态管理
- session: 会话管理
- actions: 动作处理
- inline_keyboard: 内联键盘
- native_commands: 原生指令
- chat: 聊天管理
- delivery: 消息送达确认
- media: 媒体资源处理
- profile: 用户资料
- reactions: 表情反应
- sticker: 贴纸处理
- types: 类型定义
2026-05-21 11:48:09 +08:00

68 lines
2.3 KiB
Python

from __future__ import annotations
import hmac
import logging
import secrets
import time
logger = logging.getLogger(__name__)
_PAIRING_CODES: dict[str, tuple[str, float]] = {}
_CODE_TTL_SECONDS = 300
class TelegramPairing:
id_label = "telegramUserId"
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("Telegram 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)
return False
if not hmac.compare_digest(stored_code, code):
return False
_PAIRING_CODES.pop(peer_id, None)
return True
def normalize_allow_entry(self, entry: str) -> str:
stripped = entry.strip()
for prefix in ("tg:", "telegram:"):
if stripped.startswith(prefix):
return stripped[len(prefix):]
return stripped
async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None:
logger.info("Telegram pairing approved for peer %s", peer_id)
try:
from yuxi.channel.extensions.telegram.config import TelegramConfigAdapter
adapter = TelegramConfigAdapter()
adapter._config = config
account = await adapter.resolve_account(account_id or "default")
token = account.get("token", "")
if not token:
return
import httpx
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
await client.post(
f"https://api.telegram.org/bot{token}/sendMessage",
json={
"chat_id": peer_id,
"text": "✅ 您的访问请求已批准。现在可以直接向我发送消息了。",
"parse_mode": "HTML",
},
)
except Exception:
logger.warning("Failed to send approval notification to peer %s", peer_id, exc_info=True)