Removerbot / app.py
Hardik893508's picture
Update app.py
c423e5b verified
Raw History Blame Contribute Delete
15.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,
CommandHandler,
MessageHandler,
ChatMemberHandler,
filters,
ContextTypes,
)
from telegram.request import HTTPXRequest
from telegram.error import Forbidden, BadRequest
# 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"
DM_MAP_FILE = "dm_map.json"
# โš ๏ธ APNA TELEGRAM USER ID (numeric) YAHAN DALO YA HF SPACE SECRETS ME "ADMIN_ID" SET KARO
ADMIN_ID = os.getenv("ADMIN_ID")
# ====================================================================
# โš ๏ธ YAHAN APNE EXCEPTION WALE USERS KI DETAILS DALIE โš ๏ธ
# ====================================================================
EXCLUDED_USERS = ["uflowx", "taksha_08", "6501780506"]
# --- INACTIVITY RULES ---
REMOVE_DAYS = 3 # Itne din link na bhejne par user remove ho jayega
WARNING_DAYS = REMOVE_DAYS - 1 # Removal se 1 din pehle warning bhejega (yaani 2 din)
CHECK_INTERVAL_SECONDS = 7200 # Har 2 ghante me check chalega
REMOVE_MESSAGE = "You have been removed by admins for inactive you didn't send any links in last 3 days in Group please dm @uflowx for more details"
WARNING_MESSAGE = (
"โš ๏ธ Warning: Aapne pichle 2 dino se group me koi link share nahi kiya hai. "
"Agar aapne agle 24 ghante ke andar koi link nahi bheja, toh aapko group se remove kar diya jayega. "
"Active rehne ke liye kripya jaldi ek link share karein."
)
# Global โ€” last time automated check chala (admin /status command ke liye)
LAST_CHECK_TIME = None
# --- FLASK WEB SERVER SETUP ---
app = Flask(__name__)
@app.route('/')
def home():
return "Bot is alive and running 24/7!"
@app.route('/diag')
def diag():
import httpx
results = {}
for name, url in {
"google": "https://www.google.com",
"telegram_api": "https://api.telegram.org",
}.items():
try:
r = httpx.get(url, timeout=10.0)
results[name] = f"OK ({r.status_code})"
except Exception as e:
results[name] = f"FAILED: {type(e).__name__}"
return results
def run_flask():
app.run(host="0.0.0.0", port=7860)
# --- BOT DATABASE FUNCTIONS ---
def load_json(path):
if os.path.exists(path):
try:
with open(path, "r") as f:
return json.load(f)
except Exception as e:
logging.error(f"Error loading JSON ({path}): {e}")
return {}
return {}
def save_json(path, data):
try:
with open(path, "w") as f:
json.dump(data, f, indent=4)
except Exception as e:
logging.error(f"Error saving JSON ({path}): {e}")
def load_data():
return load_json(DATA_FILE)
def save_data(data):
save_json(DATA_FILE, data)
def load_dm_map():
return load_json(DM_MAP_FILE)
def save_dm_map(data):
save_json(DM_MAP_FILE, data)
# --- TELEGRAM HANDLERS ---
# Naya member group me join kare to usko track karna shuru karo (grace period)
async def track_new_member(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_member_update = update.chat_member
if not chat_member_update:
return
new_status = chat_member_update.new_chat_member.status
old_status = chat_member_update.old_chat_member.status
# Sirf tab jab koi "member" bana ho (join kiya ho), pehle se member nahi tha
if new_status == "member" and old_status in ("left", "kicked", "restricted"):
chat_id = str(chat_member_update.chat.id)
user = chat_member_update.new_chat_member.user
user_id = str(user.id)
username = user.username or "No_Username"
if username.lower() in [u.lower() for u in EXCLUDED_USERS] or user_id in EXCLUDED_USERS:
return
data = load_data()
if chat_id not in data:
data[chat_id] = {}
# Sirf tab add karo jab pehle se track nahi ho raha (purane record ko overwrite mat karo)
if user_id not in data[chat_id]:
data[chat_id][user_id] = {
"username": username,
"last_seen": datetime.now().isoformat(),
"warned": False
}
save_data(data)
logging.info(f"[NEW MEMBER] @{username} join hua group {chat_id} me. Tracking shuru ({REMOVE_DAYS}-din grace).")
# Group me kisi bhi text message par: agar user pehli baar dikha hai to baseline set karo,
# aur agar message me link hai to last_seen reset (update) karo.
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
data = load_data()
if chat_id not in data:
data[chat_id] = {}
has_link = ("http" in text.lower()) or ("t.me" in text.lower())
if user_id not in data[chat_id]:
# Purana silent member ab pehli baar bola hai -> fresh counter shuru
data[chat_id][user_id] = {
"username": username,
"last_seen": datetime.now().isoformat(),
"warned": False
}
save_data(data)
logging.info(f"[FIRST SEEN] @{username} group {chat_id} me pehli baar track hua. Fresh {REMOVE_DAYS}-din timer.")
elif has_link:
data[chat_id][user_id] = {
"username": username,
"last_seen": datetime.now().isoformat(),
"warned": False
}
save_data(data)
logging.info(f"[LINK DETECTED] Active User updated: @{username} in group {chat_id}")
# Inactive users ko warning bhejne aur remove karne ka task
async def check_and_remove_inactive(context: ContextTypes.DEFAULT_TYPE):
global LAST_CHECK_TIME
logging.info(f"[SYSTEM] Automated check start ho gaya (warning: {WARNING_DAYS}d, remove: {REMOVE_DAYS}d)...")
data = load_data()
now = datetime.now()
LAST_CHECK_TIME = now
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:
continue
last_seen_time = datetime.fromisoformat(user_info["last_seen"])
days_inactive = (now - last_seen_time).total_seconds() / 86400
# --- CASE 1: REMOVE_DAYS ho gaye -> remove karo ---
if days_inactive >= REMOVE_DAYS:
logging.info(f"[INACTIVE DETECTED] @{username} {REMOVE_DAYS} din se link nahi bheja. 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.")
try:
await context.bot.send_message(chat_id=int(user_id), text=REMOVE_MESSAGE)
except Forbidden:
logging.warning(f"[DM FAILED] @{username} ne bot ko block kiya hai ya kabhi DM start nahi kiya.")
except Exception as dm_err:
logging.warning(f"[DM FAILED] @{username} ko message nahi bhej paye: {dm_err}")
del data[chat_id][user_id]
# --- CASE 2: WARNING_DAYS ho gaye aur abhi warning nahi bheja -> warning bhejo ---
elif days_inactive >= WARNING_DAYS and not user_info.get("warned", False):
logging.info(f"[WARNING] @{username} ko warning bheji jaa rahi hai (removal me ~1 din baaki).")
try:
await context.bot.send_message(chat_id=int(user_id), text=WARNING_MESSAGE)
except Forbidden:
logging.warning(f"[WARNING FAILED] @{username} ne bot ko block kiya hai.")
except Exception as warn_err:
logging.warning(f"[WARNING FAILED] @{username} ko warning nahi bhej paye: {warn_err}")
# Chahe DM fail ho jaye, warned=True mark kar do taaki spam na ho
user_info["warned"] = True
except Exception as e:
logging.error(f"[ERROR] User {user_id} process nahi ho paya: {e}")
if chat_id in data and not data[chat_id]:
del data[chat_id]
save_data(data)
logging.info("[SYSTEM] Automated check complete.")
# --- ADMIN COMMAND: /status ---
async def bot_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message or not update.message.from_user:
return
sender_id = str(update.message.from_user.id)
if not ADMIN_ID or sender_id != str(ADMIN_ID):
return # non-admin users ko silently ignore
data = load_data()
now = datetime.now()
total_groups = len(data)
total_users = sum(len(users) for users in data.values())
close_to_removal = []
for chat_id, users in data.items():
for user_id, info in users.items():
username = info.get("username", "No_Username")
if username.lower() in [u.lower() for u in EXCLUDED_USERS] or str(user_id) in EXCLUDED_USERS:
continue
last_seen = datetime.fromisoformat(info["last_seen"])
days_inactive = (now - last_seen).total_seconds() / 86400
if days_inactive >= WARNING_DAYS:
hours_left = max(0, round((REMOVE_DAYS - days_inactive) * 24, 1))
close_to_removal.append(f"โ€ข @{username} โ€” ~{hours_left} ghante me remove (chat: {chat_id})")
last_check_str = (
LAST_CHECK_TIME.strftime("%d-%b-%Y %I:%M %p")
if LAST_CHECK_TIME else "Abhi tak nahi chala (jald hi chalega)"
)
lines = [
"๐Ÿค– *Bot Status:* โœ… Running",
"",
f"๐Ÿ“Š Tracking: *{total_groups}* groups, *{total_users}* users",
f"โฑ Auto-check har *{CHECK_INTERVAL_SECONDS // 3600} ghante* chalta hai",
f"๐Ÿ•’ Last check: {last_check_str}",
f"๐Ÿ“ Rule: {WARNING_DAYS} din pe warning, {REMOVE_DAYS} din pe removal",
"",
]
if close_to_removal:
lines.append(f"โš ๏ธ *Removal ke close users ({len(close_to_removal)}):*")
lines.extend(close_to_removal[:20])
if len(close_to_removal) > 20:
lines.append(f"...aur {len(close_to_removal) - 20} users")
else:
lines.append("โœ… Abhi koi bhi user warning/removal ke close nahi hai.")
await update.message.reply_text("\n".join(lines), parse_mode="Markdown")
# --- PRIVATE DM RELAY (User <-> Admin) ---
async def handle_private_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message or not update.message.from_user:
return
if not ADMIN_ID:
return
sender_id = update.message.from_user.id
# Case 1: Admin ne reply kiya kisi forwarded message par -> user ko wapas bhejo
if str(sender_id) == str(ADMIN_ID):
if update.message.reply_to_message:
dm_map = load_dm_map()
replied_msg_id = str(update.message.reply_to_message.message_id)
target_user_id = dm_map.get(replied_msg_id)
if target_user_id:
try:
await context.bot.send_message(chat_id=int(target_user_id), text=update.message.text)
await update.message.reply_text("โœ… Reply bhej diya gaya.")
except Forbidden:
await update.message.reply_text("โš ๏ธ User ko message nahi bhej paye (user ne bot block kiya hai).")
except Exception as e:
await update.message.reply_text(f"โš ๏ธ Error: {e}")
else:
await update.message.reply_text("โš ๏ธ Ye purana/anjaan message hai, reply kisme bhejna hai pata nahi chala.")
return
# Case 2: Normal user ne bot ko DM kiya -> admin ko forward karo
username = update.message.from_user.username or "No_Username"
first_name = update.message.from_user.first_name or ""
try:
forwarded = await context.bot.forward_message(
chat_id=int(ADMIN_ID),
from_chat_id=update.message.chat_id,
message_id=update.message.message_id
)
# Mapping save karo taaki admin isi message par reply kare to hume pata chale kisko bhejna hai
dm_map = load_dm_map()
dm_map[str(forwarded.message_id)] = str(sender_id)
save_dm_map(dm_map)
# Admin ko ek chhota info bhi bhej do (kisne bheja)
await context.bot.send_message(
chat_id=int(ADMIN_ID),
text=f"โ˜๏ธ Upar wala message @{username} ({first_name}) ne bheja hai.\nIsi message par reply karke jawab bhejo."
)
except Exception as e:
logging.error(f"[DM RELAY ERROR] Admin ko forward nahi kar paye: {e}")
async def main():
if not TOKEN:
logging.error("CRITICAL ERROR: BOT_TOKEN secret key nahi mili!")
return
if not ADMIN_ID:
logging.warning("[WARNING] ADMIN_ID set nahi hai - DM relay aur /status command kaam nahi karega.")
custom_request = HTTPXRequest(
connect_timeout=30.0,
read_timeout=30.0,
write_timeout=30.0,
pool_timeout=30.0
)
application = (
Application.builder()
.token(TOKEN)
.request(custom_request)
.build()
)
# Admin status command
application.add_handler(CommandHandler("status", bot_status))
# Group message tracking (link detect + first-seen)
application.add_handler(
MessageHandler(filters.TEXT & filters.ChatType.GROUPS & ~filters.COMMAND, track_activity)
)
# Naye member join tracking
application.add_handler(ChatMemberHandler(track_new_member, ChatMemberHandler.CHAT_MEMBER))
# Private DM relay (user <-> admin)
application.add_handler(
MessageHandler(filters.ChatType.PRIVATE & ~filters.COMMAND, handle_private_message)
)
job_queue = application.job_queue
job_queue.run_repeating(check_and_remove_inactive, interval=CHECK_INTERVAL_SECONDS, first=15)
while True:
try:
async with application:
await application.initialize()
await application.start()
logging.info("=============================================")
logging.info(f" BOT STATUS: LIVE ({REMOVE_DAYS}-DAYS MODE) IS ACTIVE! ")
logging.info("=============================================")
await application.updater.start_polling(timeout=20, allowed_updates=Update.ALL_TYPES)
while True:
await asyncio.sleep(1)
except Exception as e:
logging.exception(f"[CONNECTION ERROR] {type(e).__name__}. 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.")