File size: 5,778 Bytes
b28ce06 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 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")
@app.get("/")
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")
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {"status": "ok", "message": "FastAPI Telegram Bot is running"}
@app.get('/sendmessage')
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())
|