subnexus-bot / bot.py
moin22's picture
Upload 3 files
c895b6e verified
Raw History Blame Contribute Delete
37.3 kB
import sys
import logging
import asyncio
# 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,
WebAppInfo,
MenuButtonCommands,
MenuButtonDefault,
BotCommand
)
from telegram.constants import ParseMode
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
filters,
ContextTypes
)
from config import (
TELEGRAM_BOT_TOKEN,
MINI_APP_URL,
TELEGRAM_CHANNEL_ID,
TELEGRAM_GROUP_ID,
TELEGRAM_PROOF_TARGET,
REMINDER_INTERVAL_HOURS,
BOT_USERNAME
)
from reminder_engine import add_subscriber, send_scheduled_reminder
from social_proof import send_live_purchase_notification
from product_fetcher import fetch_products_from_database
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Default language is English as requested
DEFAULT_LANG = "en"
USER_LANGS = {}
SUPPORT_EMAIL = "info.subnexus@gmail.com"
LANG_LABELS = {
"en": {
"name": "English", "flag": "🇺🇸",
"store_btn": "🛍️ Open Store",
"track_btn": "📦 Track Order",
"deals_btn": "🔥 Hot Deals",
"channel_btn": "📢 Channel",
"group_btn": "💬 Community",
"proof_btn": "🔮 Live Proofs",
"support_btn": "🎧 Support & Help",
"lang_btn": "🌐 Change Language"
},
"bn": {
"name": "বাংলা", "flag": "🇧🇩",
"store_btn": "🛍️ ওপেন স্টোর",
"track_btn": "📦 অর্ডার ট্র্যাক",
"deals_btn": "🔥 হট ডিল",
"channel_btn": "📢 চ্যানেল",
"group_btn": "💬 কমিউনিটি",
"proof_btn": "🔮 লাইভ প্রুফ",
"support_btn": "🎧 সাপোর্ট ও হেল্প",
"lang_btn": "🌐 ভাষা পরিবর্তন"
},
"ar": {
"name": "العربية", "flag": "🇸🇦",
"store_btn": "🛍️ فتح المتجر", "track_btn": "📦 تتبع الطلب", "deals_btn": "🔥 العروض",
"channel_btn": "📢 القناة", "group_btn": "💬 المجتمع", "proof_btn": "🔮 الإثباتات",
"support_btn": "🎧 الدعم", "lang_btn": "🌐 تغيير اللغة"
},
"hi": {
"name": "हिन्दी", "flag": "🇮🇳",
"store_btn": "🛍️ स्टोर खोलें", "track_btn": "📦 ऑर्डर ट्रैक", "deals_btn": "🔥 हॉट डील्स",
"channel_btn": "📢 चैनल", "group_btn": "💬 कम्युनिटी", "proof_btn": "🔮 लाइव प्रूफ",
"support_btn": "🎧 सहायता", "lang_btn": "🌐 भाषा बदलें"
},
"es": {
"name": "Español", "flag": "🇪🇸",
"store_btn": "🛍️ Abrir Tienda", "track_btn": "📦 Rastrear Pedido", "deals_btn": "🔥 Ofertas",
"channel_btn": "📢 Canal", "group_btn": "💬 Comunidad", "proof_btn": "🔮 Pruebas",
"support_btn": "🎧 Soporte", "lang_btn": "🌐 Cambiar Idioma"
},
"ru": {
"name": "Русский", "flag": "🇷🇺",
"store_btn": "🛍️ Открыть Магазин", "track_btn": "📦 Отследить Заказ", "deals_btn": "🔥 Акции",
"channel_btn": "📢 Канал", "group_btn": "💬 Сообщество", "proof_btn": "🔮 Пруфы",
"support_btn": "🎧 Поддержка", "lang_btn": "🌐 Сменить Язык"
},
"zh": {
"name": "简体中文", "flag": "🇨🇳",
"store_btn": "🛍️ 打开商店", "track_btn": "📦 订单追踪", "deals_btn": "🔥 特惠活动",
"channel_btn": "📢 频道", "group_btn": "💬 社区", "proof_btn": "🔮 订单证明",
"support_btn": "🎧 客服支持", "lang_btn": "🌐 切换语言"
},
"pt": {
"name": "Português", "flag": "🇵🇹",
"store_btn": "🛍️ Abrir Loja", "track_btn": "📦 Rastrear Pedido", "deals_btn": "🔥 Ofertas",
"channel_btn": "📢 Canal", "group_btn": "💬 Comunidade", "proof_btn": "🔮 Provas",
"support_btn": "🎧 Suporte", "lang_btn": "🌐 Mudar Idioma"
},
"fr": {
"name": "Français", "flag": "🇫🇷",
"store_btn": "🛍️ Ouvrir la Boutique", "track_btn": "📦 Suivi de Commande", "deals_btn": "🔥 Offres",
"channel_btn": "📢 Canal", "group_btn": "💬 Communauté", "proof_btn": "🔮 Preuves",
"support_btn": "🎧 Support", "lang_btn": "🌐 Changer de Langue"
},
"de": {
"name": "Deutsch", "flag": "🇩🇪",
"store_btn": "🛍️ Shop Öffnen", "track_btn": "📦 Bestellung Verfolgen", "deals_btn": "🔥 Angebote",
"channel_btn": "📢 Kanal", "group_btn": "💬 Community", "proof_btn": "🔮 Nachweise",
"support_btn": "🎧 Support", "lang_btn": "🌐 Sprache Ändern"
}
}
def get_main_menu_keyboard(lang=DEFAULT_LANG, is_private=True):
meta = LANG_LABELS.get(lang, LANG_LABELS[DEFAULT_LANG])
channel_url = f"https://t.me/{TELEGRAM_CHANNEL_ID.replace('@', '')}" if TELEGRAM_CHANNEL_ID else "https://t.me/subnexus_official"
group_url = f"https://t.me/{TELEGRAM_GROUP_ID.replace('@', '')}" if TELEGRAM_GROUP_ID else "https://t.me/subnexus_community"
proof_url = f"https://t.me/{TELEGRAM_PROOF_TARGET.replace('@', '')}" if TELEGRAM_PROOF_TARGET else "https://t.me/subnexus_proof"
if is_private:
store_btn = InlineKeyboardButton(
text=meta["store_btn"],
web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1&lang={lang}")
)
track_btn = InlineKeyboardButton(
text=meta["track_btn"],
web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1&lang={lang}")
)
else:
# Channels and groups cannot have web_app buttons
store_btn = InlineKeyboardButton(
text=f"{meta['store_btn']} ↗",
url=f"https://t.me/subnexus_store_bot?start=store"
)
track_btn = InlineKeyboardButton(
text=f"{meta['track_btn']} ↗",
url=f"https://t.me/subnexus_store_bot?start=track"
)
return InlineKeyboardMarkup([
# Row 1: Primary Full-Width Mini App Store button
[store_btn],
# Row 2: Track Order & Hot Deals
[
track_btn,
InlineKeyboardButton(
text=meta["deals_btn"],
callback_data="view_deals"
)
],
# Row 3: Official Ecosystem Hubs (Channel, Group, Proofs)
[
InlineKeyboardButton(text=meta["channel_btn"], url=channel_url),
InlineKeyboardButton(text=meta["group_btn"], url=group_url),
InlineKeyboardButton(text=meta["proof_btn"], url=proof_url)
],
# Row 4: Support & Language Picker
[
InlineKeyboardButton(text=meta["support_btn"], callback_data="open_support"),
InlineKeyboardButton(text=f"{meta['lang_btn']} ({meta['flag']})", callback_data="open_lang_picker")
]
])
def get_language_picker_keyboard():
"""Generates a stylish grid of popular world languages with country flags."""
keyboard = [
[
InlineKeyboardButton(text="🇺🇸 English (Default)", callback_data="set_lang_en"),
InlineKeyboardButton(text="🇧🇩 বাংলা", callback_data="set_lang_bn")
],
[
InlineKeyboardButton(text="🇸🇦 العربية", callback_data="set_lang_ar"),
InlineKeyboardButton(text="🇮🇳 हिन्दी", callback_data="set_lang_hi")
],
[
InlineKeyboardButton(text="🇪🇸 Español", callback_data="set_lang_es"),
InlineKeyboardButton(text="🇷🇺 Русский", callback_data="set_lang_ru")
],
[
InlineKeyboardButton(text="🇨🇳 简体中文", callback_data="set_lang_zh"),
InlineKeyboardButton(text="🇵🇹 Português", callback_data="set_lang_pt")
],
[
InlineKeyboardButton(text="🇫🇷 Français", callback_data="set_lang_fr"),
InlineKeyboardButton(text="🇩🇪 Deutsch", callback_data="set_lang_de")
],
[
InlineKeyboardButton(text="🔙 Back / Main Menu", callback_data="close_lang_picker")
]
]
return InlineKeyboardMarkup(keyboard)
def get_persistent_reply_keyboard(lang=DEFAULT_LANG):
"""
Persistent bottom keyboard docked in the chat - users NEVER need to type slash '/'.
Includes 1-tap buttons for Store, Track Order, Flash Deals, Support, and Community.
"""
if lang == "bn":
return ReplyKeyboardMarkup(
[
[
KeyboardButton("🛍️ ওপেন স্টোর", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1&lang=bn")),
KeyboardButton("📦 ট্র্যাক অর্ডার", web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1&lang=bn"))
],
[
KeyboardButton("🔥 ফ্ল্যাশ ডিলস"),
KeyboardButton("🎧 কাস্টমার সাপোর্ট")
],
[
KeyboardButton("💬 সাপোর্ট গ্রুপ"),
KeyboardButton("🔮 লাইভ প্রুফ"),
KeyboardButton("🌐 ভাষা পরিবর্তন")
]
],
resize_keyboard=True,
is_persistent=True
)
return ReplyKeyboardMarkup(
[
[
KeyboardButton("🛍️ Open Store", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1&lang=en")),
KeyboardButton("📦 Track Order", web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1&lang=en"))
],
[
KeyboardButton("🔥 Flash Deals"),
KeyboardButton("🎧 Customer Support")
],
[
KeyboardButton("💬 Support Group"),
KeyboardButton("🔮 Live Proofs"),
KeyboardButton("🌐 Change Language")
]
],
resize_keyboard=True,
is_persistent=True
)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
Handles /start command: greets user in English by default, records subscriber,
and supports instant deep-linking to specific products.
"""
user = update.effective_user
chat_id = update.effective_chat.id
lang = USER_LANGS.get(chat_id, DEFAULT_LANG)
# Record subscriber for automated marketing reminders
add_subscriber(chat_id, {
"id": user.id,
"first_name": user.first_name,
"username": user.username
})
# Handle deep-linking to specific product from Channel/Group
if context.args and len(context.args) > 0:
param = context.args[0].lower().replace("prod_", "")
all_prods = fetch_products_from_database()
matched = None
for p in all_prods:
p_slug = str(p.get("slug", "")).lower()
p_name = str(p.get("name", "")).lower()
if param in p_slug or param in p_name:
matched = p
break
if matched:
name = matched.get("name", "Product")
slug = matched.get("slug", "")
price_bdt = float(matched.get("price_bdt", 0))
price_usd = float(matched.get("price_usd", 0.0))
orig_bdt = float(matched.get("original_price_bdt", 0)) if matched.get("original_price_bdt") else None
product_url = f"{MINI_APP_URL}/product/{slug}?tg=1"
discount_str = ""
if orig_bdt and orig_bdt > price_bdt:
disc = round(((orig_bdt - price_bdt) / orig_bdt) * 100)
discount_str = f" <i>(<s>৳{orig_bdt:,.0f}</s>, -{disc}% Off)</i>"
p_text = (
f"🛍️ <b>{name}</b>\n\n"
f"<blockquote>🏷️ <b>PRICE TAG:</b>\n"
f"🇧🇩 Local: <b>৳{price_bdt:,.0f} BDT</b>{discount_str}\n"
f"🇺🇸 Global: <b>${price_usd:.2f} USD</b> <i>(Instant Crypto / Card)</i></blockquote>\n\n"
f"⚡ <b>Delivery:</b> Instant Digital Delivery\n"
f"🛡️ <b>Warranty:</b> 100% Replacement Guarantee\n\n"
f"👇 <i>Tap below to open this product directly inside Telegram:</i>"
)
deep_keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(
text=f"🛍️ Open {name[:24]} ↗",
web_app=WebAppInfo(url=product_url)
)
],
[
InlineKeyboardButton(
text="🏪 Browse Full Store",
web_app=WebAppInfo(url=f"{MINI_APP_URL}/shop?tg=1")
)
]
])
await update.message.reply_text(
text=p_text,
parse_mode=ParseMode.HTML,
reply_markup=deep_keyboard
)
return
if lang == "bn":
welcome_text = (
f"👋 <b>স্বাগতম, {user.first_name}!</b>\n\n"
f"<b>SubNexus</b>-এ আপনাকে স্বাগতম — প্রিমিয়াম এআই সাবস্ক্রিপশন, সফটওয়্যার লাইসেন্স কী ও ডিজিটাল টুলসের নির্ভরযোগ্য প্ল্যাটফর্ম।\n\n"
f"✨ <b>আমাদের সেবাসমূহ:</b>\n"
f"• ১০০% অথেনটিক রিটেইল সার্ভিস\n"
f"• ৫-১৫ মিনিটের মধ্যে দ্রুত ডেলিভারি\n"
f"• বিকাশ, নগদ, ব্যাংক ট্রান্সফার, কার্ড ও ক্রিপ্টো পেমেন্ট সুবিধা\n\n"
f"👇 <i>টেলিগ্রামের ভেতরেই আমাদের স্টোর দেখতে নিচের বাটনে চাপ দিন:</i>"
)
else:
welcome_text = (
f"👋 <b>Welcome, {user.first_name}!</b>\n\n"
f"Welcome to <b>SubNexus</b> — Your premier retail destination for genuine AI subscriptions, "
f"developer licenses, and authentic software keys.\n\n"
f"✨ <b>24/7 Automated Services:</b>\n"
f"• 100% Genuine, tested licenses\n"
f"• Instant digital delivery after checkout\n"
f"• bKash, Nagad, Crypto, Binance Pay & Cards accepted\n\n"
f"👇 <i>Tap below to launch our store directly inside Telegram:</i>"
)
is_private = update.effective_chat.type == "private" if update.effective_chat else True
if is_private:
# Provide persistent bottom keyboard so commands & options are always 1-tap accessible
await update.message.reply_text(
text=welcome_text,
parse_mode=ParseMode.HTML,
reply_markup=get_persistent_reply_keyboard(lang)
)
# Interactive inline action cards
await update.message.reply_text(
text="👇 <i>Select an action or launch store:</i>",
parse_mode=ParseMode.HTML,
reply_markup=get_main_menu_keyboard(lang, is_private=True)
)
else:
await update.message.reply_text(
text=welcome_text,
parse_mode=ParseMode.HTML,
reply_markup=get_main_menu_keyboard(lang, is_private=False)
)
async def support_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Shows official customer support details and direct action buttons."""
support_text = (
"🎧 <b>SubNexus Official Customer Support Desk</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"Our support team is available 24/7 to assist with your orders, licenses, and questions.\n\n"
f"📱 <b>WhatsApp Live Chat:</b> <code>+880 1973-041069</code>\n"
f"💬 <b>Support & Community Group:</b> {TELEGRAM_GROUP_ID}\n"
f"📢 <b>Announcements:</b> {TELEGRAM_CHANNEL_ID}\n"
f"🔮 <b>Live Proof Feed:</b> {TELEGRAM_PROOF_TARGET or '@subnexus_proof'}\n"
f"🤖 <b>Support Desk Bot:</b> @subnexus_support_bot\n"
f"📧 <b>Official Email:</b> <code>{SUPPORT_EMAIL}</code>\n"
f"🌐 <b>Facebook Support:</b> https://www.facebook.com/messages/t/subnexus.official\n"
f"🌐 <b>Web Store:</b> {MINI_APP_URL}\n\n"
"<i>Need help? Tap any button below to connect with us instantly!</i>"
)
keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(text="🎧 Open Live Support Desk Bot ↗", url="https://t.me/subnexus_support_bot")
],
[
InlineKeyboardButton(text="📱 WhatsApp Live Chat (Fastest) ↗", url="https://wa.me/8801973041069?text=Hello%20SubNexus%2C%20I%20need%20assistance")
],
[
InlineKeyboardButton(text="💬 Support & Community Group ↗", url=f"https://t.me/{TELEGRAM_GROUP_ID.replace('@', '')}"),
InlineKeyboardButton(text="📢 Official Channel ↗", url=f"https://t.me/{TELEGRAM_CHANNEL_ID.replace('@', '')}")
],
[
InlineKeyboardButton(text="🌐 Facebook Messenger ↗", url="https://www.facebook.com/messages/t/subnexus.official"),
InlineKeyboardButton(text="🔮 Live Proofs ↗", url=f"https://t.me/{(TELEGRAM_PROOF_TARGET or '@subnexus_proof').replace('@', '')}")
],
[
InlineKeyboardButton(text="🛍️ Open Store", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1"))
]
])
await update.message.reply_text(text=support_text, parse_mode=ParseMode.HTML, reply_markup=keyboard)
async def proof_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Direct link to the live purchase proof channel."""
proof_target = TELEGRAM_PROOF_TARGET or "@subnexus_proof"
proof_url = f"https://t.me/{proof_target.replace('@', '')}"
text = (
"🔮 <b>SubNexus Live Orders & Proofs Feed</b>\n\n"
"Monitor all real-time order completions, license dispatches, and subscriber activations 24/7 on auto-pilot!\n\n"
f"👉 <b>Join Live Proofs:</b> {proof_target}"
)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(text="🔮 Open Live Proofs Channel ↗", url=proof_url)],
[InlineKeyboardButton(text="🛍️ Open Store", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1"))]
])
await update.message.reply_text(text=text, parse_mode=ParseMode.HTML, reply_markup=keyboard)
async def track_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Directly opens order tracking in the Mini App."""
keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(
text="📦 Track Your Order Now ↗",
web_app=WebAppInfo(url=f"{MINI_APP_URL}/order-tracking?tg=1")
)
]
])
await update.message.reply_text(
text="📦 <b>Track Your SubNexus Order</b>\n\nEnter your order number or email inside the Mini App to view real-time delivery status.",
parse_mode=ParseMode.HTML,
reply_markup=keyboard
)
async def catalog_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Shows categorized digital product suite with 1-tap store launcher."""
raw_products = fetch_products_from_database()
valid_products = filter_active_products(raw_products) if raw_products else []
lang = USER_LANGS.get(update.effective_chat.id, DEFAULT_LANG)
if not valid_products:
if lang == "bn":
catalog_text = (
"⚡ <b>SubNexus অফিসিয়াল ডিজিটাল ক্যাটালগ</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"আমাদের অফিসিয়াল প্ল্যাটফর্মে আসল লাইসেন্স ও সাবস্ক্রিপশন ক্যাটালগ সিঙ্ক হচ্ছে।\n"
"ওয়েবসাইটে প্রোডাক্ট আপলোড সম্পন্ন হলেই তাৎক্ষণিক এখানে দেখতে পাবেন।\n\n"
"👇 সরাসরি স্টোর ভিজিট করতে নিচের বাটনে চাপ দিন:"
)
else:
catalog_text = (
"⚡ <b>SubNexus Official Digital Products Suite</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"Our official genuine software licenses and AI subscriptions catalog is currently syncing.\n"
"Browse our web store directly below for real-time inventory and instant fulfillment:\n"
)
else:
catalog_lines = ["⚡ <b>SubNexus Official Digital Products Suite:</b>\n"]
for p in valid_products[:10]:
name = p.get('name', '')
price = p.get('price_bdt', 0)
catalog_lines.append(f"• <b>{name}</b> — ৳{price:,.0f}")
catalog_lines.append("\n👇 <i>Tap below to browse with live prices and instant checkout:</i>")
catalog_text = "\n".join(catalog_lines)
keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(
text="🛍️ Open Full Catalog (Shop Now)",
web_app=WebAppInfo(url=f"{MINI_APP_URL}/shop?tg=1")
)
]
])
await update.message.reply_text(text=catalog_text, parse_mode=ParseMode.HTML, reply_markup=keyboard)
async def deal_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Shows flash deals or official catalog status."""
raw_products = fetch_products_from_database()
valid_products = filter_active_products(raw_products) if raw_products else []
if not valid_products:
lang = USER_LANGS.get(update.effective_chat.id, DEFAULT_LANG)
if lang == "bn":
text = (
"🔥 <b>SubNexus এক্সক্লুসিভ অফার ও ডিলস</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"আমাদের অফিসিয়াল স্টোরে আসল প্রোডাক্ট এবং প্রাইসিং যুক্ত করার কাজ চলছে।\n"
"ওয়েবসাইট সম্পূর্ণ লাইভ ও ডিপ্লয়মেন্ট সম্পন্ন হলেই এক্সক্লুসিভ অফারসমূহ এখানে লাইভ হবে।\n\n"
"🛍️ আমাদের অফিসিয়াল স্টোর ভিজিট করতে নিচের বাটনে চাপ দিন:"
)
else:
text = (
"🔥 <b>SubNexus Exclusive Deals & Offers</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"Our official store catalog is currently being prepared and synchronized.\n"
"As soon as the store goes live, exclusive flash deals will appear right here!\n\n"
"🛍️ Tap below to browse the SubNexus Store:"
)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(text="🛍️ Open SubNexus Store", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1"))],
[InlineKeyboardButton(text="🎧 Contact Support Desk", url="https://t.me/subnexus_support_bot")]
])
await update.message.reply_text(text=text, parse_mode=ParseMode.HTML, reply_markup=keyboard)
return
await send_scheduled_reminder(context.bot, send_to_channel=False)
async def auto_reply_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""24/7 Automated Assistant for incoming text and quick-reply keyboard buttons."""
user = update.effective_user
chat_id = update.effective_chat.id
lang = USER_LANGS.get(chat_id, DEFAULT_LANG)
raw_text = (update.message.text or "").strip().lower()
# Instant handler for docked keyboard buttons:
if "support" in raw_text or "সাপোর্ট" in raw_text or "help" in raw_text or "সাহায্য" in raw_text:
await support_command(update, context)
return
if "deal" in raw_text or "ডিল" in raw_text or "offer" in raw_text or "অফার" in raw_text:
await deal_command(update, context)
return
if "proof" in raw_text or "প্রুফ" in raw_text:
await proof_command(update, context)
return
if "group" in raw_text or "গ্রুপ" in raw_text or "community" in raw_text:
group_url = f"https://t.me/{TELEGRAM_GROUP_ID.replace('@', '')}"
await update.message.reply_text(
f"💬 <b>SubNexus Support & Community Group:</b>\n\nJoin our community lounge for instant discussions, updates, and customer support:\n👉 {group_url}",
parse_mode=ParseMode.HTML,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="💬 Join Support & Community Group ↗", url=group_url)]])
)
return
if "lang" in raw_text or "ভাষা" in raw_text:
await update.message.reply_text(
"🌐 <b>Select Your Preferred Language / ভাষা নির্বাচন করুন:</b>",
parse_mode=ParseMode.HTML,
reply_markup=get_language_picker_keyboard()
)
return
add_subscriber(chat_id, {
"id": user.id,
"first_name": user.first_name,
"username": user.username
})
if lang == "bn":
reply_text = (
f"👋 <b>হ্যালো {user.first_name}! SubNexus-এ আপনাকে স্বাগতম।</b>\n\n"
f"আমাদের স্টোরটি <b>২৪/৭ সম্পূর্ণ স্বয়ংক্রিয়</b>। নিচের বাটনগুলো দিয়ে সহজেই কেনাকাটা করতে পারবেন:\n\n"
f"🛒 <b>প্রোডাক্ট দেখতে:</b> <code>[ 🛍️ Open SubNexus Store ]</code> চাপুন।\n"
f"📦 <b>অর্ডার ট্র্যাক করতে:</b> <code>[ 📦 Track Order ]</code> চাপুন।\n"
f"📧 <b>সাপোর্ট ইমেইল:</b> <code>{SUPPORT_EMAIL}</code>"
)
else:
reply_text = (
f"👋 <b>Hello {user.first_name}! Welcome to SubNexus.</b>\n\n"
f"Our store operates <b>24/7 on auto-pilot</b>. You can browse and purchase anytime:\n\n"
f"🛒 <b>Browse Products:</b> Tap <code>[ 🛍️ Open SubNexus Store ]</code> below.\n"
f"📦 <b>Track Order:</b> Tap <code>[ 📦 Track Order ]</code>.\n"
f"📧 <b>Support Email:</b> <code>{SUPPORT_EMAIL}</code>"
)
is_private = update.effective_chat.type == "private" if update.effective_chat else True
await update.message.reply_text(
text=reply_text,
parse_mode=ParseMode.HTML,
reply_markup=get_main_menu_keyboard(lang, is_private=is_private)
)
async def post_deal_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Admin command: /post_deal <text>"""
deal_text = " ".join(context.args) if context.args else ""
if not deal_text:
await update.message.reply_text(
"⚠️ Usage: `/post_deal Today's special flash deal details...`",
parse_mode=ParseMode.MARKDOWN
)
return
formatted_message = (
f"⚡ <b>SPECIAL FLASH ANNOUNCEMENT</b>\n\n"
f"<blockquote>{deal_text}</blockquote>\n\n"
f"<i>Tap below to open the SubNexus Store:</i>"
)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(text="🛍️ Open SubNexus Store", web_app=WebAppInfo(url=f"{MINI_APP_URL}?tg=1"))]
])
sent_targets = []
if TELEGRAM_CHANNEL_ID:
try:
await context.bot.send_message(chat_id=TELEGRAM_CHANNEL_ID, text=formatted_message, parse_mode=ParseMode.HTML, reply_markup=keyboard)
sent_targets.append("Channel")
except Exception as e:
logger.error(f"Failed to send to channel: {e}")
if TELEGRAM_GROUP_ID:
try:
await context.bot.send_message(chat_id=TELEGRAM_GROUP_ID, text=formatted_message, parse_mode=ParseMode.HTML, reply_markup=keyboard)
sent_targets.append("Group")
except Exception as e:
logger.error(f"Failed to send to group: {e}")
await update.message.reply_text(f"✅ Broadcast complete: {', '.join(sent_targets)}")
async def callback_query_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handles inline button clicks like 'view_deals', language picker, etc."""
query = update.callback_query
await query.answer()
chat_id = update.effective_chat.id
if query.data == "view_deals":
await send_scheduled_reminder(context.bot, send_to_channel=False)
elif query.data == "open_support":
lang = USER_LANGS.get(chat_id, DEFAULT_LANG)
support_text = (
"🎧 <b>SubNexus Official Customer Support Desk</b>\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"We are available 24/7 to assist with your orders, licenses, and questions.\n\n"
f"📱 <b>WhatsApp Live Chat:</b> <code>+880 1973-041069</code>\n"
f"💬 <b>Support & Community Group:</b> {TELEGRAM_GROUP_ID}\n"
f"📢 <b>Announcements:</b> {TELEGRAM_CHANNEL_ID}\n"
f"🔮 <b>Live Proof Feed:</b> {TELEGRAM_PROOF_TARGET or '@subnexus_proof'}\n"
f"🤖 <b>Support Desk Bot:</b> @subnexus_support_bot\n"
f"📧 <b>Official Email:</b> <code>{SUPPORT_EMAIL}</code>\n"
f"🌐 <b>Facebook Support:</b> https://www.facebook.com/messages/t/subnexus.official\n"
f"🌐 <b>Web Store:</b> {MINI_APP_URL}\n\n"
"<i>Tap any option below to get assistance:</i>"
)
keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(text="🎧 Open Live Support Desk Bot ↗", url="https://t.me/subnexus_support_bot")
],
[
InlineKeyboardButton(text="📱 WhatsApp Live Chat (Fastest) ↗", url="https://wa.me/8801973041069?text=Hello%20SubNexus%2C%20I%20need%20assistance")
],
[
InlineKeyboardButton(text="💬 Support & Community Group ↗", url=f"https://t.me/{TELEGRAM_GROUP_ID.replace('@', '')}"),
InlineKeyboardButton(text="📢 Official Channel ↗", url=f"https://t.me/{TELEGRAM_CHANNEL_ID.replace('@', '')}")
],
[
InlineKeyboardButton(text="🌐 Facebook Messenger ↗", url="https://www.facebook.com/messages/t/subnexus.official"),
InlineKeyboardButton(text="🔮 Live Proofs ↗", url=f"https://t.me/{(TELEGRAM_PROOF_TARGET or '@subnexus_proof').replace('@', '')}")
],
[
InlineKeyboardButton(text="🔙 Back / Main Menu", callback_data="close_lang_picker")
]
])
await query.edit_message_text(
text=support_text,
parse_mode=ParseMode.HTML,
reply_markup=keyboard
)
elif query.data == "open_lang_picker":
await query.edit_message_text(
"🌐 <b>Select Your Preferred Language / আপনার ভাষা নির্বাচন করুন:</b>",
parse_mode=ParseMode.HTML,
reply_markup=get_language_picker_keyboard()
)
elif query.data == "close_lang_picker":
lang = USER_LANGS.get(chat_id, DEFAULT_LANG)
await query.edit_message_text(
"👋 <b>SubNexus Official Virtual Assistant</b>",
parse_mode=ParseMode.HTML,
reply_markup=get_main_menu_keyboard(lang)
)
elif query.data.startswith("set_lang_"):
lang_code = query.data.replace("set_lang_", "")
USER_LANGS[chat_id] = lang_code
meta = LANG_LABELS.get(lang_code, LANG_LABELS[DEFAULT_LANG])
await query.edit_message_text(
f"{meta['flag']} Language set to <b>{meta['name']}</b>.",
parse_mode=ParseMode.HTML,
reply_markup=get_main_menu_keyboard(lang_code)
)
async def post_init_setup(app):
"""Configures the persistent Chat Menu Button and Telegram Command Menu on launch."""
try:
# 1. Set Chat Menu Button to official Commands Menu so user can easily open the menu list
await app.bot.set_chat_menu_button(
menu_button=MenuButtonCommands()
)
logger.info("Configured official Telegram Chat Menu Button [Menu].")
# 2. Set Official Bot Commands List
commands = [
BotCommand("start", "Launch SubNexus Store & Mini App"),
BotCommand("catalog", "Browse Genuine Digital Products"),
BotCommand("deals", "View Latest Flash Offers"),
BotCommand("track", "Track Order Status"),
BotCommand("proof", "Live Orders & Proofs Feed"),
BotCommand("support", "Customer Support & Contact Info"),
BotCommand("language", "Change Language (10+ Languages)")
]
await app.bot.set_my_commands(commands)
logger.info("Configured official Telegram Bot Command Menu.")
except Exception as e:
logger.warning(f"Could not setup menu/commands on startup: {e}")
async def social_proof_job(context: ContextTypes.DEFAULT_TYPE):
"""Broadcasts live purchase updates to @subnexus_proof channel."""
await send_live_purchase_notification(context.bot)
async def reminder_job(context: ContextTypes.DEFAULT_TYPE):
"""Scheduled background job that sends promotional cards to Channel."""
await send_scheduled_reminder(context.bot, send_to_channel=True)
def main(stop_signals=None, use_signals=True):
if not TELEGRAM_BOT_TOKEN:
print("❌ Error: TELEGRAM_BOT_TOKEN is missing! Please configure it in .env")
return
print("🤖 Starting SubNexus Telegram Bot Service...")
app = (
ApplicationBuilder()
.token(TELEGRAM_BOT_TOKEN)
.post_init(post_init_setup)
.build()
)
# Register command handlers
app.add_handler(CommandHandler("start", start_command))
app.add_handler(CommandHandler("catalog", catalog_command))
app.add_handler(CommandHandler("products", catalog_command))
app.add_handler(CommandHandler("deals", deal_command))
app.add_handler(CommandHandler("deal", deal_command))
app.add_handler(CommandHandler("track", track_command))
app.add_handler(CommandHandler("proof", proof_command))
app.add_handler(CommandHandler("proofs", proof_command))
app.add_handler(CommandHandler("support", support_command))
app.add_handler(CommandHandler("help", support_command))
app.add_handler(CommandHandler("language", lambda u, c: u.message.reply_text("🌐 Select Language:", reply_markup=get_language_picker_keyboard())))
app.add_handler(CommandHandler("lang", lambda u, c: u.message.reply_text("🌐 Select Language:", reply_markup=get_language_picker_keyboard())))
app.add_handler(CommandHandler("post_deal", post_deal_command))
app.add_handler(CallbackQueryHandler(callback_query_handler))
# 24/7 Smart auto-responder for 1-on-1 private customer chats
app.add_handler(MessageHandler(filters.ChatType.PRIVATE & filters.TEXT & ~filters.COMMAND, auto_reply_message))
# Background jobs (Fully paused until website catalog is populated and deployed)
if app.job_queue:
logger.info("All automated channel/group broadcasts and social proof are completely paused.")
print("⏸️ All automated channel & group broadcasts are paused until real website products are deployed.")
print("✅ Bot is online and listening for Telegram updates...")
if use_signals:
app.run_polling(bootstrap_retries=-1)
else:
app.run_polling(stop_signals=None, bootstrap_retries=-1)
if __name__ == "__main__":
main()