Spaces:
Sleeping
Sleeping
Download app.py from Hardik893508/Musafirbot: direct link, hf CLI and curl.
- Browser
- Download file 5.8 kB
-
https://huggingface.co/spaces/Hardik893508/Musafirbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Hardik893508/Musafirbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Hardik893508/Musafirbot/resolve/main/app.py
5.8 kB
| import os | |
| import json | |
| import logging | |
| import asyncio | |
| from threading import Thread | |
| from datetime import datetime, timedelta | |
| from flask import Flask | |
| from telegram import Update | |
| from telegram.ext import Application, MessageHandler, filters, ContextTypes | |
| from telegram.request import HTTPXRequest | |
| # Logging configuration | |
| logging.basicConfig( | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| level=logging.INFO | |
| ) | |
| TOKEN = os.getenv("BOT_TOKEN") | |
| DATA_FILE = "user_activity.json" | |
| # ==================================================================== | |
| # ⚠️ YAHAN APNE EXCEPTION WALE USERS KI DETAILS DALIE ⚠️ | |
| # ==================================================================== | |
| EXCLUDED_USERS = ["apka_username", "doosra_admin", "123456789"] | |
| # --- FLASK WEB SERVER SETUP --- | |
| app = Flask(__name__) | |
| def home(): | |
| return "Bot is alive and running 24/7!" | |
| def run_flask(): | |
| app.run(host="0.0.0.0", port=7860) | |
| # --- BOT DATABASE FUNCTIONS --- | |
| def load_data(): | |
| if os.path.exists(DATA_FILE): | |
| try: | |
| with open(DATA_FILE, "r") as f: | |
| return json.load(f) | |
| except Exception as e: | |
| logging.error(f"Error loading JSON: {e}") | |
| return {} | |
| return {} | |
| def save_data(data): | |
| try: | |
| with open(DATA_FILE, "w") as f: | |
| json.dump(data, f, indent=4) | |
| except Exception as e: | |
| logging.error(f"Error saving JSON: {e}") | |
| # --- TELEGRAM HANDLERS --- | |
| async def track_activity(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if not update.message or not update.message.from_user: | |
| return | |
| chat_id = str(update.message.chat_id) | |
| user_id = str(update.message.from_user.id) | |
| username = update.message.from_user.username or "No_Username" | |
| text = update.message.text or "" | |
| # Exception list check | |
| if username.lower() in [u.lower() for u in EXCLUDED_USERS] or user_id in EXCLUDED_USERS: | |
| return | |
| if "http" in text.lower() or "t.me" in text.lower(): | |
| data = load_data() | |
| if chat_id not in data: | |
| data[chat_id] = {} | |
| data[chat_id][user_id] = { | |
| "username": username, | |
| "last_seen": datetime.now().isoformat() | |
| } | |
| save_data(data) | |
| logging.info(f"[LINK DETECTED] Active User updated: @{username} in group {chat_id}") | |
| # Inactive users ko 3 din baad remove karne ka task | |
| async def check_and_remove_inactive(context: ContextTypes.DEFAULT_TYPE): | |
| logging.info("[SYSTEM] Automated check for 3-days inactive users started...") | |
| data = load_data() | |
| now = datetime.now() | |
| # 🕒 TIME CHANGE: Yahan 7 days ko badal kar 3 days kar diya hai | |
| three_days_ago = now - timedelta(days=3) | |
| for chat_id, users in list(data.items()): | |
| for user_id, user_info in list(users.items()): | |
| try: | |
| username = user_info.get("username", "No_Username") | |
| # Exception list check | |
| if username.lower() in [u.lower() for u in EXCLUDED_USERS] or str(user_id) in EXCLUDED_USERS: | |
| logging.info(f"[EXEMPTED] User @{username} exception list me hai. Skip.") | |
| continue | |
| last_seen_time = datetime.fromisoformat(user_info["last_seen"]) | |
| if last_seen_time < three_days_ago: | |
| logging.info(f"[INACTIVE DETECTED] User @{username} 3 din se inactive hai. Removing...") | |
| await context.bot.ban_chat_member(chat_id=int(chat_id), user_id=int(user_id)) | |
| await context.bot.unban_chat_member(chat_id=int(chat_id), user_id=int(user_id)) | |
| logging.info(f"[SUCCESS] @{username} ko remove kar diya gaya.") | |
| del data[chat_id][user_id] | |
| except Exception as e: | |
| logging.error(f"[ERROR] User {user_id} ko remove nahi kar paye: {e}") | |
| if not data[chat_id]: | |
| del data[chat_id] | |
| save_data(data) | |
| async def main(): | |
| if not TOKEN: | |
| logging.error("CRITICAL ERROR: BOT_TOKEN secret key nahi mili!") | |
| return | |
| custom_request = HTTPXRequest( | |
| connect_timeout=30.0, | |
| read_timeout=30.0, | |
| write_timeout=30.0, | |
| pool_timeout=30.0 | |
| ) | |
| PROXY_BASE_URL = "https://teleapi.deno.dev/bot" | |
| application = ( | |
| Application.builder() | |
| .token(TOKEN) | |
| .request(custom_request) | |
| .base_url(PROXY_BASE_URL) | |
| .build() | |
| ) | |
| application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, track_activity)) | |
| # 🔄 INTERVAL CHANGE: Har 2 ghante (7200 seconds) me bot background me check karega | |
| job_queue = application.job_queue | |
| job_queue.run_repeating(check_and_remove_inactive, interval=7200, first=15) | |
| while True: | |
| try: | |
| async with application: | |
| await application.initialize() | |
| await application.start() | |
| logging.info("=============================================") | |
| logging.info(" BOT STATUS: LIVE (3-DAYS MODE) IS ACTIVE! ") | |
| logging.info("=============================================") | |
| await application.updater.start_polling(timeout=20) | |
| while True: | |
| await asyncio.sleep(1) | |
| except Exception as e: | |
| logging.error(f"[CONNECTION ERROR] {e}. Retrying in 10 seconds...") | |
| await asyncio.sleep(10) | |
| if __name__ == "__main__": | |
| flask_thread = Thread(target=run_flask) | |
| flask_thread.daemon = True | |
| flask_thread.start() | |
| try: | |
| asyncio.run(main()) | |
| except (KeyboardInterrupt, SystemExit): | |
| logging.info("[SHUTDOWN] Bot band ho gaya.") | |