Spaces:
Running on Zero
Running on Zero
Download payment_support_bot.py from moin22/subnexus-bot: direct link, hf CLI and curl.
- Browser
- Download file 28.1 kB
-
https://huggingface.co/spaces/moin22/subnexus-bot/resolve/main/payment_support_bot.py
- Command line
-
hf download hf://spaces/moin22/subnexus-bot/payment_support_bot.py
-
curl -L -o payment_support_bot.py https://huggingface.co/spaces/moin22/subnexus-bot/resolve/main/payment_support_bot.py
28.1 kB
| import sys | |
| import os | |
| import json | |
| import time | |
| import hashlib | |
| import logging | |
| import requests | |
| from pathlib import Path | |
| from datetime import datetime | |
| # Ensure UTF-8 output on Windows terminal | |
| if sys.platform == "win32": | |
| try: | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| except Exception: | |
| pass | |
| from telegram import ( | |
| Update, | |
| InlineKeyboardButton, | |
| InlineKeyboardMarkup, | |
| KeyboardButton, | |
| ReplyKeyboardMarkup, | |
| MenuButtonCommands, | |
| WebAppInfo, | |
| BotCommand, | |
| ) | |
| from telegram.constants import ParseMode | |
| from telegram.ext import ( | |
| ApplicationBuilder, | |
| CommandHandler, | |
| MessageHandler, | |
| CallbackQueryHandler, | |
| filters, | |
| ContextTypes, | |
| ) | |
| from config import ( | |
| PAYMENT_SUPPORT_BOT_TOKEN, | |
| ADMIN_TELEGRAM_ID, | |
| MINI_APP_URL, | |
| SUPABASE_URL, | |
| SUPABASE_ANON_KEY, | |
| PAYONEER_EMAIL, | |
| BINANCE_PAY_ID, | |
| USDT_TRC20_ADDRESS, | |
| USDT_BEP20_ADDRESS, | |
| USDT_SOLANA_ADDRESS, | |
| USDT_ERC20_ADDRESS, | |
| ) | |
| logging.basicConfig( | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| level=logging.INFO, | |
| ) | |
| logger = logging.getLogger("PaymentSupportBot") | |
| STATE_FILE = Path(__file__).resolve().parent / "payment_support_state.json" | |
| # In-memory user session state: | |
| # { str(user_id): { "order_id": str|None, "order_number": str|None, "exact_amount_usd": float|None, "selected_method": str|None, "awaiting_proof": bool, "live_chat": bool } } | |
| USER_SESSIONS: dict[str, dict] = {} | |
| ADMIN_TO_CUSTOMER_MAP: dict[int, int] = {} | |
| def load_state(): | |
| global USER_SESSIONS, ADMIN_TO_CUSTOMER_MAP | |
| if STATE_FILE.exists(): | |
| try: | |
| with open(STATE_FILE, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| USER_SESSIONS = data.get("sessions", {}) | |
| ADMIN_TO_CUSTOMER_MAP = { | |
| int(k): int(v) for k, v in data.get("admin_map", {}).items() | |
| } | |
| except Exception as e: | |
| logger.error(f"Error loading payment support state: {e}") | |
| def save_state(): | |
| try: | |
| with open(STATE_FILE, "w", encoding="utf-8") as f: | |
| json.dump( | |
| { | |
| "sessions": USER_SESSIONS, | |
| "admin_map": {str(k): v for k, v in ADMIN_TO_CUSTOMER_MAP.items()}, | |
| }, | |
| f, | |
| indent=2, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error saving payment support state: {e}") | |
| def get_session(user_id: int) -> dict: | |
| key = str(user_id) | |
| if key not in USER_SESSIONS: | |
| USER_SESSIONS[key] = { | |
| "order_id": None, | |
| "order_number": None, | |
| "exact_amount_usd": None, | |
| "selected_method": None, | |
| "awaiting_proof": False, | |
| "live_chat": False, | |
| } | |
| return USER_SESSIONS[key] | |
| def compute_unique_exact_amount(base_usd: float, order_ref: str) -> float: | |
| """ | |
| Produces a deterministic micro-offset (+$0.01 to +$0.09) based on order_ref | |
| so simultaneous identical orders can be uniquely matched by exact amount. | |
| """ | |
| if not base_usd or base_usd <= 0: | |
| return 0.0 | |
| digest = hashlib.md5(order_ref.encode("utf-8")).hexdigest() | |
| cents = (int(digest[:4], 16) % 9) + 1 # 1..9 cents | |
| return round(base_usd + (cents / 100.0), 2) | |
| def fetch_order_from_supabase(order_ref: str) -> dict | None: | |
| """Fetches order details by order_number or id from Supabase REST API.""" | |
| if not SUPABASE_URL or not SUPABASE_ANON_KEY or not order_ref: | |
| return None | |
| headers = { | |
| "apikey": SUPABASE_ANON_KEY, | |
| "Authorization": f"Bearer {SUPABASE_ANON_KEY}", | |
| "Content-Type": "application/json", | |
| } | |
| try: | |
| # Try matching order_number first | |
| url = f"{SUPABASE_URL.rstrip('/')}/rest/v1/orders?order_number=eq.{order_ref}&select=id,order_number,customer_name,customer_email,total_usd,total_bdt,payment_status,payment_method" | |
| resp = requests.get(url, headers=headers, timeout=8) | |
| if resp.status_code == 200 and resp.json(): | |
| return resp.json()[0] | |
| # Fallback: match by UUID id | |
| url2 = f"{SUPABASE_URL.rstrip('/')}/rest/v1/orders?id=eq.{order_ref}&select=id,order_number,customer_name,customer_email,total_usd,total_bdt,payment_status,payment_method" | |
| resp2 = requests.get(url2, headers=headers, timeout=8) | |
| if resp2.status_code == 200 and resp2.json(): | |
| return resp2.json()[0] | |
| except Exception as e: | |
| logger.warning(f"Failed fetching order {order_ref} from Supabase: {e}") | |
| return None | |
| def update_order_proof_in_supabase(order_ref: str, method: str, trx_id: str) -> bool: | |
| """Updates order transaction_id and payment_status in Supabase so Admin Dashboard reflects it.""" | |
| if not SUPABASE_URL or not SUPABASE_ANON_KEY or not order_ref: | |
| return False | |
| headers = { | |
| "apikey": SUPABASE_ANON_KEY, | |
| "Authorization": f"Bearer {SUPABASE_ANON_KEY}", | |
| "Content-Type": "application/json", | |
| "Prefer": "return=minimal", | |
| } | |
| payload = { | |
| "payment_method": method, | |
| "transaction_id": trx_id, | |
| "payment_status": "pending_verification", | |
| "updated_at": datetime.utcnow().isoformat(), | |
| } | |
| try: | |
| url = f"{SUPABASE_URL.rstrip('/')}/rest/v1/orders?order_number=eq.{order_ref}" | |
| resp = requests.patch(url, headers=headers, json=payload, timeout=8) | |
| if resp.status_code in (200, 204): | |
| return True | |
| except Exception as e: | |
| logger.warning(f"Failed updating order {order_ref} in Supabase: {e}") | |
| return False | |
| def get_payment_menu_keyboard() -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup([ | |
| [ | |
| InlineKeyboardButton("π³ Payoneer (Email / Invoice)", callback_data="pay_method_payoneer"), | |
| InlineKeyboardButton("π‘ Binance Pay (0% Fee)", callback_data="pay_method_binance"), | |
| ], | |
| [ | |
| InlineKeyboardButton("π Crypto Wallet (BEP20 β’ TRC20 β’ SOL β’ ERC20)", callback_data="pay_crypto_menu"), | |
| ], | |
| [ | |
| InlineKeyboardButton("π¬ Talk to Live Admin", callback_data="pay_live_admin"), | |
| ], | |
| [ | |
| InlineKeyboardButton("π¦ Track Order β", web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1")), | |
| InlineKeyboardButton("ποΈ Storefront β", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1")), | |
| ], | |
| ]) | |
| def get_crypto_network_keyboard() -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup([ | |
| [ | |
| InlineKeyboardButton("π‘ BNB Smart Chain (BEP20)", callback_data="pay_method_bep20"), | |
| InlineKeyboardButton("π΄ TRON (TRC20)", callback_data="pay_method_trc20"), | |
| ], | |
| [ | |
| InlineKeyboardButton("π£ Solana (SOL / SPL)", callback_data="pay_method_solana"), | |
| InlineKeyboardButton("π· Ethereum (ERC20)", callback_data="pay_method_erc20"), | |
| ], | |
| [ | |
| InlineKeyboardButton("β¬ οΈ Back to Payment Options", callback_data="pay_back_menu"), | |
| ], | |
| ]) | |
| def get_method_back_keyboard() -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup([ | |
| [InlineKeyboardButton("π¬ Talk to Live Admin", callback_data="pay_live_admin")], | |
| [InlineKeyboardButton("β¬ οΈ All Payment Options", callback_data="pay_back_menu")], | |
| ]) | |
| def get_persistent_payment_keyboard() -> ReplyKeyboardMarkup: | |
| """Bottom-docked quick-access payment buttons.""" | |
| return ReplyKeyboardMarkup( | |
| [ | |
| [KeyboardButton("π³ Payoneer"), KeyboardButton("π‘ Binance Pay")], | |
| [KeyboardButton("π Crypto Wallet"), KeyboardButton("π¬ Live Admin")], | |
| [ | |
| KeyboardButton("π¦ Track Order", web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1")), | |
| KeyboardButton("ποΈ Storefront", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1")), | |
| ], | |
| ], | |
| resize_keyboard=True, | |
| is_persistent=True, | |
| ) | |
| METHOD_META = { | |
| "payoneer": { | |
| "title": "π³ Payoneer (Email / Card Invoice)", | |
| "code": "other", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>How to pay via Payoneer:</b>\n" | |
| f"β’ <b>Payoneer Email:</b> <code>{PAYONEER_EMAIL}</code>\n" | |
| f"β’ <b>Exact Amount:</b> <code>{amount_str}</code>\n" | |
| f"β’ <b>Reference / Note:</b> <code>{ref}</code>\n\n" | |
| f"<i>If you have a Payoneer account, send directly to the email above. Need a Card Payment Link / Invoice? Reply with your email or tap Talk to Live Admin.</i>" | |
| ), | |
| }, | |
| "binance": { | |
| "title": "π‘ Binance Pay (0% Fee Instant)", | |
| "code": "binance", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>How to pay via Binance Pay:</b>\n" | |
| f"β’ <b>Binance Pay ID:</b> <code>{BINANCE_PAY_ID}</code>\n" | |
| f"β’ <b>Exact Amount:</b> <code>{amount_str} USDT</code>\n" | |
| f"β’ <b>Order Note:</b> <code>{ref}</code>\n\n" | |
| f"<i>Open Binance App → Pay → Send to Pay ID above (0% network fee).</i>" | |
| ), | |
| }, | |
| "bep20": { | |
| "title": "π‘ BNB Smart Chain (BEP20)", | |
| "code": "other", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>Network:</b> BNB Smart Chain (BEP20)\n" | |
| f"<b>Coin:</b> USDT / USDC / BNB\n" | |
| f"<b>Wallet Address (Tap to copy):</b>\n<code>{USDT_BEP20_ADDRESS}</code>\n" | |
| f"<b>Exact Amount:</b> <code>{amount_str} USDT</code>\n\n" | |
| f"β οΈ <i>Only send BEP20 (BNB Smart Chain) assets to this address.</i>" | |
| ), | |
| }, | |
| "trc20": { | |
| "title": "π΄ TRON Network (TRC20)", | |
| "code": "other", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>Network:</b> TRON (TRC20)\n" | |
| f"<b>Coin:</b> USDT (TRC20) / TRX\n" | |
| f"<b>Wallet Address (Tap to copy):</b>\n<code>{USDT_TRC20_ADDRESS}</code>\n" | |
| f"<b>Exact Amount:</b> <code>{amount_str} USDT</code>\n\n" | |
| f"β οΈ <i>Only send TRC20 (TRON) assets to this address.</i>" | |
| ), | |
| }, | |
| "solana": { | |
| "title": "π£ Solana Network (SPL)", | |
| "code": "other", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>Network:</b> Solana (SPL)\n" | |
| f"<b>Coin:</b> USDT / USDC / SOL\n" | |
| f"<b>Wallet Address (Tap to copy):</b>\n<code>{USDT_SOLANA_ADDRESS}</code>\n" | |
| f"<b>Exact Amount:</b> <code>{amount_str} USDT</code>\n\n" | |
| f"β οΈ <i>Only send Solana (SPL) network assets to this address.</i>" | |
| ), | |
| }, | |
| "erc20": { | |
| "title": "π· Ethereum Network (ERC20)", | |
| "code": "other", | |
| "details": lambda amount_str, ref: ( | |
| f"<b>Network:</b> Ethereum (ERC20)\n" | |
| f"<b>Coin:</b> USDT / USDC / ETH\n" | |
| f"<b>Wallet Address (Tap to copy):</b>\n<code>{USDT_ERC20_ADDRESS}</code>\n" | |
| f"<b>Exact Amount:</b> <code>{amount_str} USDT</code>\n\n" | |
| f"β οΈ <i>Only send ERC20 (Ethereum) network assets to this address.</i>" | |
| ), | |
| }, | |
| } | |
| async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| chat = update.effective_chat | |
| if chat.type != "private": | |
| return | |
| session = get_session(user.id) | |
| args = context.args or [] | |
| # Handle deep link: /start pay_SNX-1234 | |
| if args and args[0].startswith("pay_"): | |
| order_ref = args[0].replace("pay_", "", 1).strip() | |
| session["order_number"] = order_ref | |
| session["selected_method"] = None | |
| session["awaiting_proof"] = False | |
| session["live_chat"] = False | |
| order = fetch_order_from_supabase(order_ref) | |
| if order: | |
| session["order_id"] = order.get("id") | |
| base_usd = float(order.get("total_usd") or 0) | |
| session["exact_amount_usd"] = compute_unique_exact_amount(base_usd, order_ref) if base_usd > 0 else None | |
| else: | |
| session["order_id"] = None | |
| session["exact_amount_usd"] = None | |
| save_state() | |
| order_line = "" | |
| if session.get("order_number"): | |
| amt_txt = f" | Exact Total: <b>${session['exact_amount_usd']:.2f}</b>" if session.get("exact_amount_usd") else "" | |
| order_line = f"\nπ§Ύ <b>Active Order:</b> <code>{session['order_number']}</code>{amt_txt}\n" | |
| welcome_text = ( | |
| "π³ <b>SubNexus Payment Support Bot</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| f"π Hello <b>{user.first_name}</b>! Welcome to our dedicated International Payment Support desk.\n" | |
| f"{order_line}\n" | |
| "Please select your preferred international payment method below to view instructions, exact amount, and receive an instant payment receipt:" | |
| ) | |
| await update.message.reply_text( | |
| text="β‘ <i>Quick Payment Menu enabled below</i>", | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_persistent_payment_keyboard(), | |
| ) | |
| await update.message.reply_text( | |
| text=welcome_text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_payment_menu_keyboard(), | |
| ) | |
| async def send_method_instructions(target_msg, user_id: int, method_key: str): | |
| session = get_session(user_id) | |
| meta = METHOD_META.get(method_key) | |
| if not meta: | |
| return | |
| session["selected_method"] = method_key | |
| session["awaiting_proof"] = True | |
| session["live_chat"] = False | |
| save_state() | |
| ref = session.get("order_number") or f"TG-{user_id}" | |
| amount_str = f"${session['exact_amount_usd']:.2f}" if session.get("exact_amount_usd") else "Your Order Total (check Checkout)" | |
| instructions = meta["details"](amount_str, ref) | |
| text = ( | |
| f"{meta['title']}\n" | |
| "ββββββββββββββββββββββ\n" | |
| f"{instructions}\n\n" | |
| "πΈ <b>Submit Payment Proof:</b>\n" | |
| "Once paid, reply right here with your <b>Transaction ID (TxID / Reference)</b> or send a <b>Payment Screenshot</b> to receive your instant automated receipt!" | |
| ) | |
| await target_msg.reply_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_method_back_keyboard(), | |
| ) | |
| async def payoneer_command(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if update.effective_chat.type == "private": | |
| await send_method_instructions(update.message, update.effective_user.id, "payoneer") | |
| async def binance_command(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if update.effective_chat.type == "private": | |
| await send_method_instructions(update.message, update.effective_user.id, "binance") | |
| async def crypto_command(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if update.effective_chat.type == "private": | |
| text = ( | |
| "π <b>Select Crypto Network (USDT / USDC)</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| "Choose your preferred blockchain network below to view the verified wallet address:\n\n" | |
| "β’ π‘ <b>BNB Smart Chain (BEP20)</b> β Lowest fee (~$0.10)\n" | |
| "β’ π΄ <b>TRON (TRC20)</b> β Most popular\n" | |
| "β’ π£ <b>Solana (SOL / SPL)</b> β Ultra fast\n" | |
| "β’ π· <b>Ethereum (ERC20)</b> β Mainnet" | |
| ) | |
| await update.message.reply_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_crypto_network_keyboard(), | |
| ) | |
| async def admin_command(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if update.effective_chat.type != "private": | |
| return | |
| session = get_session(update.effective_user.id) | |
| session["live_chat"] = True | |
| session["awaiting_proof"] = False | |
| save_state() | |
| await update.message.reply_text( | |
| text=( | |
| "π¬ <b>Connected to Live Payment Admin</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| "Please type your message, question, or email for a custom Payoneer/Wise invoice.\n\n" | |
| "Our admin team will reply to you directly right here!" | |
| ), | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=InlineKeyboardMarkup([ | |
| [InlineKeyboardButton("β¬ οΈ All Payment Options", callback_data="pay_back_menu")] | |
| ]), | |
| ) | |
| async def callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| query = update.callback_query | |
| await query.answer() | |
| user = update.effective_user | |
| data = query.data | |
| session = get_session(user.id) | |
| if data == "pay_back_menu": | |
| session["selected_method"] = None | |
| session["awaiting_proof"] = False | |
| save_state() | |
| order_line = "" | |
| if session.get("order_number"): | |
| amt_txt = f" | Exact Total: <b>${session['exact_amount_usd']:.2f}</b>" if session.get("exact_amount_usd") else "" | |
| order_line = f"\nπ§Ύ <b>Active Order:</b> <code>{session['order_number']}</code>{amt_txt}\n" | |
| text = ( | |
| "π³ <b>SubNexus Payment Support Bot</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| f"{order_line}\n" | |
| "Select your preferred payment method below:" | |
| ) | |
| await query.edit_message_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_payment_menu_keyboard(), | |
| ) | |
| return | |
| if data == "pay_crypto_menu": | |
| text = ( | |
| "π <b>Select Crypto Network (USDT / USDC)</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| "Choose your preferred blockchain network below to view the verified wallet address:\n\n" | |
| "β’ π‘ <b>BNB Smart Chain (BEP20)</b> β Lowest fee (~$0.10)\n" | |
| "β’ π΄ <b>TRON (TRC20)</b> β Most popular\n" | |
| "β’ π£ <b>Solana (SOL / SPL)</b> β Ultra fast\n" | |
| "β’ π· <b>Ethereum (ERC20)</b> β Mainnet" | |
| ) | |
| await query.edit_message_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_crypto_network_keyboard(), | |
| ) | |
| return | |
| if data == "pay_live_admin": | |
| session["live_chat"] = True | |
| session["awaiting_proof"] = False | |
| save_state() | |
| text = ( | |
| "π¬ <b>Connected to Live Payment Admin</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| "Please type your message, question, or email for a custom Payoneer/Wise invoice.\n\n" | |
| "Our admin team will reply to you directly right here!" | |
| ) | |
| await query.edit_message_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=InlineKeyboardMarkup([ | |
| [InlineKeyboardButton("β¬ οΈ All Payment Options", callback_data="pay_back_menu")] | |
| ]), | |
| ) | |
| return | |
| if data.startswith("pay_method_"): | |
| method_key = data.replace("pay_method_", "", 1) | |
| meta = METHOD_META.get(method_key) | |
| if not meta: | |
| return | |
| session["selected_method"] = method_key | |
| session["awaiting_proof"] = True | |
| session["live_chat"] = False | |
| save_state() | |
| ref = session.get("order_number") or f"TG-{user.id}" | |
| if session.get("exact_amount_usd"): | |
| amount_str = f"${session['exact_amount_usd']:.2f}" | |
| else: | |
| amount_str = "Your Order Total (check Checkout)" | |
| instructions = meta["details"](amount_str, ref) | |
| text = ( | |
| f"{meta['title']}\n" | |
| "ββββββββββββββββββββββ\n" | |
| f"{instructions}\n\n" | |
| "πΈ <b>Submit Payment Proof:</b>\n" | |
| "Once paid, reply right here with your <b>Transaction ID (TxID / Reference)</b> or send a <b>Payment Screenshot</b> to receive your instant automated receipt!" | |
| ) | |
| await query.edit_message_text( | |
| text=text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=get_method_back_keyboard(), | |
| ) | |
| async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| chat = update.effective_chat | |
| msg = update.message | |
| if not msg: | |
| return | |
| # 1. Handle Admin Replies back to Customer | |
| admin_id_str = str(ADMIN_TELEGRAM_ID).strip() | |
| if str(user.id) == admin_id_str or str(chat.id) == admin_id_str: | |
| if msg.reply_to_message: | |
| replied_id = msg.reply_to_message.message_id | |
| target_uid = ADMIN_TO_CUSTOMER_MAP.get(replied_id) | |
| if target_uid: | |
| try: | |
| if msg.text: | |
| await context.bot.send_message( | |
| chat_id=target_uid, | |
| text=f"π³ <b>Payment Admin Reply:</b>\nββββββββββββββββ\n{msg.text}", | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| elif msg.photo: | |
| await context.bot.send_photo( | |
| chat_id=target_uid, | |
| photo=msg.photo[-1].file_id, | |
| caption=f"π³ <b>Payment Admin Reply:</b>\n{msg.caption or ''}", | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| await msg.reply_text("β Reply delivered to customer.", quote=True) | |
| except Exception as e: | |
| await msg.reply_text(f"β Failed to send reply: {e}", quote=True) | |
| return | |
| if chat.type != "private": | |
| return | |
| # 2. Handle Bottom Persistent Keyboard Buttons | |
| if msg.text: | |
| txt = msg.text.strip() | |
| if txt == "π³ Payoneer": | |
| await send_method_instructions(msg, user.id, "payoneer") | |
| return | |
| elif txt == "π‘ Binance Pay": | |
| await send_method_instructions(msg, user.id, "binance") | |
| return | |
| elif txt == "π Crypto Wallet": | |
| await crypto_command(update, context) | |
| return | |
| elif txt == "π¬ Live Admin": | |
| await admin_command(update, context) | |
| return | |
| session = get_session(user.id) | |
| order_ref = session.get("order_number") or f"TG-{user.id}" | |
| method_key = session.get("selected_method") or "other" | |
| method_title = METHOD_META.get(method_key, {}).get("title", "International Payment") | |
| method_code = METHOD_META.get(method_key, {}).get("code", "other") | |
| # Determine if this looks like a payment proof (photo, document, or awaiting_proof text) | |
| is_proof = bool(msg.photo or msg.document or session.get("awaiting_proof")) | |
| # Forward to Admin | |
| username_display = f"@{user.username}" if user.username else f"ID: {user.id}" | |
| exact_amt = f"${session['exact_amount_usd']:.2f}" if session.get("exact_amount_usd") else "N/A" | |
| admin_header = ( | |
| f"π³ <b>PAYMENT PROOF / SUPPORT MSG</b>\n" | |
| f"π€ Customer: <b>{user.full_name}</b> ({username_display})\n" | |
| f"π§Ύ Order Ref: <code>{order_ref}</code> | Exact: <b>{exact_amt}</b>\n" | |
| f"π Method: {method_title}\n" | |
| f"ββββββββββββββββββββββ\n" | |
| ) | |
| try: | |
| target_admin = int(admin_id_str) if admin_id_str.lstrip("-").isdigit() else admin_id_str | |
| if msg.photo: | |
| sent = await context.bot.send_photo( | |
| chat_id=target_admin, | |
| photo=msg.photo[-1].file_id, | |
| caption=admin_header + (msg.caption or "Screenshot submitted."), | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| elif msg.document: | |
| sent = await context.bot.send_document( | |
| chat_id=target_admin, | |
| document=msg.document.file_id, | |
| caption=admin_header + (msg.caption or "Document submitted."), | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| else: | |
| sent = await context.bot.send_message( | |
| chat_id=target_admin, | |
| text=admin_header + (msg.text or ""), | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| ADMIN_TO_CUSTOMER_MAP[sent.message_id] = user.id | |
| save_state() | |
| except Exception as e: | |
| logger.error(f"Failed forwarding to admin: {e}") | |
| # Issue Auto Payment Receipt if payment proof was submitted | |
| if is_proof: | |
| trx_ref = (msg.text or msg.caption or "Screenshot Submitted").strip()[:80] | |
| receipt_id = f"RCP-{int(time.time()) % 1000000}" | |
| if session.get("order_number"): | |
| update_order_proof_in_supabase(session["order_number"], method_code, trx_ref) | |
| session["awaiting_proof"] = False | |
| save_state() | |
| receipt_text = ( | |
| "π§Ύ <b>SUBNEXUS AUTO PAYMENT RECEIPT</b>\n" | |
| "ββββββββββββββββββββββ\n" | |
| f"β’ <b>Receipt ID:</b> <code>{receipt_id}</code>\n" | |
| f"β’ <b>Order Ref:</b> <code>{order_ref}</code>\n" | |
| f"β’ <b>Method:</b> {method_title}\n" | |
| f"β’ <b>Exact Amount:</b> {exact_amt}\n" | |
| f"β’ <b>Reference/Proof:</b> <code>{trx_ref}</code>\n" | |
| f"β’ <b>Time:</b> {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}\n" | |
| "β’ <b>Status:</b> β³ <i>Pending Admin Verification</i>\n" | |
| "ββββββββββββββββββββββ\n" | |
| "β Your payment proof has been logged in our <b>Admin Verification Dashboard</b>.\n" | |
| "Once approved, your digital product & credentials will be delivered automatically!" | |
| ) | |
| await msg.reply_text( | |
| text=receipt_text, | |
| parse_mode=ParseMode.HTML, | |
| reply_markup=InlineKeyboardMarkup([ | |
| [InlineKeyboardButton("π¦ Track Order Status β", web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1"))], | |
| [InlineKeyboardButton("β¬ οΈ Payment Menu", callback_data="pay_back_menu")], | |
| ]), | |
| ) | |
| else: | |
| await msg.reply_text( | |
| "β Your message has been sent to our <b>Payment Admin</b>. We will reply shortly!", | |
| parse_mode=ParseMode.HTML, | |
| ) | |
| async def post_init_setup(app): | |
| try: | |
| await app.bot.set_my_commands([ | |
| BotCommand("start", "Open International Payment Menu"), | |
| BotCommand("payoneer", "Payoneer Email & Invoice"), | |
| BotCommand("binance", "Binance Pay (0% Fee)"), | |
| BotCommand("crypto", "Crypto Wallet (BEP20 / TRC20 / SOL / ERC20)"), | |
| BotCommand("admin", "Talk to Live Payment Admin"), | |
| ]) | |
| await app.bot.set_chat_menu_button(menu_button=MenuButtonCommands()) | |
| except Exception as e: | |
| logger.warning(f"Failed to set commands for Payment Support Bot: {e}") | |
| def main(use_signals=False): | |
| if not PAYMENT_SUPPORT_BOT_TOKEN: | |
| logger.warning("β οΈ PAYMENT_SUPPORT_BOT_TOKEN not set! Payment Support Bot will not start.") | |
| return | |
| load_state() | |
| app = ApplicationBuilder().token(PAYMENT_SUPPORT_BOT_TOKEN).post_init(post_init_setup).build() | |
| app.add_handler(CommandHandler("start", start_command)) | |
| app.add_handler(CommandHandler("payoneer", payoneer_command)) | |
| app.add_handler(CommandHandler("binance", binance_command)) | |
| app.add_handler(CommandHandler("crypto", crypto_command)) | |
| app.add_handler(CommandHandler("admin", admin_command)) | |
| app.add_handler(CallbackQueryHandler(callback_handler)) | |
| app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, handle_message)) | |
| logger.info("π³ SubNexus Payment Support Bot is live and polling...") | |
| if not use_signals: | |
| import asyncio | |
| loop = asyncio.new_event_loop() | |
| asyncio.set_event_loop(loop) | |
| app.run_polling(drop_pending_updates=True, stop_signals=None) | |
| else: | |
| app.run_polling(drop_pending_updates=True) | |
| if __name__ == "__main__": | |
| main(use_signals=True) | |