FreshPixels commited on
Commit
35d2d28
·
verified ·
1 Parent(s): 1a564ca

Create server.py

Browse files
Files changed (1) hide show
  1. server.py +61 -0
server.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json, urllib.request, subprocess
2
+ from http.server import BaseHTTPRequestHandler, HTTPServer
3
+
4
+ PORT = 7860
5
+ 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: return
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
+ # Обязательно отдаем 200 OK Телеграму
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
+ # Собираем лог (берем последние 4000 символов, чтобы влезло в лимит ТГ)
45
+ reply = result.stdout.strip()
46
+ if not reply:
47
+ reply = result.stderr.strip()
48
+
49
+ send_tg(chat_id, reply[-4000:] if reply else "✅ Цикл завершен (вывод пуст).")
50
+ except Exception as e:
51
+ send_tg(chat_id, f"❌ Ошибка системы: {e}")
52
+
53
+ def do_GET(self):
54
+ self.send_response(200)
55
+ self.end_headers()
56
+ self.wfile.write(b"Server Online")
57
+
58
+ if __name__ == "__main__":
59
+ print(f"Starting Hermes Webhook Bridge on port {PORT}")
60
+ HTTPServer(('0.0.0.0', PORT), WebhookHandler).serve_forever()
61
+