understanding commited on
Commit
431014c
Β·
verified Β·
1 Parent(s): ad6ca7e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +75 -33
main.py CHANGED
@@ -2,51 +2,93 @@
2
 
3
  import logging
4
  import asyncio
5
- import uvicorn
6
  from fastapi import FastAPI
7
- from contextlib import asynccontextmanager
 
8
 
9
  from bot import start_bot
 
10
 
11
- logging.basicConfig(level=logging.INFO)
12
- logger = logging.getLogger("main")
13
 
14
- app = FastAPI()
 
 
 
15
 
16
- # Lifespan event for startup/shutdown (new style β†’ no deprecation warning!)
17
- @asynccontextmanager
18
- async def lifespan(app: FastAPI):
19
- logger.info("===== Application Startup =====")
20
 
21
- # Start bot in background
22
- dp, bot = start_bot()
 
23
 
24
- asyncio.create_task(dp.start_polling(bot))
25
- logger.info("Starting bot polling in background...")
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- yield
 
 
 
 
28
 
29
- logger.info("===== Application Shutdown =====")
30
- await bot.session.close()
 
31
 
32
- # Set FastAPI lifespan
33
- app.router.lifespan_context = lifespan
 
34
 
35
- # Healthcheck endpoint
36
- @app.get("/health")
37
- async def health():
38
- return {"status": "ok", "message": "Terabox Bot is running πŸš€"}
39
 
40
- # Optionally index page
41
- @app.get("/")
42
- async def index():
43
- return {
44
- "bot": "Terabox Downloader Bot",
45
- "version": "1.0",
46
- "health": "/health",
47
- "workers": "4",
48
- "note": "Send /start to the bot in Telegram to begin."
49
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
51
  if __name__ == "__main__":
52
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
2
 
3
  import logging
4
  import asyncio
 
5
  from fastapi import FastAPI
6
+ from fastapi.responses import HTMLResponse, PlainTextResponse
7
+ import uvicorn
8
 
9
  from bot import start_bot
10
+ import db_utils
11
 
12
+ import config
 
13
 
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
17
+ )
18
 
19
+ logger = logging.getLogger("main")
 
 
 
20
 
21
+ # --- App & Bot setup ---
22
+ app = FastAPI(title="Terabox Downloader Bot API")
23
+ dp, bot = start_bot()
24
 
25
+ # --- Status Variables ---
26
+ APP_STATUS = {
27
+ "bot_running": False,
28
+ "workers": config.CONCURRENT_WORKERS,
29
+ "active_batches": 0,
30
+ "active_users": 0,
31
+ }
32
+
33
+ # --- Background Bot Runner ---
34
+ async def run_bot_polling():
35
+ from aiogram import Dispatcher
36
+ APP_STATUS["bot_running"] = True
37
+ await dp.start_polling(bot)
38
 
39
+ # --- FastAPI Routes ---
40
+ @app.on_event("startup")
41
+ async def on_startup():
42
+ logger.info("===== Application Startup =====")
43
+ await db_utils.initialize_database()
44
 
45
+ # Count users
46
+ active_users = await db_utils.get_all_active_user_ids_db()
47
+ APP_STATUS["active_users"] = len(active_users)
48
 
49
+ # Start bot in background
50
+ logger.info("Starting bot polling in background...")
51
+ asyncio.create_task(run_bot_polling())
52
 
53
+ @app.get("/health", response_class=PlainTextResponse)
54
+ async def health_check():
55
+ return "βœ… Terabox Bot is running."
 
56
 
57
+ @app.get("/", response_class=HTMLResponse)
58
+ async def index_page():
59
+ html = f"""
60
+ <html>
61
+ <head>
62
+ <title>πŸš€ Terabox Downloader Bot Dashboard</title>
63
+ <style>
64
+ body {{ font-family: Arial, sans-serif; background-color: #f9f9f9; color: #333; }}
65
+ .container {{ max-width: 600px; margin: auto; padding: 20px; text-align: center; }}
66
+ .status {{ background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
67
+ .status h2 {{ color: #2c3e50; }}
68
+ .status p {{ font-size: 18px; }}
69
+ .footer {{ margin-top: 20px; font-size: 14px; color: #888; }}
70
+ </style>
71
+ </head>
72
+ <body>
73
+ <div class="container">
74
+ <h1>πŸš€ Terabox Downloader Bot</h1>
75
+ <div class="status">
76
+ <h2>Status</h2>
77
+ <p>Bot Running: <b style="color:green;">{APP_STATUS['bot_running']}</b></p>
78
+ <p>Concurrent Workers: <b>{APP_STATUS['workers']}</b></p>
79
+ <p>Active Users (cached): <b>{APP_STATUS['active_users']}</b></p>
80
+ <p>Active Batches (live): <b>{APP_STATUS['active_batches']}</b></p>
81
+ </div>
82
+ <div class="footer">
83
+ &copy; 2025 Terabox Bot | Powered by FastAPI & Aiogram
84
+ </div>
85
+ </div>
86
+ </body>
87
+ </html>
88
+ """
89
+ return html
90
 
91
+ # --- Main runner ---
92
  if __name__ == "__main__":
93
+ logger.info("===== Starting Uvicorn Server =====")
94
+ uvicorn.run("main:app", host="0.0.0.0", port=7860)