kkapil9112/Hguuuuuv45botPublic · Bot Template

AITelegram commerce bot for an admin-managed digital store: admins create categories, products, time-based plans, stock entries and license keys, and can grant reseller roles or adjust user balances. End users can view their balance, start a deposit flow with an inline amount keypad, apply coupon codes, and navigate back to the store menu. It uses Bot properties for product/stock/coupon data and Libs.ResourcesLib for per-user balances.

Commercecommerceshopreselleradmin-panelbalanceproduct-management
ProfileTelegram
102 commands0 envUpdated 29d agoCreated Aug 7, 2026
Back to folder

commands/_start.js

javascript · 585 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") || "8812621370";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>— BALA MOOD 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        [{ text: "Payment Proofs", url: "https://t.me/+VYyZnIw--NA1Zjc1", style: "success", icon_custom_emoji_id: "5330237710655306682" }],141        [{ text: "Support", callback_data: "/support", style: "danger", icon_custom_emoji_id: "6267129592998270736" }]142      ];143 144      if (Bot.getProperty("reseller_system_enabled") && !Bot.getProperty("is_reseller_" + userId)) {145        multiColorKeyboard.push([146          { text: "Reseller Upgrade", callback_data: "/reseller_upgrade", style: "success", icon_custom_emoji_id: "6102856637343600044" }147        ]);148      }149 150      Api.sendMessage({151        chat_id: chat.chatid,152        text: welcomeMessage,153        parse_mode: "HTML",154        reply_markup: JSON.stringify({ inline_keyboard: multiColorKeyboard })155      });156    } catch (menuErr) {157      Bot.sendMessage("🛑 <b>Menu Send Error:</b> <code>" + menuErr.message + "</code>", { parse_mode: "HTML" });158    }159  }160 161  // [Auto-Track User] List me user track karne ke liye162  var trackedUsers = Bot.getProperty("all_users_list") || [];163  if (!trackedUsers.includes(userId)) {164    trackedUsers.push(userId);165    Bot.setProperty("all_users_list", trackedUsers, "json");166  }167 168  // 🛡️ [ANTI-DUPLICATE CHECK] Agar user already verified hai toh seedhe menu par bhejein169  // ✅ FIXED: pehle sirf exact "msgText === '/start'" ya "callbackData === '/trigger_contact_popup'"170  // match hone par hi menu bhejta tha. Kisi bhi button jo callback_data "/start" call karta tha171  // (jaise cancel-order ke baad "Back to Menu"), us case me match fail ho jaata tha aur user ko172  // koi response nahi milta tha. Ab ye check robust hai — jab tak ye genuinely ek contact-share173  // event nahi hai ya admin ek mid-flow step me nahi hai, verified user ko hamesha menu milega.174  var couponGenStep = User.getProperty("coupon_gen_step");175  var awaitingCouponFor = User.getProperty("awaiting_coupon_for");176  var isAlreadyVerified = Bot.getProperty("verified_" + userId);177  var isContactShareEvent = !!(request && request.contact && request.contact.user_id);178  var isAdminMidFlow = (userId === adminId && (currentStep || isAwaitingBroadcast || couponGenStep ||179    User.getProperty("addbal_step") || User.getProperty("rembal_step") || User.getProperty("checkbal_step")));180  var isUserMidFlow = !!awaitingCouponFor;181 182  // ✅ NEW: User ne jo bhi "/start"/"/START"/"/Start" type kiya, menu aane ke183  // baad us typed command-message ko vanish (delete) kar do — chat clean rahe.184  if (msgText.toLowerCase() === "/start" && request && request.message_id) {185    try { Api.deleteMessage({ chat_id: chat.chatid, message_id: request.message_id }); } catch (delStartErr) {}186  }187 188  if (isAlreadyVerified && !isContactShareEvent && !isAdminMidFlow && !isUserMidFlow) {189    sendMainMenu();190    return;191  }192 193  // ==========================================194  // ⚡ MODULE: LIVE CONTACT RECEIVER & VERIFIER195  // ==========================================196  if (request && request.contact && request.contact.user_id) {197    if (String(request.contact.user_id) === userId) {198      199      var phoneNumber = request.contact.phone_number;200      var fullName = ((user.first_name || "") + " " + (user.last_name || "")).trim() || "No Name";201      var username = user.username ? "@" + user.username : "No Username";202 203      // Permanently mark user as verified globally204      Bot.setProperty("verified_" + userId, true, "boolean");205      Bot.setProperty("phone_" + userId, phoneNumber, "string");206      // ✅ NEW: Joined date save karo (Profile section me dikhane ke liye)207      if (!Bot.getProperty("joined_date_" + userId)) {208        Bot.setProperty("joined_date_" + userId, new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" }), "string");209      }210      211      // 1. USER DETAILS TO ADMIN212      var adminNotification = 213        "<blockquote><b>" + EMJ_CROWN + " NEW USER VERIFIED " + EMJ_VERIFIED_CHECK + "</b></blockquote>\n" +214        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +215        "<b>👤 Name:</b> " + fullName + "\n" +216        "<b>🆔 User ID:</b> <code>" + userId + "</code>\n" +217        "<b>🌐 Username:</b> " + username + "\n" +218        "<b>📞 Number:</b> <code>" + phoneNumber + "</code>\n" +219        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>";220 221      Api.sendMessage({222        chat_id: adminId,223        text: adminNotification,224        parse_mode: "HTML"225      });226 227      // 2. USER SUCCESS MESSAGE (With your exact requested custom emojis)228      var successMessage = 229        "<blockquote><b>" + EMJ_NEW_ACCESS + " ACCESS GRANTED " + EMJ_NEW_ACCESS + "</b></blockquote>\n" +230        "<b>" + EMJ_VERIFIED_CHECK + " Verification Successful!</b>\n" +231        "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +232        "<b>Welcome to BALA MOOD STORE </b>\n" +233        "<b>Your profile is now securely fully verified.</b>\n\n" +234        "<b>" + EMJ_ROCKET + " Store Loaded Successfully Use Now! " + EMJ_CROWN + "</b>";235 236      Api.sendMessage({237        chat_id: chat.chatid,238        text: successMessage,239        parse_mode: "HTML",240        reply_markup: JSON.stringify({ remove_keyboard: true }) 241      });242 243      // ✅ FIX: Direct inline menu instead of unreliable Bot.runCommand("/menu")244      sendMainMenu();245      return; 246    } else {247      Bot.sendMessage("❌ <b>Verification Failed!</b> Please share your own contact number only.", { parse_mode: "HTML" });248      return;249    }250  }251 252  // ==========================================253  // 📱 MODULE 0: VERIFICATION CALLBACK HANDLER254  // ==========================================255  if (msgText.toLowerCase() === "/start" || callbackData === "/trigger_contact_popup") {256    257    var verifyMessage = 258      "<blockquote><b>" + EMJ_ROCKET + " BALA MOOD STORE " + EMJ_RADAR + "</b></blockquote>\n" +259      "<b>" + EMJ_STAR + " Welcome, " + (user.first_name || "User") + " " + EMJ_DROP + "</b>\n" +260      "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +261      "<b>" + EMJ_RED_DOT + " VERIFICATION REQUIRED " + EMJ_CHECK + "</b>\n" +262      "<b>━━━━━━━━━━━━━━━━━━━━━━━━━━</b>\n" +263      "<b>" + EMJ_RADAR + " To start shopping, please verify your phone number.</b>\n\n" +264      "<b>" + EMJ_ROCKET + " Why we need this:</b>\n" +265      "<b>  • Secure your purchases " + EMJ_CHECK + "</b>\n" +266      "<b>  • Deliver your books to you " + EMJ_DROP + "</b>\n" +267      "<b>  • Protect your account " + EMJ_STAR + "</b>\n\n" +268      "<b>" + EMJ_RED_DOT + " Tap the blue button below to verify your account:</b>";269 270    // Standard native reply keyboard because contact sharing works securely here271    var nativeKeyboard = {272      keyboard: [273        [{ text: "✅ Verify Account", request_contact: true }]274      ],275      resize_keyboard: true,276      one_time_keyboard: true277    };278 279    Api.sendMessage({280      chat_id: chat.chatid,281      text: verifyMessage,282      parse_mode: "HTML",283      reply_markup: JSON.stringify(nativeKeyboard)284    });285    return; 286  }287 288  // ==========================================289  // 📦 MODULE 1: STEP-BY-STEP PRODUCT CREATION (UPDATED FOR WEBSITE API ID)290  // ==========================================291  if (userId === adminId && currentStep) {292    if (currentStep === "waiting_for_name") {293      if (!msgText) {294        Bot.sendMessage("⚠️ Invalid name. Please type a valid Product Name:");295        return;296      }297      User.setProperty("temp_product_name", msgText, "string");298      User.setProperty("add_product_step", "waiting_for_emoji", "string");299      Bot.sendMessage("💎 Great! Now send the <b>Premium Emoji ID</b> for this product:", { parse_mode: "HTML" });300      return; 301    }302    303    if (currentStep === "waiting_for_emoji") {304      if (!msgText) {305        Bot.sendMessage("⚠️ Invalid Emoji ID. Please send a valid Telegram Premium Emoji ID:");306        return;307      }308      User.setProperty("temp_product_emoji", msgText, "string");309      User.setProperty("add_product_step", "waiting_for_pid", "string");310      Bot.sendMessage("🔑 Nice! Now please enter the <b>Website API Product ID (PID)</b> for this item:", { parse_mode: "HTML" });311      return;312    }313 314    if (currentStep === "waiting_for_pid") {315      if (!msgText) {316        Bot.sendMessage("⚠️ Invalid Product ID. Please type a valid Website PID:");317        return;318      }319 320      var savedName = User.getProperty("temp_product_name");321      var savedEmoji = User.getProperty("temp_product_emoji");322      var savedPid = msgText; // User ne jo PID abhi bheja323 324      var productList = Bot.getProperty("stored_products") || [];325      if (!Array.isArray(productList)) { productList = []; }326      327      // Saving Name, Emoji and Website API ID (id) inside database object328      productList.push({ 329        name: savedName, 330        emoji: savedEmoji, 331        id: savedPid, 332        plans: [] 333      });334 335      Bot.setProperty("stored_products", productList, "json");336      337      // Cleanup temporary states338      User.setProperty("add_product_step", null, "string");339      User.setProperty("temp_product_name", null, "string");340      User.setProperty("temp_product_emoji", null, "string");341      342      var successMsg = "✅ <b>Product Added Successfully!</b>\n\n" +343                       "📦 <b>Name:</b> " + savedName + "\n" +344                       "💎 <b>Emoji ID:</b> <code>" + savedEmoji + "</code>\n" +345                       "🔑 <b>API Product ID (PID):</b> <code>" + savedPid + "</code>\n\n" +346                       "<i>Aap is product ke andar plans baad me configure kar sakte hain. Automatically website se integration ho gaya hai!</i>";347                       348      Bot.sendMessage(successMsg, { parse_mode: "HTML" });349      return; 350    }351  }352 353  // ==========================================354  // 💵 MODULE 5: ADMIN BALANCE TOOLS (Add Bal / Remove Bal / Check Bal355  // button-click continuation — fixes buttons that previously just356  // showed a "Wrong Format" error with no way to actually complete it)357  // ==========================================358  if (userId === adminId) {359    var addbalStep = User.getProperty("addbal_step");360    var rembalStep = User.getProperty("rembal_step");361    var checkbalStep = User.getProperty("checkbal_step");362 363    if (addbalStep === "waiting_input" && msgText) {364      User.setProperty("addbal_step", null, "string");365      Bot.run({ command: "/addbal", options: { message: "/addbal " + msgText.trim() } });366      return;367    }368    if (rembalStep === "waiting_input" && msgText) {369      User.setProperty("rembal_step", null, "string");370      Bot.run({ command: "/rembal", options: { message: "/rembal " + msgText.trim() } });371      return;372    }373    if (checkbalStep === "waiting_input" && msgText) {374      User.setProperty("checkbal_step", null, "string");375      Bot.run({ command: "/checkbal", options: { params: msgText.trim() } });376      return;377    }378  }379 380  // ==========================================381  // 🎟 MODULE 3: ADMIN COUPON GENERATOR (step-by-step wizard)382  // ==========================================383  if (userId === adminId && couponGenStep) {384 385    if (couponGenStep === "code") {386      if (!msgText) { Bot.sendMessage("⚠️ Kripya ek valid coupon code bhejein."); return; }387      var couponCodeUpper = msgText.trim().toUpperCase();388      if (Bot.getProperty("coupon_" + couponCodeUpper)) {389        Bot.sendMessage("❌ Ye coupon code pehle se exist karta hai! Doosra naam try karein.");390        return;391      }392      User.setProperty("coupon_gen_code", couponCodeUpper, "string");393      User.setProperty("coupon_gen_step", "maxclaims", "string");394      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" });395      return;396    }397 398    if (couponGenStep === "maxclaims") {399      var maxClaimsVal = parseInt(msgText.trim());400      if (isNaN(maxClaimsVal) || maxClaimsVal <= 0) { Bot.sendMessage("❌ Kripya ek valid number bhejein (jaise 50)."); return; }401      User.setProperty("coupon_gen_maxclaims", maxClaimsVal, "number");402      User.setProperty("coupon_gen_step", "discount", "string");403      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" });404      return;405    }406 407    if (couponGenStep === "discount") {408      var discountVal = parseFloat(msgText.trim());409      if (isNaN(discountVal) || discountVal <= 0 || discountVal > 100) { Bot.sendMessage("❌ Discount 1 se 100 ke beech honi chahiye."); return; }410      User.setProperty("coupon_gen_discount", discountVal, "number");411      User.setProperty("coupon_gen_step", "scope", "string");412      Bot.sendMessage(413        "<tg-emoji emoji-id='6093677128295914531'>🎯</tg-emoji> <b>Scope batayein:</b>\n\n" +414        "• Sabhi products/plans ke liye: <code>global</code> likh kar bhejein\n" +415        "• Sirf ek specific product+plan ke liye: <code>Product Name | Duration</code>\n" +416        "  <i>Example:</i> <code>Atomic Habits (Book) | 1d</code>",417        { parse_mode: "HTML" }418      );419      return;420    }421 422    if (couponGenStep === "scope") {423      var scopeInput = msgText.trim();424      var couponData = {425        code: User.getProperty("coupon_gen_code"),426        maxClaims: User.getProperty("coupon_gen_maxclaims"),427        discountPercent: User.getProperty("coupon_gen_discount"),428        claimedBy: [],429        isPaused: false,430        createdAt: new Date().toLocaleDateString()431      };432 433      if (scopeInput.toLowerCase() === "global") {434        couponData.scope = "global";435      } else if (scopeInput.indexOf("|") > -1) {436        var scopeParts = scopeInput.split("|");437        couponData.scope = "specific";438        couponData.productName = scopeParts[0].trim();439        couponData.duration = scopeParts[1].trim();440      } else {441        Bot.sendMessage("❌ Galat format! 'global' likhein ya 'Product Name | Duration' format me bhejein.");442        return;443      }444 445      Bot.setProperty("coupon_" + couponData.code, couponData, "json");446 447      // ✅ NEW: master list me bhi add karo, taaki /coupons admin command sabko list kar sake448      var couponList = Bot.getProperty("coupon_list") || [];449      if (couponList.indexOf(couponData.code) === -1) {450        couponList.push(couponData.code);451        Bot.setProperty("coupon_list", couponList, "json");452      }453 454      // Cleanup wizard state455      User.setProperty("coupon_gen_step", null, "string");456      User.setProperty("coupon_gen_code", null, "string");457      User.setProperty("coupon_gen_maxclaims", null, "number");458      User.setProperty("coupon_gen_discount", null, "number");459 460      Bot.sendMessage(461        "<blockquote>🎟 <b>COUPON CREATED SUCCESSFULLY!</b></blockquote>\n\n" +462        "🏷 <b>Code:</b> <code>" + couponData.code + "</code>\n" +463        "👥 <b>Max Claims:</b> " + couponData.maxClaims + "\n" +464        "💸 <b>Discount:</b> " + couponData.discountPercent + "%\n" +465        "🎯 <b>Scope:</b> " + (couponData.scope === "global" ? "🌍 Global (All Plans)" : "📦 " + couponData.productName + " (" + couponData.duration + ")"),466        { parse_mode: "HTML" }467      );468      return;469    }470  }471 472  // ==========================================473  // 🎟 MODULE 4: USER — APPLY COUPON CODE TEXT ENTRY474  // ==========================================475  if (awaitingCouponFor) {476    var enteredCode = msgText.trim().toUpperCase();477    var couponRec = Bot.getProperty("coupon_" + enteredCode);478 479    User.setProperty("awaiting_coupon_for", null, "string");480 481    if (!couponRec) {482      Bot.sendMessage("❌ <b>Invalid Coupon Code!</b>", { parse_mode: "HTML" });483      return;484    }485    if (couponRec.isPaused) {486      Bot.sendMessage("⏸ Ye coupon abhi paused hai, thodi der baad try karein.", { parse_mode: "HTML" });487      return;488    }489    if (!Array.isArray(couponRec.claimedBy)) { couponRec.claimedBy = []; }490    if (couponRec.claimedBy.indexOf(userId) > -1) {491      Bot.sendMessage("⚠️ Aapne ye coupon already use kar liya hai!", { parse_mode: "HTML" });492      return;493    }494    if (couponRec.claimedBy.length >= couponRec.maxClaims) {495      Bot.sendMessage("❌ Is coupon ki claim limit khatam ho gayi hai!", { parse_mode: "HTML" });496      return;497    }498 499    var couponTargetParts = awaitingCouponFor.split(" ");500    var cTargetProdIdx = couponTargetParts[0];501    var cTargetPlanIdx = couponTargetParts[1];502 503    if (couponRec.scope === "specific") {504      var cProductList = Bot.getProperty("stored_products") || [];505      var cProduct = cProductList[Number(cTargetProdIdx)];506      var cPlan = cProduct ? cProduct.plans[Number(cTargetPlanIdx)] : null;507      var cDurationDisplay = cPlan ? (cPlan.durationDisplay || (cPlan.days + " Days")) : "";508      var matchesProduct = cProduct && cProduct.name.trim().toLowerCase() === couponRec.productName.trim().toLowerCase();509      var matchesDuration = cDurationDisplay.toLowerCase().indexOf(String(couponRec.duration).toLowerCase().replace(/[^a-z0-9]/g, "")) > -1 ||510                             String(couponRec.duration).replace(/[^0-9]/g, "") === String(cPlan ? cPlan.days : "");511      if (!matchesProduct) {512        Bot.sendMessage("❌ Ye coupon is product ke liye valid nahi hai!", { parse_mode: "HTML" });513        return;514      }515    }516 517    // ✅ Valid — apply and mark claimed518    couponRec.claimedBy.push(userId);519    Bot.setProperty("coupon_" + enteredCode, couponRec, "json");520    User.setProperty("applied_coupon_" + cTargetProdIdx + "_" + cTargetPlanIdx, enteredCode, "string");521 522    Bot.sendMessage("🎉 <b>Coupon Applied!</b> -" + couponRec.discountPercent + "% discount added.", { parse_mode: "HTML" });523 524    Bot.run({525      command: "buyitem",526      options: { params: cTargetProdIdx + " " + cTargetPlanIdx }527    });528    return;529  }530 531  // ==========================================532  // 📢 MODULE 2: PREMIUM BROADCAST SYSTEM533  // ==========================================534  if (userId === adminId && isAwaitingBroadcast) {535    User.setProperty("awaiting_broadcast_data", false, "boolean");536    var userList = Bot.getProperty("all_users_list") || [];537 538    if (userList.length === 0) {539      Bot.sendMessage("❌ Bot mein abhi tak koi bhi user registered nahi hai.");540      return;541    }542 543    var targetMessageId = null;544    if (request) {545      if (request.message_id) { targetMessageId = request.message_id; }546      else if (request.message && request.message.message_id) { targetMessageId = request.message.message_id; }547    }548 549    if (!targetMessageId) {550      Bot.sendMessage("❌ Unable to fetch message ID for broadcast.");551      return;552    }553 554    Bot.sendMessage("⏳ Sending premium broadcast to " + userList.length + " users... Please wait.");555 556    // ✅ FIXED: pehle ek bhi blocked/invalid user Api.copyMessage() ko throw karwa deta557    // tha, jo bahar wale catch() tak chala jaata tha — isse loop beech me hi ruk jaata558    // tha (baaki users ko broadcast nahi jaata tha) aur admin ko scary "Error in handling"559    // dikhta tha, jabki zyada tar users ko message mil chuka hota tha. Ab har send apne560    // try/catch me hai, aur end me accurate success/fail count milega.561    var sentCount = 0;562    var failedCount = 0;563    for (var i = 0; i < userList.length; i++) {564      try {565        Api.copyMessage({566          chat_id: String(userList[i]),567          from_chat_id: adminId,568          message_id: Number(targetMessageId)569        });570        sentCount++;571      } catch (perUserErr) {572        failedCount++;573      }574    }575    Bot.sendMessage(576      "✅ <b>Broadcast Complete!</b>\n" +577      "📤 <b>Sent:</b> " + sentCount + " users\n" +578      (failedCount > 0 ? "⚠️ <b>Failed/Blocked:</b> " + failedCount + " users" : "🎉 <b>No failures!</b>"),579      { parse_mode: "HTML" }580    );581  }582 583} catch (err) {584  Bot.sendMessage("Error in handling: " + err.message);585}