Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,78 +1,343 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import os
|
| 5 |
-
import requests
|
| 6 |
import logging
|
| 7 |
-
import
|
| 8 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
logging.basicConfig(
|
| 12 |
level=logging.INFO,
|
| 13 |
-
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 14 |
)
|
| 15 |
-
logger = logging.getLogger(
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
logger.error("
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
headers = {
|
| 45 |
-
"Authorization": f"Bot {
|
| 46 |
"Content-Type": "application/json"
|
| 47 |
}
|
| 48 |
-
|
| 49 |
-
# Ein Beispielkommando, das wir registrieren würden
|
| 50 |
-
commands_to_register = [{
|
| 51 |
-
"name": "ping",
|
| 52 |
-
"description": "Antwortet mit Pong!",
|
| 53 |
-
"type": 1
|
| 54 |
-
}]
|
| 55 |
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
-
logger.info(f"Versuche, Kommandos an {url} zu senden...")
|
| 59 |
-
response = requests.put(url, headers=headers, json=commands_to_register, timeout=10)
|
| 60 |
-
|
| 61 |
-
# Überprüfe den Status-Code der Antwort
|
| 62 |
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
except Exception as e:
|
| 75 |
-
logger.error(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
if __name__ == "__main__":
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# Flask backend for Discord Bot interactions
|
| 3 |
+
# Handles Discord interaction requests and routes commands to bank logic
|
| 4 |
+
# Minimalist, efficient, and designed for integration with bank.py
|
| 5 |
+
# Author: V. Kücükbudak, 2025
|
| 6 |
+
# License: See LICENSE file for usage restrictions
|
| 7 |
+
from flask import Flask, request, jsonify
|
| 8 |
import os
|
|
|
|
| 9 |
import logging
|
| 10 |
+
from waitress import serve
|
| 11 |
+
from nacl.signing import VerifyKey
|
| 12 |
+
from nacl.exceptions import BadSignatureError
|
| 13 |
+
import threading
|
| 14 |
+
import requests
|
| 15 |
+
import time
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
import asyncio
|
| 18 |
+
|
| 19 |
+
# --- Importiere das Bank-Modul ---
|
| 20 |
+
import bank
|
| 21 |
+
|
| 22 |
+
# --- Importiere HOF-Update-Skript ---
|
| 23 |
+
try:
|
| 24 |
+
import update_hof
|
| 25 |
+
HOF_SCRIPT_AVAILABLE = True
|
| 26 |
+
except ImportError:
|
| 27 |
+
HOF_SCRIPT_AVAILABLE = False
|
| 28 |
+
print("WARNUNG: update_hof.py konnte nicht gefunden werden. Der /update-hof Befehl wird nicht funktionieren.")
|
| 29 |
|
| 30 |
+
# Logging konfigurieren
|
| 31 |
logging.basicConfig(
|
| 32 |
level=logging.INFO,
|
| 33 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 34 |
)
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
# Konfiguration
|
| 38 |
+
PUBLIC_KEY = os.getenv('Public_Key', '').strip()
|
| 39 |
+
APPLICATION_ID = os.getenv('Application_ID', '').strip()
|
| 40 |
+
PORT = int(os.getenv('PORT', 7860))
|
| 41 |
+
BOT_TOKEN = os.getenv('BOT_TOKEN', '').strip()
|
| 42 |
+
GUILD_ID = os.getenv('GUILD_ID', '').strip()
|
| 43 |
+
|
| 44 |
+
app = Flask(__name__)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
|
| 48 |
+
logger.info("Successfully initialized verify_key")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.error(f"Error initializing verify_key: {str(e)}")
|
| 51 |
+
verify_key = None
|
| 52 |
+
|
| 53 |
+
START_TIME = datetime.utcnow()
|
| 54 |
+
|
| 55 |
+
# --- Hilfsfunktionen für Follow-up-Nachrichten ---
|
| 56 |
+
def send_followup_message(application_id, interaction_token, bot_token, content, flags=0):
|
| 57 |
+
"""Sendet eine Follow-up-Nachricht an eine Discord-Interaktion."""
|
| 58 |
+
url = f"https://discord.com/api/v10/webhooks/{application_id}/{interaction_token}"
|
| 59 |
+
headers = {"Authorization": f"Bot {bot_token}"}
|
| 60 |
+
json_data = {"content": content, "flags": flags}
|
| 61 |
+
try:
|
| 62 |
+
response = requests.post(url, headers=headers, json=json_data, timeout=10)
|
| 63 |
+
response.raise_for_status()
|
| 64 |
+
except requests.exceptions.RequestException as e:
|
| 65 |
+
logger.error(f"Fehler beim Senden der Follow-up Nachricht: {e}")
|
| 66 |
+
|
| 67 |
+
# --- Background-Funktion für HOF-Update ---
|
| 68 |
+
def run_hof_update_background(interaction_token):
|
| 69 |
+
logger.info("Starte HOF-Update im Hintergrund...")
|
| 70 |
+
try:
|
| 71 |
+
update_hof.main()
|
| 72 |
+
status_message = "✅ Hall of Fame Update wurde erfolgreich angestoßen und abgeschlossen. Details siehe Logs."
|
| 73 |
+
logger.info("HOF-Update-Skript erfolgreich durchgelaufen.")
|
| 74 |
+
except Exception as e:
|
| 75 |
+
status_message = f"❌ Beim Ausführen des Hall of Fame Updates ist ein Fehler aufgetreten.\n**Fehler:** `{str(e)}`"
|
| 76 |
+
logger.error(f"Fehler im HOF-Update-Skript: {e}", exc_info=True)
|
| 77 |
|
| 78 |
+
send_followup_message(APPLICATION_ID, interaction_token, BOT_TOKEN, status_message)
|
| 79 |
+
|
| 80 |
+
# --- NEU: Backup-Service für Bankdaten ---
|
| 81 |
+
def start_bank_backup_service():
|
| 82 |
+
"""Startet den stündlichen Backup-Service für Bankdaten"""
|
| 83 |
+
try:
|
| 84 |
+
import upload_bank_data
|
| 85 |
+
logger.info("Starte Bankdaten-Backup-Service...")
|
| 86 |
+
upload_bank_data.main()
|
| 87 |
+
except ImportError as e:
|
| 88 |
+
logger.warning(f"upload_bank_data.py nicht gefunden. Bankdaten-Backup deaktiviert. Fehler: {e}")
|
| 89 |
+
|
| 90 |
+
# --- NEU: Callback-Funktion zum Senden des Ergebnisses der Bank-Operation ---
|
| 91 |
+
def send_bank_result_callback(future, application_id, interaction_token, bot_token):
|
| 92 |
+
"""Wird aufgerufen, wenn die Bank-Operation abgeschlossen ist, um die Follow-up-Nachricht zu senden."""
|
| 93 |
try:
|
| 94 |
+
result = future.result() # Holen des Ergebnisses aus der Future
|
| 95 |
+
content = result['content']
|
| 96 |
+
flags = result['flags']
|
| 97 |
+
send_followup_message(application_id, interaction_token, bot_token, content, flags)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
logger.error(f"Fehler beim Senden der Bank-Follow-up-Nachricht (Callback): {e}", exc_info=True)
|
| 100 |
+
send_followup_message(application_id, interaction_token, bot_token,
|
| 101 |
+
"❌ Ein kritischer Fehler ist bei der Verarbeitung deines Bankbefehls aufgetreten.", 64)
|
| 102 |
+
|
| 103 |
+
# --- Funktion zur Registrierung von Discord Slash Commands ---
|
| 104 |
+
def register_commands():
|
| 105 |
+
commands_to_register = [
|
| 106 |
+
{
|
| 107 |
+
"name": "settings",
|
| 108 |
+
"description": "Zeigt Bot-Einstellungen und Status an.",
|
| 109 |
+
"type": 1
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"name": "update-hof",
|
| 113 |
+
"description": "Löst ein manuelles Update der Hall of Fame aus (nur für Admins).",
|
| 114 |
+
"type": 1
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"name": "balance",
|
| 118 |
+
"description": "Zeigt dein aktuelles Bankguthaben an.",
|
| 119 |
+
"type": 1
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"name": "daily",
|
| 123 |
+
"description": "Fordere deine tägliche Belohnung ein.",
|
| 124 |
+
"type": 1
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"name": "transfer",
|
| 128 |
+
"description": "Überweist Credits an einen anderen Benutzer.",
|
| 129 |
+
"type": 1,
|
| 130 |
+
"options": [
|
| 131 |
+
{
|
| 132 |
+
"name": "recipient",
|
| 133 |
+
"description": "Der Benutzer, an den du Credits überweisen möchtest.",
|
| 134 |
+
"type": 6, # USER
|
| 135 |
+
"required": True
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"name": "amount",
|
| 139 |
+
"description": "Die Menge an Credits, die du überweisen möchtest.",
|
| 140 |
+
"type": 10, # NUMBER
|
| 141 |
+
"required": True
|
| 142 |
+
}
|
| 143 |
+
]
|
| 144 |
+
}
|
| 145 |
+
]
|
| 146 |
+
|
| 147 |
+
if GUILD_ID:
|
| 148 |
+
url = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands"
|
| 149 |
+
logger.info(f"Registriere Befehle für Gilde ID: {GUILD_ID}")
|
| 150 |
+
else:
|
| 151 |
+
url = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/commands"
|
| 152 |
+
logger.info("Registriere globale Befehle (kann bis zu 1 Stunde dauern, bis sie erscheinen!)")
|
| 153 |
+
|
| 154 |
headers = {
|
| 155 |
+
"Authorization": f"Bot {BOT_TOKEN}",
|
| 156 |
"Content-Type": "application/json"
|
| 157 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
try:
|
| 160 |
+
response = requests.put(url, headers=headers, json=commands_to_register)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
response.raise_for_status()
|
| 162 |
+
logger.info("Slash-Befehle erfolgreich bei Discord registriert.")
|
| 163 |
+
logger.debug(f"Discord API Antwort: {response.json()}")
|
| 164 |
+
except requests.exceptions.RequestException as e:
|
| 165 |
+
logger.error(f"Fehler beim Registrieren der Slash-Befehle bei Discord: {e}", exc_info=True)
|
| 166 |
+
if hasattr(e, 'response') and e.response is not None:
|
| 167 |
+
logger.error(f"Discord API Fehlerdetails: {e.response.text}")
|
| 168 |
+
except Exception as e:
|
| 169 |
+
logger.error(f"Ein unerwarteter Fehler beim Registrieren der Befehle ist aufgetreten: {e}", exc_info=True)
|
| 170 |
+
|
| 171 |
+
# --- Standard-Funktionen und -Routen ---
|
| 172 |
+
|
| 173 |
+
def verify_discord_request():
|
| 174 |
+
try:
|
| 175 |
+
signature = request.headers.get('X-Signature-Ed25519')
|
| 176 |
+
timestamp = request.headers.get('X-Signature-Timestamp')
|
| 177 |
+
|
| 178 |
+
if not signature or not timestamp:
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
body = request.data.decode('utf-8')
|
| 182 |
+
verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
|
| 183 |
+
return True
|
| 184 |
+
except Exception as e:
|
| 185 |
+
logger.error(f"Verification error: {str(e)}")
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
@app.route("/", methods=["GET"])
|
| 189 |
+
def health_check():
|
| 190 |
+
"""Hugging Face nutzt diesen Endpoint um zu prüfen ob der Space läuft"""
|
| 191 |
+
return jsonify({
|
| 192 |
+
"status": "running",
|
| 193 |
+
"message": "Discord bot is running!",
|
| 194 |
+
"hof_script_found": HOF_SCRIPT_AVAILABLE
|
| 195 |
+
})
|
| 196 |
+
|
| 197 |
+
@app.route("/interactions", methods=["POST"])
|
| 198 |
+
def interactions():
|
| 199 |
+
if not verify_key or not verify_discord_request():
|
| 200 |
+
return "Invalid request signature", 401
|
| 201 |
+
|
| 202 |
+
try:
|
| 203 |
+
data = request.json
|
| 204 |
|
| 205 |
+
if data.get("type") == 1: # Ping
|
| 206 |
+
return jsonify({"type": 1})
|
| 207 |
+
|
| 208 |
+
if data.get("type") == 2: # Command
|
| 209 |
+
command_data = data.get("data", {})
|
| 210 |
+
command_name = command_data.get("name")
|
| 211 |
+
user_id = data.get("member", {}).get("user", {}).get("id")
|
| 212 |
+
interaction_token = data["token"]
|
| 213 |
+
options = command_data.get("options", [])
|
| 214 |
+
|
| 215 |
+
logger.info(f"Received command: {command_name} from user {user_id}")
|
| 216 |
+
|
| 217 |
+
if command_name == "settings":
|
| 218 |
+
uptime_delta = datetime.utcnow() - START_TIME
|
| 219 |
+
days, rem = divmod(uptime_delta.total_seconds(), 86400)
|
| 220 |
+
hours, rem = divmod(rem, 3600)
|
| 221 |
+
minutes, _ = divmod(rem, 60)
|
| 222 |
+
uptime_str = f"{int(days)}d {int(hours)}h {int(minutes)}m"
|
| 223 |
+
server_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S MEZ")
|
| 224 |
+
content = (
|
| 225 |
+
f"**Bot Status**\n"
|
| 226 |
+
f"✅ **Status:** Aktiv und verifiziert!\n"
|
| 227 |
+
f"⏰ **Server-Zeit:** `{server_time_str}`\n"
|
| 228 |
+
f"🚀 **Uptime:** `{uptime_str}`"
|
| 229 |
+
)
|
| 230 |
+
return jsonify({"type": 4, "data": {"content": content}})
|
| 231 |
+
|
| 232 |
+
elif command_name == "update-hof":
|
| 233 |
+
permissions = data.get("member", {}).get("permissions")
|
| 234 |
+
is_admin = permissions and (int(permissions) & 0x8) == 0x8
|
| 235 |
+
|
| 236 |
+
if not is_admin:
|
| 237 |
+
return jsonify({
|
| 238 |
+
"type": 4,
|
| 239 |
+
"data": {"content": "❌ Du hast keine Berechtigung, diesen Befehl auszuführen.", "flags": 64}
|
| 240 |
+
})
|
| 241 |
+
|
| 242 |
+
if not HOF_SCRIPT_AVAILABLE:
|
| 243 |
+
return jsonify({
|
| 244 |
+
"type": 4,
|
| 245 |
+
"data": {"content": "❌ Das `update_hof.py` Skript konnte auf dem Server nicht gefunden werden."}
|
| 246 |
+
})
|
| 247 |
+
|
| 248 |
+
threading.Thread(target=run_hof_update_background, args=(interaction_token,)).start()
|
| 249 |
+
return jsonify({"type": 5})
|
| 250 |
+
|
| 251 |
+
# --- Bankbefehle: Aufgabe in Queue legen ---
|
| 252 |
+
elif command_name in ["balance", "daily", "transfer"]:
|
| 253 |
+
if bank.bank_system_instance is None:
|
| 254 |
+
return jsonify({"type": 4, "data": {"content": "Die Bank ist noch nicht bereit. Bitte versuche es in Kürze erneut.", "flags": 64}})
|
| 255 |
+
|
| 256 |
+
# Wir legen die Aufgabe in die Queue, aber die Future muss im Event-Loop des Bank-Threads erstellt werden.
|
| 257 |
+
# Dazu erstellen wir eine Coroutine, die das macht und geben sie an run_coroutine_threadsafe.
|
| 258 |
+
async def put_task_and_get_future():
|
| 259 |
+
# Eine Future im Event-Loop des Bank-Threads erstellen
|
| 260 |
+
cmd_future = asyncio.get_event_loop().create_future()
|
| 261 |
+
await bank.bank_task_queue.put({
|
| 262 |
+
'command_name': command_name,
|
| 263 |
+
'user_id': user_id,
|
| 264 |
+
'interaction_token': interaction_token,
|
| 265 |
+
'options': options,
|
| 266 |
+
'future': cmd_future # Die im Bank-Loop erstellte Future
|
| 267 |
+
})
|
| 268 |
+
return cmd_future # Diese Future zurückgeben
|
| 269 |
+
|
| 270 |
+
# Führe die Coroutine im Bank-Thread aus und hole die Future zurück
|
| 271 |
+
# Diese `command_future` ist im Event-Loop gebunden.
|
| 272 |
+
command_future = asyncio.run_coroutine_threadsafe(
|
| 273 |
+
put_task_and_get_future(),
|
| 274 |
+
bank.bank_system_instance._asyncio_loop
|
| 275 |
+
).result() # `.result()` blockiert hier, bis die Future ERSTELLT wurde (nicht bis die Aufgabe fertig ist)
|
| 276 |
+
|
| 277 |
+
# Wenn das Ergebnis verfügbar ist, sende die Follow-up-Nachricht
|
| 278 |
+
# Wir müssen einen separaten Thread dafür nutzen, weil add_done_callback im gleichen Loop läuft
|
| 279 |
+
# und der Event-Loop des Bank-Systems blockiert wäre, wenn der Callback synchron ist .
|
| 280 |
+
# Eigentlich! Werde nochmal nachdenken!
|
| 281 |
+
threading.Thread(target=lambda: command_future.add_done_callback(
|
| 282 |
+
lambda f: send_bank_result_callback(f, APPLICATION_ID, interaction_token, BOT_TOKEN)
|
| 283 |
+
)).start()
|
| 284 |
+
|
| 285 |
+
return jsonify({"type": 5}) # DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE
|
| 286 |
+
|
| 287 |
+
return jsonify({"type": 1})
|
| 288 |
+
|
| 289 |
except Exception as e:
|
| 290 |
+
logger.error(f"Error processing request: {str(e)}", exc_info=True)
|
| 291 |
+
return "Internal server error", 500
|
| 292 |
+
|
| 293 |
+
def health_check_worker():
|
| 294 |
+
"""Background worker der regelmäßig den Health-Check Endpoint aufruft"""
|
| 295 |
+
while True:
|
| 296 |
+
time.sleep(3600)
|
| 297 |
+
try:
|
| 298 |
+
response = requests.get(f"http://127.0.0.1:{PORT}/")
|
| 299 |
+
logger.info(f"Health check status: {response.status_code}")
|
| 300 |
+
except Exception as e:
|
| 301 |
+
logger.error(f"Health check failed: {str(e)}")
|
| 302 |
+
|
| 303 |
+
# --- NEU: Funktion zum Starten des Bank-Systems im eigenen Asyncio Loop, ist nämlich stabiler so als mit waitress ---
|
| 304 |
+
def start_bank_system_loop_in_thread():
|
| 305 |
+
"""Startet den dedizierten asyncio Event Loop für das Bank-System."""
|
| 306 |
+
loop = asyncio.new_event_loop()
|
| 307 |
+
asyncio.set_event_loop(loop)
|
| 308 |
+
bank.bank_system_instance._asyncio_loop = loop # Speichere den Loop im BankSystem-Instanz! Sehr wichtig da wir die Daten bei HF im /tmp bereich lassen. Achtung!
|
| 309 |
+
# Nicht gespeicherte Dateien gehen verloren! Beachte upload_bank_data.py die als vorlage für jegilche server dienen kann, bei diesem Test haben wir für eine Seite Neocities.org genommen.
|
| 310 |
+
try:
|
| 311 |
+
loop.run_until_complete(bank.initialize_bank_system_and_run_tasks())
|
| 312 |
+
finally:
|
| 313 |
+
loop.close()
|
| 314 |
|
| 315 |
if __name__ == "__main__":
|
| 316 |
+
logger.info(f"Starting Discord bot on port {PORT}...")
|
| 317 |
+
|
| 318 |
+
# Bank-System vor Thread-Start initialisieren
|
| 319 |
+
bank.bank_system_instance = bank.BankSystem()
|
| 320 |
+
|
| 321 |
+
# Bank-System in eigenem Thread starten
|
| 322 |
+
bank_thread = threading.Thread(target=start_bank_system_loop_in_thread, daemon=True)
|
| 323 |
+
bank_thread.start()
|
| 324 |
+
|
| 325 |
+
# Kurze Pause für Initialisierung!
|
| 326 |
+
time.sleep(2)
|
| 327 |
+
logger.info("Bank-System Initialisierungs-Thread gestartet und Event Loop läuft.")
|
| 328 |
+
|
| 329 |
+
if not BOT_TOKEN:
|
| 330 |
+
logger.warning("WARNUNG: BOT_TOKEN ist nicht gesetzt. Follow-up-Nachrichten und Befehlsregistrierung werden fehlschlagen.")
|
| 331 |
+
else:
|
| 332 |
+
register_commands()
|
| 333 |
+
|
| 334 |
+
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 335 |
+
health_thread.start()
|
| 336 |
+
|
| 337 |
+
# Starte Bankdaten-Backup-Service
|
| 338 |
+
backup_thread = threading.Thread(target=start_bank_backup_service, daemon=True)
|
| 339 |
+
backup_thread.start()
|
| 340 |
+
logger.info("Bankdaten-Backup-Service gestartet.")
|
| 341 |
+
|
| 342 |
+
logger.info("Starting Flask app with Waitress server...")
|
| 343 |
+
serve(app, host="0.0.0.0", port=PORT)
|