Spaces:
Running
Running
Update app/app.py
Browse files- app/app.py +81 -53
app/app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py -
|
| 2 |
# Flask backend for Discord Bot interactions
|
| 3 |
# Main application logic and command routing.
|
| 4 |
# Author: V. Kücükbudak, 2025
|
|
@@ -12,26 +12,22 @@ import time
|
|
| 12 |
from datetime import datetime
|
| 13 |
import asyncio
|
| 14 |
import sys
|
|
|
|
| 15 |
|
| 16 |
-
# --- Fundaments
|
| 17 |
-
from . import bank
|
| 18 |
-
from . import discord_api
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
# import app.bank as bank
|
| 22 |
-
# import app.discord_api as discord_api
|
| 23 |
-
|
| 24 |
-
# --- Fundaments importieren (absoluter Import) ---
|
| 25 |
from fundaments.config_handler import config_service
|
| 26 |
|
| 27 |
-
# Rest deines Codes bleibt gleich...
|
| 28 |
logging.basicConfig(
|
| 29 |
level=logging.INFO,
|
| 30 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 31 |
)
|
| 32 |
logger = logging.getLogger(__name__)
|
| 33 |
|
| 34 |
-
#
|
| 35 |
DISCORD_API_CLIENT = None
|
| 36 |
PORT = None
|
| 37 |
BOT_TOKEN = None
|
|
@@ -39,24 +35,47 @@ BOT_TOKEN = None
|
|
| 39 |
app = Flask(__name__)
|
| 40 |
START_TIME = datetime.utcnow()
|
| 41 |
|
| 42 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def send_bank_result_callback(future, interaction_token):
|
| 44 |
-
"""
|
| 45 |
try:
|
| 46 |
result = future.result()
|
| 47 |
content = result['content']
|
| 48 |
flags = result['flags']
|
| 49 |
DISCORD_API_CLIENT.send_followup_message(content, interaction_token, flags)
|
| 50 |
except Exception as e:
|
| 51 |
-
logger.error(f"
|
| 52 |
DISCORD_API_CLIENT.send_followup_message(
|
| 53 |
-
"❌
|
| 54 |
interaction_token,
|
| 55 |
flags=64
|
| 56 |
)
|
| 57 |
|
| 58 |
def start_bank_system_loop_in_thread():
|
| 59 |
-
"""
|
| 60 |
loop = asyncio.new_event_loop()
|
| 61 |
asyncio.set_event_loop(loop)
|
| 62 |
bank.bank_system_instance._asyncio_loop = loop
|
|
@@ -68,7 +87,7 @@ def start_bank_system_loop_in_thread():
|
|
| 68 |
# --- Flask Routes ---
|
| 69 |
@app.route("/", methods=["GET"])
|
| 70 |
def health_check():
|
| 71 |
-
"""Hugging Face
|
| 72 |
return jsonify({
|
| 73 |
"status": "running",
|
| 74 |
"message": "Discord bot is running!",
|
|
@@ -82,10 +101,10 @@ def interactions():
|
|
| 82 |
try:
|
| 83 |
data = request.json
|
| 84 |
|
| 85 |
-
if data.get("type") == 1:
|
| 86 |
return jsonify({"type": 1})
|
| 87 |
|
| 88 |
-
if data.get("type") == 2:
|
| 89 |
command_data = data.get("data", {})
|
| 90 |
command_name = command_data.get("name")
|
| 91 |
user_id = data.get("member", {}).get("user", {}).get("id") or data.get("user", {}).get("id")
|
|
@@ -103,16 +122,16 @@ def interactions():
|
|
| 103 |
server_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S MEZ")
|
| 104 |
content = (
|
| 105 |
f"**Bot Status**\n"
|
| 106 |
-
f"✅ **Status:**
|
| 107 |
-
f"⏰ **Server
|
| 108 |
f"🚀 **Uptime:** `{uptime_str}`"
|
| 109 |
)
|
| 110 |
return jsonify({"type": 4, "data": {"content": content}})
|
| 111 |
|
| 112 |
-
# ---
|
| 113 |
elif command_name in ["balance", "daily", "transfer"]:
|
| 114 |
if bank.bank_system_instance is None:
|
| 115 |
-
return jsonify({"type": 4, "data": {"content": "
|
| 116 |
|
| 117 |
async def put_task_and_get_future():
|
| 118 |
cmd_future = asyncio.get_event_loop().create_future()
|
|
@@ -133,7 +152,7 @@ def interactions():
|
|
| 133 |
lambda f: send_bank_result_callback(f, interaction_token)
|
| 134 |
)
|
| 135 |
|
| 136 |
-
return jsonify({"type": 5})
|
| 137 |
|
| 138 |
return jsonify({"type": 1})
|
| 139 |
|
|
@@ -142,7 +161,7 @@ def interactions():
|
|
| 142 |
return "Internal server error", 500
|
| 143 |
|
| 144 |
def health_check_worker():
|
| 145 |
-
"""Background worker
|
| 146 |
while True:
|
| 147 |
time.sleep(3600)
|
| 148 |
try:
|
|
@@ -152,22 +171,22 @@ def health_check_worker():
|
|
| 152 |
logger.error(f"Health check failed: {str(e)}")
|
| 153 |
|
| 154 |
def initialize_services(fundaments=None):
|
| 155 |
-
"""
|
| 156 |
global DISCORD_API_CLIENT, PORT, BOT_TOKEN
|
| 157 |
|
| 158 |
-
#
|
| 159 |
PORT = config_service.get_int('PORT', 7860)
|
| 160 |
BOT_TOKEN = config_service.get('BOT_TOKEN')
|
| 161 |
APPLICATION_ID = config_service.get('APPLICATION_ID')
|
| 162 |
PUBLIC_KEY = config_service.get('PUBLIC_KEY')
|
| 163 |
GUILD_ID = config_service.get('GUILD_ID')
|
| 164 |
|
| 165 |
-
#
|
| 166 |
if not BOT_TOKEN or not APPLICATION_ID or not PUBLIC_KEY:
|
| 167 |
-
logger.error("
|
| 168 |
sys.exit(1)
|
| 169 |
|
| 170 |
-
# Discord
|
| 171 |
DISCORD_API_CLIENT = discord_api.DiscordAPI(
|
| 172 |
application_id=APPLICATION_ID,
|
| 173 |
bot_token=BOT_TOKEN,
|
|
@@ -175,70 +194,79 @@ def initialize_services(fundaments=None):
|
|
| 175 |
public_key=PUBLIC_KEY
|
| 176 |
)
|
| 177 |
|
| 178 |
-
#
|
| 179 |
bank.bank_system_instance = bank.BankSystem()
|
| 180 |
|
| 181 |
-
logger.info("Services
|
| 182 |
|
| 183 |
async def start_application(fundaments=None):
|
| 184 |
"""
|
| 185 |
-
Async-
|
| 186 |
"""
|
| 187 |
-
logger.info("
|
| 188 |
|
| 189 |
-
#
|
| 190 |
initialize_services(fundaments)
|
| 191 |
|
| 192 |
-
#
|
| 193 |
bank_thread = threading.Thread(target=start_bank_system_loop_in_thread, daemon=True)
|
| 194 |
bank_thread.start()
|
| 195 |
|
| 196 |
-
#
|
| 197 |
await asyncio.sleep(2)
|
| 198 |
-
logger.info("Bank
|
| 199 |
|
| 200 |
-
#
|
| 201 |
-
DISCORD_API_CLIENT.register_commands()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
#
|
| 204 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 205 |
health_thread.start()
|
| 206 |
|
| 207 |
-
logger.info(f"
|
| 208 |
|
| 209 |
-
# Waitress
|
| 210 |
def run_server():
|
| 211 |
serve(app, host="0.0.0.0", port=PORT)
|
| 212 |
|
| 213 |
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 214 |
server_thread.start()
|
| 215 |
|
| 216 |
-
logger.info("Flask
|
| 217 |
|
| 218 |
-
# Hier könntest du weitere async Tasks hinzufügen
|
| 219 |
try:
|
| 220 |
-
# Endlos-Loop um die Anwendung am Laufen zu halten
|
| 221 |
while True:
|
| 222 |
-
await asyncio.sleep(60)
|
| 223 |
logger.debug("Application heartbeat")
|
| 224 |
except KeyboardInterrupt:
|
| 225 |
-
logger.info("
|
| 226 |
|
| 227 |
-
#
|
| 228 |
if __name__ == "__main__":
|
| 229 |
-
logger.info(f"
|
| 230 |
|
| 231 |
initialize_services()
|
| 232 |
|
| 233 |
-
#
|
| 234 |
bank_thread = threading.Thread(target=start_bank_system_loop_in_thread, daemon=True)
|
| 235 |
bank_thread.start()
|
| 236 |
time.sleep(2)
|
| 237 |
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 241 |
health_thread.start()
|
| 242 |
|
| 243 |
logger.info("Starting Flask app with Waitress server...")
|
| 244 |
-
serve(app, host="0.0.0.0", port=config_service.get_int('PORT', 7860))
|
|
|
|
| 1 |
+
# app/app.py - Extended Version
|
| 2 |
# Flask backend for Discord Bot interactions
|
| 3 |
# Main application logic and command routing.
|
| 4 |
# Author: V. Kücükbudak, 2025
|
|
|
|
| 12 |
from datetime import datetime
|
| 13 |
import asyncio
|
| 14 |
import sys
|
| 15 |
+
import socket # added for DNS check
|
| 16 |
|
| 17 |
+
# --- Fundaments imports ---
|
| 18 |
+
from . import bank
|
| 19 |
+
from . import discord_api
|
| 20 |
|
| 21 |
+
# --- Absolute imports from fundaments ---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
from fundaments.config_handler import config_service
|
| 23 |
|
|
|
|
| 24 |
logging.basicConfig(
|
| 25 |
level=logging.INFO,
|
| 26 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 27 |
)
|
| 28 |
logger = logging.getLogger(__name__)
|
| 29 |
|
| 30 |
+
# Global configuration variables
|
| 31 |
DISCORD_API_CLIENT = None
|
| 32 |
PORT = None
|
| 33 |
BOT_TOKEN = None
|
|
|
|
| 35 |
app = Flask(__name__)
|
| 36 |
START_TIME = datetime.utcnow()
|
| 37 |
|
| 38 |
+
# --- DNS Wait Helpers ---
|
| 39 |
+
async def wait_for_dns(host="discord.com", timeout=15):
|
| 40 |
+
"""Async: wait until DNS resolution for host works or timeout occurs."""
|
| 41 |
+
start = time.time()
|
| 42 |
+
while time.time() - start < timeout:
|
| 43 |
+
try:
|
| 44 |
+
socket.gethostbyname(host)
|
| 45 |
+
return True
|
| 46 |
+
except socket.gaierror:
|
| 47 |
+
await asyncio.sleep(1)
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
def wait_for_dns_sync(host="discord.com", timeout=15):
|
| 51 |
+
"""Sync: wait until DNS resolution for host works or timeout occurs."""
|
| 52 |
+
start = time.time()
|
| 53 |
+
while time.time() - start < timeout:
|
| 54 |
+
try:
|
| 55 |
+
socket.gethostbyname(host)
|
| 56 |
+
return True
|
| 57 |
+
except socket.gaierror:
|
| 58 |
+
time.sleep(1)
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
# --- Bank callback ---
|
| 62 |
def send_bank_result_callback(future, interaction_token):
|
| 63 |
+
"""Called when the bank operation finishes, sends a follow-up message."""
|
| 64 |
try:
|
| 65 |
result = future.result()
|
| 66 |
content = result['content']
|
| 67 |
flags = result['flags']
|
| 68 |
DISCORD_API_CLIENT.send_followup_message(content, interaction_token, flags)
|
| 69 |
except Exception as e:
|
| 70 |
+
logger.error(f"Error sending bank follow-up message (callback): {e}", exc_info=True)
|
| 71 |
DISCORD_API_CLIENT.send_followup_message(
|
| 72 |
+
"❌ A critical error occurred while processing your bank command.",
|
| 73 |
interaction_token,
|
| 74 |
flags=64
|
| 75 |
)
|
| 76 |
|
| 77 |
def start_bank_system_loop_in_thread():
|
| 78 |
+
"""Starts the dedicated asyncio event loop for the bank system."""
|
| 79 |
loop = asyncio.new_event_loop()
|
| 80 |
asyncio.set_event_loop(loop)
|
| 81 |
bank.bank_system_instance._asyncio_loop = loop
|
|
|
|
| 87 |
# --- Flask Routes ---
|
| 88 |
@app.route("/", methods=["GET"])
|
| 89 |
def health_check():
|
| 90 |
+
"""Used by Hugging Face to check if the Space is running."""
|
| 91 |
return jsonify({
|
| 92 |
"status": "running",
|
| 93 |
"message": "Discord bot is running!",
|
|
|
|
| 101 |
try:
|
| 102 |
data = request.json
|
| 103 |
|
| 104 |
+
if data.get("type") == 1: # Ping
|
| 105 |
return jsonify({"type": 1})
|
| 106 |
|
| 107 |
+
if data.get("type") == 2: # Command
|
| 108 |
command_data = data.get("data", {})
|
| 109 |
command_name = command_data.get("name")
|
| 110 |
user_id = data.get("member", {}).get("user", {}).get("id") or data.get("user", {}).get("id")
|
|
|
|
| 122 |
server_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S MEZ")
|
| 123 |
content = (
|
| 124 |
f"**Bot Status**\n"
|
| 125 |
+
f"✅ **Status:** Active and verified!\n"
|
| 126 |
+
f"⏰ **Server Time:** `{server_time_str}`\n"
|
| 127 |
f"🚀 **Uptime:** `{uptime_str}`"
|
| 128 |
)
|
| 129 |
return jsonify({"type": 4, "data": {"content": content}})
|
| 130 |
|
| 131 |
+
# --- Bank commands: add task to queue ---
|
| 132 |
elif command_name in ["balance", "daily", "transfer"]:
|
| 133 |
if bank.bank_system_instance is None:
|
| 134 |
+
return jsonify({"type": 4, "data": {"content": "Bank system not ready yet. Please try again shortly.", "flags": 64}})
|
| 135 |
|
| 136 |
async def put_task_and_get_future():
|
| 137 |
cmd_future = asyncio.get_event_loop().create_future()
|
|
|
|
| 152 |
lambda f: send_bank_result_callback(f, interaction_token)
|
| 153 |
)
|
| 154 |
|
| 155 |
+
return jsonify({"type": 5}) # DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE
|
| 156 |
|
| 157 |
return jsonify({"type": 1})
|
| 158 |
|
|
|
|
| 161 |
return "Internal server error", 500
|
| 162 |
|
| 163 |
def health_check_worker():
|
| 164 |
+
"""Background worker that periodically calls the health-check endpoint."""
|
| 165 |
while True:
|
| 166 |
time.sleep(3600)
|
| 167 |
try:
|
|
|
|
| 171 |
logger.error(f"Health check failed: {str(e)}")
|
| 172 |
|
| 173 |
def initialize_services(fundaments=None):
|
| 174 |
+
"""Initialize services with optional fundaments."""
|
| 175 |
global DISCORD_API_CLIENT, PORT, BOT_TOKEN
|
| 176 |
|
| 177 |
+
# Load configuration values
|
| 178 |
PORT = config_service.get_int('PORT', 7860)
|
| 179 |
BOT_TOKEN = config_service.get('BOT_TOKEN')
|
| 180 |
APPLICATION_ID = config_service.get('APPLICATION_ID')
|
| 181 |
PUBLIC_KEY = config_service.get('PUBLIC_KEY')
|
| 182 |
GUILD_ID = config_service.get('GUILD_ID')
|
| 183 |
|
| 184 |
+
# Validation
|
| 185 |
if not BOT_TOKEN or not APPLICATION_ID or not PUBLIC_KEY:
|
| 186 |
+
logger.error("Critical error: Missing Discord environment variables.")
|
| 187 |
sys.exit(1)
|
| 188 |
|
| 189 |
+
# Initialize Discord API client
|
| 190 |
DISCORD_API_CLIENT = discord_api.DiscordAPI(
|
| 191 |
application_id=APPLICATION_ID,
|
| 192 |
bot_token=BOT_TOKEN,
|
|
|
|
| 194 |
public_key=PUBLIC_KEY
|
| 195 |
)
|
| 196 |
|
| 197 |
+
# Initialize bank system
|
| 198 |
bank.bank_system_instance = bank.BankSystem()
|
| 199 |
|
| 200 |
+
logger.info("Services initialized successfully.")
|
| 201 |
|
| 202 |
async def start_application(fundaments=None):
|
| 203 |
"""
|
| 204 |
+
Async-compatible start function for main.py
|
| 205 |
"""
|
| 206 |
+
logger.info("Starting Discord bot application...")
|
| 207 |
|
| 208 |
+
# Initialize services
|
| 209 |
initialize_services(fundaments)
|
| 210 |
|
| 211 |
+
# Start bank system in its own thread
|
| 212 |
bank_thread = threading.Thread(target=start_bank_system_loop_in_thread, daemon=True)
|
| 213 |
bank_thread.start()
|
| 214 |
|
| 215 |
+
# Short pause for initialization
|
| 216 |
await asyncio.sleep(2)
|
| 217 |
+
logger.info("Bank system thread started.")
|
| 218 |
|
| 219 |
+
# --- Old direct call ---
|
| 220 |
+
# DISCORD_API_CLIENT.register_commands()
|
| 221 |
+
# --- New: wait for DNS before registering commands ---
|
| 222 |
+
if await wait_for_dns():
|
| 223 |
+
DISCORD_API_CLIENT.register_commands()
|
| 224 |
+
else:
|
| 225 |
+
logger.error("DNS resolution for discord.com failed. Commands not registered.")
|
| 226 |
|
| 227 |
+
# Start health check worker
|
| 228 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 229 |
health_thread.start()
|
| 230 |
|
| 231 |
+
logger.info(f"Starting Flask app with Waitress on port {PORT}...")
|
| 232 |
|
| 233 |
+
# Run Waitress server in its own thread
|
| 234 |
def run_server():
|
| 235 |
serve(app, host="0.0.0.0", port=PORT)
|
| 236 |
|
| 237 |
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 238 |
server_thread.start()
|
| 239 |
|
| 240 |
+
logger.info("Flask server started. Bot is running...")
|
| 241 |
|
|
|
|
| 242 |
try:
|
|
|
|
| 243 |
while True:
|
| 244 |
+
await asyncio.sleep(60)
|
| 245 |
logger.debug("Application heartbeat")
|
| 246 |
except KeyboardInterrupt:
|
| 247 |
+
logger.info("Application shutting down...")
|
| 248 |
|
| 249 |
+
# For direct execution (backwards compatibility)
|
| 250 |
if __name__ == "__main__":
|
| 251 |
+
logger.info(f"Starting Discord bot on port {config_service.get_int('PORT', 7860)}...")
|
| 252 |
|
| 253 |
initialize_services()
|
| 254 |
|
| 255 |
+
# Start bank system thread
|
| 256 |
bank_thread = threading.Thread(target=start_bank_system_loop_in_thread, daemon=True)
|
| 257 |
bank_thread.start()
|
| 258 |
time.sleep(2)
|
| 259 |
|
| 260 |
+
# --- Old direct call ---
|
| 261 |
+
# DISCORD_API_CLIENT.register_commands()
|
| 262 |
+
# --- New: wait for DNS before registering commands ---
|
| 263 |
+
if wait_for_dns_sync():
|
| 264 |
+
DISCORD_API_CLIENT.register_commands()
|
| 265 |
+
else:
|
| 266 |
+
logger.error("DNS resolution for discord.com failed. Commands not registered.")
|
| 267 |
|
| 268 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 269 |
health_thread.start()
|
| 270 |
|
| 271 |
logger.info("Starting Flask app with Waitress server...")
|
| 272 |
+
serve(app, host="0.0.0.0", port=config_service.get_int('PORT', 7860))
|