File size: 1,523 Bytes
60e9648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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())