import os import time import sqlite3 import threading import urllib.request from datetime import datetime, timezone from playwright.sync_api import sync_playwright, Error as PlaywrightError import config def keep_awake_loop(): """Thread qui maintient le Space éveillé.""" print("💤 Thread Keep-Awake activé (ping toutes les 3h).") while True: time.sleep(3 * 60 * 60) # 3 heures for url in config.KEEP_AWAKE_URLS: try: req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) with urllib.request.urlopen(req, timeout=15) as response: print(f"✅ Keep-Awake ping: {url}") except Exception: pass def init_db(): """Crée la DB et la table si elles n'existent pas.""" os.makedirs(os.path.dirname(config.DB_PATH), exist_ok=True) os.makedirs(os.path.dirname(config.STATE_PATH), exist_ok=True) conn = sqlite3.connect(config.DB_PATH, timeout=10) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS rounds ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp TEXT NOT NULL, jour INTEGER NOT NULL, heure TEXT NOT NULL, cote REAL NOT NULL )''') # Mode WAL indispensable pour que le Bot écrive et que l'API lise en même temps plus tard c.execute('PRAGMA journal_mode=WAL;') conn.commit() conn.close() print("✅ Base de données /data/aviator_db.db initialisée.") def save_cote(cote): """Insère une cote brute avec le temps GMT.""" now_utc = datetime.now(timezone.utc) timestamp_iso = now_utc.isoformat() jour = now_utc.weekday() # 0=Lundi, 6=Dimanche heure = now_utc.strftime("%H:%M:%S") try: conn = sqlite3.connect(config.DB_PATH, timeout=5) conn.execute("BEGIN IMMEDIATE") conn.cursor().execute( "INSERT INTO rounds (timestamp, jour, heure, cote) VALUES (?, ?, ?, ?)", (timestamp_iso, jour, heure, cote) ) conn.commit() conn.close() print(f"✅ Sauvegardé : {cote:.2f}x | {heure} GMT") except Exception as e: print(f"❌ Erreur DB : {e}") def extract_cotes(page): """Extrait la cote depuis l'iFrame Spribe.""" try: selectors = '.payout.ng-star-inserted, app-bubble-multiplier' for frame in page.frames: if "aviator" in frame.url or "spribe" in frame.url: elements = frame.locator(selectors).all_inner_texts() if elements: return [e.strip() for e in elements if e.strip()] elements = page.locator(selectors).all_inner_texts() return [e.strip() for e in elements if e.strip()] except Exception: return [] def run(): init_db() phone = config.BETPAWA_PHONE password = config.BETPAWA_PASSWORD if not phone or not password: print("❌ Identifiants manquants dans les Variables/Secrets HF !") return # Démarrage du thread Keep-Awake awake_thread = threading.Thread(target=keep_awake_loop, daemon=True) awake_thread.start() with sync_playwright() as p: print("🌐 Lancement de Chromium...") browser = p.chromium.launch( headless=False, args=["--window-size=1920,950", "--no-sandbox", "--disable-dev-shm-usage"] ) needs_login = not os.path.exists(config.STATE_PATH) context = browser.new_context( viewport=config.DESKTOP_VIEWPORT, screen=config.DESKTOP_VIEWPORT, storage_state=config.STATE_PATH if not needs_login else None ) page = context.new_page() try: # CONNEXION if needs_login: print("🔐 Connexion à Betpawa...") page.goto(config.LOGIN_URL, wait_until="domcontentloaded", timeout=30000) page.wait_for_selector('input[name="username"]', timeout=15000) page.locator('input[name="username"]').first.fill(phone) page.locator('input[name="password"]').first.fill(password) page.keyboard.press("Enter") page.wait_for_timeout(5000) if '/login' in page.url: print("❌ Mauvais identifiants ou captcha.") while True: time.sleep(60) context.storage_state(path=config.STATE_PATH) print("✅ Connexion réussie.") else: print("🔄 Session existante trouvée.") # OUVERTURE AVIATOR print("🎰 Ouverture d'Aviator...") page.goto(config.AVIATOR_URL, wait_until="domcontentloaded", timeout=30000) page.wait_for_timeout(2000) if "login" in page.url: print("⚠️ Session expirée, reconnexion...") page.goto(config.LOGIN_URL, wait_until="domcontentloaded", timeout=30000) page.locator('input[name="username"]').first.fill(phone) page.locator('input[name="password"]').first.fill(password) page.keyboard.press("Enter") page.wait_for_timeout(5000) context.storage_state(path=config.STATE_PATH) page.goto(config.AVIATOR_URL, wait_until="domcontentloaded", timeout=30000) print("⏳ Chargement du jeu (20s)...") time.sleep(20) # BOUCLE DE COLLECTE print("🚀 Collecte active !") derniere_cote_vue = None while True: try: current_cotes_str = extract_cotes(page) if not current_cotes_str: time.sleep(1) continue latest_cote_str = current_cotes_str[0] if 'x' in latest_cote_str.lower(): cote_actuelle = float(latest_cote_str.lower().replace('x', '').replace(',', '.')) else: time.sleep(1) continue if cote_actuelle != derniere_cote_vue: derniere_cote_vue = cote_actuelle save_cote(cote_actuelle) time.sleep(0.5) except PlaywrightError: print("⚠️ Micro-bug iframe, pause 5s...") time.sleep(5) except Exception as e: print(f"⚠️ Erreur boucle : {e}") time.sleep(3) except Exception as e: print(f"❌ FATALE : {e}") finally: try: context.storage_state(path=config.STATE_PATH) context.close() browser.close() except Exception: pass if __name__ == "__main__": run()