Download main.py from deploy199/README: direct link, hf CLI and curl.
- Browser
- Download file 5.78 kB
-
https://huggingface.co/spaces/deploy199/README/resolve/main/main.py
- Command line
-
hf download hf://spaces/deploy199/README/main.py
-
curl -L -o main.py https://huggingface.co/spaces/deploy199/README/resolve/main/main.py
5.78 kB
| import asyncio | |
| from fastapi import FastAPI, HTTPException | |
| from pyrogram import Client, idle | |
| import uvicorn | |
| import os | |
| import logging | |
| from dotenv import load_dotenv | |
| from command import setup_handlers | |
| import httpx | |
| from time import sleep | |
| import threading | |
| # Load environment variables | |
| load_dotenv() | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = FastAPI(title="FastAPI Telegram Bot Integration") | |
| # Get environment variables | |
| API_ID = os.environ.get("API_ID") | |
| API_HASH = os.environ.get("API_HASH") | |
| BOT_TOKEN = os.environ.get("BOT_TOKEN") | |
| # Validate environment variables | |
| if not (API_ID and API_HASH and BOT_TOKEN): | |
| raise Exception("Missing one or more required environment variables: API_ID, API_HASH, BOT_TOKEN") | |
| # Global bot instance for API endpoints | |
| running_bot = None | |
| # Auto-alive functionality to keep HuggingFace Space active | |
| def keep_alive(): | |
| """Keep the app alive by pinging itself every 5 minutes""" | |
| base_url = os.environ.get("BASE_URL") | |
| hf_token = os.environ.get("HF_TOKEN") | |
| if not base_url: | |
| logger.info("BASE_URL not set, auto-alive disabled") | |
| return | |
| headers = {"User-Agent": "FastAPI-Telegram-Bot-KeepAlive"} | |
| # Add HuggingFace token if available and URL contains hf.space | |
| if "huggingface.co" in base_url and hf_token: | |
| headers["Authorization"] = f"Bearer {hf_token}" | |
| logger.info(f"Auto-alive enabled for: {base_url}") | |
| while True: | |
| try: | |
| # Ping the health endpoint to keep the app alive | |
| ping_url = f"{base_url.rstrip('/')}/health" | |
| response = httpx.get(ping_url, headers=headers, timeout=10) | |
| if response.status_code == 200: | |
| logger.info(f"✅ Keep-alive ping successful: {response.status_code}") | |
| else: | |
| logger.warning(f"⚠️ Keep-alive ping returned: {response.status_code}") | |
| except Exception as e: | |
| logger.error(f"❌ Keep-alive ping failed: {e}") | |
| # Wait 5 minutes before next ping | |
| sleep(300) | |
| def start_keep_alive(): | |
| """Start the keep-alive functionality in a separate thread""" | |
| keep_alive_thread = threading.Thread(target=keep_alive, daemon=True) | |
| keep_alive_thread.start() | |
| logger.info("Keep-alive thread started") | |
| async def root(): | |
| """Root endpoint - Main page for HuggingFace Spaces""" | |
| return { | |
| "title": "FastAPI Telegram Bot Integration", | |
| "description": "A production-ready FastAPI application integrated with a Telegram bot using Pyrogram", | |
| "status": "running", | |
| "endpoints": { | |
| "health": "/health", | |
| "send_message": "/sendmessage?log={chat_id}&msg={message}", | |
| "docs": "/docs", | |
| "redoc": "/redoc" | |
| }, | |
| "telegram_bot": { | |
| "status": "active" if running_bot else "inactive", | |
| "commands": ["/start", "/ngrok", "/setapi"] | |
| }, | |
| "auto_alive": { | |
| "status": "enabled" if os.environ.get("BASE_URL") else "disabled", | |
| "base_url": os.environ.get("BASE_URL", "not_set") | |
| } | |
| } | |
| async def health_check(): | |
| """Health check endpoint""" | |
| return {"status": "ok", "message": "FastAPI Telegram Bot is running"} | |
| async def send_message(log: str, msg: str): | |
| """Send message endpoint""" | |
| try: | |
| if running_bot is None: | |
| raise HTTPException(status_code=500, detail="Bot not initialized") | |
| await running_bot.send_message(chat_id=log, text=str(msg)) | |
| logger.info(f"Message sent to chat {log}: {msg}") | |
| return {'message': "Done 👍"} | |
| except Exception as e: | |
| logger.error(f"Error sending message: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def main(): | |
| """Main function following Pyrogram docs pattern""" | |
| global running_bot | |
| try: | |
| # Start keep-alive functionality first | |
| start_keep_alive() | |
| # Create bot client (using one client as requested) | |
| app_client = Client( | |
| ':memory:', | |
| api_id=int(API_ID), | |
| api_hash=API_HASH, | |
| bot_token=BOT_TOKEN | |
| ) | |
| # Set up handlers | |
| setup_handlers(app_client) | |
| # Start the client | |
| await app_client.start() | |
| logger.info("Telegram bot started successfully") | |
| # Store reference for API endpoints | |
| running_bot = app_client | |
| # Configure and start FastAPI server concurrently | |
| config = uvicorn.Config( | |
| app, | |
| host="0.0.0.0", | |
| port=7860, | |
| log_level="info", | |
| loop="asyncio" | |
| ) | |
| server = uvicorn.Server(config) | |
| # Start FastAPI server as background task | |
| server_task = asyncio.create_task(server.serve()) | |
| logger.info("FastAPI server and Telegram bot are running...") | |
| logger.info("Auto-alive functionality is active to prevent HuggingFace Space sleep") | |
| # Wait for termination signal (following Pyrogram docs pattern) | |
| await idle() | |
| # Stop the client (following Pyrogram docs pattern) | |
| await app_client.stop() | |
| logger.info("Telegram bot stopped") | |
| # Stop FastAPI server | |
| server.should_exit = True | |
| except Exception as e: | |
| logger.error(f"Error in main execution: {e}") | |
| if __name__ == '__main__': | |
| asyncio.run(main()) | |