Spaces:
Runtime error
Runtime error
Update server.py
Browse files
server.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import os, json, urllib.request, subprocess, traceback
|
| 2 |
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 3 |
|
| 4 |
PORT = 7860
|
|
@@ -6,26 +6,30 @@ TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
|
| 6 |
ALLOWED_USER = os.environ.get("TELEGRAM_ALLOWED_USERS", "")
|
| 7 |
CF_URL = os.environ.get("CF_WORKER_URL", "").rstrip('/')
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
def send_tg(chat_id, text):
|
| 10 |
-
"""Отправка сообщений в Telegram ЧЕРЕЗ Cloudflare"""
|
| 11 |
if not CF_URL or not TOKEN:
|
| 12 |
-
|
| 13 |
return
|
| 14 |
url = f"{CF_URL}/bot{TOKEN}/sendMessage"
|
| 15 |
data = json.dumps({"chat_id": chat_id, "text": str(text)}).encode('utf-8')
|
| 16 |
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
| 17 |
try:
|
| 18 |
urllib.request.urlopen(req)
|
| 19 |
-
|
| 20 |
except Exception as e:
|
| 21 |
-
|
| 22 |
|
| 23 |
class WebhookHandler(BaseHTTPRequestHandler):
|
| 24 |
def do_POST(self):
|
| 25 |
length = int(self.headers.get('Content-Length', 0))
|
| 26 |
data = json.loads(self.rfile.read(length))
|
| 27 |
|
| 28 |
-
# Сразу отдаем 200 OK
|
| 29 |
self.send_response(200)
|
| 30 |
self.end_headers()
|
| 31 |
|
|
@@ -33,22 +37,21 @@ class WebhookHandler(BaseHTTPRequestHandler):
|
|
| 33 |
chat_id = str(data["message"]["chat"]["id"])
|
| 34 |
text = data["message"]["text"]
|
| 35 |
|
| 36 |
-
|
| 37 |
|
| 38 |
if ALLOWED_USER and chat_id != ALLOWED_USER:
|
| 39 |
-
|
| 40 |
send_tg(chat_id, "⛔ Доступ закрыт.")
|
| 41 |
return
|
| 42 |
|
| 43 |
-
|
| 44 |
-
send_tg(chat_id, "🤖 Задача принята! Гермес приступил к выполнению цикла...")
|
| 45 |
|
| 46 |
-
# Запускаем локального агента Гермеса
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
# Передаем API ключ Nvidia прямо в окружение команды на всякий случай
|
| 50 |
my_env = os.environ.copy()
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
|
| 53 |
result = subprocess.run(cmd, capture_output=True, text=True, env=my_env)
|
| 54 |
|
|
@@ -56,22 +59,22 @@ class WebhookHandler(BaseHTTPRequestHandler):
|
|
| 56 |
err_reply = result.stderr.strip()
|
| 57 |
|
| 58 |
if err_reply:
|
| 59 |
-
|
| 60 |
|
| 61 |
if not reply:
|
| 62 |
reply = err_reply
|
| 63 |
|
| 64 |
if reply:
|
| 65 |
-
|
| 66 |
send_tg(chat_id, reply[-4000:])
|
| 67 |
else:
|
| 68 |
-
|
| 69 |
-
send_tg(chat_id, "✅
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
error_trace = traceback.format_exc()
|
| 73 |
-
|
| 74 |
-
send_tg(chat_id, f"❌ Ошибка
|
| 75 |
|
| 76 |
def do_GET(self):
|
| 77 |
self.send_response(200)
|
|
@@ -79,6 +82,6 @@ class WebhookHandler(BaseHTTPRequestHandler):
|
|
| 79 |
self.wfile.write(b"Server Online")
|
| 80 |
|
| 81 |
if __name__ == "__main__":
|
| 82 |
-
|
| 83 |
HTTPServer(('0.0.0.0', PORT), WebhookHandler).serve_forever()
|
| 84 |
|
|
|
|
| 1 |
+
import os, json, urllib.request, subprocess, traceback, sys
|
| 2 |
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 3 |
|
| 4 |
PORT = 7860
|
|
|
|
| 6 |
ALLOWED_USER = os.environ.get("TELEGRAM_ALLOWED_USERS", "")
|
| 7 |
CF_URL = os.environ.get("CF_WORKER_URL", "").rstrip('/')
|
| 8 |
|
| 9 |
+
def log(msg):
|
| 10 |
+
"""Специальный print, который мгновенно пробивает буфер Hugging Face"""
|
| 11 |
+
print(msg, flush=True)
|
| 12 |
+
sys.stdout.flush()
|
| 13 |
+
|
| 14 |
def send_tg(chat_id, text):
|
|
|
|
| 15 |
if not CF_URL or not TOKEN:
|
| 16 |
+
log("❌ Ошибка: Не задан CF_WORKER_URL или TELEGRAM_BOT_TOKEN")
|
| 17 |
return
|
| 18 |
url = f"{CF_URL}/bot{TOKEN}/sendMessage"
|
| 19 |
data = json.dumps({"chat_id": chat_id, "text": str(text)}).encode('utf-8')
|
| 20 |
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
| 21 |
try:
|
| 22 |
urllib.request.urlopen(req)
|
| 23 |
+
log(f"✈️ Сообщение успешно отправлено в чат {chat_id}")
|
| 24 |
except Exception as e:
|
| 25 |
+
log(f"❌ Ошибка отправки в Telegram: {e}")
|
| 26 |
|
| 27 |
class WebhookHandler(BaseHTTPRequestHandler):
|
| 28 |
def do_POST(self):
|
| 29 |
length = int(self.headers.get('Content-Length', 0))
|
| 30 |
data = json.loads(self.rfile.read(length))
|
| 31 |
|
| 32 |
+
# Сразу отдаем 200 OK, чтобы Телеграм отстал
|
| 33 |
self.send_response(200)
|
| 34 |
self.end_headers()
|
| 35 |
|
|
|
|
| 37 |
chat_id = str(data["message"]["chat"]["id"])
|
| 38 |
text = data["message"]["text"]
|
| 39 |
|
| 40 |
+
log(f"📥 Получено: {text}")
|
| 41 |
|
| 42 |
if ALLOWED_USER and chat_id != ALLOWED_USER:
|
| 43 |
+
log("⛔ Блокировка: чужой ID.")
|
| 44 |
send_tg(chat_id, "⛔ Доступ закрыт.")
|
| 45 |
return
|
| 46 |
|
| 47 |
+
send_tg(chat_id, "🤖 Принято! Думаю...")
|
|
|
|
| 48 |
|
|
|
|
| 49 |
try:
|
| 50 |
+
log("🧠 Запускаю команду hermes...")
|
|
|
|
| 51 |
my_env = os.environ.copy()
|
| 52 |
+
|
| 53 |
+
# Используем префикс openai/ для кастомных прокси и имя модели из твоего скрина
|
| 54 |
+
cmd = ["hermes", "chat", "--cli", "-m", "openai/z-ai/glm-5.1", "-z", text]
|
| 55 |
|
| 56 |
result = subprocess.run(cmd, capture_output=True, text=True, env=my_env)
|
| 57 |
|
|
|
|
| 59 |
err_reply = result.stderr.strip()
|
| 60 |
|
| 61 |
if err_reply:
|
| 62 |
+
log(f"⚠️ Лог Гермеса (stderr): {err_reply}")
|
| 63 |
|
| 64 |
if not reply:
|
| 65 |
reply = err_reply
|
| 66 |
|
| 67 |
if reply:
|
| 68 |
+
log(f"📤 Ответ получен: {len(reply)} симв.")
|
| 69 |
send_tg(chat_id, reply[-4000:])
|
| 70 |
else:
|
| 71 |
+
log("❓ Гермес вернул пустоту.")
|
| 72 |
+
send_tg(chat_id, "✅ Пустой ответ от Гермеса.")
|
| 73 |
|
| 74 |
except Exception as e:
|
| 75 |
error_trace = traceback.format_exc()
|
| 76 |
+
log(f"❌ ОШИБКА:\n{error_trace}")
|
| 77 |
+
send_tg(chat_id, f"❌ Ошибка: {e}")
|
| 78 |
|
| 79 |
def do_GET(self):
|
| 80 |
self.send_response(200)
|
|
|
|
| 82 |
self.wfile.write(b"Server Online")
|
| 83 |
|
| 84 |
if __name__ == "__main__":
|
| 85 |
+
log(f"Starting Hermes Webhook Bridge on port {PORT}")
|
| 86 |
HTTPServer(('0.0.0.0', PORT), WebhookHandler).serve_forever()
|
| 87 |
|