Spaces:
Running on Zero
Running on Zero
Download app.py from moin22/subnexus-bot: direct link, hf CLI and curl.
- Browser
- Download file 8.11 kB
-
https://huggingface.co/spaces/moin22/subnexus-bot/resolve/main/app.py
- Command line
-
hf download hf://spaces/moin22/subnexus-bot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/moin22/subnexus-bot/resolve/main/app.py
8.11 kB
| 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} | |
| ``` | |
| """ | |
| 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))) | |