Spaces:
Running
Running
Update app/app.py
Browse files- app/app.py +88 -10
app/app.py
CHANGED
|
@@ -36,28 +36,71 @@ app = Flask(__name__)
|
|
| 36 |
START_TIME = datetime.utcnow()
|
| 37 |
|
| 38 |
# --- DNS Wait Helpers ---
|
| 39 |
-
async def wait_for_dns(host="discord.com", timeout=
|
| 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 |
-
|
|
|
|
| 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."""
|
|
@@ -74,6 +117,7 @@ def send_bank_result_callback(future, 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()
|
|
@@ -93,6 +137,7 @@ def health_check():
|
|
| 93 |
"message": "Discord bot is running!",
|
| 94 |
})
|
| 95 |
|
|
|
|
| 96 |
@app.route("/interactions", methods=["POST"])
|
| 97 |
def interactions():
|
| 98 |
if not DISCORD_API_CLIENT.verify_discord_request():
|
|
@@ -160,6 +205,7 @@ def interactions():
|
|
| 160 |
logger.error(f"Error processing request: {str(e)}", exc_info=True)
|
| 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:
|
|
@@ -170,6 +216,24 @@ def health_check_worker():
|
|
| 170 |
except Exception as e:
|
| 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
|
|
@@ -199,6 +263,7 @@ def initialize_services(fundaments=None):
|
|
| 199 |
|
| 200 |
logger.info("Services initialized successfully.")
|
| 201 |
|
|
|
|
| 202 |
async def start_application(fundaments=None):
|
| 203 |
"""
|
| 204 |
Async-compatible start function for main.py
|
|
@@ -220,9 +285,14 @@ async def start_application(fundaments=None):
|
|
| 220 |
# DISCORD_API_CLIENT.register_commands()
|
| 221 |
# --- New: wait for DNS before registering commands ---
|
| 222 |
if await wait_for_dns():
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
else:
|
| 225 |
-
logger.error("DNS resolution for discord.com failed.
|
|
|
|
| 226 |
|
| 227 |
# Start health check worker
|
| 228 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
|
@@ -236,6 +306,9 @@ async def start_application(fundaments=None):
|
|
| 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 |
|
|
@@ -261,9 +334,14 @@ if __name__ == "__main__":
|
|
| 261 |
# DISCORD_API_CLIENT.register_commands()
|
| 262 |
# --- New: wait for DNS before registering commands ---
|
| 263 |
if wait_for_dns_sync():
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
else:
|
| 266 |
-
logger.error("DNS resolution for discord.com failed.
|
|
|
|
| 267 |
|
| 268 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 269 |
health_thread.start()
|
|
|
|
| 36 |
START_TIME = datetime.utcnow()
|
| 37 |
|
| 38 |
# --- DNS Wait Helpers ---
|
| 39 |
+
async def wait_for_dns(host="discord.com", timeout=60):
|
| 40 |
"""Async: wait until DNS resolution for host works or timeout occurs."""
|
| 41 |
start = time.time()
|
| 42 |
+
attempt = 0
|
| 43 |
while time.time() - start < timeout:
|
| 44 |
+
attempt += 1
|
| 45 |
try:
|
| 46 |
+
addr = socket.gethostbyname(host)
|
| 47 |
+
logger.info(f"DNS resolved {host} -> {addr} (attempt {attempt})")
|
| 48 |
return True
|
| 49 |
+
except socket.gaierror as e:
|
| 50 |
+
logger.warning(f"DNS attempt {attempt} failed for {host}: {e}. Retrying...")
|
| 51 |
await asyncio.sleep(1)
|
| 52 |
+
logger.error(f"DNS timed out after {timeout}s for {host}")
|
| 53 |
return False
|
| 54 |
|
| 55 |
+
|
| 56 |
+
def wait_for_dns_sync(host="discord.com", timeout=60):
|
| 57 |
"""Sync: wait until DNS resolution for host works or timeout occurs."""
|
| 58 |
start = time.time()
|
| 59 |
+
attempt = 0
|
| 60 |
while time.time() - start < timeout:
|
| 61 |
+
attempt += 1
|
| 62 |
try:
|
| 63 |
+
addr = socket.gethostbyname(host)
|
| 64 |
+
logger.info(f"DNS resolved {host} -> {addr} (attempt {attempt})")
|
| 65 |
return True
|
| 66 |
+
except socket.gaierror as e:
|
| 67 |
+
logger.warning(f"DNS attempt {attempt} failed for {host}: {e}. Retrying...")
|
| 68 |
time.sleep(1)
|
| 69 |
+
logger.error(f"DNS timed out after {timeout}s for {host}")
|
| 70 |
return False
|
| 71 |
|
| 72 |
+
|
| 73 |
+
# --- Background retry for registering commands ---
|
| 74 |
+
def register_commands_with_retry(max_attempts=12, base_delay=5):
|
| 75 |
+
"""Try to register commands in background with exponential backoff."""
|
| 76 |
+
attempt = 0
|
| 77 |
+
while attempt < max_attempts:
|
| 78 |
+
attempt += 1
|
| 79 |
+
try:
|
| 80 |
+
# Ensure DNS is available before attempting registration
|
| 81 |
+
try:
|
| 82 |
+
addr = socket.gethostbyname("discord.com")
|
| 83 |
+
logger.info(f"Background register: DNS resolved discord.com -> {addr}")
|
| 84 |
+
except socket.gaierror as e:
|
| 85 |
+
logger.warning(f"Background register: DNS not ready: {e}")
|
| 86 |
+
raise
|
| 87 |
+
|
| 88 |
+
logger.info(f"Attempting to register Discord commands (attempt {attempt})...")
|
| 89 |
+
# DISCORD_API_CLIENT.register_commands() logs errors internally
|
| 90 |
+
DISCORD_API_CLIENT.register_commands()
|
| 91 |
+
logger.info("Discord commands registration attempted (background).")
|
| 92 |
+
return
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.warning(f"Register attempt {attempt} failed: {e}")
|
| 95 |
+
# exponential backoff
|
| 96 |
+
delay = base_delay * (2 ** (attempt - 1))
|
| 97 |
+
if delay > 300:
|
| 98 |
+
delay = 300
|
| 99 |
+
logger.info(f"Retrying register in {delay}s (attempt {attempt+1}/{max_attempts})")
|
| 100 |
+
time.sleep(delay)
|
| 101 |
+
logger.error("Exhausted register attempts. Commands not registered.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
# --- Bank callback ---
|
| 105 |
def send_bank_result_callback(future, interaction_token):
|
| 106 |
"""Called when the bank operation finishes, sends a follow-up message."""
|
|
|
|
| 117 |
flags=64
|
| 118 |
)
|
| 119 |
|
| 120 |
+
|
| 121 |
def start_bank_system_loop_in_thread():
|
| 122 |
"""Starts the dedicated asyncio event loop for the bank system."""
|
| 123 |
loop = asyncio.new_event_loop()
|
|
|
|
| 137 |
"message": "Discord bot is running!",
|
| 138 |
})
|
| 139 |
|
| 140 |
+
|
| 141 |
@app.route("/interactions", methods=["POST"])
|
| 142 |
def interactions():
|
| 143 |
if not DISCORD_API_CLIENT.verify_discord_request():
|
|
|
|
| 205 |
logger.error(f"Error processing request: {str(e)}", exc_info=True)
|
| 206 |
return "Internal server error", 500
|
| 207 |
|
| 208 |
+
|
| 209 |
def health_check_worker():
|
| 210 |
"""Background worker that periodically calls the health-check endpoint."""
|
| 211 |
while True:
|
|
|
|
| 216 |
except Exception as e:
|
| 217 |
logger.error(f"Health check failed: {str(e)}")
|
| 218 |
|
| 219 |
+
|
| 220 |
+
# debug endpoint to test DNS/HTTP from inside container
|
| 221 |
+
@app.route('/debug-dns', methods=['GET'])
|
| 222 |
+
def debug_dns():
|
| 223 |
+
"""Return DNS + simple HTTP test for discord.com from inside the Space."""
|
| 224 |
+
try:
|
| 225 |
+
addr = socket.gethostbyname("discord.com")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
addr = f"DNS error: {e}"
|
| 228 |
+
http_ok = None
|
| 229 |
+
try:
|
| 230 |
+
r = requests.get("https://discord.com/api/v10/", timeout=5)
|
| 231 |
+
http_ok = f"{r.status_code} {r.reason}"
|
| 232 |
+
except Exception as e:
|
| 233 |
+
http_ok = f"HTTP error: {e}"
|
| 234 |
+
return jsonify({"dns": str(addr), "http": http_ok})
|
| 235 |
+
|
| 236 |
+
|
| 237 |
def initialize_services(fundaments=None):
|
| 238 |
"""Initialize services with optional fundaments."""
|
| 239 |
global DISCORD_API_CLIENT, PORT, BOT_TOKEN
|
|
|
|
| 263 |
|
| 264 |
logger.info("Services initialized successfully.")
|
| 265 |
|
| 266 |
+
|
| 267 |
async def start_application(fundaments=None):
|
| 268 |
"""
|
| 269 |
Async-compatible start function for main.py
|
|
|
|
| 285 |
# DISCORD_API_CLIENT.register_commands()
|
| 286 |
# --- New: wait for DNS before registering commands ---
|
| 287 |
if await wait_for_dns():
|
| 288 |
+
try:
|
| 289 |
+
DISCORD_API_CLIENT.register_commands()
|
| 290 |
+
except Exception as e:
|
| 291 |
+
logger.warning(f"Initial register failed: {e}. Background retry will handle it.")
|
| 292 |
+
threading.Thread(target=register_commands_with_retry, daemon=True).start()
|
| 293 |
else:
|
| 294 |
+
logger.error("DNS resolution for discord.com failed. Starting background retry.")
|
| 295 |
+
threading.Thread(target=register_commands_with_retry, daemon=True).start()
|
| 296 |
|
| 297 |
# Start health check worker
|
| 298 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
|
|
|
| 306 |
|
| 307 |
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 308 |
server_thread.start()
|
| 309 |
+
|
| 310 |
+
# start background retryer as extra precaution (will exit quickly if already registered)
|
| 311 |
+
threading.Thread(target=register_commands_with_retry, daemon=True).start()
|
| 312 |
|
| 313 |
logger.info("Flask server started. Bot is running...")
|
| 314 |
|
|
|
|
| 334 |
# DISCORD_API_CLIENT.register_commands()
|
| 335 |
# --- New: wait for DNS before registering commands ---
|
| 336 |
if wait_for_dns_sync():
|
| 337 |
+
try:
|
| 338 |
+
DISCORD_API_CLIENT.register_commands()
|
| 339 |
+
except Exception as e:
|
| 340 |
+
logger.warning(f"Initial register failed: {e}. Background retry will handle it.")
|
| 341 |
+
threading.Thread(target=register_commands_with_retry, daemon=True).start()
|
| 342 |
else:
|
| 343 |
+
logger.error("DNS resolution for discord.com failed. Starting background retry.")
|
| 344 |
+
threading.Thread(target=register_commands_with_retry, daemon=True).start()
|
| 345 |
|
| 346 |
health_thread = threading.Thread(target=health_check_worker, daemon=True)
|
| 347 |
health_thread.start()
|