import os import urllib.request import urllib.error from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler import socketserver PORT = 7860 TARGET = "http://127.0.0.1:8081" DIR_PATH = "/tmp/telegram-bot-api" BUFFER_SIZE = 64 * 1024 # 64KB 流式缓冲区大小 # 允许端口快速重用,防止服务重启时端口被锁 socketserver.TCPServer.allow_reuse_address = True class RobustProxyHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): # 记录日志,方便直接在 Hugging Face Space 的 Logs 页面进行实时排查 print(f"[{self.log_date_time_string()}] {format % args}") def do_GET(self): # 拦截下载文件请求,直接读取本地磁盘文件返回,解决 404 问题 if self.path.startswith("/file/bot"): parts = self.path.split("/", 3) if len(parts) >= 4: # 兼容清除双斜杠,防止 Windows/Linux 路径重写冲突 file_path = "/" + parts[3].lstrip("/") file_path = os.path.normpath(file_path) # 检查文件是否存在且路径在指定沙箱内 if os.path.exists(file_path) and file_path.startswith(DIR_PATH): file_size = os.path.getsize(file_path) self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Length", str(file_size)) self.end_headers() # 64KB 分片流式读取,杜绝大文件导致的 OOM 内存崩溃 try: with open(file_path, "rb") as f: while True: chunk = f.read(BUFFER_SIZE) if not chunk: break self.wfile.write(chunk) return except Exception as e: self.log_message("流式传输本地文件出错: %s", str(e)) return self.send_error(404, "File not found or access denied") return self.forward("GET") def do_POST(self): self.forward("POST") def forward(self, method): # 转发请求给本地的 telegram-bot-api 服务 url = TARGET + self.path headers = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "content-length")} content_length = int(self.headers.get('Content-Length', 0)) # 转发 POST 载荷时进行读取 body = None if content_length > 0: body = self.rfile.read(content_length) req = urllib.request.Request(url, data=body, headers=headers, method=method) try: # 增加 60 秒网络超时时间,防止线程无限挂起卡死 with urllib.request.urlopen(req, timeout=60) as res: self.send_response(res.status) for k, v in res.getheaders(): if k.lower() not in ("transfer-encoding", "content-encoding", "connection"): self.send_header(k, v) self.end_headers() # 64KB 分片流式转发网络响应,内存安全 while True: chunk = res.read(BUFFER_SIZE) if not chunk: break self.wfile.write(chunk) except urllib.error.HTTPError as e: self.send_response(e.code) for k, v in e.headers.items(): self.send_header(k, v) self.end_headers() self.wfile.write(e.read()) except Exception as e: self.log_message("转发 %s 失败: %s", self.path, str(e)) self.send_error(500, str(e)) if __name__ == "__main__": # ── Hugging Face 唤醒自适应 ── # 在后台启动真实的 telegram-bot-api 之前,先强杀残留进程,防止端口 8081 被占用导致启动失败 os.system("pkill -f telegram-bot-api >/dev/null 2>&1 || true") api_id = os.environ.get("TELEGRAM_API_ID", "") api_hash = os.environ.get("TELEGRAM_API_HASH", "") cmd = f"telegram-bot-api --local --http-port 8081 --api-id={api_id} --api-hash={api_hash} --dir={DIR_PATH} &" os.system(cmd) # 使用 ThreadingHTTPServer 开启多线程并发模式,完美应对多用户或机器人 Webhook 的高并发 server = ThreadingHTTPServer(("0.0.0.0", PORT), RobustProxyHandler) print(f"Robust Multi-Threaded Proxy server running on port {PORT}...") server.serve_forever()