File-Store-Bot / plugins /anti_sleep.py
File Store Bot
Initialize File Store Bot for Hugging Face free Gradio Deployment
60e9648
Raw History Blame Contribute Delete
1.52 kB
"""
Anti-sleep plugin for Render.
Pings the bot's own web URL every 5 minutes to prevent Render free tier from sleeping.
Set RENDER_URL environment variable to your Render URL (e.g. https://my-bot.onrender.com)
"""
import asyncio
import os
import aiohttp
from pyrogram import Client
RENDER_URL = os.environ.get("RENDER_URL", "")
SPACE_HOST = os.environ.get("SPACE_HOST", "")
# Build target ping URL (auto-detect Hugging Face Space hostname if present)
PING_URL = RENDER_URL
if not PING_URL and SPACE_HOST:
PING_URL = f"https://{SPACE_HOST}"
PING_INTERVAL = 4 * 60 # 4 minutes
async def keep_alive_loop():
if not PING_URL:
print("[Anti-Sleep] No self-ping URL configured. Bot is ready for external pings.")
return
await asyncio.sleep(30) # wait for bot to fully start
async with aiohttp.ClientSession() as session:
while True:
try:
headers = {"User-Agent": "HF-Space-Self-Ping"}
async with session.get(PING_URL, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:
print(f"[Anti-Sleep] Pinged {PING_URL} → {resp.status}")
except Exception as e:
print(f"[Anti-Sleep] Ping failed to {PING_URL}: {e}")
await asyncio.sleep(PING_INTERVAL)
# Hook into bot startup
original_start = Client.start.__wrapped__ if hasattr(Client.start, "__wrapped__") else None
async def _patched_start(self):
await Client.start(self)
asyncio.create_task(keep_alive_loop())