import sys
import json
import logging
from typing import List, Dict, Any, Optional
from pathlib import Path
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from telegram.constants import ParseMode
# Ensure UTF-8 output on Windows terminal
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
pass
from config import (
TELEGRAM_BOT_TOKEN,
TELEGRAM_CHANNEL_ID,
TELEGRAM_GROUP_ID,
MINI_APP_URL,
SUBSCRIBERS_FILE,
BOT_USERNAME
)
from product_fetcher import fetch_products_from_database
from gemini_copywriter import generate_ai_enhanced_card
logger = logging.getLogger(__name__)
def get_product_brand_icon(name: str, slug: str) -> str:
"""Dynamically detects real brand icons based on product keywords."""
text = (name + " " + slug).lower()
if "gemini" in text or "google" in text:
return "✨"
if "chatgpt" in text or "gpt" in text or "openai" in text:
return "🤖"
if "claude" in text or "anthropic" in text:
return "🔮"
if "canva" in text:
return "🎨"
if "spotify" in text:
return "🎧"
if "netflix" in text:
return "🍿"
if "windows" in text or "office" in text or "microsoft" in text:
return "🪟"
if "figma" in text:
return "📐"
if "jetbrains" in text or "code" in text or "dev" in text:
return "💻"
if "vpn" in text or "nord" in text:
return "🛡️"
if "duolingo" in text:
return "🦉"
return "⚡"
def build_dynamic_product_card(product: Dict[str, Any]) -> str:
"""
100% Dynamic card builder that pulls directly from the Supabase Database.
No hardcoding whatsoever.
"""
name = product.get("name", "Genuine Digital Product")
slug = product.get("slug", "")
price_bdt = product.get("price_bdt", 0)
price_usd = product.get("price_usd", 0.0)
original_bdt = product.get("original_price_bdt")
short_desc = product.get("short_description") or product.get("description")
warranty = product.get("refund_policy") or "100% Replacement Warranty & Verified Delivery"
delivery_time = product.get("delivery_time") or "Instant delivery after payment"
brand_icon = get_product_brand_icon(name, slug)
# Format price with discount if original price is available
if original_bdt and original_bdt > price_bdt:
discount = round(((original_bdt - price_bdt) / original_bdt) * 100)
price_line = f"💵 Price: ৳{price_bdt:,.0f} / ${price_usd:.2f} (৳{original_bdt:,.0f}, -{discount}% Off)"
else:
price_line = f"💵 Price: ৳{price_bdt:,.0f} / ${price_usd:.2f}"
lines = [
"🔥 Flash Sale!",
"",
f"{brand_icon} {name}",
"",
price_line,
f"⚡ {delivery_time}"
]
# Add dynamic short description from database if present
if short_desc:
# Strip long text to keep Telegram card crisp
clean_desc = short_desc.strip().replace("\n", " ")
if len(clean_desc) > 120:
clean_desc = clean_desc[:117] + "..."
lines.append(f"🔹 {clean_desc}")
lines.append(f"🛡️ {warranty}")
lines.append("⌛ Limited-time offer. Price goes back up after sale.")
lines.append("")
lines.append("Tap 'Open Product' below to buy directly:")
return "\n".join(lines)
def load_subscribers() -> List[int]:
"""Loads subscriber chat IDs from file."""
if not SUBSCRIBERS_FILE.exists():
return []
try:
with open(SUBSCRIBERS_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
return data.get('subscribers', [])
except Exception as e:
logger.error(f"Failed to load subscribers: {e}")
return []
def add_subscriber(chat_id: int, user_info: Dict[str, Any] = None):
"""Registers a new user chat_id for scheduled reminders."""
subs = set(load_subscribers())
if chat_id not in subs:
subs.add(chat_id)
try:
with open(SUBSCRIBERS_FILE, 'w', encoding='utf-8') as f:
json.dump({"subscribers": list(subs)}, f, indent=2)
logger.info(f"Registered new subscriber chat_id: {chat_id}")
except Exception as e:
logger.error(f"Failed to save subscriber: {e}")
_current_deal_index = 0
def filter_active_products(products: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Filters out any internal simulation or test items."""
cleaned = []
for p in products:
name = str(p.get("name", "")).lower()
slug = str(p.get("slug", "")).lower()
if "sourcing" in name or "on-demand" in name or "demo" in slug or "test" in slug or "vip shared" in name:
continue
cleaned.append(p)
return cleaned
async def send_scheduled_reminder(bot: Bot, send_to_channel: bool = True):
"""
Cycles to the next real product directly from Supabase Database and sends the promo card.
100% dynamic, synchronized with website.
"""
global _current_deal_index
raw_products = fetch_products_from_database()
valid_products = filter_active_products(raw_products) if raw_products else []
if not valid_products:
logger.info("No active products available in database to broadcast.")
return
product = valid_products[_current_deal_index % len(valid_products)]
_current_deal_index += 1
slug = product.get("slug", "")
text = generate_ai_enhanced_card(product)
product_direct_url = f"{MINI_APP_URL}/product/{slug}?tg=1" if slug else f"{MINI_APP_URL}/shop?tg=1"
bot_deep_link = f"https://t.me/{BOT_USERNAME}?start={slug}" if slug else f"https://t.me/{BOT_USERNAME}?start=shop"
# Private chat keyboard (Native WebApp button inside 1-on-1 chat)
private_keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(
text="🛍️ Open Product ↗",
web_app=WebAppInfo(url=product_direct_url)
)
]
])
# Channel & Group keyboard (Deep-link that opens Telegram bot seamlessly without external browser prompt)
channel_keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton(
text="🛍️ Open Product ↗",
url=bot_deep_link
)
]
])
# 1. Send to subscribers
subscribers = load_subscribers()
sent_count = 0
for chat_id in subscribers:
try:
# Use native WebApp button only for private 1-on-1 users (chat_id > 0)
target_kb = private_keyboard if int(chat_id) > 0 else channel_keyboard
await bot.send_message(
chat_id=chat_id,
text=text,
parse_mode=ParseMode.HTML,
reply_markup=target_kb,
disable_web_page_preview=True
)
sent_count += 1
except Exception as e:
logger.warning(f"Could not send reminder to {chat_id}: {e}")
logger.info(f"Sent scheduled reminder to {sent_count} active subscriber(s).")
# 2. Send to channel
if send_to_channel and TELEGRAM_CHANNEL_ID:
try:
await bot.send_message(
chat_id=TELEGRAM_CHANNEL_ID,
text=text,
parse_mode=ParseMode.HTML,
reply_markup=channel_keyboard,
disable_web_page_preview=True
)
logger.info("Sent scheduled reminder to Channel.")
except Exception as e:
logger.warning(f"Could not send reminder to Channel: {e}")