Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import osimport timeimport randomimport threadingimport chessimport chess.svgimport torchimport torch.nn as nnimport gradio as grfrom seleniumbase import SBfrom huggingface_hub import HfApi# --- 1. ULTRA-LIGHT BRAIN (Fast Inference) ---class BulletNet(nn.Module):def __init__(self):super().__init__()self.net = nn.Sequential(nn.Linear(64, 128),nn.ReLU(),nn.Linear(128, 64),nn.Flatten(),nn.Linear(64, 1))def forward(self, x): return self.net(x)# --- 2. SHARED STATE ---class State:def __init__(self):self.board = chess.Board()self.status = "System Booting..."self.last_move = "None"self.active_game = Falsestate = State()# --- 3. HIGH-SPEED BOT ENGINE ---def run_bullet_bot():USER = os.getenv("LICHESS_USER")PASS = os.getenv("LICHESS_PASS")with SB(uc=True, headless=True) as sb:try:# Loginstate.status = "Logging in..."sb.uc_open_with_reconnect("https://lichess.org/login", 5)sb.type("#form3-username", USER)sb.type("#form3-password", PASS)sb.click("button.submit")time.sleep(3)# Auto-join 1+0 Bullet Hookstate.status = "Searching 1+0 Bullet..."sb.open("https://lichess.org/setup/hook")while True:# FAST CHECK: Is the board present?if sb.is_element_visible(".cg-wrap"):state.active_game = True# 1. Scrape FEN directly from DOM (Instant)raw_fen = sb.get_attribute(".cg-wrap", "data-fen")if raw_fen and raw_fen != state.board.fen():state.board = chess.Board(raw_fen)# 2. Check Turn (Assume we play as White for this logic)if state.board.turn == chess.WHITE:state.status = "⚡ MOVING"legal_moves = list(state.board.legal_moves)if legal_moves:# Decision Logicmove = random.choice(legal_moves)uci = move.uci()from_sq, to_sq = uci[:2], uci[2:]# 3. JS INJECTION (Bypasses Mouse Simulation)js_move = f"document.querySelector('.cg-wrap').chessground.move('{from_sq}', '{to_sq}')"sb.execute_script(js_move)state.last_move = ucitime.sleep(0.1) # Small jitter to prevent instant flagelse:if state.active_game:state.status = "Game Ended. Seeking new match..."sb.open("https://lichess.org/setup/hook")state.active_game = Falsestate.board.reset()time.sleep(0.05) # 20Hz Polling rate for Bullet speedsexcept Exception as e:state.status = f"Bot Error: {str(e)[:40]}"# --- 4. LIVE DASHBOARD ---def update_ui():# Only render SVG if game state changed to save CPUboard_svg = chess.svg.board(state.board, size=400)return board_svg, state.last_move, state.statuswith gr.Blocks() as demo:gr.Markdown("# ⚡ High-Speed Bullet Bot Dashboard")with gr.Row():view = gr.HTML()with gr.Column():m_info = gr.Label(label="Last Move")s_info = gr.Label(label="Status")timer = gr.Timer(1.0) # UI updates slower than the bot to save RAMtimer.tick(update_ui, outputs=[view, m_info, s_info])if __name__ == "__main__":threading.Thread(target=run_bullet_bot, daemon=True).start()demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Monochrome())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import osimport timeimport threadingimport gradio as grfrom seleniumbase import SBclass BotState:def __init__(self):self.status = "Initializing..."self.hp = 100self.resources = {"Wood": 0, "Stone": 0, "Food": 0}self.active = Falseself.last_log = "Waiting for game start..."state = BotState()def run_bot_engine():# uc=True + xvfb=True is the ultimate stealth combowith SB(uc=True, xvfb=True, interval=0.05) as sb:try:state.status = "🌐 Loading Moomoo.io..."# Open with reconnect to shake off basic bot trackerssb.uc_open_with_reconnect("https://moomoo.io", reconnect_time=5)# --- CAPTCHA BYPASS ---state.status = "🛡️ Handling Anti-Bot..."# activate_cdp_mode is more stealthy than standard seleniumsb.activate_cdp_mode("https://moomoo.io")sb.sleep(2)# This handles the 'I am not a robot' checkbox automaticallysb.solve_captcha()# --- ENTER GAME ---sb.type("#nameInput", "Survival_Bot_v1")sb.click("#enterGame")state.active = Truestate.status = "🟢 SURVIVING"while True:# 1. READ GAME STATE (JavaScript Injection)# We pull data directly from the DOM and Game UIgame_data = sb.execute_script("""return {hp: parseInt(document.getElementById('healthBar')?.style.width) || 100,food: parseInt(document.getElementById('foodDisplay')?.innerText) || 0,wood: parseInt(document.getElementById('woodDisplay')?.innerText) || 0,stone: parseInt(document.getElementById('stoneDisplay')?.innerText) || 0}""")state.hp = game_data['hp']state.resources = {"Wood": game_data['wood'], "Stone": game_data['stone'], "Food": game_data['food']}# 2. SURVIVAL HEURISTICS (Based on your strategies)if state.hp < 60:sb.press_keys("body", "q") # Instant Healstate.last_log = "⚠️ Low HP: Healing used."elif state.resources['Wood'] < 50:sb.press_keys("body", "e") # Toggle Auto-hitstate.last_log = "🪓 Farming for survival."# Prevent CPU overheating on HF Spacestime.sleep(0.1)except Exception as e:state.status = "❌ Fatal Error"state.last_log = f"Error: {str(e)[:100]}"# --- GRADIO INTERFACE ---def get_stats():res = state.resourcesreturn f"**Status:** {state.status}\n\n**HP:** {state.hp}%\n**Resources:** 🪵 {res['Wood']} | 🪨 {res['Stone']} | 🍎 {res['Food']}\n\n**Log:** {state.last_log}"with gr.Blocks(title="Moomoo Survival AI") as demo:gr.Markdown("# 🐮 Moomoo.io AI Survival Bot")with gr.Row():with gr.Column():output = gr.Markdown("Loading bot data...")with gr.Column():gr.Image("https://moomoo.io/img/favicon.png", width=100)# Auto-refresh UI every 1.5 secondsgr.Timer(1.5).tick(get_stats, outputs=output)if __name__ == "__main__":threading.Thread(target=run_bot_engine, daemon=True).start()demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+67-91