阿泰知识库
友善软路由R4S R6S等各种软路由固件信息整理
openai codex 跳过yes
关于funstat镜像获取和阿泰制作的镜像机器人
💻 Codex 安装与配置教程(适用于 macOS M 系列芯片)文章末尾添加了英特尔芯片区别
💻 Codex 安装与配置教程(适用于 Windows 系统)
Telegram BOT (@openaiw_bot) 探索与 MCP 封装项目
funstat BOT 完整功能列表(基于截图分析)
funstat BOT MCP 封装 - 系统架构规划
重要发现:@openaiw_bot 响应机制问题与解决方案
Telegram 请求限制分析与批量调用架构设计
funstat BOT MCP 封装 - 完整架构流程图 (Mermaid)
Telegram客服系统 - 完整开发文档
Telegram客服系统 - 完整测试报告 (2025-10-26)
Funstat BOT MCP 封装 - 完整流程图集
Funstat BOT MCP 包装项目 - 完成总结
Funstat MCP Server - 快速开始教程(完整版)
Session 文件安全更新 - 完成报告
多用户部署指南 - 如何让其他人使用 Funstat MCP
5种完美的永久替代部署方案
本文档使用 MrDoc 发布
-
+
首页
Telegram 请求限制分析与批量调用架构设计
# Telegram 请求限制分析与批量调用架构设计 ## 1. Telegram 请求限制详解 ### 1.1 个人账号 → BOT 的限制 | 限制类型 | 限制值 | 说明 | |---------|-------|------| | **消息发送速率** | ~30 条/秒 | 同一个对话中 | | **不同 BOT** | 无限制 | 向不同 BOT 发送没有限制 | | **同一 BOT** | ~20 条/秒 | 向同一个 BOT 发送 | | **Flood Wait** | 10-300 秒 | 触发限制后的等待时间 | | **日总量** | 无硬限制 | 但过于频繁会被标记 | ### 1.2 BOT → 用户的限制 (Bot API) | 限制类型 | 限制值 | 说明 | |---------|-------|------| | **消息发送** | 30 条/秒 | 全局限制 | | **同一群组** | 20 条/分钟 | 群组消息限制 | | **同一用户** | 无限制 | 私聊无限制 | | **并发连接** | 无限制 | Bot API 支持高并发 | ### 1.3 MTProto (Telethon/Pyrogram) 的限制 | 限制类型 | 限制值 | 说明 | |---------|-------|------| | **消息发送** | ~30 条/秒 | 动态调整 | | **API 调用** | 无固定限制 | 基于行为判断 | | **Flood Wait** | 自动处理 | 库会自动等待 | | **多账号** | 支持 | 可以使用多个账号 | --- ## 2. 批量请求架构设计 ### 架构 A: 单用户 + 请求队列 ⭐ 推荐 ``` 多个 Claude 用户 ↓ MCP Server (请求队列) ↓ 单个 Telegram 用户账号 ↓ @openaiw_bot ``` **特点**: - ✅ 简单可靠 - ✅ 容易维护 - ✅ 成本低(只需一个账号) - ⚠️ 受单账号限制(~20 请求/秒) **适用场景**: - 中小规模使用(< 1000 请求/天) - 个人或小团队使用 --- ### 架构 B: 多用户池 + 负载均衡 🚀 高性能 ``` 多个 Claude 用户 ↓ MCP Server (负载均衡器) ↓ ↓ ↓ [用户1] [用户2] [用户3] ... [用户N] ↓ ↓ ↓ ↓ @openaiw_bot ``` **特点**: - ✅ 高并发(N × 20 请求/秒) - ✅ 容错性强(一个账号失败不影响其他) - ✅ 可扩展 - ⚠️ 需要多个 Telegram 账号 - ⚠️ 管理复杂度高 **适用场景**: - 大规模使用(> 10000 请求/天) - 商业应用 - 需要高可用性 --- ### 架构 C: 智能调度 + 缓存 💡 最优化 ``` 多个 Claude 用户 ↓ MCP Server ├── 请求队列 ├── 智能调度器 ├── 结果缓存 (Redis) └── 多账号池 ↓ ↓ ↓ [账号1] [账号2] [账号3] ↓ @openaiw_bot ``` **特点**: - ✅ 最佳性能 - ✅ 缓存常见查询 - ✅ 智能限流 - ✅ 成本优化 - ⚠️ 实现复杂 **适用场景**: - 企业级应用 - 需要极致性能 --- ## 3. 请求流程详解 ### 3.1 单次请求流程 ``` 用户 → Claude → MCP Tool 调用 ↓ MCP Server ↓ 检查请求队列 ↓ 是否在限流中? ↙ ↘ 是 否 ↓ ↓ 加入队列 立即执行 ↓ ↓ 等待执行 发送给 Telegram ↓ Telethon Client ↓ @openaiw_bot ↓ 接收响应 ↓ 格式化 + 返回 ↓ Claude ↓ 用户 ``` ### 3.2 批量请求流程 ``` 多个并发请求 ↓ 请求队列 (FIFO) ↓ 速率限制器 (Token Bucket) ↓ 每 50ms 处理一个请求 ↓ 发送给 Telegram ↓ 收集响应 ↓ 返回给各自的调用者 ``` --- ## 4. 限流算法设计 ### 4.1 令牌桶算法 (Token Bucket) ```python class RateLimiter: def __init__(self, rate=20, per_second=1): self.rate = rate # 每秒 20 个请求 self.tokens = rate self.updated_at = time.time() async def acquire(self): """获取令牌(阻塞直到有令牌)""" while True: now = time.time() elapsed = now - self.updated_at # 补充令牌 self.tokens = min( self.rate, self.tokens + elapsed * self.rate ) self.updated_at = now if self.tokens >= 1: self.tokens -= 1 return True # 等待下一个令牌 wait_time = (1 - self.tokens) / self.rate await asyncio.sleep(wait_time) ``` ### 4.2 请求队列 ```python class RequestQueue: def __init__(self): self.queue = asyncio.Queue() self.rate_limiter = RateLimiter(rate=18) # 留 2 个余量 async def add_request(self, request): """添加请求到队列""" await self.queue.put(request) async def process_queue(self): """处理队列(后台任务)""" while True: request = await self.queue.get() # 限流 await self.rate_limiter.acquire() # 执行请求 await self.execute_request(request) ``` --- ## 5. 多账号负载均衡 ### 5.1 轮询策略 (Round Robin) ```python class AccountPool: def __init__(self, accounts): self.accounts = accounts self.current = 0 def get_next_account(self): """获取下一个账号""" account = self.accounts[self.current] self.current = (self.current + 1) % len(self.accounts) return account ``` ### 5.2 最少使用策略 (Least Used) ```python class AccountPool: def __init__(self, accounts): self.accounts = { account: {"usage": 0, "last_used": 0} for account in accounts } def get_best_account(self): """获取最空闲的账号""" return min( self.accounts.items(), key=lambda x: (x[1]["usage"], x[1]["last_used"]) )[0] ``` --- ## 6. 缓存策略 ### 6.1 查询结果缓存 ```python class ResponseCache: def __init__(self): self.cache = {} self.ttl = 3600 # 1 小时 def get(self, query): """获取缓存""" if query in self.cache: cached_time, result = self.cache[query] if time.time() - cached_time < self.ttl: return result return None def set(self, query, result): """设置缓存""" self.cache[query] = (time.time(), result) ``` **适合缓存的查询**: - ✅ 用户信息查询(用户 ID 不变) - ✅ 热门群组列表(变化慢) - ❌ 实时搜索(结果动态变化) --- ## 7. 错误处理策略 ### 7.1 Flood Wait 处理 ```python from telethon.errors import FloodWaitError async def send_with_retry(client, message): """带自动重试的发送""" max_retries = 3 for attempt in range(max_retries): try: return await client.send_message('@openaiw_bot', message) except FloodWaitError as e: wait_time = e.seconds logger.warning(f"Flood wait: {wait_time}s") if attempt < max_retries - 1: await asyncio.sleep(wait_time) else: raise ``` ### 7.2 账号故障转移 ```python async def send_with_fallback(pools, message): """使用账号池发送,支持故障转移""" failed_accounts = [] for _ in range(len(pools)): account = pools.get_next_account() try: return await account.send_message(message) except Exception as e: logger.error(f"Account {account.phone} failed: {e}") failed_accounts.append(account) continue raise Exception("All accounts failed") ``` --- ## 8. 性能指标 ### 单账号性能 | 场景 | 吞吐量 | 响应时间 | |-----|-------|---------| | 空闲时 | 20 请求/秒 | 1-2 秒 | | 高峰期 | 15 请求/秒 | 2-5 秒 | | Flood Wait | 5 请求/秒 | 5-10 秒 | ### 多账号性能 (10 个账号) | 场景 | 吞吐量 | 响应时间 | |-----|-------|---------| | 空闲时 | 180 请求/秒 | 1-2 秒 | | 高峰期 | 120 请求/秒 | 2-4 秒 | | 部分失败 | 90 请求/秒 | 3-6 秒 | --- ## 9. 推荐配置 ### 小规模(个人使用) ```json { "mode": "single_account", "rate_limit": 18, "queue_size": 100, "timeout": 20, "cache_enabled": true, "cache_ttl": 3600 } ``` ### 中等规模(团队使用) ```json { "mode": "account_pool", "accounts": 3, "rate_limit_per_account": 18, "load_balancer": "round_robin", "queue_size": 500, "cache_enabled": true, "cache_ttl": 1800 } ``` ### 大规模(商业应用) ```json { "mode": "smart_scheduler", "accounts": 10, "rate_limit_per_account": 18, "load_balancer": "least_used", "queue_size": 2000, "cache_enabled": true, "cache_backend": "redis", "cache_ttl": 3600, "auto_scaling": true } ``` --- ## 10. 成本估算 ### 账号成本 - **单个 Telegram 账号**: 免费(需要手机号) - **虚拟手机号**: $1-5/月/号 - **服务器**: $5-50/月 ### 运营成本 | 规模 | 账号数 | 服务器 | 月成本 | |-----|-------|--------|-------| | 小规模 | 1 | 基础 VPS | $5-10 | | 中等 | 3-5 | 中等 VPS | $20-50 | | 大规模 | 10+ | 高性能服务器 | $100-500 | --- **下一步**: 根据你的实际需求(请求量、预算、技术复杂度),选择合适的架构方案。
kttai
2025年10月26日 14:39
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码