Untitled

Anonymous
Plain Text
10/08/2025 3:17 PM
16.8 KB
22
Indexable
Never
# naruto_tracker_bot.py
# Version: wait-for-embed + robust parsing + JSON storage + CMD logging + ERROR FIXED
# pip install -U discord.py

import discord
import re
import json
import os
import logging
import asyncio
from typing import Optional, List, Tuple, Any, Callable

# ====== Logging (hiện log chi tiết trong CMD) ======
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

# ====== Config ======
DATA_FILE = "data.json"
MONTH_MINUTES = 43200  # 30 days
DAY_MINUTES = 1440
HOUR_MINUTES = 60

# Intents
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True

client = discord.Client(intents=intents)

# ====== Data Handling ======
def load_data() -> dict:
    """Load data from JSON file with error handling."""
    try:
        if not os.path.exists(DATA_FILE):
            return {
                "user": {"name": None, "weekly": 0, "global": 0},
                "weekly_top10": [],
                "global_top10": []
            }
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
            # Validate structure
            if "user" not in data:
                data["user"] = {"name": None, "weekly": 0, "global": 0}
            if "weekly_top10" not in data:
                data["weekly_top10"] = []
            if "global_top10" not in data:
                data["global_top10"] = []
            return data
    except (json.JSONDecodeError, IOError) as e:
        logging.error(f"Error loading data: {e}")
        return {
            "user": {"name": None, "weekly": 0, "global": 0},
            "weekly_top10": [],
            "global_top10": []
        }

def save_data(d: dict) -> bool:
    """Save data to JSON file with error handling."""
    try:
        # Create backup before saving
        if os.path.exists(DATA_FILE):
            backup_file = DATA_FILE + ".backup"
            with open(DATA_FILE, "r", encoding="utf-8") as src, open(backup_file, "w", encoding="utf-8") as dst:
                dst.write(src.read())
        
        with open(DATA_FILE, "w", encoding="utf-8") as f:
            json.dump(d, f, ensure_ascii=False, indent=2)
        return True
    except IOError as e:
        logging.error(f"Error saving data: {e}")
        return False

# Thread-safe data operations
import asyncio
data_lock = asyncio.Lock()

async def get_data() -> dict:
    """Get data with lock."""
    async with data_lock:
        return load_data()

async def update_data(update_func: Callable[[dict], None]) -> bool:
    """Update data safely with lock."""
    async with data_lock:
        data = load_data()
        update_func(data)
        return save_data(data)

# ====== Helpers ======
def parse_number(text: str) -> int:
    """Parse number from text with commas."""
    try:
        if text is None:
            return 0
        return int(text.replace(",", "").replace(".", "").strip())
    except (ValueError, AttributeError):
        return 0

def diff_to_time(diff: int) -> str:
    """Convert time difference to human readable format."""
    sign = "+" if diff >= 0 else "-"
    diff = abs(diff)
    months = diff // MONTH_MINUTES
    diff %= MONTH_MINUTES
    days = diff // DAY_MINUTES
    diff %= DAY_MINUTES
    hours = diff // HOUR_MINUTES
    minutes = diff % HOUR_MINUTES
    parts = []
    if months: parts.append(f"{months}mth")
    if days: parts.append(f"{days}d")
    if hours: parts.append(f"{hours}h")
    if minutes: parts.append(f"{minutes}min")
    if not parts: parts = ["0min"]
    return f"{sign}{' '.join(parts)}"

def build_comparison_embed(title: str, user_value: int, top10: List[Tuple[str, int]]) -> discord.Embed:
    """Build comparison embed."""
    desc = f"**Your missions:** `{user_value:,}`\n\n"
    for rank, (name, value) in enumerate(top10, 1):
        diff = user_value - value
        desc += f"**#{rank} {name}** → {value:,}  ({diff_to_time(diff)})\n"
    return discord.Embed(title=title, description=desc, color=0x00ff88)

def extract_number_from_line(line: str) -> Optional[int]:
    """Return integer number found before 'missions' in a line, or None."""
    if not line:
        return None
    # More robust pattern matching
    patterns = [
        r"([0-9,]+)\s*missions",
        r"missions\s*([0-9,]+)",
        r"([0-9,]+)\s*completed"
    ]
    for pattern in patterns:
        m = re.search(pattern, line, re.IGNORECASE)
        if m:
            return parse_number(m.group(1))
    return None

def extract_name_from_line(line: str) -> Optional[str]:
    """Given a line that contains '1. name -----> 123 missions', extract the name robustly."""
    if not line:
        return None
    
    # Find the mission number first
    m = re.search(r"([0-9,]+)\s*missions", line, re.IGNORECASE)
    if not m:
        return None
        
    name_part = line[:m.start()].strip()
    # Remove leading rank like '1.' or '1)' or '#1'
    name_part = re.sub(r"^[\s#]*\d+[\.\)\-\–\—]*\s*", "", name_part)
    # Remove trailing separators like '----->' or '-' or '->'
    name_part = re.sub(r"[\-\–\—>\s]*$", "", name_part)
    return name_part.strip() if name_part.strip() else None

async def find_embed(channel, predicate: Callable, lookback: int = 12, wait_timeout: int = 10) -> Optional[discord.Embed]:
    """
    1) Scan last `lookback` messages for an embed matching predicate.
    2) If not found, wait up to wait_timeout seconds for a new message with embed matching predicate.
    Returns the embed object or None.
    """
    # scan recent history first
    logging.info(f"Scanning last {lookback} messages for embed...")
    try:
        async for m in channel.history(limit=lookback):
            if not m.embeds:
                continue
            for emb in m.embeds:
                try:
                    if predicate(emb):
                        logging.info("Found matching embed in history.")
                        return emb
                except Exception as e:
                    logging.debug(f"Error checking embed: {e}")
                    continue
    except Exception as e:
        logging.warning(f"History scan error: {e}")

    # if not found, wait for a new message with embed
    logging.info(f"No matching embed found in history — waiting up to {wait_timeout}s for new embed...")
    
    def check(new_msg: discord.Message) -> bool:
        if new_msg.channel != channel or not new_msg.embeds:
            return False
        try:
            for emb in new_msg.embeds:
                if predicate(emb):
                    return True
            return False
        except Exception:
            return False

    try:
        new_msg = await client.wait_for("message", check=check, timeout=wait_timeout)
        logging.info("Received new message with matching embed.")
        return new_msg.embeds[0]  # Return first matching embed
    except asyncio.TimeoutError:
        logging.warning("Timeout waiting for embed.")
        return None

# ====== Event handlers (improved) ======
@client.event
async def on_ready():
    logging.info(f"✅ Logged in as {client.user}")
    print(f"✅ Logged in as {client.user}")
    logging.info("Bot is online and ready!")
    # Set bot status
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="your missions"))

@client.event
async def on_message(msg: discord.Message):
    if msg.author.bot:
        return

    content = msg.content.lower().strip()
    logging.info(f"Message received: {content} | Author: {msg.author}")

    # ----------------- n pr -----------------
    if content == "n pr":
        # predicate: embed contains 'Missions completed' or similar
        def predicate_profile(emb):
            try:
                raw = (emb.title or "") + "\n" + (emb.description or "")
                for f in emb.fields:
                    raw += f"\n{f.name}: {f.value}"
                return (
                    re.search(r"missions\s*completed", raw, re.IGNORECASE) is not None
                    or re.search(r"weekly\s*missions", raw, re.IGNORECASE) is not None
                    or "profile" in (emb.title or "").lower()
                )
            except Exception:
                return False

        emb = await find_embed(msg.channel, predicate_profile, lookback=12, wait_timeout=10)
        if not emb:
            await msg.reply("❌ Không tìm thấy embed profile (Missions completed) trong 10 tin gần nhất hoặc trong 10s chờ.")
            return

        # parse global and weekly from embed (both may appear)
        raw = (emb.description or "")
        for f in emb.fields:
            raw += f"\n{f.name}: {f.value}"
            
        # More robust pattern matching
        patterns_global = [
            r"Missions\s*completed[:\s]*([0-9,]+)",
            r"Total\s*missions[:\s]*([0-9,]+)",
            r"Global[:\s]*([0-9,]+)",
            r"Lifetime[:\s]*([0-9,]+)"
        ]
        patterns_weekly = [
            r"Weekly\s*missions[:\s]*([0-9,]+)",
            r"This\s*week[:\s]*([0-9,]+)",
            r"Weekly[:\s]*([0-9,]+)"
        ]
        
        g = None
        w = None
        
        for pattern in patterns_global:
            found = re.search(pattern, raw, re.IGNORECASE)
            if found:
                g = parse_number(found.group(1))
                break
                
        for pattern in patterns_weekly:
            found = re.search(pattern, raw, re.IGNORECASE)
            if found:
                w = parse_number(found.group(1))
                break

        async def update_profile_data():
            data = await get_data()
            if g is not None:
                data["user"]["global"] = g
                logging.info(f"✅ Found global missions: {g}")
            if w is not None:
                data["user"]["weekly"] = w
                logging.info(f"✅ Found weekly missions: {w}")
                
            # Set user name from embed title if possible
            if emb.title:
                nm = re.sub(r"'s profile", "", emb.title, flags=re.IGNORECASE).strip()
                if nm:
                    data["user"]["name"] = nm

            # fallback to message author name if user name not set
            if not data["user"].get("name"):
                data["user"]["name"] = msg.author.display_name

            return await update_data(lambda d: d.update(data))

        success = await update_profile_data()
        if success:
            current_data = await get_data()
            await msg.reply(
                f"✅ Saved profile. Global = `{current_data['user']['global']:,}`; "
                f"Weekly = `{current_data['user']['weekly']:,}`."
            )
        else:
            await msg.reply("❌ Lỗi khi lưu dữ liệu profile.")
        return

    # ----------------- checkw -----------------
    if content == "checkw":
        # predicate: embed title/desc contains 'weekly'
        def predicate_weekly(emb):
            try:
                t = (emb.title or "").lower()
                d = (emb.description or "").lower()
                return "weekly" in t or "weekly" in d
            except Exception:
                return False

        emb = await find_embed(msg.channel, predicate_weekly, lookback=12, wait_timeout=10)
        if not emb:
            await msg.reply("❌ Không tìm thấy Weekly leaderboard trong 10 tin gần nhất hoặc trong 10s chờ.")
            return

        desc = emb.description or ""
        top10 = []
        for line in desc.splitlines():
            num = extract_number_from_line(line)
            if num is None:
                continue
            name = extract_name_from_line(line) or "unknown"
            top10.append([name, num])

        if not top10:
            logging.warning("Parsed weekly embed but found 0 lines matching pattern.")
            await msg.reply("❌ Đã tìm thấy embed Weekly nhưng không parse được dòng nào.")
            return

        async def update_weekly_data():
            data = await get_data()
            data["weekly_top10"] = top10
            return await update_data(lambda d: d.update(data))

        success = await update_weekly_data()
        if success:
            current_data = await get_data()
            logging.info(f"✅ Weekly top10 parsed: {len(top10)} entries")
            embed_out = build_comparison_embed("Weekly Comparison", current_data["user"]["weekly"], top10)
            await msg.reply(embed=embed_out)
        else:
            await msg.reply("❌ Lỗi khi lưu dữ liệu weekly.")
        return

    # ----------------- n top m -----------------
    if content == "n top m":
        # predicate: embed contains 'lifetime'
        def predicate_lifetime(emb):
            try:
                t = (emb.title or "").lower()
                d = (emb.description or "").lower()
                return "lifetime" in t or "lifetime" in d or "global" in t or "global" in d
            except Exception:
                return False

        emb = await find_embed(msg.channel, predicate_lifetime, lookback=12, wait_timeout=10)
        if not emb:
            await msg.reply("❌ Không tìm thấy Lifetime leaderboard trong 10 tin gần nhất hoặc trong 10s chờ.")
            return

        desc = emb.description or ""
        top10 = []
        for line in desc.splitlines():
            num = extract_number_from_line(line)
            if num is None:
                continue
            name = extract_name_from_line(line) or "unknown"
            top10.append([name, num])

        if not top10:
            logging.warning("Parsed lifetime embed but found 0 lines matching pattern.")
            await msg.reply("❌ Đã tìm thấy embed Lifetime nhưng không parse được dòng nào.")
            return

        async def update_global_data():
            data = await get_data()
            data["global_top10"] = top10
            return await update_data(lambda d: d.update(data))

        success = await update_global_data()
        if success:
            current_data = await get_data()
            logging.info(f"✅ Lifetime top10 parsed: {len(top10)} entries")
            embed_out = build_comparison_embed("Lifetime Comparison", current_data["user"]["global"], top10)
            await msg.reply(embed=embed_out)
        else:
            await msg.reply("❌ Lỗi khi lưu dữ liệu lifetime.")
        return

    # ----------------- n m -----------------
    if content == "n m":
        async def increment_missions():
            data = await get_data()
            data["user"]["weekly"] = data["user"].get("weekly", 0) + 1
            data["user"]["global"] = data["user"].get("global", 0) + 1
            return await update_data(lambda d: d.update(data))

        success = await increment_missions()
        if success:
            current_data = await get_data()
            logging.info(f"+1 mission | Weekly={current_data['user']['weekly']} | Global={current_data['user']['global']}")
            await msg.reply(
                f"🕓 +1 mission!\n"
                f"Weekly: `{current_data['user']['weekly']:,}` | "
                f"Lifetime: `{current_data['user']['global']:,}`"
            )
        else:
            await msg.reply("❌ Lỗi khi cập nhật missions.")
        return

    # ----------------- checkdata -----------------
    if content == "checkdata":
        current_data = await get_data()
        embed = discord.Embed(title="📊 Current Data", color=0x3498db)
        embed.add_field(name="User", value=current_data["user"]["name"] or "Unknown", inline=False)
        embed.add_field(name="Weekly", value=f"{current_data['user']['weekly']:,}", inline=True)
        embed.add_field(name="Global", value=f"{current_data['user']['global']:,}", inline=True)
        
        weekly_sample = "\n".join([f"{n} - {v:,}" for n, v in current_data["weekly_top10"][:3]]) or "None"
        global_sample = "\n".join([f"{n} - {v:,}" for n, v in current_data["global_top10"][:3]]) or "None"
        
        embed.add_field(name="Weekly Top10 (sample)", value=weekly_sample, inline=False)
        embed.add_field(name="Global Top10 (sample)", value=global_sample, inline=False)
        
        await msg.reply(embed=embed)
        logging.info("Displayed current JSON data.")
        return

# ====== Error handlers ======
@client.event
async def on_error(event, *args, **kwargs):
    logging.error(f"Error in event {event}: {args} {kwargs}")

# ====== Run bot ======
if __name__ == "__main__":
    # Get token from environment variable (recommended) or use placeholder
    TOKEN = os.getenv('DISCORD_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE')
    
    if TOKEN == 'YOUR_BOT_TOKEN_HERE':
        logging.error("Please set DISCORD_BOT_TOKEN environment variable or update the token in code")
        exit(1)
    
    try:
        client.run(TOKEN)
    except discord.LoginFailure:
        logging.error("Invalid bot token provided")
    except KeyboardInterrupt:
        logging.info("Bot stopped by user")
    except Exception as e:
        logging.error(f"Unexpected error: {e}")
Editor is loading...
Leave a Comment