Spaces:
Runtime error
Runtime error
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# filename: main.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import asyncio
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# IMPORTANT: Load environment variables from .env file at the very beginning
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
from fastapi import FastAPI
|
| 12 |
+
from fastapi.responses import FileResponse, PlainTextResponse
|
| 13 |
+
import uvicorn
|
| 14 |
+
|
| 15 |
+
# Now, import our application modules AFTER loading the environment
|
| 16 |
+
import config
|
| 17 |
+
from core.bot import bot, start_bot_runtime
|
| 18 |
+
from database import manager as db_manager
|
| 19 |
+
|
| 20 |
+
# Import all handler modules so Telethon can register the event handlers
|
| 21 |
+
from handlers import start, admin, user, links
|
| 22 |
+
|
| 23 |
+
# --- Logging Configuration ---
|
| 24 |
+
# Creates the logs directory if it doesn't exist
|
| 25 |
+
os.makedirs("logs", exist_ok=True)
|
| 26 |
+
|
| 27 |
+
logging.basicConfig(
|
| 28 |
+
level=logging.INFO,
|
| 29 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 30 |
+
handlers=[
|
| 31 |
+
logging.StreamHandler(), # To show logs in the console
|
| 32 |
+
logging.FileHandler("logs/bot.log", mode='a', encoding='utf-8') # To save logs to a file
|
| 33 |
+
]
|
| 34 |
+
)
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# --- FastAPI Application Setup ---
|
| 39 |
+
app = FastAPI(
|
| 40 |
+
title="Terabox Bot Service",
|
| 41 |
+
description="The backend service for the Terabox Downloader Telegram Bot.",
|
| 42 |
+
version="1.0.0"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# --- FastAPI Events: Startup and Shutdown ---
|
| 47 |
+
@app.on_event("startup")
|
| 48 |
+
async def startup_event():
|
| 49 |
+
"""
|
| 50 |
+
This function runs once when the application starts.
|
| 51 |
+
It initializes everything needed for the bot to run.
|
| 52 |
+
"""
|
| 53 |
+
logger.info("===== APPLICATION STARTUP =====")
|
| 54 |
+
|
| 55 |
+
# 1. Initialize the database and create indexes for fast queries
|
| 56 |
+
await db_manager.setup_database_indexes()
|
| 57 |
+
|
| 58 |
+
# 2. Start the Telethon client
|
| 59 |
+
logger.info("Starting Telegram client...")
|
| 60 |
+
await bot.start(bot_token=config.BOT_TOKEN)
|
| 61 |
+
me = await bot.get_me()
|
| 62 |
+
logger.info(f"Bot client started successfully as @{me.username}")
|
| 63 |
+
|
| 64 |
+
# 3. Start the bot's core engine (workers, scheduler)
|
| 65 |
+
start_bot_runtime()
|
| 66 |
+
|
| 67 |
+
# 4. Run the bot's main event loop in the background
|
| 68 |
+
asyncio.create_task(bot.run_until_disconnected())
|
| 69 |
+
logger.info("Bot is now running and listening for events...")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@app.on_event("shutdown")
|
| 73 |
+
async def shutdown_event():
|
| 74 |
+
"""This function runs once when the application is shutting down."""
|
| 75 |
+
logger.info("===== APPLICATION SHUTDOWN =====")
|
| 76 |
+
if bot.is_connected():
|
| 77 |
+
await bot.disconnect()
|
| 78 |
+
logger.info("Bot client has been disconnected.")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# --- FastAPI Routes (Web Endpoints) ---
|
| 82 |
+
@app.get("/", response_class=FileResponse)
|
| 83 |
+
async def read_index():
|
| 84 |
+
"""
|
| 85 |
+
Serves the main web interface if index.html exists.
|
| 86 |
+
Otherwise, returns a simple status message.
|
| 87 |
+
"""
|
| 88 |
+
index_path = "index.html"
|
| 89 |
+
if os.path.exists(index_path):
|
| 90 |
+
return FileResponse(index_path)
|
| 91 |
+
return PlainTextResponse("The bot service is running. The web UI (index.html) was not found.")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@app.get("/health", response_class=PlainTextResponse)
|
| 95 |
+
async def health_check():
|
| 96 |
+
"""A simple endpoint for health checks and monitoring."""
|
| 97 |
+
if bot.is_connected():
|
| 98 |
+
return PlainTextResponse("✅ OK: Bot service is running and connected to Telegram.")
|
| 99 |
+
else:
|
| 100 |
+
return PlainTextResponse("❌ ERROR: Bot service is running but not connected to Telegram.", status_code=503)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# --- Main Execution Block ---
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
logger.info("Starting Uvicorn server...")
|
| 106 |
+
# Uvicorn runs the FastAPI application.
|
| 107 |
+
# 'reload=True' is for development; you might remove it in production.
|
| 108 |
+
uvicorn.run(
|
| 109 |
+
"main:app",
|
| 110 |
+
host="0.0.0.0",
|
| 111 |
+
port=8080, # Common port for web services
|
| 112 |
+
reload=True # Automatically restarts the server when you save a file
|
| 113 |
+
)
|