ForcePilot/backend/package/yuxi/channel/extensions/twitch/token.py
Kris 0babb1ca8e feat(channel): 添加 Tlon 渠道扩展
新增 Tlon 渠道扩展,支持在 Yuxi 平台中集成 Tlon/Urbit 去中心化通讯平台。

包含以下功能模块:
- tlon_api: Tlon API 客户端封装
- config: 渠道配置管理
- gateway: SSE/WebSocket 网关接入
- sse_client: SSE 客户端
- outbound: 外发消息管理
- send: 消息发送
- security: 安全校验
- auth: 认证管理
- monitor: 渠道状态监控
- status: 会话状态管理
- session: 会话管理
- approval: 审批流程
- channel_mgmt: 频道管理
- channel_ops: 频道操作
- contacts: 联系人管理
- discovery: 服务发现
- doctor: 健康诊断
- expose: 服务暴露
- gallery: 图库管理
- history: 历史记录
- hooks: 钩子管理
- media: 媒体资源处理
- notebook: 笔记本功能
- settings_store: 设置存储
- setup: 初始化设置
- story: 故事功能
- targets: 目标管理
- cite_parser: 引用解析
- utils: 工具函数
- types: 类型定义
2026-05-21 11:55:25 +08:00

90 lines
3.0 KiB
Python

import logging
import os
import re
import aiohttp
from yuxi.channel.extensions.twitch.config import TwitchAccountConfig
logger = logging.getLogger(__name__)
def resolve_twitch_token(account: TwitchAccountConfig, account_id: str = "default") -> tuple[str, str]:
token = account.access_token
if token:
return normalize_twitch_token(token), "config"
if account_id == "default":
env_token = os.getenv("OPENCLAW_TWITCH_ACCESS_TOKEN") or os.getenv("TWITCH_ACCESS_TOKEN")
if env_token:
return normalize_twitch_token(env_token), "env"
return "", "none"
def normalize_twitch_token(token: str) -> str:
token = token.strip()
if not token.lower().startswith("oauth:"):
token = f"oauth:{token}"
return token
def denormalize_token(token: str) -> str:
if token.lower().startswith("oauth:"):
return token[6:]
return token
def is_oauth_token(token: str) -> bool:
return bool(token) and token.lower().startswith("oauth:")
def extract_access_token(account: TwitchAccountConfig) -> str:
token = account.access_token
return denormalize_token(token)
def detect_mentions(text: str, bot_username: str) -> bool:
mentions = re.findall(r"@(\w+)", text)
bot_lower = bot_username.lower()
return any(m.lower() == bot_lower for m in mentions)
async def validate_twitch_token(account: TwitchAccountConfig) -> dict:
token, _ = resolve_twitch_token(account)
bare = denormalize_token(token)
if not bare:
return {"valid": False, "reason": "no token configured"}
url = "https://id.twitch.tv/oauth2/validate"
headers = {"Authorization": f"OAuth {bare}"}
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:
if resp.status == 200:
data = await resp.json()
return {"valid": True, **data}
return {"valid": False, "status": resp.status, "message": await resp.text()}
except Exception as e:
return {"valid": False, "error": str(e)}
async def refresh_twitch_token(account: TwitchAccountConfig) -> dict:
if not account.refresh_token or not account.client_id or not account.client_secret:
return {"ok": False, "error": "missing refresh_token, client_id, or client_secret"}
url = "https://id.twitch.tv/oauth2/token"
params = {
"grant_type": "refresh_token",
"refresh_token": account.refresh_token,
"client_id": account.client_id,
"client_secret": account.client_secret,
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=params, timeout=aiohttp.ClientTimeout(total=10)) as resp:
data = await resp.json()
if resp.status == 200:
return {"ok": True, **data}
return {"ok": False, "error": data.get("message", f"HTTP {resp.status}")}
except Exception as e:
return {"ok": False, "error": str(e)}