import asyncio import logging import sys import os import re import html from typing import List, Tuple, Optional, Dict if hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8') from http.server import HTTPServer, BaseHTTPRequestHandler import threading from telegram import Update from telegram.constants import ParseMode from telegram.ext import ( ApplicationBuilder, CommandHandler, ContextTypes, ChatMemberHandler, MessageHandler, filters ) from config import load_config, save_config from cluster_engine import ClusterEngine from tracker_listener import WalletTracker from metadata import get_token_details from card_formatter import format_telegram_card, get_token_keyboard, sanitize_telegram_html logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logger = logging.getLogger("RunnerBot") cfg_initial = load_config() cluster_engine = ClusterEngine(sssss_bundler_wallets=cfg_initial.get("SSSSS_BUNDLER_WALLETS", [])) def ensure_chat_registered(chat_id: str): """Auto-register chat ID into persistent configuration and secondary chats file""" if not chat_id: return chat_id = str(chat_id) cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) if chat_id not in chat_ids: chat_ids.add(chat_id) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) if not cfg.get("TELEGRAM_CHAT_ID"): cfg["TELEGRAM_CHAT_ID"] = chat_id save_config(cfg) logger.info(f"Auto-registered chat broadcast destination: {chat_id}") async def global_message_listener(update: Update, context: ContextTypes.DEFAULT_TYPE): """Ensure any incoming chat interaction automatically registers the chat destination""" if update.effective_chat: ensure_chat_registered(str(update.effective_chat.id)) class HealthCheckHandler(BaseHTTPRequestHandler): """Lightweight HTTP server to keep Hugging Face Spaces container running 24/7 on port 7860""" def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html; charset=utf-8") self.end_headers() html = """ Solana Runner Radar Bot

🚀 Solana Runner & Sniper Radar Bot

Status: Active & Polling 24/7

Cloud Container is healthy and broadcasting alerts to registered Telegram chats and groups.

""" self.wfile.write(html.encode("utf-8")) def log_message(self, format, *args): pass def start_health_check_server(): port = int(os.environ.get("PORT", 7860)) try: server = HTTPServer(("0.0.0.0", port), HealthCheckHandler) t = threading.Thread(target=server.serve_forever, daemon=True) t.start() logger.info(f"Health check web server running on port {port}") except Exception as e: logger.warning(f"Could not start health check web server on port {port}: {e}") def get_registered_chat_ids() -> set: cfg = load_config() chat_ids = set() primary = cfg.get("TELEGRAM_CHAT_ID") if primary: chat_ids.add(str(primary)) for cid in cfg.get("TELEGRAM_CHAT_IDS", []): if cid: chat_ids.add(str(cid)) return chat_ids async def send_alert(app, text: str, image_url: str = None, mint: str = ""): chat_ids = get_registered_chat_ids() if not chat_ids: logger.warning("No registered chat IDs configured. Alert skipped.") return reply_markup = get_token_keyboard(mint) if mint else None clean_html_text = sanitize_telegram_html(text) for chat_id in list(chat_ids): try: if image_url and (image_url.startswith("http://") or image_url.startswith("https://")): await app.bot.send_photo( chat_id=chat_id, photo=image_url, caption=clean_html_text, parse_mode=ParseMode.HTML, reply_markup=reply_markup ) else: await app.bot.send_message( chat_id=chat_id, text=clean_html_text, parse_mode=ParseMode.HTML, disable_web_page_preview=False, reply_markup=reply_markup ) except Exception as e: logger.error(f"Failed to send HTML alert to chat {chat_id}: {e}") # Robust fallback: strip all HTML markup so raw tags never display in chat plain_fallback = re.sub(r'<[^>]+>', '', text).strip() try: await app.bot.send_message( chat_id=chat_id, text=plain_fallback, parse_mode=None, reply_markup=reply_markup ) except Exception as e2: logger.error(f"Failed fallback send to {chat_id}: {e2}") # Command Handlers async def chat_member_update(update: Update, context: ContextTypes.DEFAULT_TYPE): """Automatically register groups when bot is added, and unregister when removed""" result = update.my_chat_member if not result: return chat = result.chat new_status = result.new_chat_member.status cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) if new_status in ["member", "administrator"]: chat_ids.add(str(chat.id)) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) save_config(cfg) logger.info(f"Bot added to group {chat.title or chat.id} ({chat.id})") try: await context.bot.send_message( chat_id=chat.id, text=( "🤖 Solana Runner & Sniper Radar Bot Connected!\n\n" f"✅ Group Registered: {chat.id}\n" "All smart-money convergence clusters and high-conviction sniper alerts will be broadcasted here automatically!\n\n" "Type /status to check active thresholds." ), parse_mode=ParseMode.HTML ) except Exception as e: logger.error(f"Failed to send greeting to group {chat.id}: {e}") elif new_status in ["left", "kicked"]: if str(chat.id) in chat_ids: chat_ids.remove(str(chat.id)) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) save_config(cfg) logger.info(f"Bot removed from group {chat.id}") async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): chat_id = str(update.effective_chat.id) chat_type = update.effective_chat.type is_group = chat_type in ["group", "supergroup", "channel"] cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) if chat_id not in chat_ids: chat_ids.add(chat_id) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) if not cfg.get("TELEGRAM_CHAT_ID"): cfg["TELEGRAM_CHAT_ID"] = chat_id save_config(cfg) sol_wallets = [a for a in cfg.get("WALLETS", {}).keys() if not a.startswith("0x")] bsc_wallets = [a for a in cfg.get("WALLETS", {}).keys() if a.startswith("0x")] wallets_count = len(cfg.get("WALLETS", {})) if is_group: title = update.effective_chat.title or "This Group" msg = ( f"🤖 Multi-Chain Runner Bot Active in {title}!\n\n" f"✅ Group Connected: {chat_id}\n" f"đŸŽ¯ Tracking {len(sol_wallets)} Solana + {len(bsc_wallets)} BSC smart-money wallets.\n\n" "All runner alerts (cluster co-buys & conviction snipes across Solana & BSC) will be broadcasted here automatically!\n\n" "Group Commands:\n" "â€ĸ /check <address> — Audit any token (SOL, BSC, Robinhood) & view Developer Card\n" "â€ĸ /status — View active multi-chain filters & signals architecture\n" "â€ĸ /wallets — View tracked smart-money sniper wallets\n" "â€ĸ /chats — View all registered broadcast destinations" ) else: msg = ( "🤖 Multi-Chain (Solana, BSC & Robinhood) Runner Radar Bot Active!\n\n" f"✅ Your Chat ID is registered: {chat_id}\n" f"đŸŽ¯ Tracking {len(sol_wallets)} Solana + {len(bsc_wallets)} BSC + {len(rh_wallets)} Robinhood elite wallets.\n\n" "Available Commands:\n" "â€ĸ /wallets — View all tracked wallets by chain\n" "â€ĸ /addwallet <address> <name> [rh] — Add sniper wallet\n" "â€ĸ /addwallets <bulk paste> — Bulk import multiple addresses\n" "â€ĸ /removewallet <address> — Remove tracked wallet\n" "â€ĸ /minbuy <amount> [sol|bnb|rh] — Set minimum buy filter\n" "â€ĸ /maxmc <usd> [rh] — Set max market cap filter ($20k SOL/BSC, $70k Robinhood)\n" "â€ĸ /volratio <multiplier|off> — Volume >> MarketCap turnover signal filter\n" "â€ĸ /check <address> — Audit any Solana mint, BSC CA, or Robinhood token\n" "â€ĸ /chats — View all registered broadcast destinations\n" "â€ĸ /testalert [sol|bsc|rh|charity] — Send demo VIP alert card\n" "â€ĸ /status — Check engine filters vs signals architecture\n\n" "💡 Tip: Add this bot to any Telegram group or channel and send /start there to broadcast calls to your group too!" ) await update.message.reply_text(msg, parse_mode=ParseMode.HTML) async def chats_command(update: Update, context: ContextTypes.DEFAULT_TYPE): chat_ids = get_registered_chat_ids() if not chat_ids: await update.message.reply_text("No chats currently registered. Send /start or /addchat to register.") return lines = [f"đŸ“ĸ Registered Broadcast Chats ({len(chat_ids)}):\n"] for cid in chat_ids: lines.append(f"â€ĸ {cid}") lines.append("\nAlerts will be broadcasted to all registered chats & groups automatically!\nTo add another: /addchat <id>\nTo remove: /removechat <id>") await update.message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML) async def id_command(update: Update, context: ContextTypes.DEFAULT_TYPE): chat = update.effective_chat title = chat.title or "Direct Message" await update.message.reply_text( f"🆔 Chat Identification:\n" f"â€ĸ Title: {html.escape(title)}\n" f"â€ĸ Chat ID: {chat.id}\n" f"â€ĸ Type: {chat.type}\n\n" f"To broadcast alerts here, send: /addchat {chat.id}", parse_mode=ParseMode.HTML ) async def addchat_command(update: Update, context: ContextTypes.DEFAULT_TYPE): if not context.args: target_id = str(update.effective_chat.id) else: target_id = context.args[0].strip() cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) chat_ids.add(target_id) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) if not cfg.get("TELEGRAM_CHAT_ID"): cfg["TELEGRAM_CHAT_ID"] = target_id save_config(cfg) await update.message.reply_text( f"✅ Chat Successfully Registered!\n" f"â€ĸ Chat ID: {target_id}\n" f"â€ĸ Total Active Broadcast Destinations: {len(chat_ids)}\n\n" "All smart-money convergence alerts and runner calls will be delivered here automatically.", parse_mode=ParseMode.HTML ) async def removechat_command(update: Update, context: ContextTypes.DEFAULT_TYPE): if not context.args: target_id = str(update.effective_chat.id) else: target_id = context.args[0].strip() cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) if target_id in chat_ids: chat_ids.remove(target_id) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) if cfg.get("TELEGRAM_CHAT_ID") == target_id: cfg["TELEGRAM_CHAT_ID"] = list(chat_ids)[0] if chat_ids else "" save_config(cfg) await update.message.reply_text(f"đŸ—‘ī¸ Removed chat {target_id} from broadcasts.", parse_mode=ParseMode.HTML) else: await update.message.reply_text(f"âš ī¸ Chat {target_id} was not in the registered list.", parse_mode=ParseMode.HTML) async def wallets_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() wallets = cfg.get("WALLETS", {}) if not wallets: await update.message.reply_text("No wallets currently tracked. Use /addwallet to add one.") return sol_lines = [] bsc_lines = [] rh_lines = [] for addr, name in wallets.items(): if addr.startswith("0x"): n_low = name.lower() if "rh" in n_low or "robinhood" in n_low or "robin" in n_low: rh_lines.append(f" â€ĸ {name}: {addr}") else: bsc_lines.append(f" â€ĸ {name}: {addr}") else: sol_lines.append(f" â€ĸ {name}: {addr}") lines = ["đŸ‘Ĩ Tracked Sniper Wallets:\n"] if sol_lines: lines.append(f"đŸĒ Solana ({len(sol_lines)}):") lines.extend(sol_lines) lines.append("") if bsc_lines: lines.append(f"🟡 BNB Chain / BSC ({len(bsc_lines)}):") lines.extend(bsc_lines) lines.append("") if rh_lines: lines.append(f"🏹 Robinhood Chain ({len(rh_lines)}):") lines.extend(rh_lines) lines.append("") lines.append("To add: /addwallet <address> [nickname] [rh] or /addwallets <bulk paste>") await update.message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML) def extract_wallets_from_text(text: str) -> list: """ Extract all Solana (Base58 32-44 chars), BSC (0x 40 hex chars), and Robinhood (0x 40 hex chars) addresses with optional nicknames from a text block. Returns list of (address: str, nickname: str, chain: str). """ results = [] lines = text.strip().splitlines() sol_base58_pattern = r'[1-9A-HJ-NP-Za-km-z]{32,44}' evm_pattern = r'0x[a-fA-F0-9]{40}' seen_addrs = set() for line in lines: line_str = line.strip() if not line_str: continue evm_matches = list(re.finditer(evm_pattern, line_str, re.IGNORECASE)) sol_matches = list(re.finditer(sol_base58_pattern, line_str)) is_line_rh = bool(re.search(r'(?i)(?:^|[\s_])(?:rh|robinhood|robin)(?:$|[\s_])|robinhood|robin', line_str)) matches = [] for m in evm_matches: matched_chain = "robinhood" if is_line_rh else "bsc" matches.append((m.start(), m.end(), m.group(0), matched_chain)) for m in sol_matches: if not any(m.start() >= bm.start() and m.end() <= bm.end() for bm in evm_matches): matches.append((m.start(), m.end(), m.group(0), "solana")) matches.sort(key=lambda x: x[0]) if not matches: continue if len(matches) == 1: start, end, addr, chain = matches[0] if addr in seen_addrs: continue seen_addrs.add(addr) nickname = (line_str[:start] + " " + line_str[end:]).strip() # Clean out trailing chain tags from nickname nickname = re.sub(r'\b(rh|robinhood|bsc|solana|bnb|eth)\b', '', nickname, flags=re.IGNORECASE) nickname = re.sub(r'[,;:\-â€ĸ]+', '', nickname).strip() if not nickname or len(nickname) < 2: if chain == "robinhood": prefix = "RH" elif chain == "bsc": prefix = "BSC" else: prefix = "Sniper" nickname = f"{prefix}_{addr[:4]}_{addr[-4:]}" elif chain == "robinhood" and not ("rh" in nickname.lower() or "robin" in nickname.lower()): nickname = f"RH_{nickname}" results.append((addr, nickname, chain)) else: for start, end, addr, chain in matches: if addr in seen_addrs: continue seen_addrs.add(addr) if chain == "robinhood": prefix = "RH" elif chain == "bsc": prefix = "BSC" else: prefix = "Sniper" nickname = f"{prefix}_{addr[:4]}_{addr[-4:]}" results.append((addr, nickname, chain)) return results async def addwallet_command(update: Update, context: ContextTypes.DEFAULT_TYPE): raw_text = update.message.text or "" cmd_prefix = raw_text.split()[0] if raw_text.split() else "" content = raw_text[len(cmd_prefix):].strip() if not content: await update.message.reply_text( "âš ī¸ Add Wallet Usage:\n" "â€ĸ Single with nickname: /addwallet <address> <nickname> [rh]\n" "â€ĸ Single without nickname: /addwallet <address> (auto-named)\n" "â€ĸ Bulk import: /addwallets <paste multiple addresses>\n\n" "Supports Solana Base58, BSC 0x, and Robinhood Chain 0x addresses (include 'rh' or 'RH_' for Robinhood).", parse_mode=ParseMode.HTML ) return extracted = extract_wallets_from_text(content) if not extracted: await update.message.reply_text( "❌ No valid Solana Base58 (32-44 chars) or EVM (0x + 40 hex) addresses found.", parse_mode=ParseMode.HTML ) return cfg = load_config() wallets = cfg.setdefault("WALLETS", {}) added_lines = [] for addr, nickname, chain in extracted: wallets[addr] = nickname if chain == "robinhood": chain_emoji = "🏹" elif chain == "bsc": chain_emoji = "🟡" else: chain_emoji = "đŸĒ" added_lines.append(f"â€ĸ {chain_emoji} {html.escape(nickname)}: {addr}") save_config(cfg) total_wallets = len(wallets) summary_text = "\n".join(added_lines[:15]) more_text = f"\n...and {len(added_lines) - 15} more" if len(added_lines) > 15 else "" await update.message.reply_text( f"✅ Successfully Tracked {len(extracted)} Wallet(s)!\n\n" f"{summary_text}{more_text}\n\n" f"📊 Total Active Tracked Wallets: {total_wallets}\n" "Live multi-chain sniping radar will immediately alert on incoming buys.", parse_mode=ParseMode.HTML ) async def addwallets_command(update: Update, context: ContextTypes.DEFAULT_TYPE): """Alias for bulk wallet addition""" await addwallet_command(update, context) async def removewallet_command(update: Update, context: ContextTypes.DEFAULT_TYPE): if not context.args: await update.message.reply_text("Usage: /removewallet <address or nickname>", parse_mode=ParseMode.HTML) return query = context.args[0].strip() cfg = load_config() wallets = cfg.get("WALLETS", {}) target_addr = None target_name = None if query in wallets: target_addr = query target_name = wallets[query] else: # Case-insensitive or nickname match for addr, name in wallets.items(): if addr.lower() == query.lower() or name.lower() == query.lower(): target_addr = addr target_name = name break if target_addr: wallets.pop(target_addr, None) save_config(cfg) await update.message.reply_text(f"✅ Removed wallet {html.escape(target_name)} ({target_addr})", parse_mode=ParseMode.HTML) else: await update.message.reply_text("❌ Wallet address or nickname not found in tracked list.", parse_mode=ParseMode.HTML) async def minbuy_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() current_sol = cfg.get("MIN_BUY_SOL", 0.2) current_bnb = cfg.get("MIN_BUY_BNB", 0.05) current_eth = cfg.get("MIN_BUY_ETH", 0.01) if not context.args: await update.message.reply_text( f"📊 Current Anti-Spray Min Buy Thresholds:\n" f"â€ĸ Solana: {current_sol} SOL\n" f"â€ĸ BSC: {current_bnb} BNB\n" f"â€ĸ Robinhood: {current_eth} ETH\n\n" f"To change: /minbuy <amount> [sol|bnb|rh|eth]\n" f"Example: /minbuy 0.3 sol or /minbuy 0.02 rh", parse_mode=ParseMode.HTML ) return try: val = float(context.args[0].strip()) target_chain = context.args[1].strip().lower() if len(context.args) > 1 else "sol" if val < 0.001: await update.message.reply_text("❌ Minimum buy must be at least 0.001.") return if target_chain in ["eth", "rh", "robinhood"]: cfg["MIN_BUY_ETH"] = val save_config(cfg) cluster_engine.min_buy_eth = val chain_text = f"Robinhood Chain buys â‰Ĩ {val} ETH" elif target_chain in ["bnb", "bsc"]: cfg["MIN_BUY_BNB"] = val save_config(cfg) cluster_engine.min_buy_bnb = val chain_text = f"BSC (BNB Chain) buys â‰Ĩ {val} BNB" else: cfg["MIN_BUY_SOL"] = val save_config(cfg) cluster_engine.min_buy_sol = val chain_text = f"Solana buys â‰Ĩ {val} SOL" await update.message.reply_text( f"✅ Min Buy Filter Updated!\n" f"Only {chain_text} will be counted.\n" "Micro-spray noise below this threshold will be ignored.", parse_mode=ParseMode.HTML ) except ValueError: await update.message.reply_text("❌ Invalid number. Example: /minbuy 0.02 rh", parse_mode=ParseMode.HTML) async def maxmc_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() current_general = cfg.get("MAX_ENTRY_MC", 20000) current_rh = cfg.get("MAX_ENTRY_MC_ROBINHOOD", 70000) if not context.args: await update.message.reply_text( f"💰 Max Entry Market Cap Filters:\n" f"â€ĸ Solana & BSC: ${current_general:,.0f}\n" f"â€ĸ Robinhood Chain: ${current_rh:,.0f} (Strict $70k Cap)\n\n" f"To change Solana/BSC: /maxmc <usd_amount>\n" f"To change Robinhood: /maxmc <usd_amount> rh\n" f"Example: /maxmc 70000 rh", parse_mode=ParseMode.HTML ) return try: val = float(context.args[0].strip().replace(",", "").replace("$", "")) target_chain = context.args[1].strip().lower() if len(context.args) > 1 else "sol" if val <= 1000: await update.message.reply_text("❌ Max MC must be at least $1,000.") return if target_chain in ["rh", "robinhood", "eth"]: cfg["MAX_ENTRY_MC_ROBINHOOD"] = val save_config(cfg) await update.message.reply_text( f"✅ Robinhood Max Entry MC Updated!\n" f"Robinhood tokens above ${val:,.0f} will NOT be called.", parse_mode=ParseMode.HTML ) else: cfg["MAX_ENTRY_MC"] = val save_config(cfg) await update.message.reply_text( f"✅ Solana & BSC Max Entry MC Updated!\n" f"Tokens above ${val:,.0f} will NOT be called.", parse_mode=ParseMode.HTML ) except ValueError: await update.message.reply_text("❌ Invalid number. Example: /maxmc 70000 rh", parse_mode=ParseMode.HTML) async def volratio_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() current_enabled = cfg.get("REQUIRE_VOLUME_GT_MC", True) current_ratio = cfg.get("MIN_VOLUME_TO_MC_RATIO", 1.0) if not context.args: status_str = f"đŸŸĸ Active (Vol â‰Ĩ {current_ratio}x MC)" if current_enabled else "âšĒ Off" await update.message.reply_text( f"🌊 Volume >> MarketCap Turnover Filter:\n" f"â€ĸ Status: {status_str}\n" f"â€ĸ Current Minimum Ratio: {current_ratio}x\n\n" "Tokens with Volume < MarketCap are hidden to eliminate bundled launches and floor-holding cartels.\n\n" "Usage:\n" "â€ĸ /volratio 1.0 — Require Volume â‰Ĩ 1.0x MarketCap (Volume > MC)\n" "â€ĸ /volratio 1.5 — Require Volume â‰Ĩ 1.5x MarketCap (Heavier turnover)\n" "â€ĸ /volratio off — Disable volume filter", parse_mode=ParseMode.HTML ) return arg = context.args[0].lower().strip() if arg in ["off", "disable", "false", "0"]: cfg["REQUIRE_VOLUME_GT_MC"] = False save_config(cfg) await update.message.reply_text("âšĒ Volume >> MarketCap Filter Disabled.", parse_mode=ParseMode.HTML) elif arg in ["on", "enable", "true"]: cfg["REQUIRE_VOLUME_GT_MC"] = True save_config(cfg) await update.message.reply_text(f"✅ Volume >> MarketCap Filter Enabled! (Vol â‰Ĩ {current_ratio}x MC)", parse_mode=ParseMode.HTML) else: try: val = float(arg.replace("x", "")) if val <= 0: await update.message.reply_text("❌ Ratio must be greater than 0.") return cfg["REQUIRE_VOLUME_GT_MC"] = True cfg["MIN_VOLUME_TO_MC_RATIO"] = val save_config(cfg) await update.message.reply_text( f"✅ Volume >> MarketCap Filter Updated!\n" f"Tokens must now have Volume â‰Ĩ {val}x MarketCap to be called.\n" "Coins with low turnover, bundles, or held floors will be hidden by elimination.", parse_mode=ParseMode.HTML ) except ValueError: await update.message.reply_text("❌ Invalid value. Example: /volratio 1.0 or /volratio off", parse_mode=ParseMode.HTML) async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE): if not context.args: await update.message.reply_text("Usage: /check <token_mint_address>", parse_mode=ParseMode.HTML) return mint = context.args[0].strip() wait_msg = await update.message.reply_text("🔍 Fetching on-chain metadata, market data & lore...") try: cfg = load_config() rpc_url = cfg.get("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com") token_details = await asyncio.to_thread(get_token_details, mint, rpc_url) # Check cluster engine for any tracked buys stats = cluster_engine.get_cluster_stats(mint) mock_signal = { "type": "AUDIT", "unique_wallets_count": len(stats.get("unique_wallets", [])), "total_sol": stats.get("total_sol", 0.0), "time_span_seconds": 0, "buys": [{"wallet_name": w, "sol_amount": 0.0} for w in stats.get("unique_wallets", [])] } card = format_telegram_card(token_details, mock_signal) reply_markup = get_token_keyboard(mint) await wait_msg.delete() img = token_details.get("image_url") if img and (img.startswith("http://") or img.startswith("https://")): await update.message.reply_photo(photo=img, caption=card, parse_mode=ParseMode.HTML, reply_markup=reply_markup) else: await update.message.reply_text(card, parse_mode=ParseMode.HTML, disable_web_page_preview=False, reply_markup=reply_markup) except Exception as e: await wait_msg.edit_text(f"❌ Error fetching token details: {e}") async def testalert_command(update: Update, context: ContextTypes.DEFAULT_TYPE): # Auto-register current chat if not already registered caller_id = str(update.effective_chat.id) cfg = load_config() chat_ids = set(str(c) for c in cfg.get("TELEGRAM_CHAT_IDS", [])) if caller_id not in chat_ids: chat_ids.add(caller_id) cfg["TELEGRAM_CHAT_IDS"] = list(chat_ids) if not cfg.get("TELEGRAM_CHAT_ID"): cfg["TELEGRAM_CHAT_ID"] = caller_id save_config(cfg) # Check chain or type requested target_arg = context.args[0].lower() if context.args else "" is_charity = "charity" in target_arg is_rh = target_arg in ["rh", "robinhood", "robin"] is_bsc = target_arg in ["bsc", "bnb"] and not is_rh is_accum = target_arg in ["accum", "dca", "accumulation"] or (not is_charity and not is_rh and not is_bsc) if is_charity: await update.message.reply_text("🚀 Generating test alert for Charity Coin with Buybacks (Unlimited MC Bypass)...") test_mint = "6p6xgHyF7AeQEyaxqa8D360k8V5N44pump" token = { "mint": test_mint, "chain": "solana", "currency": "SOL", "name": "WaterAid Charity", "symbol": "WATER", "market_cap": 145000, # > $20k, demonstrates unlimited bypass "multiplier": 24.1, "bonding_curve_pct": 100.0, "volume": 220000.0, "vol_24h": 220000.0, "vol_to_mc_ratio": 1.52, "vol_5m": 35200.0, "buy_ratio_5m": 2.8, "is_charity_buyback": True, "charity_buyback_reason": "Direct charity cause with automated buybacks", "dev_description": "Clean water humanitarian project donating 50% of creator royalties directly to charity foundations with continuous buyback and burn mechanics.", "lore": "Verified charity token funding well construction in remote villages with dedicated community buybacks.", "twitter": "https://x.com/search?q=WaterAidSolana", "telegram": "https://t.me/WaterAidSolana", "website": "https://wateraid-solana.org" } signal = { "type": "CHARITY_BUYBACK", "chain": "solana", "currency": "SOL", "primary_wallet": "Putrick", "wallet_addr": "AVjEtg2ECYKXYeqdRQXvaaAZBjfTjYuSMTR4WLhKoeQN", "amount": 2.5, "sol_amount": 2.5, "unique_wallets_count": 1, "total_amount": 2.5, "total_sol": 2.5, "time_span_seconds": 0, "buys": [ {"wallet_name": "Putrick", "amount": 2.5, "time": 100, "sig": "5xYzA1B2C3D4"} ] } elif is_accum: await update.message.reply_text("🚀 Generating test alert for 3x Consecutive Buys (â‰Ĩ1.0 SOL each, 0 Sells)...") rpc_url = cfg.get("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com") test_mint = "33jENUQnjoitkMFpvNJcSHyLAHFWJuHwT6E3E8CNpump" token = await asyncio.to_thread(get_token_details, test_mint, rpc_url) signal = { "type": "ACCUMULATION", "chain": "solana", "currency": "SOL", "primary_wallet": "Putrick", "wallet_addr": "AVjEtg2ECYKXYeqdRQXvaaAZBjfTjYuSMTR4WLhKoeQN", "buy_count": 3, "total_amount": 4.5, "total_sol": 4.5, "amount": 1.75, "sol_amount": 1.75, "time_span_seconds": 185, "buys": [ {"wallet_name": "Putrick", "amount": 1.25, "time": 100, "sig": "4aBcDeFg1234"}, {"wallet_name": "Putrick", "amount": 1.50, "time": 190, "sig": "7hIjKlMn5678"}, {"wallet_name": "Putrick", "amount": 1.75, "time": 285, "sig": "9oPqRsTu9012"} ] } elif is_rh: await update.message.reply_text("🚀 Generating test alert for Robinhood Chain runner ($ROBIN)...") test_mint = "0x008df4b3e857d06c4603aeb11f267ccd32ce2005" token = await asyncio.to_thread(get_token_details, test_mint, chain_hint="robinhood") if not token.get("name") or token.get("name") == "Unknown Token": token["name"] = "Robinhood Runner" token["symbol"] = "ROBIN" token["chain"] = "robinhood" token["currency"] = "ETH" token["market_cap"] = 48500 token["multiplier"] = 8.1 token["bonding_curve_pct"] = 69.3 token["dev_description"] = "Community-led Robinhood chain runner. Native Robinhood Orbit L2 liquidity locked." token["twitter"] = f"https://x.com/search?q={test_mint}" signal = { "type": "ACCUMULATION", "chain": "robinhood", "currency": "ETH", "primary_wallet": "RH_Deployer", "buy_count": 3, "unique_wallets_count": 1, "total_amount": 0.55, "total_sol": 0.55, "amount": 0.25, "time_span_seconds": 95, "buys": [ {"wallet_name": "RH_Deployer", "amount": 0.15, "time": 100, "sig": "0x1111"}, {"wallet_name": "RH_Deployer", "amount": 0.15, "time": 140, "sig": "0x2222"}, {"wallet_name": "RH_Deployer", "amount": 0.25, "time": 195, "sig": "0x3333"} ] } else: await update.message.reply_text("🚀 Generating test alert for BSC runner token ($CAKE)...") test_mint = "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" token = await asyncio.to_thread(get_token_details, test_mint) signal = { "type": "ACCUMULATION", "chain": "bsc", "currency": "BNB", "primary_wallet": "BSC_Whale", "buy_count": 3, "unique_wallets_count": 1, "total_amount": 3.75, "total_sol": 3.75, "amount": 1.5, "time_span_seconds": 120, "buys": [ {"wallet_name": "BSC_Whale", "amount": 1.0, "time": 100, "sig": "0xaaaa"}, {"wallet_name": "BSC_Whale", "amount": 1.25, "time": 150, "sig": "0xbbbb"}, {"wallet_name": "BSC_Whale", "amount": 1.5, "time": 220, "sig": "0xcccc"} ] } card = format_telegram_card(token, signal) reply_markup = get_token_keyboard(test_mint, chain="robinhood" if is_rh else ("bsc" if is_bsc else "solana")) img = token.get("image_url") # 1. Deliver to caller chat if img and (img.startswith("http://") or img.startswith("https://")): await update.message.reply_photo(photo=img, caption=card, parse_mode=ParseMode.HTML, reply_markup=reply_markup) else: await update.message.reply_text(card, parse_mode=ParseMode.HTML, disable_web_page_preview=False, reply_markup=reply_markup) # 2. Also broadcast to all other registered chats/groups registered_destinations = get_registered_chat_ids() other_chats = [cid for cid in registered_destinations if cid != caller_id] if other_chats: broadcast_success = 0 for cid in other_chats: try: if img and (img.startswith("http://") or img.startswith("https://")): await context.bot.send_photo(chat_id=cid, photo=img, caption=card, parse_mode=ParseMode.HTML, reply_markup=reply_markup) else: await context.bot.send_message(chat_id=cid, text=card, parse_mode=ParseMode.HTML, disable_web_page_preview=False, reply_markup=reply_markup) broadcast_success += 1 except Exception as e: logger.error(f"Failed to broadcast test alert to {cid}: {e}") await update.message.reply_text( f"đŸ“ĸ Broadcast Sent! Delivered to {broadcast_success} registered group(s)/channel(s).", parse_mode=ParseMode.HTML ) else: await update.message.reply_text( "â„šī¸ No other groups registered yet.\n" "To broadcast alerts to your group:\n" "1. Add the bot to your group.\n" "2. Make the bot an Admin (so Telegram delivers group commands).\n" "3. Send /start in the group (or send /addchat <group_id> here).", parse_mode=ParseMode.HTML ) async def phanes_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() if not context.args: current = cfg.get("AUTO_PHANES_TRIGGER", True) state_str = "đŸŸĸ ON (Posting 1-tap CA & /c@phanes_bot)" if current else "âšĒ OFF" await update.message.reply_text( f"🤖 Phanes Auto-Trigger Status: {state_str}\n\n" "To toggle: /phanes on or /phanes off", parse_mode=ParseMode.HTML ) return arg = context.args[0].lower() if arg in ["on", "enable", "true", "1"]: cfg["AUTO_PHANES_TRIGGER"] = True save_config(cfg) await update.message.reply_text("✅ Phanes Auto-Trigger Enabled!\nEvery call will post a follow-up 1-tap CA with /c@phanes_bot <CA>.", parse_mode=ParseMode.HTML) elif arg in ["off", "disable", "false", "0"]: cfg["AUTO_PHANES_TRIGGER"] = False save_config(cfg) await update.message.reply_text("âšĒ Phanes Auto-Trigger Disabled.", parse_mode=ParseMode.HTML) else: await update.message.reply_text("Usage: /phanes on or /phanes off", parse_mode=ParseMode.HTML) async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE): cfg = load_config() wallets = cfg.get("WALLETS", {}) sol_wallets = [a for a in wallets.keys() if not a.startswith("0x")] bsc_wallets = [] rh_wallets = [] for a, name in wallets.items(): if a.startswith("0x"): n_low = name.lower() if "rh" in n_low or "robinhood" in n_low or "robin" in n_low: rh_wallets.append(a) else: bsc_wallets.append(a) min_cobuy = cfg.get("MIN_WALLETS_COBUY", 2) min_buy_sol = cfg.get("MIN_BUY_SOL", 1.0) min_buy_bnb = cfg.get("MIN_BUY_BNB", 0.25) min_buy_eth = cfg.get("MIN_BUY_ETH", 0.05) max_mc = cfg.get("MAX_ENTRY_MC", 20000) max_mc_rh = cfg.get("MAX_ENTRY_MC_ROBINHOOD", 70000) req_lore = cfg.get("REQUIRE_LORE", True) req_socials = cfg.get("REQUIRE_SOCIALS", True) req_dev_desc = cfg.get("REQUIRE_DEV_DESCRIPTION", True) req_vol_gt_mc = cfg.get("REQUIRE_VOLUME_GT_MC", True) min_vol_ratio = cfg.get("MIN_VOLUME_TO_MC_RATIO", 1.0) rotator_window = cfg.get("ROTATOR_THROTTLE_SECONDS", 180) broadcast_count = len(get_registered_chat_ids()) ensure_chat_registered(str(update.effective_chat.id)) lore_status = "đŸŸĸ Required" if req_lore else "âšĒ Off" soc_status = "đŸŸĸ Required" if req_socials else "âšĒ Off" dev_desc_status = "đŸŸĸ STRICT (Empty/unvetted desc filtered)" if req_dev_desc else "âšĒ Off" vol_status = f"đŸŸĸ STRICT (Vol â‰Ĩ {min_vol_ratio}x MC â€ĸ Low-turnover bundled rugs hidden)" if req_vol_gt_mc else "âšĒ Off" msg = ( "📊 Multi-Chain Engine Architecture: Filters vs. Signals\n" "━━━━━━━━━━━━━━━━━━━━\n" "🌐 Engine Status: đŸŸĸ Running & Polling 24/7 (Solana, BSC & Robinhood Chain)\n" f"đŸŽ¯ Tracked Wallets: {len(sol_wallets)} Solana + {len(bsc_wallets)} BSC + {len(rh_wallets)} Robinhood ({len(wallets)} total)\n" f"đŸ“ĸ Active Broadcast Chats: {broadcast_count}\n\n" "đŸ›Ąī¸ FILTERS (Gating Requirements — Discards non-compliant tokens):\n" f" ├ 💰 Max Entry MC: ${max_mc:,.0f} (Solana & BSC) | ${max_mc_rh:,.0f} (Robinhood)\n" f" ├ 📜 Developer Description: {dev_desc_status}\n" f" ├ 📖 Lore / Thesis: {lore_status}\n" f" ├ 🌐 Official Socials: {soc_status}\n" f" ├ đŸ’ĩ Anti-Spray Min Buy: â‰Ĩ{min_buy_sol} SOL | â‰Ĩ{min_buy_bnb} BNB | â‰Ĩ{min_buy_eth} ETH\n" f" └ âąī¸ Anti-Rotator Throttle: đŸŸĸ Active ({rotator_window}s cooldown)\n\n" "🚨 SIGNALS (Triggers & Alert Badges):\n" f" ├ 🌊 Volume >> MC Turnover: {vol_status}\n" " ├ 💎 3x Consecutive Accumulation: đŸŸĸ Active (3 buys in a row without selling, â‰Ĩ1.0 SOL each)\n" " ├ đŸŽ—ī¸ Charity & Buyback Radar: đŸŸĸ Active (Verified charity + buybacks, Unlimited MC Bypass)\n" f" ├ đŸ‘Ĩ Smart Money Cluster: đŸŸĸ Active (â‰Ĩ{min_cobuy} tracked wallets co-buying in 300s window)\n" " └ đŸŽ¯ Conviction Whale Entry: đŸŸĸ Active (â‰Ĩ1.5 SOL / 0.4 BNB / 0.1 ETH single buy)\n" "━━━━━━━━━━━━━━━━━━━━\n" "💡 Tip: The bot automatically tracks your smart-money wallets in real time!" ) await update.message.reply_text(msg, parse_mode=ParseMode.HTML) def main(): cfg = load_config() token = cfg.get("TELEGRAM_BOT_TOKEN") if not token or token == "YOUR_TELEGRAM_BOT_TOKEN_HERE": print("\n" + "="*60) print("âš ī¸ TELEGRAM_BOT_TOKEN is missing in config.json!") print("Please set your bot token from @BotFather in config.json") print("="*60 + "\n") # Start web health check server for Hugging Face Spaces port 7860 start_health_check_server() app = ApplicationBuilder().token(token if token else "MOCK_TOKEN").build() # Auto-register every incoming chat interaction app.add_handler(MessageHandler(filters.ALL, global_message_listener), group=-1) # Register handlers app.add_handler(ChatMemberHandler(chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER)) app.add_handler(CommandHandler("start", start_command)) app.add_handler(CommandHandler("wallets", wallets_command)) app.add_handler(CommandHandler("addwallet", addwallet_command)) app.add_handler(CommandHandler("addwallets", addwallets_command)) app.add_handler(CommandHandler("removewallet", removewallet_command)) app.add_handler(CommandHandler("minbuy", minbuy_command)) app.add_handler(CommandHandler("maxmc", maxmc_command)) app.add_handler(CommandHandler("volratio", volratio_command)) app.add_handler(CommandHandler("check", check_command)) app.add_handler(CommandHandler("chats", chats_command)) app.add_handler(CommandHandler("id", id_command)) app.add_handler(CommandHandler("addchat", addchat_command)) app.add_handler(CommandHandler("removechat", removechat_command)) app.add_handler(CommandHandler("testalert", testalert_command)) app.add_handler(CommandHandler("status", status_command)) app.add_handler(CommandHandler("phanes", phanes_command)) # Setup background tracker tracker = WalletTracker( cluster_engine=cluster_engine, alert_callback=lambda text, img, mint: send_alert(app, text, img, mint) ) # Start bot print("Starting Solana Runner Telegram Bot...") # Add tracker loop to event loop when bot starts async def post_init(application): asyncio.create_task(tracker.run_loop()) app.post_init = post_init from telegram import Update app.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main()