Alibrown commited on
Commit
030e7f6
·
verified ·
1 Parent(s): 11bcb6e

Update app/app.py

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