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