Alibrown commited on
Commit
993ae60
·
verified ·
1 Parent(s): 1eb7900

Update app/app.py

Browse files
Files changed (1) hide show
  1. app/app.py +60 -45
app/app.py CHANGED
@@ -4,6 +4,9 @@ import logging
4
  from waitress import serve
5
  from nacl.signing import VerifyKey
6
  from nacl.exceptions import BadSignatureError
 
 
 
7
 
8
  # Logging konfigurieren
9
  logging.basicConfig(
@@ -12,85 +15,97 @@ logging.basicConfig(
12
  )
13
  logger = logging.getLogger(__name__)
14
 
15
- # Konfiguration aus Umgebungsvariablen
16
- PUBLIC_KEY = os.getenv('Public_Key', '').strip() # Strip entfernt Leerzeichen
17
  APPLICATION_ID = os.getenv('Application_ID', '').strip()
 
18
 
19
  app = Flask(__name__)
20
 
21
  try:
22
- # Versuche den Public Key zu verifizieren
23
  verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
24
  logger.info("Successfully initialized verify_key")
25
  except Exception as e:
26
  logger.error(f"Error initializing verify_key: {str(e)}")
27
  verify_key = None
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.route("/", methods=["GET"])
30
  def health_check():
 
31
  return jsonify({
32
- "status": "healthy",
33
  "message": "Discord bot is running!",
34
  "public_key_present": bool(PUBLIC_KEY),
35
- "verify_key_initialized": verify_key is not None,
36
- "application_id_present": bool(APPLICATION_ID)
37
- })
38
-
39
- @app.route("/debug", methods=["GET"])
40
- def debug():
41
- # Zeige wichtige Informationen (aber keine sensiblen Daten!)
42
- return jsonify({
43
- "public_key_length": len(PUBLIC_KEY) if PUBLIC_KEY else 0,
44
- "application_id_length": len(APPLICATION_ID) if APPLICATION_ID else 0,
45
- "verify_key_status": "initialized" if verify_key else "failed",
46
- "environment_variables": list(os.environ.keys())
47
  })
48
 
49
  @app.route("/interactions", methods=["POST"])
50
  def interactions():
51
- logger.info("Received interaction request")
52
- logger.info(f"Headers: {dict(request.headers)}")
53
-
54
  if not verify_key:
55
  logger.error("verify_key not initialized")
56
  return "Configuration error", 500
57
 
58
- # Verify the request
59
- signature = request.headers.get('X-Signature-Ed25519')
60
- timestamp = request.headers.get('X-Signature-Timestamp')
61
-
62
- logger.info(f"Signature present: {bool(signature)}")
63
- logger.info(f"Timestamp present: {bool(timestamp)}")
64
-
65
- if not signature or not timestamp:
66
- logger.warning("Missing headers")
67
  return "Invalid request signature", 401
68
 
69
  try:
70
- body = request.data.decode('utf-8')
71
- verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
72
-
73
- # Process the verified request
74
  data = request.json
75
 
 
76
  if data.get("type") == 1:
77
- logger.info("Responding to ping")
78
  return jsonify({"type": 1})
79
-
 
80
  if data.get("type") == 2:
81
- return jsonify({
82
- "type": 4,
83
- "data": {
84
- "content": "Command received!"
85
- }
86
- })
87
 
88
- return jsonify({"error": "Unknown type"}), 400
 
 
 
 
 
 
 
 
89
 
90
  except Exception as e:
91
- logger.error(f"Error: {str(e)}")
92
- return "Invalid request signature", 401
 
 
 
 
 
 
 
 
 
 
93
 
94
  if __name__ == "__main__":
95
- logger.info("Starting Discord bot...")
96
- serve(app, host="0.0.0.0", port=8080)
 
 
 
 
 
 
 
4
  from waitress import serve
5
  from nacl.signing import VerifyKey
6
  from nacl.exceptions import BadSignatureError
7
+ import threading
8
+ import requests
9
+ import time
10
 
11
  # Logging konfigurieren
12
  logging.basicConfig(
 
15
  )
16
  logger = logging.getLogger(__name__)
17
 
18
+ # Konfiguration
19
+ PUBLIC_KEY = os.getenv('Public_Key', '').strip()
20
  APPLICATION_ID = os.getenv('Application_ID', '').strip()
21
+ PORT = int(os.getenv('PORT', 7860)) # Hugging Face nutzt standardmäßig Port 7860
22
 
23
  app = Flask(__name__)
24
 
25
  try:
 
26
  verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
27
  logger.info("Successfully initialized verify_key")
28
  except Exception as e:
29
  logger.error(f"Error initializing verify_key: {str(e)}")
30
  verify_key = None
31
 
32
+ def verify_discord_request():
33
+ try:
34
+ signature = request.headers.get('X-Signature-Ed25519')
35
+ timestamp = request.headers.get('X-Signature-Timestamp')
36
+
37
+ if not signature or not timestamp:
38
+ return False
39
+
40
+ body = request.data.decode('utf-8')
41
+ verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
42
+ return True
43
+ except Exception as e:
44
+ logger.error(f"Verification error: {str(e)}")
45
+ return False
46
+
47
  @app.route("/", methods=["GET"])
48
  def health_check():
49
+ """Hugging Face nutzt diesen Endpoint um zu prüfen ob der Space läuft"""
50
  return jsonify({
51
+ "status": "running",
52
  "message": "Discord bot is running!",
53
  "public_key_present": bool(PUBLIC_KEY),
54
+ "verify_key_initialized": verify_key is not None
 
 
 
 
 
 
 
 
 
 
 
55
  })
56
 
57
  @app.route("/interactions", methods=["POST"])
58
  def interactions():
 
 
 
59
  if not verify_key:
60
  logger.error("verify_key not initialized")
61
  return "Configuration error", 500
62
 
63
+ if not verify_discord_request():
 
 
 
 
 
 
 
 
64
  return "Invalid request signature", 401
65
 
66
  try:
 
 
 
 
67
  data = request.json
68
 
69
+ # Discord Ping Verification
70
  if data.get("type") == 1:
71
+ logger.info("Responding to ping verification")
72
  return jsonify({"type": 1})
73
+
74
+ # Slash Commands
75
  if data.get("type") == 2:
76
+ command = data.get("data", {}).get("name")
77
+ logger.info(f"Received command: {command}")
 
 
 
 
78
 
79
+ if command == "settings":
80
+ return jsonify({
81
+ "type": 4,
82
+ "data": {
83
+ "content": "✅ Bot ist aktiv und verifiziert!"
84
+ }
85
+ })
86
+
87
+ return jsonify({"type": 1})
88
 
89
  except Exception as e:
90
+ logger.error(f"Error processing request: {str(e)}")
91
+ return "Internal server error", 500
92
+
93
+ def health_check_worker():
94
+ """Background worker der regelmäßig den Health-Check Endpoint aufruft"""
95
+ while True:
96
+ try:
97
+ response = requests.get(f"http://localhost:{PORT}/")
98
+ logger.info(f"Health check status: {response.status_code}")
99
+ except Exception as e:
100
+ logger.error(f"Health check failed: {str(e)}")
101
+ time.sleep(30)
102
 
103
  if __name__ == "__main__":
104
+ logger.info(f"Starting Discord bot on port {PORT}...")
105
+
106
+ # Starte Health-Check Worker in separatem Thread
107
+ health_thread = threading.Thread(target=health_check_worker, daemon=True)
108
+ health_thread.start()
109
+
110
+ # Starte Server
111
+ serve(app, host="0.0.0.0", port=PORT)