amanjha18v/AMAN_SHOPS_BOTPublic · Bot Template

AIAMAN SHOP STORE appears to be a Telegram automation bot. Commands include /*, /addbal, /addbal_all, /addbal_binance, /addbal_binance_approve, /addbal_binance_paid, /addbal_upi, /addcat_id. Observed in code: messaging, http, libs, keyboards, payments.

Utilityutility
ProfileTelegram
132 commands0 envUpdated 7h agoCreated Sep 4, 2026
Back to folder

commands/_start.js

javascript · 908 lines

Raw
1/**#command2name: /start3answer: 4keyboard: 5parse_mode: markdown6aliases: /START,/Start,/STArt,/stARt7allow_only_group: false8need_reply: false9is_web: 010#command**/11 12try { 13  var adminId = Bot.getProperty("owner_id") || "5191323229";14  var userId = String(user.telegramid);15 16  // ⭐ TELEGRAM STARS — fallback event detection (payment events may route here17  // generically depending on the platform, so we check and delegate explicitly)18  if (request && request.pre_checkout_query) {19    Bot.run({ command: "/onPreCheckoutQuery" });20    return;21  }22  if (request && request.message && request.message.successful_payment) {23    Bot.run({ command: "/onSuccessfulPayment" });24    return;25  }26  27  // Safe variable fallbacks for BJS environment28  var msgText = (typeof message !== 'undefined' && message) ? message.trim() : "";29  // ✅ FIXED: pehle "data" naam ka ek undefined global variable padha ja raha tha, jo hamesha30  // empty rehta tha — isliye koi bhi callback button jo "/start" call karta tha (jaise "Back to31  // Menu"), silently fail ho jaata tha aur user ko koi response hi nahi milta tha.32  var callbackData = (request && request.callback_query && request.callback_query.data) ? request.callback_query.data : "";33 34  // =====================================================35  // 🛠 MAINTENANCE MODE GATE (✅ NEW)36  // Owner/Co-Admins hamesha through jaate hain; baaki sabko premium screen dikhta hai.37  // =====================================================38  var isMaintenanceOn = Bot.getProperty("maintenance_mode") || false;39  var isOwnerOrCoAdmin = (userId === adminId) || Bot.getProperty("co_admin_" + userId);40 41  if (isMaintenanceOn && !isOwnerOrCoAdmin) {42    Bot.sendMessage(43      "<blockquote><tg-emoji emoji-id='6100657257605763582'>🛠</tg-emoji> <b>BOT UNDER MAINTENANCE</b></blockquote>\n\n" +44      "<i>Hum kuch premium improvements kar rahe hain! Kripya thodi der baad wapas try karein.</i>\n\n" +45      "<tg-emoji emoji-id='6100170496077204999'>👑</tg-emoji> <i>Dhanyawad for your patience!</i>",46      { parse_mode: "HTML" }47    );48    return;49  }50 51  // ✅ NEW: Maintenance abhi-abhi hata hai — is user ko ek baar premium "We're Back!" welcome do52  var maintenanceRemovedAt = Bot.getProperty("maintenance_removed_at");53  var userSeenMaintenanceRemoved = User.getProperty("seen_maintenance_removed_at");54  if (!isMaintenanceOn && maintenanceRemovedAt && userSeenMaintenanceRemoved !== maintenanceRemovedAt) {55    User.setProperty("seen_maintenance_removed_at", maintenanceRemovedAt, "number");56    Api.sendMessage({57      chat_id: chat.chatid,58      text: "<blockquote><tg-emoji emoji-id='6102856637343600044'>✅</tg-emoji> <b>MAINTENANCE REMOVED — WE'RE BACK!</b></blockquote>\n\n" +59            "<tg-emoji emoji-id='6091571559233755994'>🚀</tg-emoji> <i>Bot fully automated system ke saath phir se live hai!</i>\n" +60            "<i>Tap /start to continue, or Buy Now to grab your keys instantly.</i>",61      parse_mode: "HTML",62      reply_markup: JSON.stringify({63        inline_keyboard: [[64          { text: "Buy Now", callback_data: "/buy_hack", style: "success", icon_custom_emoji_id: "6312263493051489212" }65        ]]66      })67    });68  }69  70  var currentStep = User.getProperty("add_product_step");71  var isAwaitingBroadcast = User.getProperty("awaiting_broadcast_data");72 73  // 🎨 PREMIUM CUSTOM EMOJIS DEFINITION (Fixed with escaped double quotes)74  var EMJ_VERIFIED_CHECK = "<tg-emoji emoji-id=\"5875465628285931233\">✔️</tg-emoji>";75  var EMJ_CROWN          = "<tg-emoji emoji-id=\"6311975081702597046\">👑</tg-emoji>";76  var EMJ_DROP           = "<tg-emoji emoji-id=\"6080228009439141516\">💧</tg-emoji>";77  var EMJ_CHECK          = "<tg-emoji emoji-id=\"6080214566191505147\">✅</tg-emoji>";78  var EMJ_ROCKET         = "<tg-emoji emoji-id=\"6091571559233755994\">🚀</tg-emoji>";79  var EMJ_RADAR          = "<tg-emoji emoji-id=\"6093591495237967001\">📡</tg-emoji>";80  var EMJ_STAR           = "<tg-emoji emoji-id=\"6093677128295914531\">✨</tg-emoji>";81  var EMJ_RED_DOT        = "<tg-emoji emoji-id=\"6093854128193152827\">🔴</tg-emoji>";82  83  // Access Granted ke liye aapka requested special premium custom emoji84  var EMJ_NEW_ACCESS     = "<tg-emoji emoji-id=\"5875465628285931233\">✔️</tg-emoji>";85 86  // ==========================================87  // 🏠 HELPER: DIRECTLY SEND MAIN SHOP MENU88  // (Bot.runCommand("/menu") is unreliable in BJS -> inline it instead)89  // ==========================================90  function sendMainMenu() {91    try {92      // ✅ FIXED: ab same wallet store se read hoga jo purchase flows use karte hain93      // (Libs.ResourcesLib "balance" resource + admin bonus balance), taaki balance sab jagah same dikhe.94      var userBal = (function() {95        var resBal = 0;96        try { resBal = Number(Libs.ResourcesLib.userRes("balance").value()) || 0; } catch (e) {}97        var bonusBal = Number(Bot.getProperty("balance" + userId) || 0);98        return (resBal + bonusBal).toFixed(2);99      })();100 101      var EMJ_HEADER_ROCKET = "<tg-emoji emoji-id='5217822164362739968'>🚀</tg-emoji>";102      var EMJ_HEADER_NEW    = "<tg-emoji emoji-id='6082603117763894396'>✨</tg-emoji>";103      var EMJ_HEADER_SHIELD = "<tg-emoji emoji-id='6113743082358841933'>🔰</tg-emoji>";104 105      var MSG_EMJ_STORE     = "<tg-emoji emoji-id='5866053971960929280'>🛒</tg-emoji>";106      var MSG_EMJ_FFID      = "<tg-emoji emoji-id='5334890573281114250'>🎮</tg-emoji>";107      var MSG_EMJ_PROFILE   = "<tg-emoji emoji-id='5260399854500191689'>🔰</tg-emoji>";108      var MSG_EMJ_ADDBAL    = "<tg-emoji emoji-id='6147815702163102310'>✨</tg-emoji>";109      var MSG_EMJ_HISTORY   = "<tg-emoji emoji-id='6113743082358841933'>🔰</tg-emoji>";110      var MSG_EMJ_LUDO      = "<tg-emoji emoji-id='5371043439020353782'>🎲</tg-emoji>";111      var MSG_EMJ_TUTORIAL  = "<tg-emoji emoji-id='5258077307985207053'>📹</tg-emoji>";112      var MSG_EMJ_PROOF     = "<tg-emoji emoji-id='5330237710655306682'>✅</tg-emoji>";113      var MSG_EMJ_SUPPORT   = "<tg-emoji emoji-id='5436113877181941026'>🔰</tg-emoji>";114 115      var EMJ_PREMIUM_MENU  = "<tg-emoji emoji-id='5406745015365943482'>✨</tg-emoji>";116      var EMJ_YOUR_BALANCE  = "<tg-emoji emoji-id='5231200819986047254'>💰</tg-emoji>";117      var EMJ_GET_STARTED   = "<tg-emoji emoji-id='6057415823222379852'>👇</tg-emoji>";118 119      var welcomeMessage =120        "<tg-emoji emoji-id=\"6266967801580231067\">💎</tg-emoji> <tg-emoji emoji-id=\"5866053971960929280\">🏪</tg-emoji> <b>— AMAN SHOP STORE —</b> <tg-emoji emoji-id=\"5866053971960929280\">🏪</tg-emoji> <tg-emoji emoji-id=\"6266967801580231067\">💎</tg-emoji>\n\n" +121        "<tg-emoji emoji-id=\"6102856637343600044\">🎉</tg-emoji> <b>Hello, " + ((user && user.first_name) ? user.first_name.toUpperCase() : "RESELLER") + "!</b>\n\n" +122        "<tg-emoji emoji-id=\"6080228009439141516\">💧</tg-emoji> <b>Genuine, limited-stock books. Instant delivery.</b>\n\n" +123        "<tg-emoji emoji-id=\"6147767796097884213\">📦</tg-emoji> Wide product catalog\n" +124        "<tg-emoji emoji-id=\"6215386799133433653\">🔒</tg-emoji> Instant delivery on payment\n" +125        "<tg-emoji emoji-id=\"6267068789146260253\">💰</tg-emoji> Multiple payment gateways\n" +126        "<tg-emoji emoji-id=\"6100170496077204999\">👑</tg-emoji> 24/7 admin support\n\n" +127        "<i>" + EMJ_YOUR_BALANCE + " Balance: ₹" + userBal + "</i>\n\n" +128        "<i>Tap any button below to begin:</i> " + EMJ_GET_STARTED;129 130      var multiColorKeyboard = [131        [{ text: "Shop Now", callback_data: "/buy_hack", style: "primary", icon_custom_emoji_id: "5866053971960929280" }],132        [133          { text: "Profile", callback_data: "/profile", style: "primary", icon_custom_emoji_id: "6145572393499762737" },134          { text: "Add Balance", callback_data: "/addfund", style: "success", icon_custom_emoji_id: "5409048419211682843" }135        ],136        [137          { text: "My Keys", callback_data: "/mykey", style: "primary", icon_custom_emoji_id: "6215386799133433653" },138          { text: "How to use", callback_data: "/how", style: "danger", icon_custom_emoji_id: "6192842983948162969" }139        ],140        [141          { text: "Download Files", callback_data: "/download_updates", style: "primary", icon_custom_emoji_id: "5208790878931415568" },142          { text: "Daily Gift", callback_data: "/dailygift", style: "success", icon_custom_emoji_id: "6194922667242429131" }143        ],144        [145          { text: "Refer & Earn", callback_data: "/refer", style: "success", icon_custom_emoji_id: "5823654080584618403" },146          { text: "Support", callback_data: "/support", style: "danger", icon_custom_emoji_id: "6267129592998270736" }147        ],148        [{ text: "Payment Proofs", url: (Bot.getProperty("payment_proof_link") || "https://t.me/GaluModz_Proof"), style: "success", icon_custom_emoji_id: "5330237710655306682" }]149      ];150 151      if (Bot.getProperty("reseller_system_enabled") && !Bot.getProperty("is_reseller_" + userId)) {152        multiColorKeyboard.push([153          { text: "Reseller Upgrade", callback_data: "/reseller_upgrade", style: "success", icon_custom_emoji_id: "6102856637343600044" }154        ]);155      }156 157      Api.sendMessage({158        chat_id: chat.chatid,159        text: welcomeMessage,160        parse_mode: "HTML",161        reply_markup: JSON.stringify({ inline_keyboard: multiColorKeyboard })162      });163    } catch (menuErr) {164      Bot.sendMessage("🛑 <b>Menu Send Error:</b> <code>" + menuErr.message + "</code>", { parse_mode: "HTML" });165    }166  }167 168  // [Auto-Track User] List me user track karne ke liye169  var trackedUsers = Bot.getProperty("all_users_list") || [];170  if (!trackedUsers.includes(userId)) {171    trackedUsers.push(userId);172    Bot.setProperty("all_users_list", trackedUsers, "json");173 174    // ==========================================175    // 🎁 REFER & EARN — capture referral on this user's very first /start176    // Deep link format: https://t.me/<bot>?start=ref<referrerTelegramId>177    // ==========================================178    try {179      var refParam = (typeof params !== "undefined" && params) ? String(params).trim() : "";180      if (refParam.toLowerCase().indexOf("ref") === 0) {181        var referrerId = refParam.substring(3).replace(/[^0-9]/g, "");182        if (referrerId && referrerId !== userId && !User.getProperty("referred_by")) {183          User.setProperty("referred_by", referrerId, "string");184 185          var refList = Bot.getProperty("referrals_of_" + referrerId) || [];186          if (refList.indexOf(userId) === -1) {187            refList.push(userId);188            Bot.setProperty("referrals_of_" + referrerId, refList, "json");189          }190 191          try {192            Api.sendMessage({193              chat_id: referrerId,194              text: "<blockquote><tg-emoji emoji-id='6102856637343600044'>🎉</tg-emoji> <b>New Referral!</b>\n\n" +195                    "<tg-emoji emoji-id='5260399854500191689'>👤</tg-emoji> " + (user && user.first_name ? user.first_name : "A user") +196                    " ne aapke link se bot join kiya hai.\n<i>Jab wo balance add ya purchase karega, aapko bonus milega!</i></blockquote>",197              parse_mode: "HTML"198            });199          } catch (e) {}200        }201      }202    } catch (e) {}203  }204 205  // 🛡️ [ANTI-DUPLICATE CHECK] Agar user already verified hai toh seedhe menu par bhejein206  // ✅ FIXED: pehle sirf exact "msgText === '/start'" ya "callbackData === '/trigger_contact_popup'"207  // match hone par hi menu bhejta tha. Kisi bhi button jo callback_data "/start" call karta tha208  // (jaise cancel-order ke baad "Back to Menu"), us case me match fail ho jaata tha aur user ko209  // koi response nahi milta tha. Ab ye check robust hai — jab tak ye genuinely ek contact-share210  // event nahi hai ya admin ek mid-flow step me nahi hai, verified user ko hamesha menu milega.211  var couponGenStep = User.getProperty("coupon_gen_step");212  var awaitingCouponFor = User.getProperty("awaiting_coupon_for");213  var isAlreadyVerified = Bot.getProperty("verified_" + userId);214  var isContactShareEvent = !!(request && request.contact && request.contact.user_id);215  var isAdminMidFlow = (userId === adminId && (currentStep || isAwaitingBroadcast || couponGenStep ||216    User.getProperty("addbal_step") || User.getProperty("addbalall_step") || User.getProperty("rembal_step") || User.getProperty("checkbal_step") ||217    User.getProperty("set_download_link_step") || User.getProperty("set_payment_upi_step") ||218    User.getProperty("set_payment_binance_step") ||219    User.getProperty("set_dailygift_price_step") || User.getProperty("set_refer_earn_step") ||220    User.getProperty("set_how_link_step") || User.getProperty("set_proof_link_step") || User.getProperty("set_support_link_step")));221  var binanceUtrStep = User.getProperty("binance_utr_step");222  var isUserMidFlow = !!awaitingCouponFor || !!binanceUtrStep;223 224  // ✅ NEW: User ne jo bhi "/start"/"/START"/"/Start" type kiya, menu aane ke225  // baad us typed command-message ko vanish (delete) kar do — chat clean rahe.226  if (msgText.toLowerCase() === "/start" && request && request.message_id) {227    try { Api.deleteMessage({ chat_id: chat.chatid, message_id: request.message_id }); } catch (delStartErr) {}228  }229 230  if (isAlreadyVerified && !isContactShareEvent && !isAdminMidFlow && !isUserMidFlow) {231    sendMainMenu();232    return;233  }234 235  // ==========================================236  // ⚡ MODULE: LIVE CONTACT RECEIVER & VERIFIER237  // ==========================================238  if (request && request.contact && request.contact.user_id) {239    if (String(request.contact.user_id) === userId) {240      241      var phoneNumber = request.contact.phone_number;242      var fullName = ((user.first_name || "") + " " + (user.last_name || "")).trim() || "No Name";243      var username = user.username ? "@" + user.username : "No Username";244 245      // Permanently mark user as verified globally246      Bot.setProperty("verified_" + userId, true, "boolean");247      Bot.setProperty("phone_" + userId, phoneNumber, "string");248      // ✅ NEW: Joined date save karo (Profile section me dikhane ke liye)249      if (!Bot.getProperty("joined_date_" + userId)) {250        Bot.setProperty("joined_date_" + userId, new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" }), "string");251      }252      253      // 1. USER DETAILS TO ADMIN254      var adminNotification = 255        "<blockquote><b>" + EMJ_CROWN + " NEW USER VERIFIED " + EMJ_VERIFIED_CHECK + "</b></blockquote>\n" +256        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +257        "<b>👤 Name:</b> " + fullName + "\n" +258        "<b>🆔 User ID:</b> <code>" + userId + "</code>\n" +259        "<b>🌐 Username:</b> " + username + "\n" +260        "<b>📞 Number:</b> <code>" + phoneNumber + "</code>\n" +261        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>";262 263      Api.sendMessage({264        chat_id: adminId,265        text: adminNotification,266        parse_mode: "HTML"267      });268 269      // 2. USER SUCCESS MESSAGE (With your exact requested custom emojis)270      var successMessage = 271        "<blockquote><b>" + EMJ_NEW_ACCESS + " ACCESS GRANTED " + EMJ_NEW_ACCESS + "</b></blockquote>\n" +272        "<b>" + EMJ_VERIFIED_CHECK + " Verification Successful!</b>\n" +273        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +274        "<b>Welcome to AMAN SHOP STORE PANEL </b>\n" +275        "<b>Your profile is now securely fully verified.</b>\n\n" +276        "<b>" + EMJ_ROCKET + " Store Loaded Successfully Use Now! " + EMJ_CROWN + "</b>";277 278      Api.sendMessage({279        chat_id: chat.chatid,280        text: successMessage,281        parse_mode: "HTML",282        reply_markup: JSON.stringify({ remove_keyboard: true }) 283      });284 285      // ✅ FIX: Direct inline menu instead of unreliable Bot.runCommand("/menu")286      sendMainMenu();287      return; 288    } else {289      Bot.sendMessage("❌ <b>Verification Failed!</b> Please share your own contact number only.", { parse_mode: "HTML" });290      return;291    }292  }293 294  // ==========================================295  // 📱 MODULE 0: VERIFICATION CALLBACK HANDLER296  // ==========================================297  if (msgText.toLowerCase() === "/start" || callbackData === "/trigger_contact_popup") {298    299    var verifyMessage = 300      "<blockquote><b>" + EMJ_ROCKET + " AMAN SHOP STORE " + EMJ_RADAR + "</b></blockquote>\n" +301      "<b>" + EMJ_STAR + " Welcome, " + (user.first_name || "User") + " " + EMJ_DROP + "</b>\n" +302      "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +303      "<b>" + EMJ_RED_DOT + " VERIFICATION REQUIRED " + EMJ_CHECK + "</b>\n" +304      "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +305      "<b>" + EMJ_RADAR + " To start shopping, please verify your phone number.</b>\n\n" +306      "<b>" + EMJ_ROCKET + " Why we need this:</b>\n" +307      "<b>  • Secure your purchases " + EMJ_CHECK + "</b>\n" +308      "<b>  • Deliver your books to you " + EMJ_DROP + "</b>\n" +309      "<b>  • Protect your account " + EMJ_STAR + "</b>\n\n" +310      "<b>" + EMJ_RED_DOT + " Tap the blue button below to verify your account:</b>";311 312    // Standard native reply keyboard because contact sharing works securely here313    var nativeKeyboard = {314      keyboard: [315        [{ text: "✅ Verify Account", request_contact: true }]316      ],317      resize_keyboard: true,318      one_time_keyboard: true319    };320 321    Api.sendMessage({322      chat_id: chat.chatid,323      text: verifyMessage,324      parse_mode: "HTML",325      reply_markup: JSON.stringify(nativeKeyboard)326    });327    return; 328  }329 330  // ==========================================331  // 📦 MODULE 1: STEP-BY-STEP PRODUCT CREATION (UPDATED FOR WEBSITE API ID)332  // ==========================================333  if (userId === adminId && currentStep) {334    if (currentStep === "waiting_for_name") {335      if (!msgText) {336        Bot.sendMessage("⚠️ Invalid name. Please type a valid Product Name:");337        return;338      }339      User.setProperty("temp_product_name", msgText, "string");340      User.setProperty("add_product_step", "waiting_for_emoji", "string");341      Bot.sendMessage("💎 Great! Now send the <b>Premium Emoji ID</b> for this product:", { parse_mode: "HTML" });342      return; 343    }344    345    if (currentStep === "waiting_for_emoji") {346      if (!msgText) {347        Bot.sendMessage("⚠️ Invalid Emoji ID. Please send a valid Telegram Premium Emoji ID:");348        return;349      }350      User.setProperty("temp_product_emoji", msgText, "string");351      User.setProperty("add_product_step", "waiting_for_pid", "string");352      Bot.sendMessage("🔑 Nice! Now please enter the <b>Website API Product ID (PID)</b> for this item:", { parse_mode: "HTML" });353      return;354    }355 356    if (currentStep === "waiting_for_pid") {357      if (!msgText) {358        Bot.sendMessage("⚠️ Invalid Product ID. Please type a valid Website PID:");359        return;360      }361 362      var savedName = User.getProperty("temp_product_name");363      var savedEmoji = User.getProperty("temp_product_emoji");364      var savedPid = msgText; // User ne jo PID abhi bheja365 366      var productList = Bot.getProperty("stored_products") || [];367      if (!Array.isArray(productList)) { productList = []; }368      369      // Saving Name, Emoji and Website API ID (id) inside database object370      productList.push({ 371        name: savedName, 372        emoji: savedEmoji, 373        id: savedPid, 374        plans: [] 375      });376 377      Bot.setProperty("stored_products", productList, "json");378      379      // Cleanup temporary states380      User.setProperty("add_product_step", null, "string");381      User.setProperty("temp_product_name", null, "string");382      User.setProperty("temp_product_emoji", null, "string");383      384      var successMsg = "✅ <b>Product Added Successfully!</b>\n\n" +385                       "📦 <b>Name:</b> " + savedName + "\n" +386                       "💎 <b>Emoji ID:</b> <code>" + savedEmoji + "</code>\n" +387                       "🔑 <b>API Product ID (PID):</b> <code>" + savedPid + "</code>\n\n" +388                       "<i>Aap is product ke andar plans baad me configure kar sakte hain. Automatically website se integration ho gaya hai!</i>";389                       390      Bot.sendMessage(successMsg, { parse_mode: "HTML" });391      return; 392    }393  }394 395  // ==========================================396  // 🟡 MODULE 4b: ADMIN — BINANCE PAYMENT CONFIG WIZARD397  // Step 1: QR (photo OR image URL — whichever the admin sends, both work).398  // Step 2: Binance Pay ID. Step 3: USDT Address. Step 4: USD rate.399  // ==========================================400  if (userId === adminId) {401    var setPaymentBinanceStep = User.getProperty("set_payment_binance_step");402 403    // ✅ ROBUST photo detection — different update shapes have shown up in this404    // environment, so we check every place Telegram (or this platform) might405    // put the photo array before giving up.406    var incomingPhotoArr = null;407    try {408      if (request) {409        if (request.message && request.message.photo && request.message.photo.length) {410          incomingPhotoArr = request.message.photo;411        } else if (request.photo && request.photo.length) {412          incomingPhotoArr = request.photo;413        } else if (request.update && request.update.message && request.update.message.photo && request.update.message.photo.length) {414          incomingPhotoArr = request.update.message.photo;415        }416      }417    } catch (photoDetectErr) {}418 419    if (setPaymentBinanceStep === "waiting_qr") {420      var savedQr = false;421 422      if (incomingPhotoArr) {423        var largestPhoto = incomingPhotoArr[incomingPhotoArr.length - 1];424        var qrFileId = largestPhoto.file_id;425        Bot.setProperty("binance_qr_file_id", qrFileId, "string");426        Bot.setProperty("binance_qr_url", null, "string");427        savedQr = true;428      } else if (msgText && (msgText.trim().indexOf("http://") === 0 || msgText.trim().indexOf("https://") === 0)) {429        Bot.setProperty("binance_qr_url", msgText.trim(), "string");430        Bot.setProperty("binance_qr_file_id", null, "string");431        savedQr = true;432      }433 434      if (savedQr) {435        User.setProperty("set_payment_binance_step", "waiting_binance_id", "string");436        Bot.sendMessage(437          "✅ <b>QR Saved!</b>\n\n" +438          "<i>Step 2/4 —</i> Ab apna <b>Binance Pay ID</b> bhejein (jaise: <code>839548203</code>):",439          { parse_mode: "HTML" }440        );441        return;442      }443 444      // ❌ Neither a photo nor a URL was recognised — don't silently drop it.445      Bot.sendMessage(446        "⚠️ QR receive nahi hua. Kripya QR ko ya toh <b>photo/image</b> ke roop me bhejein, ya QR image ka <b>direct URL link</b> (https://...) paste karein.",447        { parse_mode: "HTML" }448      );449      return;450    }451 452    if (setPaymentBinanceStep === "waiting_binance_id" && msgText) {453      Bot.setProperty("binance_pay_id", msgText.trim(), "string");454      User.setProperty("set_payment_binance_step", "waiting_usdt_address", "string");455      Bot.sendMessage(456        "✅ <b>Binance Pay ID Saved!</b>\n\n" +457        "<i>Step 3/4 —</i> Ab apna <b>USDT Address</b> bhejein (jaise: <code>TNvySU5Wk2mBAJNpBLGwvLk9pk4EgkeLXt</code>):",458        { parse_mode: "HTML" }459      );460      return;461    }462 463    if (setPaymentBinanceStep === "waiting_usdt_address" && msgText) {464      Bot.setProperty("binance_usdt_address", msgText.trim(), "string");465      User.setProperty("set_payment_binance_step", "waiting_usd_rate", "string");466      var rateNow = Bot.getProperty("usd_rate") || 91;467      Bot.sendMessage(468        "✅ <b>USDT Address Saved!</b>\n\n" +469        "<i>Step 4/4 —</i> Ab USD conversion rate bhejein (₹ kitne ka $1, jaise <code>91</code>).\n" +470        "<i>Current:</i> <code>₹" + rateNow + " = $1</code>\n" +471        "<i>Same rakhna ho to bhi number type karke bhej dein.</i>",472        { parse_mode: "HTML" }473      );474      return;475    }476 477    if (setPaymentBinanceStep === "waiting_usd_rate" && msgText) {478      var finalRate = parseFloat(msgText.trim());479      if (isNaN(finalRate) || finalRate <= 0) {480        Bot.sendMessage("❌ Invalid rate! Ek valid positive number bhejein, jaise 91.", { parse_mode: "HTML" });481        return;482      }483      Bot.setProperty("usd_rate", finalRate, "string");484      User.setProperty("set_payment_binance_step", null, "string");485 486      var qrStatusMsg = Bot.getProperty("binance_qr_file_id") || Bot.getProperty("binance_qr_url") ? "✅ Set" : "❌ Not set";487      Bot.sendMessage(488        "<blockquote>🟡 <b>BINANCE PAY CONFIG COMPLETE!</b></blockquote>\n\n" +489        "🖼 <b>QR:</b> " + qrStatusMsg + "\n" +490        "🆔 <b>Binance Pay ID:</b> <code>" + Bot.getProperty("binance_pay_id") + "</code>\n" +491        "💳 <b>USDT Address:</b> <code>" + Bot.getProperty("binance_usdt_address") + "</code>\n" +492        "💱 <b>USD Rate:</b> <code>₹" + finalRate + " = $1</code>\n\n" +493        "<i>Binance Pay ab live hai!</i>",494        { parse_mode: "HTML" }495      );496      return;497    }498  }499 500  // ==========================================501  // 🟡 MODULE 4c: USER — BINANCE PROOF SUBMISSION (screenshot only)502  // ==========================================503  if (binanceUtrStep === "awaiting_screenshot") {504    var ssPhotoArr = null;505    try {506      if (request) {507        if (request.message && request.message.photo && request.message.photo.length) {508          ssPhotoArr = request.message.photo;509        } else if (request.photo && request.photo.length) {510          ssPhotoArr = request.photo;511        } else if (request.update && request.update.message && request.update.message.photo && request.update.message.photo.length) {512          ssPhotoArr = request.update.message.photo;513        }514      }515    } catch (ssPhotoDetectErr) {}516 517    if (!ssPhotoArr) {518      Bot.sendMessage("⚠️ Kripya payment screenshot ek <b>image/photo</b> ke roop me bhejein.", { parse_mode: "HTML" });519      return;520    }521 522    var ssLargest = ssPhotoArr[ssPhotoArr.length - 1];523    var ssFileId = ssLargest.file_id;524 525    var subInr = User.getProperty("binance_pending_amount_inr");526    var subUsd = User.getProperty("binance_pending_amount_usd");527    var adminSupportId = Bot.getProperty("owner_id") || "5191323229";528 529    var fullNameSub = ((user.first_name || "") + " " + (user.last_name || "")).trim() || "No Name";530    var usernameSub = user.username ? "@" + user.username : "No Username";531 532    var adminCaption =533      "<blockquote><tg-emoji emoji-id='6312263493051489212'>🟡</tg-emoji> <b>NEW BINANCE PAY SUBMISSION</b></blockquote>\n" +534      "👤 <b>User:</b> <a href='tg://user?id=" + userId + "'>" + fullNameSub + "</a> (<code>" + userId + "</code>)\n" +535      "🌐 <b>Username:</b> " + usernameSub + "\n" +536      "💰 <b>Amount:</b> $<code>" + subUsd + "</code> <i>(₹" + subInr + ")</i>\n\n" +537      "<i>Verify the screenshot, then credit balance with the button below or:</i>\n<code>/addbal " + userId + "|" + subInr + "</code>";538 539    try {540      Api.sendPhoto({541        chat_id: adminSupportId,542        photo: ssFileId,543        caption: adminCaption,544        parse_mode: "HTML",545        reply_markup: JSON.stringify({546          inline_keyboard: [[547            { text: "✅ Approve & Credit ₹" + subInr, callback_data: "/addbal_binance_approve " + userId + " " + subInr, style: "success" }548          ]]549        })550      });551    } catch (notifyAdminErr) {}552 553    User.setProperty("binance_utr_step", null, "string");554    User.setProperty("binance_pending_amount_inr", null, "string");555    User.setProperty("binance_pending_amount_usd", null, "string");556 557    Bot.sendMessage(558      "<blockquote><tg-emoji emoji-id='6147936236125298267'>⏳</tg-emoji> <b>WAIT FOR ADMIN CHECK</b></blockquote>\n\n" +559      "<i>Aapka payment screenshot admin ko bhej diya gaya hai. Admin manually verify karke aapka balance add karega — thodi der wait karein!</i>",560      {561        parse_mode: "HTML",562        reply_markup: JSON.stringify({ inline_keyboard: [[{ text: "Back to Menu", callback_data: "/back", style: "primary" }]] })563      }564    );565    return;566  }567 568  // ==========================================569  // 💵 MODULE 5: ADMIN BALANCE TOOLS (Add Bal / Remove Bal / Check Bal570  // button-click continuation — fixes buttons that previously just571  // showed a "Wrong Format" error with no way to actually complete it)572  // ==========================================573  if (userId === adminId) {574    var addbalStep = User.getProperty("addbal_step");575    var addbalAllStep = User.getProperty("addbalall_step");576    var rembalStep = User.getProperty("rembal_step");577    var checkbalStep = User.getProperty("checkbal_step");578 579    if (addbalStep === "waiting_input" && msgText) {580      User.setProperty("addbal_step", null, "string");581 582      // ✅ FIXED: pehle sirf Bot.run(...) se /addbal ko dobara call kiya jaata tha —583      // agar us re-run me "message" text sahi se forward nahi hota tha (jo wildcard584      // "*" -> /start delegation ke through hone par silently fail ho sakta tha),585      // toh balance kabhi credit hi nahi hota tha aur admin ko koi error bhi nahi586      // dikhta tha. Ab balance yahin, isi jagah, seedha add hota hai — kisi doosre587      // command re-run par depend nahi karta. Bot.run wala call sirf backup ke588      // taur par neeche rakha hai.589      var addbalData = msgText.trim();590 591      if (addbalData.indexOf("|") === -1) {592        Bot.sendMessage("❌ *Invalid Format! Use:* `user_id|amount`", { parse_mode: "Markdown" });593        return;594      }595 596      var addbalParts = addbalData.split("|");597      var addbalTargetId = addbalParts[0].trim();598      var addbalAmount = parseFloat(addbalParts[1].trim());599 600      if (!addbalTargetId || isNaN(addbalAmount) || addbalAmount <= 0) {601        Bot.sendMessage("❌ *Invalid Format! Use:* `user_id|amount`", { parse_mode: "Markdown" });602        return;603      }604 605      try {606        // Primary wallet resource (same store the rest of the bot reads for purchases)607        try {608          Libs.ResourcesLib.anotherUserRes("balance", addbalTargetId).add(addbalAmount);609        } catch (resErr) {}610 611        // ✅ Bonus-balance property — this is the SAME property /menu reads and adds612        // on top of the resource balance. Writing it here too guarantees the credited613        // amount always shows up for the user even if the resource write above fails614        // silently for a user who never triggered it before.615        var prevBonus = Number(Bot.getProperty("balance" + addbalTargetId) || 0);616        Bot.setProperty("balance" + addbalTargetId, (prevBonus + addbalAmount).toFixed(2), "string");617 618        Bot.sendMessage("✅ Success! Added " + addbalAmount + " to user " + addbalTargetId, { parse_mode: "HTML" });619 620        try {621          Api.sendMessage({622            chat_id: addbalTargetId,623            text: "<blockquote>" +624              "<tg-emoji emoji-id='6192822213486321961'>🗣</tg-emoji> Admin Added: " + addbalAmount + "\n" +625              "<tg-emoji emoji-id='6266967801580231067'>💎</tg-emoji> Balance Credited!\n" +626              "<tg-emoji emoji-id='6267068789146260253'>💰</tg-emoji> Wallet Updated\n" +627              "<tg-emoji emoji-id='5866053971960929280'>🛒</tg-emoji> /start TO SHOP NOW" +628              "</blockquote>",629            parse_mode: "HTML"630          });631        } catch (notifyErr) {}632      } catch (addbalErr) {633        Bot.sendMessage("⚠️ *Error:* " + addbalErr.message, { parse_mode: "Markdown" });634      }635      return;636    }637    if (addbalAllStep === "waiting_input" && msgText) {638      User.setProperty("addbalall_step", null, "string");639      Bot.run({ command: "/addbal_all", options: { message: "/addbal_all " + msgText.trim() } });640      return;641    }642    if (rembalStep === "waiting_input" && msgText) {643      User.setProperty("rembal_step", null, "string");644      Bot.run({ command: "/rembal", options: { message: "/rembal " + msgText.trim() } });645      return;646    }647    if (checkbalStep === "waiting_input" && msgText) {648      User.setProperty("checkbal_step", null, "string");649      Bot.run({ command: "/checkbal", options: { message: "/checkbal " + msgText.trim() } });650      return;651    }652 653    var setDownloadLinkStep = User.getProperty("set_download_link_step");654    if (setDownloadLinkStep === "waiting_input" && msgText) {655      User.setProperty("set_download_link_step", null, "string");656      Bot.run({ command: "/set_update_link", options: { params: msgText.trim() } });657      return;658    }659 660    var setPaymentUpiStep = User.getProperty("set_payment_upi_step");661    if (setPaymentUpiStep === "waiting_input" && msgText) {662      User.setProperty("set_payment_upi_step", null, "string");663      Bot.run({ command: "/set_payment_upi", options: { params: msgText.trim() } });664      return;665    }666 667    var setDailyGiftPriceStep = User.getProperty("set_dailygift_price_step");668    if (setDailyGiftPriceStep === "waiting_input" && msgText) {669      User.setProperty("set_dailygift_price_step", null, "string");670      Bot.run({ command: "/set_dailygift_price", options: { params: msgText.trim() } });671      return;672    }673 674    var setReferEarnStep = User.getProperty("set_refer_earn_step");675    if (setReferEarnStep === "waiting_input" && msgText) {676      User.setProperty("set_refer_earn_step", null, "string");677      Bot.run({ command: "/set_refer_earn", options: { params: msgText.trim() } });678      return;679    }680 681    var setHowLinkStep = User.getProperty("set_how_link_step");682    if (setHowLinkStep === "waiting_input" && msgText) {683      User.setProperty("set_how_link_step", null, "string");684      Bot.run({ command: "/set_how_link", options: { params: msgText.trim() } });685      return;686    }687 688    var setProofLinkStep = User.getProperty("set_proof_link_step");689    if (setProofLinkStep === "waiting_input" && msgText) {690      User.setProperty("set_proof_link_step", null, "string");691      Bot.run({ command: "/set_proof_link", options: { params: msgText.trim() } });692      return;693    }694 695    var setSupportLinkStep = User.getProperty("set_support_link_step");696    if (setSupportLinkStep === "waiting_input" && msgText) {697      User.setProperty("set_support_link_step", null, "string");698      Bot.run({ command: "/set_support_link", options: { params: msgText.trim() } });699      return;700    }701  }702 703  // ==========================================704  // 🎟 MODULE 3: ADMIN COUPON GENERATOR (step-by-step wizard)705  // ==========================================706  if (userId === adminId && couponGenStep) {707 708    if (couponGenStep === "code") {709      if (!msgText) { Bot.sendMessage("⚠️ Kripya ek valid coupon code bhejein."); return; }710      var couponCodeUpper = msgText.trim().toUpperCase();711      if (Bot.getProperty("coupon_" + couponCodeUpper)) {712        Bot.sendMessage("❌ Ye coupon code pehle se exist karta hai! Doosra naam try karein.");713        return;714      }715      User.setProperty("coupon_gen_code", couponCodeUpper, "string");716      User.setProperty("coupon_gen_step", "maxclaims", "string");717      Bot.sendMessage("<tg-emoji emoji-id='6091571559233755994'>👥</tg-emoji> <b>Kitne users ye coupon use (claim) kar sakte hain?</b>\n<i>Sirf number bhejein, jaise: 50</i>", { parse_mode: "HTML" });718      return;719    }720 721    if (couponGenStep === "maxclaims") {722      var maxClaimsVal = parseInt(msgText.trim());723      if (isNaN(maxClaimsVal) || maxClaimsVal <= 0) { Bot.sendMessage("❌ Kripya ek valid number bhejein (jaise 50)."); return; }724      User.setProperty("coupon_gen_maxclaims", maxClaimsVal, "number");725      User.setProperty("coupon_gen_step", "discount", "string");726      Bot.sendMessage("<tg-emoji emoji-id='6093591495237967001'>💸</tg-emoji> <b>Kitne % discount dena hai?</b>\n<i>Sirf number bhejein (1-100), jaise: 10</i>", { parse_mode: "HTML" });727      return;728    }729 730    if (couponGenStep === "discount") {731      var discountVal = parseFloat(msgText.trim());732      if (isNaN(discountVal) || discountVal <= 0 || discountVal > 100) { Bot.sendMessage("❌ Discount 1 se 100 ke beech honi chahiye."); return; }733      User.setProperty("coupon_gen_discount", discountVal, "number");734      User.setProperty("coupon_gen_step", "scope", "string");735      Bot.sendMessage(736        "<tg-emoji emoji-id='6093677128295914531'>🎯</tg-emoji> <b>Scope batayein:</b>\n\n" +737        "• Sabhi products/plans ke liye: <code>global</code> likh kar bhejein\n" +738        "• Sirf ek specific product+plan ke liye: <code>Product Name | Duration</code>\n" +739        "  <i>Example:</i> <code>Atomic Habits (Book) | 1d</code>",740        { parse_mode: "HTML" }741      );742      return;743    }744 745    if (couponGenStep === "scope") {746      var scopeInput = msgText.trim();747      var couponData = {748        code: User.getProperty("coupon_gen_code"),749        maxClaims: User.getProperty("coupon_gen_maxclaims"),750        discountPercent: User.getProperty("coupon_gen_discount"),751        claimedBy: [],752        isPaused: false,753        createdAt: new Date().toLocaleDateString()754      };755 756      if (scopeInput.toLowerCase() === "global") {757        couponData.scope = "global";758      } else if (scopeInput.indexOf("|") > -1) {759        var scopeParts = scopeInput.split("|");760        couponData.scope = "specific";761        couponData.productName = scopeParts[0].trim();762        couponData.duration = scopeParts[1].trim();763      } else {764        Bot.sendMessage("❌ Galat format! 'global' likhein ya 'Product Name | Duration' format me bhejein.");765        return;766      }767 768      Bot.setProperty("coupon_" + couponData.code, couponData, "json");769 770      // ✅ NEW: master list me bhi add karo, taaki /coupons admin command sabko list kar sake771      var couponList = Bot.getProperty("coupon_list") || [];772      if (couponList.indexOf(couponData.code) === -1) {773        couponList.push(couponData.code);774        Bot.setProperty("coupon_list", couponList, "json");775      }776 777      // Cleanup wizard state778      User.setProperty("coupon_gen_step", null, "string");779      User.setProperty("coupon_gen_code", null, "string");780      User.setProperty("coupon_gen_maxclaims", null, "number");781      User.setProperty("coupon_gen_discount", null, "number");782 783      Bot.sendMessage(784        "<blockquote>🎟 <b>COUPON CREATED SUCCESSFULLY!</b></blockquote>\n\n" +785        "🏷 <b>Code:</b> <code>" + couponData.code + "</code>\n" +786        "👥 <b>Max Claims:</b> " + couponData.maxClaims + "\n" +787        "💸 <b>Discount:</b> " + couponData.discountPercent + "%\n" +788        "🎯 <b>Scope:</b> " + (couponData.scope === "global" ? "🌍 Global (All Plans)" : "📦 " + couponData.productName + " (" + couponData.duration + ")"),789        { parse_mode: "HTML" }790      );791      return;792    }793  }794 795  // ==========================================796  // 🎟 MODULE 4: USER — APPLY COUPON CODE TEXT ENTRY797  // ==========================================798  if (awaitingCouponFor) {799    var enteredCode = msgText.trim().toUpperCase();800    var couponRec = Bot.getProperty("coupon_" + enteredCode);801 802    User.setProperty("awaiting_coupon_for", null, "string");803 804    if (!couponRec) {805      Bot.sendMessage("❌ <b>Invalid Coupon Code!</b>", { parse_mode: "HTML" });806      return;807    }808    if (couponRec.isPaused) {809      Bot.sendMessage("⏸ Ye coupon abhi paused hai, thodi der baad try karein.", { parse_mode: "HTML" });810      return;811    }812    if (!Array.isArray(couponRec.claimedBy)) { couponRec.claimedBy = []; }813    if (couponRec.claimedBy.indexOf(userId) > -1) {814      Bot.sendMessage("⚠️ Aapne ye coupon already use kar liya hai!", { parse_mode: "HTML" });815      return;816    }817    if (couponRec.claimedBy.length >= couponRec.maxClaims) {818      Bot.sendMessage("❌ Is coupon ki claim limit khatam ho gayi hai!", { parse_mode: "HTML" });819      return;820    }821 822    var couponTargetParts = awaitingCouponFor.split(" ");823    var cTargetProdIdx = couponTargetParts[0];824    var cTargetPlanIdx = couponTargetParts[1];825 826    if (couponRec.scope === "specific") {827      var cProductList = Bot.getProperty("stored_products") || [];828      var cProduct = cProductList[Number(cTargetProdIdx)];829      var cPlan = cProduct ? cProduct.plans[Number(cTargetPlanIdx)] : null;830      var cDurationDisplay = cPlan ? (cPlan.durationDisplay || (cPlan.days + " Days")) : "";831      var matchesProduct = cProduct && cProduct.name.trim().toLowerCase() === couponRec.productName.trim().toLowerCase();832      var matchesDuration = cDurationDisplay.toLowerCase().indexOf(String(couponRec.duration).toLowerCase().replace(/[^a-z0-9]/g, "")) > -1 ||833                             String(couponRec.duration).replace(/[^0-9]/g, "") === String(cPlan ? cPlan.days : "");834      if (!matchesProduct) {835        Bot.sendMessage("❌ Ye coupon is product ke liye valid nahi hai!", { parse_mode: "HTML" });836        return;837      }838    }839 840    // ✅ Valid — apply and mark claimed841    couponRec.claimedBy.push(userId);842    Bot.setProperty("coupon_" + enteredCode, couponRec, "json");843    User.setProperty("applied_coupon_" + cTargetProdIdx + "_" + cTargetPlanIdx, enteredCode, "string");844 845    Bot.sendMessage("🎉 <b>Coupon Applied!</b> -" + couponRec.discountPercent + "% discount added.", { parse_mode: "HTML" });846 847    Bot.run({848      command: "buyitem",849      options: { params: cTargetProdIdx + " " + cTargetPlanIdx }850    });851    return;852  }853 854  // ==========================================855  // 📢 MODULE 2: PREMIUM BROADCAST SYSTEM856  // ==========================================857  if (userId === adminId && isAwaitingBroadcast) {858    User.setProperty("awaiting_broadcast_data", false, "boolean");859    var userList = Bot.getProperty("all_users_list") || [];860 861    if (userList.length === 0) {862      Bot.sendMessage("❌ Bot mein abhi tak koi bhi user registered nahi hai.");863      return;864    }865 866    var targetMessageId = null;867    if (request) {868      if (request.message_id) { targetMessageId = request.message_id; }869      else if (request.message && request.message.message_id) { targetMessageId = request.message.message_id; }870    }871 872    if (!targetMessageId) {873      Bot.sendMessage("❌ Unable to fetch message ID for broadcast.");874      return;875    }876 877    Bot.sendMessage("⏳ Sending premium broadcast to " + userList.length + " users... Please wait.");878 879    // ✅ FIXED: pehle ek bhi blocked/invalid user Api.copyMessage() ko throw karwa deta880    // tha, jo bahar wale catch() tak chala jaata tha — isse loop beech me hi ruk jaata881    // tha (baaki users ko broadcast nahi jaata tha) aur admin ko scary "Error in handling"882    // dikhta tha, jabki zyada tar users ko message mil chuka hota tha. Ab har send apne883    // try/catch me hai, aur end me accurate success/fail count milega.884    var sentCount = 0;885    var failedCount = 0;886    for (var i = 0; i < userList.length; i++) {887      try {888        Api.copyMessage({889          chat_id: String(userList[i]),890          from_chat_id: adminId,891          message_id: Number(targetMessageId)892        });893        sentCount++;894      } catch (perUserErr) {895        failedCount++;896      }897    }898    Bot.sendMessage(899      "✅ <b>Broadcast Complete!</b>\n" +900      "📤 <b>Sent:</b> " + sentCount + " users\n" +901      (failedCount > 0 ? "⚠️ <b>Failed/Blocked:</b> " + failedCount + " users" : "🎉 <b>No failures!</b>"),902      { parse_mode: "HTML" }903    );904  }905 906} catch (err) {907  Bot.sendMessage("Error in handling: " + err.message);908}