Spaces:
Running
Running
| import os | |
| import asyncio | |
| import threading | |
| from flask import Flask | |
| from telethon import TelegramClient, events, errors | |
| from telethon.sessions import StringSession | |
| # --- 1. STAY-AWAKE WEB SERVER --- | |
| # This page is for UptimeRobot/BetterStack to ping 24/7. | |
| app = Flask(__name__) | |
| def home(): | |
| return "Status: Userbot is Active and Monitoring 24/7", 200 | |
| def run_web_server(): | |
| # Hugging Face Spaces use port 7860 | |
| app.run(host='0.0.0.0', port=7860) | |
| # --- 2. TELEGRAM INSTANT FORWARDER --- | |
| # Values are pulled from your "Secrets" in the Settings tab | |
| API_ID = int(os.environ.get("API_ID")) | |
| API_HASH = os.environ.get("API_HASH") | |
| STRING_SESSION = os.environ.get("STRING_SESSION") | |
| TARGET_ID = int(os.environ.get("TARGET_ID")) | |
| # StringSession(STRING_SESSION) ensures it logs in using your code, not a file. | |
| # connection_retries=None ensures it never gives up if the internet drops. | |
| client = TelegramClient( | |
| StringSession(STRING_SESSION), | |
| API_ID, | |
| API_HASH, | |
| connection_retries=None | |
| ) | |
| async def instant_forwarder(event): | |
| try: | |
| # Copies the message to your 'Saved Messages' immediately. | |
| # This catches it before the sender can delete it. | |
| await event.forward_to('me') | |
| print(f"Captured: Message from {TARGET_ID} forwarded successfully.") | |
| except errors.FloodWaitError as e: | |
| # If Telegram tells us to slow down, we wait and continue. | |
| await asyncio.sleep(e.seconds) | |
| except Exception as e: | |
| print(f"Error during forwarding: {e}") | |
| # --- 3. STARTING THE BOT --- | |
| if __name__ == "__main__": | |
| # Start the web server in a background thread | |
| threading.Thread(target=run_web_server, daemon=True).start() | |
| print("Userbot is connecting to Telegram...") | |
| try: | |
| client.start() | |
| print("--- SUCCESS: Bot is now online and listening! ---") | |
| # This is the correct method to keep the bot running non-stop | |
| client.run_until_disconnected() | |
| except Exception as e: | |
| print(f"Failed to start client: {e}") | |