JeorgeC commited on
Commit
3ed5087
·
verified ·
1 Parent(s): 08e396b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -11
app.py CHANGED
@@ -1,22 +1,100 @@
1
  import os
2
  import threading
3
  import time
 
 
 
4
  from main import bot, app, run_bot, run_api
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  def start_bot():
7
- """Start the Discord bot in background"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  try:
9
- run_bot()
 
10
  except Exception as e:
11
- print(f"Bot error: {e}")
 
12
 
13
- # Start Discord bot in background thread
14
- bot_thread = threading.Thread(target=start_bot, daemon=True)
15
- bot_thread.start()
16
-
17
- # Optional: Give the bot some time
18
- time.sleep(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # Start FastAPI app if run directly (for docker)
21
  if __name__ == "__main__":
22
- run_api()
 
1
  import os
2
  import threading
3
  import time
4
+ import signal
5
+ import sys
6
+ import logging
7
  from main import bot, app, run_bot, run_api
8
 
9
+ # Configure logging
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
13
+ )
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Global flag to control shutdown
17
+ shutdown_flag = threading.Event()
18
+
19
+ def signal_handler(signum, frame):
20
+ """Handle shutdown signals gracefully"""
21
+ logger.info(f"Received signal {signum}, initiating graceful shutdown...")
22
+ shutdown_flag.set()
23
+
24
  def start_bot():
25
+ """Start the Discord bot with error handling and restart logic"""
26
+ while not shutdown_flag.is_set():
27
+ try:
28
+ logger.info("Starting Discord bot...")
29
+ run_bot()
30
+ except Exception as e:
31
+ logger.error(f"Bot error: {e}")
32
+ if not shutdown_flag.is_set():
33
+ logger.info("Restarting bot in 5 seconds...")
34
+ time.sleep(5)
35
+ else:
36
+ break
37
+ logger.info("Bot thread shutting down.")
38
+
39
+ def start_api():
40
+ """Start FastAPI with error handling"""
41
  try:
42
+ logger.info("Starting FastAPI server...")
43
+ run_api()
44
  except Exception as e:
45
+ logger.error(f"API server error: {e}")
46
+ shutdown_flag.set()
47
 
48
+ def health_monitor():
49
+ """Monitor bot health and restart if needed"""
50
+ while not shutdown_flag.is_set():
51
+ time.sleep(30) # Check every 30 seconds
52
+ if not bot.is_ready() and not shutdown_flag.is_set():
53
+ logger.warning("Bot appears to be disconnected, but letting Discord.py handle reconnection...")
54
+
55
+ def main():
56
+ """Main function to coordinate all services"""
57
+ # Set up signal handlers for graceful shutdown
58
+ signal.signal(signal.SIGINT, signal_handler)
59
+ signal.signal(signal.SIGTERM, signal_handler)
60
+
61
+ logger.info("Starting Discord Flashcard Bot API...")
62
+
63
+ # Verify Discord token is present
64
+ if not os.getenv('DISCORD_BOT_TOKEN'):
65
+ logger.error("DISCORD_BOT_TOKEN environment variable not set!")
66
+ sys.exit(1)
67
+
68
+ # Start Discord bot in background thread
69
+ bot_thread = threading.Thread(target=start_bot, daemon=False, name="DiscordBot")
70
+ bot_thread.start()
71
+ logger.info("Discord bot thread started")
72
+
73
+ # Give the bot some time to initialize
74
+ time.sleep(3)
75
+
76
+ # Start health monitor
77
+ health_thread = threading.Thread(target=health_monitor, daemon=True, name="HealthMonitor")
78
+ health_thread.start()
79
+ logger.info("Health monitor thread started")
80
+
81
+ # Start FastAPI server (this will block)
82
+ try:
83
+ start_api()
84
+ except KeyboardInterrupt:
85
+ logger.info("Received keyboard interrupt")
86
+ except Exception as e:
87
+ logger.error(f"Unexpected error in main: {e}")
88
+ finally:
89
+ logger.info("Initiating shutdown...")
90
+ shutdown_flag.set()
91
+
92
+ # Wait for bot thread to finish
93
+ if bot_thread.is_alive():
94
+ logger.info("Waiting for bot thread to finish...")
95
+ bot_thread.join(timeout=10)
96
+
97
+ logger.info("Application shutdown complete")
98
 
 
99
  if __name__ == "__main__":
100
+ main()