Spaces:
Runtime error
Runtime error
File size: 4,479 Bytes
3b56810 baadb7b 3b56810 baadb7b a7b6c44 baadb7b 4de9648 091ec58 4d774a8 3b56810 4d774a8 3b56810 4d774a8 3b56810 4d774a8 baadb7b 4d774a8 658f161 4d774a8 a373cc2 658f161 baadb7b 4d774a8 baadb7b 4d774a8 3b56810 4d774a8 3b56810 baadb7b 4d774a8 baadb7b 4d774a8 4de9648 baadb7b 4d774a8 baadb7b 4d774a8 baadb7b 4d774a8 baadb7b 4de9648 baadb7b 4de9648 4d774a8 baadb7b 4d774a8 349b1a9 4d774a8 baadb7b 4d774a8 349b1a9 a7b6c44 3b56810 4d774a8 3b56810 4d774a8 3b56810 4d774a8 baadb7b 4d774a8 | 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 | 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)
|