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 = """
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()