import os import sys import time import asyncio import logging import random import threading import datetime from collections import deque import gradio as gr try: import spaces gpu_decorator = spaces.GPU except ImportError: def gpu_decorator(fn): return fn # Ensure UTF-8 output on Windows / Linux if sys.platform == "win32": try: sys.stdout.reconfigure(encoding='utf-8') except Exception: pass LOG_BUFFER = deque(maxlen=30) class BufferHandler(logging.Handler): def emit(self, record): try: LOG_BUFFER.append(self.format(record)) except Exception: pass logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) _buf_handler = BufferHandler() _buf_handler.setFormatter(logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s", "%H:%M:%S")) logging.getLogger().addHandler(_buf_handler) logger = logging.getLogger("SubNexusGradioMaster") start_time = datetime.datetime.now() worker_states = { "store": "Starting...", "support": "Starting...", "payment_support": "Starting...", "proof": "Starting...", } _threads = {} def run_store_bot(): """Runs SubNexus Storefront Bot with automatic crash/conflict recovery.""" while True: try: worker_states["store"] = "🟢 Polling Active" asyncio.set_event_loop(asyncio.new_event_loop()) from bot import main as store_main logger.info("🛍️ Starting SubNexus Store Bot...") store_main(use_signals=False) worker_states["store"] = "🟡 Exited — restarting in 15s" logger.warning("Store Bot exited cleanly; restarting in 15s...") except Exception as e: worker_states["store"] = f"🔴 Error ({type(e).__name__}) — retrying in 15s" logger.error(f"Store Bot error: {e}", exc_info=True) time.sleep(15) def run_support_bot(): """Runs SubNexus Support Desk Bot with automatic crash/conflict recovery.""" while True: try: worker_states["support"] = "🟢 Polling Active" asyncio.set_event_loop(asyncio.new_event_loop()) from support_bot import main as support_main logger.info("🎧 Starting SubNexus Support Desk Bot...") support_main(use_signals=False) worker_states["support"] = "🟡 Exited — restarting in 15s" logger.warning("Support Bot exited cleanly; restarting in 15s...") except Exception as e: worker_states["support"] = f"🔴 Error ({type(e).__name__}) — retrying in 15s" logger.error(f"Support Bot error: {e}", exc_info=True) time.sleep(15) def run_payment_support_bot(): """Runs SubNexus Payment Support Bot with automatic crash/conflict recovery.""" while True: try: worker_states["payment_support"] = "🟢 Polling Active" asyncio.set_event_loop(asyncio.new_event_loop()) from payment_support_bot import main as payment_support_main logger.info("💳 Starting SubNexus Payment Support Bot...") payment_support_main(use_signals=False) worker_states["payment_support"] = "🟡 Exited — restarting in 15s" logger.warning("Payment Support Bot exited cleanly; restarting in 15s...") except Exception as e: worker_states["payment_support"] = f"🔴 Error ({type(e).__name__}) — retrying in 15s" logger.error(f"Payment Support Bot error: {e}", exc_info=True) time.sleep(15) async def run_social_proof_loop(): """Posts verified purchase proofs to @subnexus_proof every 12 to 25 minutes.""" from telegram import Bot from config import TELEGRAM_BOT_TOKEN from social_proof import send_live_purchase_notification if not TELEGRAM_BOT_TOKEN: worker_states["proof"] = "⚠️ Missing TELEGRAM_BOT_TOKEN" logger.warning("TELEGRAM_BOT_TOKEN missing. Social proof drip paused.") return bot = Bot(token=TELEGRAM_BOT_TOKEN) worker_states["proof"] = "🟢 Dripping every 12-25m" logger.info("🔮 SubNexus Social Proof Drip Engine activated! (Posting every 12-25 mins)") await asyncio.sleep(60) while True: try: logger.info("Broadcasting scheduled social proof to @subnexus_proof...") await send_live_purchase_notification(bot) except Exception as e: logger.error(f"Social proof loop error: {e}") delay_seconds = random.randint(720, 1500) logger.info(f"Next social proof post scheduled in {delay_seconds // 60} minutes.") await asyncio.sleep(delay_seconds) def start_social_proof_thread(): while True: try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(run_social_proof_loop()) except Exception as e: worker_states["proof"] = f"🔴 Error ({type(e).__name__}) — retrying in 15s" logger.error(f"Proof thread crashed: {e}", exc_info=True) time.sleep(15) _started = False _start_lock = threading.Lock() def start_bot_cluster(): """Starts all bot services in background daemon threads (once per process).""" global _started with _start_lock: if _started: return _started = True logger.info("🚀 Launching SubNexus Telegram Cluster background workers...") _threads["proof"] = threading.Thread(target=start_social_proof_thread, daemon=True, name="ProofThread") _threads["proof"].start() _threads["support"] = threading.Thread(target=run_support_bot, daemon=True, name="SupportThread") _threads["support"].start() _threads["payment_support"] = threading.Thread(target=run_payment_support_bot, daemon=True, name="PaymentSupportThread") _threads["payment_support"].start() _threads["store"] = threading.Thread(target=run_store_bot, daemon=True, name="StoreThread") _threads["store"].start() # Start bot cluster on startup start_bot_cluster() def get_status(): uptime = str(datetime.datetime.now() - start_time).split('.')[0] from config import TELEGRAM_BOT_TOKEN, SUPPORT_BOT_TOKEN, PAYMENT_SUPPORT_BOT_TOKEN, MINI_APP_URL store_cfg = "Configured" if TELEGRAM_BOT_TOKEN else "Missing Token" support_cfg = "Configured" if SUPPORT_BOT_TOKEN else "Missing Token" payment_cfg = "Configured" if PAYMENT_SUPPORT_BOT_TOKEN else "Missing Token" recent_logs = "\n".join(list(LOG_BUFFER)[-12:]) or "No logs captured yet." return f""" ### 🟢 SubNexus Telegram Bot Cluster Status: ACTIVE * **Uptime:** `{uptime}` * **Store Bot (`@subnexus_store_bot`):** `{store_cfg}` | {worker_states['store']} * **Support Bot (`@subnexus_support_bot`):** `{support_cfg}` | {worker_states['support']} * **Payment Support Bot (`@subnexus_payment_support_bot`):** `{payment_cfg}` | {worker_states['payment_support']} * **Proof Channel (`@subnexus_proof`):** {worker_states['proof']} * **Store URL (`MINI_APP_URL`):** [{MINI_APP_URL}]({MINI_APP_URL}) #### 📜 Recent Worker Logs ```text {recent_logs} ``` """ @gpu_decorator def gpu_node_check(): """Required ZeroGPU hook for Hugging Face free-tier Gradio Spaces.""" return "✅ SubNexus Cloud Node Active (ZeroGPU Ready)" with gr.Blocks(title="SubNexus Telegram Cluster") as demo: gr.Markdown("# ⚡ SubNexus Telegram Cloud Cluster") gr.Markdown("24/7 High-Availability Autonomous Commerce & Customer Support Engine.") status_box = gr.Markdown(value=get_status) refresh_btn = gr.Button("🔄 Refresh Status", variant="primary") refresh_btn.click(fn=get_status, outputs=status_box) with gr.Accordion("Cloud Node Diagnostics", open=False): diag_out = gr.Textbox(label="Node Health", value="Ready") diag_btn = gr.Button("⚡ Run Node Check") diag_btn.click(fn=gpu_node_check, outputs=diag_out) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))