Spaces:
Runtime error
Runtime error
Update server.py
Browse files
server.py
CHANGED
|
@@ -7,91 +7,108 @@ ALLOWED_USER = os.environ.get("TELEGRAM_ALLOWED_USERS", "").strip()
|
|
| 7 |
CF_URL = os.environ.get("CF_WORKER_URL", "").rstrip('/')
|
| 8 |
|
| 9 |
def log(msg):
|
| 10 |
-
"""Мгновенный вывод в логи Hugging Face"""
|
| 11 |
print(msg, flush=True)
|
| 12 |
sys.stdout.flush()
|
| 13 |
|
| 14 |
def send_tg(chat_id, text):
|
| 15 |
-
"""Отправка в Telegram через Cloudflare
|
| 16 |
-
if not CF_URL or not TOKEN:
|
| 17 |
-
log("❌ Ошибка: Не задан CF_WORKER_URL или TELEGRAM_BOT_TOKEN")
|
| 18 |
-
return
|
| 19 |
-
|
| 20 |
url = f"{CF_URL}/bot{TOKEN}/sendMessage"
|
| 21 |
data = json.dumps({"chat_id": chat_id, "text": str(text)}).encode('utf-8')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
# 🎭 Маскируемся под Google Chrome, чтобы Cloudflare не выдавал 403
|
| 24 |
headers = {
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
}
|
| 28 |
req = urllib.request.Request(url, data=data, headers=headers)
|
| 29 |
|
| 30 |
-
try:
|
| 31 |
-
urllib.request.urlopen(req, timeout=
|
| 32 |
-
|
|
|
|
| 33 |
except urllib.error.HTTPError as e:
|
| 34 |
-
# Е
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
except Exception as e:
|
| 38 |
-
|
| 39 |
|
| 40 |
class WebhookHandler(BaseHTTPRequestHandler):
|
| 41 |
def do_POST(self):
|
| 42 |
length = int(self.headers.get('Content-Length', 0))
|
| 43 |
data = json.loads(self.rfile.read(length))
|
| 44 |
-
|
| 45 |
self.send_response(200)
|
| 46 |
self.end_headers()
|
| 47 |
|
| 48 |
if "message" in data and "text" in data["message"]:
|
| 49 |
chat_id = str(data["message"]["chat"]["id"])
|
| 50 |
text = data["message"]["text"]
|
| 51 |
-
|
| 52 |
log(f"📥 Получено: {text}")
|
| 53 |
|
| 54 |
if ALLOWED_USER and chat_id != ALLOWED_USER:
|
| 55 |
-
log("⛔ Блокировка: чужой ID.")
|
| 56 |
send_tg(chat_id, "⛔ Доступ закрыт.")
|
| 57 |
return
|
| 58 |
|
| 59 |
-
send_tg(chat_id, "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
try:
|
| 62 |
-
log("🧠 Выполняю команду hermes...")
|
| 63 |
my_env = os.environ.copy()
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
"--cli"
|
| 71 |
-
]
|
| 72 |
-
log(f"⚙️ Полная команда: {' '.join(cmd)}")
|
| 73 |
-
|
| 74 |
result = subprocess.run(cmd, capture_output=True, text=True, env=my_env)
|
| 75 |
|
| 76 |
reply = result.stdout.strip()
|
| 77 |
err_reply = result.stderr.strip()
|
| 78 |
|
| 79 |
-
if err_reply:
|
| 80 |
-
log(f"⚠️ Лог Гермеса (stderr): {err_reply}")
|
| 81 |
-
|
| 82 |
if not reply:
|
| 83 |
reply = err_reply
|
| 84 |
|
| 85 |
if reply:
|
| 86 |
-
log(f"📤 Ответ получен: {len(reply)} симв.")
|
| 87 |
send_tg(chat_id, reply[-4000:])
|
| 88 |
else:
|
| 89 |
-
log("❓ Гермес вернул пустоту.")
|
| 90 |
send_tg(chat_id, "✅ Пустой ответ от Гермеса.")
|
| 91 |
|
| 92 |
except Exception as e:
|
| 93 |
-
error_trace = traceback.format_exc()
|
| 94 |
-
log(f"❌ ОШИБКА:\n{error_trace}")
|
| 95 |
send_tg(chat_id, f"❌ Системная ошибка: {e}")
|
| 96 |
|
| 97 |
def do_GET(self):
|
|
|
|
| 7 |
CF_URL = os.environ.get("CF_WORKER_URL", "").rstrip('/')
|
| 8 |
|
| 9 |
def log(msg):
|
|
|
|
| 10 |
print(msg, flush=True)
|
| 11 |
sys.stdout.flush()
|
| 12 |
|
| 13 |
def send_tg(chat_id, text):
|
| 14 |
+
"""Отправка в Telegram через Cloudflare"""
|
| 15 |
+
if not CF_URL or not TOKEN: return
|
|
|
|
|
|
|
|
|
|
| 16 |
url = f"{CF_URL}/bot{TOKEN}/sendMessage"
|
| 17 |
data = json.dumps({"chat_id": chat_id, "text": str(text)}).encode('utf-8')
|
| 18 |
+
headers = {"Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}
|
| 19 |
+
req = urllib.request.Request(url, data=data, headers=headers)
|
| 20 |
+
try: urllib.request.urlopen(req, timeout=15)
|
| 21 |
+
except: pass
|
| 22 |
+
|
| 23 |
+
def check_api():
|
| 24 |
+
"""ПРЯМОЙ РЕНТГЕН ТВОЕГО ПРОВАЙДЕРА API"""
|
| 25 |
+
base = os.environ.get("OPENAI_API_BASE", "").strip().rstrip('/')
|
| 26 |
+
key = os.environ.get("OPENAI_API_KEY", "").strip()
|
| 27 |
+
|
| 28 |
+
if not base or not key:
|
| 29 |
+
return False, "❌ В секретах Hugging Face не найдены OPENAI_API_BASE или OPENAI_API_KEY!"
|
| 30 |
+
|
| 31 |
+
if not base.endswith("/v1"):
|
| 32 |
+
base += "/v1"
|
| 33 |
+
|
| 34 |
+
url = f"{base}/chat/completions"
|
| 35 |
+
|
| 36 |
+
# Отправляем тестовый запрос напрямую в агрегатор
|
| 37 |
+
data = json.dumps({
|
| 38 |
+
"model": "z-ai/glm-5.1",
|
| 39 |
+
"messages": [{"role": "user", "content": "Привет"}],
|
| 40 |
+
"max_tokens": 10
|
| 41 |
+
}).encode('utf-8')
|
| 42 |
|
|
|
|
| 43 |
headers = {
|
| 44 |
+
"Authorization": f"Bearer {key}",
|
| 45 |
+
"Content-Type": "application/json"
|
| 46 |
}
|
| 47 |
req = urllib.request.Request(url, data=data, headers=headers)
|
| 48 |
|
| 49 |
+
try:
|
| 50 |
+
resp = urllib.request.urlopen(req, timeout=10)
|
| 51 |
+
res_data = json.loads(resp.read().decode('utf-8'))
|
| 52 |
+
return True, "✅ API работает отлично!"
|
| 53 |
except urllib.error.HTTPError as e:
|
| 54 |
+
# ВОТ ЗДЕСЬ МЫ ПОЙМАЕМ РЕАЛЬНУЮ ОШИБКУ ПРОВАЙДЕРА
|
| 55 |
+
err_msg = e.read().decode('utf-8', errors='ignore')
|
| 56 |
+
return False, f"❌ Провайдер API отклонил запрос (Код {e.code}):\n{err_msg}"
|
| 57 |
+
except Exception as e:
|
| 58 |
+
return False, f"❌ Ошибка соединения с провайдером API: {e}"
|
| 59 |
|
| 60 |
class WebhookHandler(BaseHTTPRequestHandler):
|
| 61 |
def do_POST(self):
|
| 62 |
length = int(self.headers.get('Content-Length', 0))
|
| 63 |
data = json.loads(self.rfile.read(length))
|
|
|
|
| 64 |
self.send_response(200)
|
| 65 |
self.end_headers()
|
| 66 |
|
| 67 |
if "message" in data and "text" in data["message"]:
|
| 68 |
chat_id = str(data["message"]["chat"]["id"])
|
| 69 |
text = data["message"]["text"]
|
|
|
|
| 70 |
log(f"📥 Получено: {text}")
|
| 71 |
|
| 72 |
if ALLOWED_USER and chat_id != ALLOWED_USER:
|
|
|
|
| 73 |
send_tg(chat_id, "⛔ Доступ закрыт.")
|
| 74 |
return
|
| 75 |
|
| 76 |
+
send_tg(chat_id, "🔍 Сканирую провайдера API...")
|
| 77 |
+
|
| 78 |
+
# --- ЗАПУСК ДИАГНОСТИКИ ---
|
| 79 |
+
api_ok, api_msg = check_api()
|
| 80 |
+
|
| 81 |
+
if not api_ok:
|
| 82 |
+
log(f"⚠️ ОШИБКА API: {api_msg}")
|
| 83 |
+
# Отправляем реальную ошибку провайдера прямо тебе в бота!
|
| 84 |
+
send_tg(chat_id, api_msg[:4000])
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
# Если API ответило нормально, запускаем Гермеса
|
| 88 |
+
send_tg(chat_id, "🤖 API в норме! Запускаю Гермеса...")
|
| 89 |
|
| 90 |
try:
|
|
|
|
| 91 |
my_env = os.environ.copy()
|
| 92 |
+
api_base = my_env.get("OPENAI_API_BASE", "")
|
| 93 |
+
if api_base and not api_base.endswith("/v1"):
|
| 94 |
+
my_env["OPENAI_API_BASE"] = api_base.rstrip('/') + "/v1"
|
| 95 |
+
my_env["OPENAI_BASE_URL"] = my_env["OPENAI_API_BASE"]
|
| 96 |
+
|
| 97 |
+
cmd = ["hermes", "-m", "openai/z-ai/glm-5.1", "-z", text, "chat", "--cli"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
result = subprocess.run(cmd, capture_output=True, text=True, env=my_env)
|
| 99 |
|
| 100 |
reply = result.stdout.strip()
|
| 101 |
err_reply = result.stderr.strip()
|
| 102 |
|
|
|
|
|
|
|
|
|
|
| 103 |
if not reply:
|
| 104 |
reply = err_reply
|
| 105 |
|
| 106 |
if reply:
|
|
|
|
| 107 |
send_tg(chat_id, reply[-4000:])
|
| 108 |
else:
|
|
|
|
| 109 |
send_tg(chat_id, "✅ Пустой ответ от Гермеса.")
|
| 110 |
|
| 111 |
except Exception as e:
|
|
|
|
|
|
|
| 112 |
send_tg(chat_id, f"❌ Системная ошибка: {e}")
|
| 113 |
|
| 114 |
def do_GET(self):
|