import os import logging import asyncio import threading from flask import Flask from playwright.async_api import async_playwright from telegram import Update from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters, CommandHandler # --- Flask Health Check (Keeps Hugging Face Space "Running") --- app = Flask(__name__) @app.route('/') def health_check(): return "Bot is active and running!", 200 def run_health_server(): # Hugging Face expects port 7860 to be active app.run(host="0.0.0.0", port=7860) # --- Logging Configuration --- logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # Fetch Token from Environment (Set this in HF Secrets) BOT_TOKEN = os.getenv("BOT_TOKEN") async def scrape_pocket_fm(story_name): """Scraping logic with Playwright.""" async with async_playwright() as p: try: # Added flags to handle containerized browser environment browser = await p.chromium.launch( headless=True, args=[ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu" ] ) context = await browser.new_context( user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" ) page = await context.new_page() search_url = f"https://www.pocketfm.com/search?query={story_name.replace(' ', '%20')}" # Navigate with a generous timeout await page.goto(search_url, wait_until="networkidle", timeout=60000) await asyncio.sleep(4) # Wait for dynamic JS content # Extract content from the main container if await page.locator("main").count() > 0: content = await page.locator("main").inner_text() result = content.strip() if content.strip() else "No results found." else: result = "Could not find the search result container." await browser.close() return result except Exception as e: logger.error(f"Scraping error: {e}") return f"⚠️ Error during search: {str(e)}" async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): """Handles incoming text messages.""" user_query = update.message.text chat_id = update.effective_chat.id # Notify user that search is starting status_msg = await context.bot.send_message( chat_id=chat_id, text=f"🔍 Searching Pocket FM for: *{user_query}*...\nThis may take a moment.", parse_mode='Markdown' ) result = await scrape_pocket_fm(user_query) # Telegram message limit is 4096 characters if len(result) > 4000: result = result[:4000] + "\n... (Truncated due to length)" await context.bot.send_message( chat_id=chat_id, text=f"✅ **Results for {user_query}:**\n\n{result}", parse_mode='Markdown' ) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): """Greeting command.""" await update.message.reply_text( "👋 Hi! I'm your Pocket FM Scraper.\nSend me any story name and I'll find the details for you." ) if __name__ == '__main__': if not BOT_TOKEN: logger.error("BOT_TOKEN environment variable is missing!") exit(1) # 1. Start Flask in the background logger.info("Starting health check server...") threading.Thread(target=run_health_server, daemon=True).start() # 2. Build Telegram Application with EXTENDED TIMEOUTS # This fixes the 'ConnectTimeout' error by giving the network more time to initialize application = ( ApplicationBuilder() .token(BOT_TOKEN) .connect_timeout(60) # Increased to 60s .read_timeout(60) .write_timeout(60) .pool_timeout(60) .build() ) # 3. Add Handlers application.add_handler(CommandHandler('start', start)) application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message)) # 4. Launch the Bot logger.info("Bot initialization complete. Starting polling...") application.run_polling(drop_pending_updates=True)