Alibrown commited on
Commit
3faff69
·
verified ·
1 Parent(s): 37574c6

Update app/app.py

Browse files
Files changed (1) hide show
  1. app/app.py +56 -55
app/app.py CHANGED
@@ -4,7 +4,6 @@ import logging
4
  from waitress import serve
5
  from nacl.signing import VerifyKey
6
  from nacl.exceptions import BadSignatureError
7
- import json
8
 
9
  # Logging konfigurieren
10
  logging.basicConfig(
@@ -14,82 +13,84 @@ logging.basicConfig(
14
  logger = logging.getLogger(__name__)
15
 
16
  # Konfiguration aus Umgebungsvariablen
17
- PUBLIC_KEY = os.getenv('Public_Key')
18
- APPLICATION_ID = os.getenv('Application_ID')
19
-
20
- if not PUBLIC_KEY or not APPLICATION_ID:
21
- logger.error("Missing required environment variables!")
22
- logger.error("Please set Public_Key and Application_ID in Hugging Face Spaces variables")
23
- raise ValueError("Missing required environment variables")
24
 
25
  app = Flask(__name__)
26
- verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY))
27
 
28
- def verify_discord_request():
29
- signature = request.headers.get('X-Signature-Ed25519')
30
- timestamp = request.headers.get('X-Signature-Timestamp')
31
-
32
- if not signature or not timestamp:
33
- logger.warning("Missing Discord signature headers")
34
- return False
35
-
36
- try:
37
- body = request.data.decode('utf-8')
38
- verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
39
- return True
40
- except (BadSignatureError, Exception) as e:
41
- logger.warning(f"Failed to verify request: {str(e)}")
42
- return False
43
 
44
  @app.route("/", methods=["GET"])
45
  def health_check():
46
- logger.info("Health check endpoint called")
47
  return jsonify({
48
  "status": "healthy",
49
- "message": "Discord bot is running on Hugging Face Spaces!",
50
- "application_id": APPLICATION_ID[:6] + "..." if APPLICATION_ID else "Not set",
51
- "public_key_set": bool(PUBLIC_KEY),
 
 
 
 
 
 
 
 
 
 
 
52
  })
53
 
54
  @app.route("/interactions", methods=["POST"])
55
  def interactions():
56
- # Verify the request is from Discord
57
- if not verify_discord_request():
58
- logger.warning("Failed to verify Discord request")
59
- return "Invalid request signature", 401
 
 
60
 
61
- if not request.is_json:
62
- logger.warning("Received non-JSON request")
63
- return jsonify({"error": "Expected JSON data"}), 400
 
 
 
 
 
 
 
64
 
65
  try:
 
 
 
 
66
  data = request.json
67
- logger.info(f"Received verified interaction type: {data.get('type')}")
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 Command Handler
75
  if data.get("type") == 2:
76
- command = data.get("data", {}).get("name")
77
- logger.info(f"Received command: {command}")
78
- if command == "settings":
79
- return jsonify({
80
- "type": 4,
81
- "data": {
82
- "content": f"🔧 Bot Einstellungen:\n• Application ID: {APPLICATION_ID[:6]}...\n• Verifizierung: ✅ Aktiv"
83
- }
84
- })
85
-
86
- return jsonify({"error": "Unknown interaction type"}), 400
87
 
88
  except Exception as e:
89
- logger.error(f"Error processing request: {str(e)}")
90
- return jsonify({"error": "Internal server error"}), 500
91
 
92
  if __name__ == "__main__":
93
- logger.info(f"Starting Discord bot (Application ID: {APPLICATION_ID[:6]}...)")
94
- logger.info("Public Key verification is enabled")
95
  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
 
8
  # Logging konfigurieren
9
  logging.basicConfig(
 
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)