import os, json, urllib.request, subprocess, traceback from http.server import BaseHTTPRequestHandler, HTTPServer PORT = 7860 TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "") ALLOWED_USER = os.environ.get("TELEGRAM_ALLOWED_USERS", "") CF_URL = os.environ.get("CF_WORKER_URL", "").rstrip('/') def send_tg(chat_id, text): """Отправка сообщений в Telegram ЧЕРЕЗ Cloudflare""" if not CF_URL or not TOKEN: print("❌ Ошибка отправки: Не задан CF_WORKER_URL или TELEGRAM_BOT_TOKEN") return url = f"{CF_URL}/bot{TOKEN}/sendMessage" data = json.dumps({"chat_id": chat_id, "text": str(text)}).encode('utf-8') req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) try: urllib.request.urlopen(req) print(f"✈️ Сообщение успешно отправлено в чат {chat_id}") except Exception as e: print(f"❌ Ошибка отправки в Telegram: {e}") class WebhookHandler(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers.get('Content-Length', 0)) data = json.loads(self.rfile.read(length)) # Сразу отдаем 200 OK self.send_response(200) self.end_headers() if "message" in data and "text" in data["message"]: chat_id = str(data["message"]["chat"]["id"]) text = data["message"]["text"] print(f"📥 Получено сообщение от chat_id {chat_id}: {text}") if ALLOWED_USER and chat_id != ALLOWED_USER: print(f"⛔ Блокировка: chat_id {chat_id} не совпадает с ALLOWED_USER {ALLOWED_USER}") send_tg(chat_id, "⛔ Доступ закрыт.") return # Отправляем первое проверочное сообщение send_tg(chat_id, "🤖 Задача принята! Гермес приступил к выполнению цикла...") # Запускаем локального агента Гермеса try: print("🧠 Запускаю команду hermes...") # Передаем API ключ Nvidia прямо в окружение команды на всякий случай my_env = os.environ.copy() cmd = ["hermes", "chat", "--cli", "-m", "nvidia/glm-5.1", "-z", text] result = subprocess.run(cmd, capture_output=True, text=True, env=my_env) reply = result.stdout.strip() err_reply = result.stderr.strip() if err_reply: print(f"⚠️ Лог Гермеса (stderr): {err_reply}") if not reply: reply = err_reply if reply: print(f"📤 Ответ от Гермеса получен, длина: {len(reply)} симв.") send_tg(chat_id, reply[-4000:]) else: print("❓ Гермес вернул абсолютно пустой ответ.") send_tg(chat_id, "✅ Цикл завершен, но Гермес ничего не вывел.") except Exception as e: error_trace = traceback.format_exc() print(f"❌ КРИТИЧЕСКАЯ ОШИБКА В СИСТЕМЕ:\n{error_trace}") send_tg(chat_id, f"❌ Ошибка системы: {e}") def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(b"Server Online") if __name__ == "__main__": print(f"Starting Hermes Webhook Bridge on port {PORT}") HTTPServer(('0.0.0.0', PORT), WebhookHandler).serve_forever()