ForcePilot/backend/package/yuxi/channel/extensions/douyin/pairing.py
Kris 4552bde837 feat(douyin): 新增抖音渠道插件,支持私信收发与相关能力
该提交实现了完整的抖音开放平台IM渠道插件,包含:
1. 基础配置与账号管理能力
2. 消息去重、安全策略校验
3. 流式回复、多媒体消息发送
4. Webhook回调处理与事件解析
5. 配对认证与流量限流机制
2026-05-21 10:45:37 +08:00

58 lines
1.6 KiB
Python

import random
import time
CODE_LENGTH = 6
CODE_TTL_SECONDS = 600
PENDING_MAX = 3
RATE_LIMIT_SECONDS = 3600
class DouyinPairing:
def __init__(self):
self._pending: dict[str, dict] = {}
self._openid_last_code_at: dict[str, float] = {}
def generate_code(self, open_id: str) -> str | None:
now = time.time()
if open_id in self._openid_last_code_at:
elapsed = now - self._openid_last_code_at[open_id]
if elapsed < RATE_LIMIT_SECONDS:
return None
if len(self._pending) >= PENDING_MAX:
oldest = min(self._pending.values(), key=lambda p: p["created_at"])
if now - oldest["created_at"] < CODE_TTL_SECONDS:
return None
expired_openid = next(k for k, v in self._pending.items() if v == oldest)
del self._pending[expired_openid]
code = _generate_code()
self._pending[open_id] = {"code": code, "created_at": now}
self._openid_last_code_at[open_id] = now
return code
def verify(self, open_id: str, code: str) -> bool:
entry = self._pending.get(open_id)
if not entry:
return False
if time.time() - entry["created_at"] > CODE_TTL_SECONDS:
del self._pending[open_id]
return False
if entry["code"] != code.upper().strip():
return False
del self._pending[open_id]
return True
def get_pending_count(self) -> int:
return len(self._pending)
def _generate_code() -> str:
no_ambiguous = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
return "".join(random.choices(no_ambiguous, k=CODE_LENGTH))