Alibrown commited on
Commit
46724e2
·
verified ·
1 Parent(s): edb4434

Create app/app.py

Browse files
Files changed (1) hide show
  1. app/app.py +115 -0
app/app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Discord Bot Boilerplate by S. Volkan Kücükbudak
2
+ # Dev Link: https://github.com/VolkanSah/HF-Discord-Bot
3
+ # HF-Demo: https://huggingface.co/spaces/Alibrown/AI-Discord-free/
4
+ # You can use it for free (privat and commercial) do not sell my script, only your own work!
5
+ from flask import Flask, request, jsonify
6
+ import os
7
+ import logging
8
+ from waitress import serve
9
+ from nacl.signing import VerifyKey
10
+ from nacl.exceptions import BadSignatureError
11
+ import threading
12
+ import requests
13
+ import time
14
+
15
+ # Logging konfigurieren
16
+ logging.basicConfig(
17
+ level=logging.INFO,
18
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
19
+ )
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Konfiguration
23
+ PUBLIC_KEY = os.getenv('Public_Key', '').strip()
24
+ APPLICATION_ID = os.getenv('Application_ID', '').strip()
25
+ PORT = int(os.getenv('PORT', 7860)) # Hugging Face nutzt standardmäßig Port 7860
26
+
27
+ app = Flask(__name__)
28
+
29
+ try:
30
+ verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
31
+ logger.info("Successfully initialized verify_key")
32
+ except Exception as e:
33
+ logger.error(f"Error initializing verify_key: {str(e)}")
34
+ verify_key = None
35
+
36
+ def verify_discord_request():
37
+ try:
38
+ signature = request.headers.get('X-Signature-Ed25519')
39
+ timestamp = request.headers.get('X-Signature-Timestamp')
40
+
41
+ if not signature or not timestamp:
42
+ return False
43
+
44
+ body = request.data.decode('utf-8')
45
+ verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
46
+ return True
47
+ except Exception as e:
48
+ logger.error(f"Verification error: {str(e)}")
49
+ return False
50
+
51
+ @app.route("/", methods=["GET"])
52
+ def health_check():
53
+ """Hugging Face nutzt diesen Endpoint um zu prüfen ob der Space läuft"""
54
+ return jsonify({
55
+ "status": "running",
56
+ "message": "Discord bot is running!",
57
+ "public_key_present": bool(PUBLIC_KEY),
58
+ "verify_key_initialized": verify_key is not None
59
+ })
60
+
61
+ @app.route("/interactions", methods=["POST"])
62
+ def interactions():
63
+ if not verify_key:
64
+ logger.error("verify_key not initialized")
65
+ return "Configuration error", 500
66
+
67
+ if not verify_discord_request():
68
+ return "Invalid request signature", 401
69
+
70
+ try:
71
+ data = request.json
72
+
73
+ # Discord Ping Verification
74
+ if data.get("type") == 1:
75
+ logger.info("Responding to ping verification")
76
+ return jsonify({"type": 1})
77
+
78
+ # Slash Commands
79
+ if data.get("type") == 2:
80
+ command = data.get("data", {}).get("name")
81
+ logger.info(f"Received command: {command}")
82
+
83
+ if command == "settings":
84
+ return jsonify({
85
+ "type": 4,
86
+ "data": {
87
+ "content": "✅ Bot ist aktiv und verifiziert!"
88
+ }
89
+ })
90
+
91
+ return jsonify({"type": 1})
92
+
93
+ except Exception as e:
94
+ logger.error(f"Error processing request: {str(e)}")
95
+ return "Internal server error", 500
96
+
97
+ def health_check_worker():
98
+ """Background worker der regelmäßig den Health-Check Endpoint aufruft"""
99
+ while True:
100
+ try:
101
+ response = requests.get(f"http://localhost:{PORT}/")
102
+ logger.info(f"Health check status: {response.status_code}")
103
+ except Exception as e:
104
+ logger.error(f"Health check failed: {str(e)}")
105
+ time.sleep(30)
106
+
107
+ if __name__ == "__main__":
108
+ logger.info(f"Starting Discord bot on port {PORT}...")
109
+
110
+ # Starte Health-Check Worker in separatem Thread
111
+ health_thread = threading.Thread(target=health_check_worker, daemon=True)
112
+ health_thread.start()
113
+
114
+ # Starte Server
115
+ serve(app, host="0.0.0.0", port=PORT)