import discord from discord.ext import commands, tasks from discord import app_commands import aiohttp from aiohttp import web import asyncio import datetime import os import re import io import zipfile import time import json import sys import traceback from dateutil import parser as dateutil_parser from datetime import timezone import cloudscraper import concurrent.futures import translator import shortener # ───────────────────────────────────────── # CONFIG # ───────────────────────────────────────── def _clean_env(value: str | None) -> str: if value is None: return "" value = value.strip() if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'): value = value[1:-1].strip() return value def _env_first(*names: str, default: str = "") -> tuple[str, str]: for name in names: value = _clean_env(os.environ.get(name)) if value: return value, name return default, "" TOKEN, TOKEN_ENV_NAME = _env_first("DISCORD_BOT_TOKEN", "BOT_TOKEN", "TOKEN") GUILD_ID = int(_env_first("DISCORD_GUILD_ID", "GUILD_ID", default="1492076309323714570")[0]) CHANNEL_ID = int(_env_first("DISCORD_CHANNEL_ID", "CHANNEL_ID", default="1492120264551432193")[0]) MAX_GEN_PER_DAY = int(_env_first("MAX_GEN_PER_DAY", default="20")[0]) STEAM_API_KEY, STEAM_API_KEY_ENV_NAME = _env_first("STEAM_API_KEY", "STEAM_KEY") HF_TOKEN, HF_TOKEN_ENV_NAME = _env_first("HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGING_FACE_TOKEN") HF_REPO = _env_first("HF_REPO", default="Immaking/Luas")[0] HF_SUBFOLDER = "lua-manifest games" # thư mục chứa ZIP gộp (lua+manifest) HF_LUA_FOLDER = "lua" # thư mục chứa riêng file .lua HF_MANIFEST_FOLDER = "manifests" # thư mục chứa riêng manifest .zip HF_WORKSHOP_FOLDER = "workshop" # thư mục chứa workshop .manifest HF_DEPOT_FOLDER = "depots" # thư mục chứa depot .manifest FIX_LINK = "https://cs.rin.ru/forum/" # thay link thực nếu có DISCORD_OAUTH_CLIENT_ID = os.environ.get("CATSTEAM_DISCORD_CLIENT_ID", "1512105027270082651") DISCORD_OAUTH_CLIENT_SECRET, DISCORD_OAUTH_CLIENT_SECRET_ENV_NAME = _env_first( "CATSTEAM_DISCORD_CLIENT_SECRET", "DISCORD_CLIENT_SECRET", ) DISCORD_OAUTH_REDIRECT_URI = os.environ.get("CATSTEAM_DISCORD_REDIRECT_URI", "http://localhost:8765/callback") CATSTEAM_USER_AGENT = "Catsteam/2.0 (+https://discord.gg/Zamm885Msn)" def _log_startup_config() -> None: def fmt(value: str, source: str) -> str: return f"present via {source}" if value and source else "missing" print("[Config] DISCORD bot token:", fmt(TOKEN, TOKEN_ENV_NAME), flush=True) print("[Config] HF token:", fmt(HF_TOKEN, HF_TOKEN_ENV_NAME), flush=True) print("[Config] Steam API key:", fmt(STEAM_API_KEY, STEAM_API_KEY_ENV_NAME), flush=True) print("[Config] Discord OAuth secret:", fmt(DISCORD_OAUTH_CLIENT_SECRET, DISCORD_OAUTH_CLIENT_SECRET_ENV_NAME), flush=True) # Steam app search cache (per query, short TTL) _search_cache: dict[str, tuple[float, list]] = {} # query -> (timestamp, results) CACHE_TTL = 60 # seconds # ───────────────────────────────────────── # AIOHTTP WEB PROXY (Keep-Alive & Hide HF Links) # ───────────────────────────────────────── async def handle_ping(request): return web.Response(text="Bot is alive!") async def handle_download(request): appid = request.match_info.get('appid', '') if not appid.isdigit(): return web.Response(status=400, text="Invalid App ID") filename = f"{appid}.zip" encoded = filename.replace(" ", "%20") subfolder = HF_SUBFOLDER.replace(" ", "%20") url = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{subfolder}/{encoded}" headers = {"Authorization": f"Bearer {HF_TOKEN}"} async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as resp: if resp.status != 200: return web.Response(status=404, text=f"File {filename} not found on HF (Status: {resp.status})") # Streaming the file back to the user without downloading the whole thing to RAM response = web.StreamResponse( status=200, reason='OK', headers={ 'Content-Disposition': f'attachment; filename="{filename}"', 'Content-Type': 'application/zip' } ) await response.prepare(request) async for chunk in resp.content.iter_chunked(8192): await response.write(chunk) await response.write_eof() return response async def handle_discord_oauth_exchange(request): if not DISCORD_OAUTH_CLIENT_SECRET: return web.json_response( {"ok": False, "error": "CATSTEAM_DISCORD_CLIENT_SECRET chưa được cấu hình trên backend."}, status=500, ) try: body = await request.json() except Exception: return web.json_response({"ok": False, "error": "Body JSON không hợp lệ."}, status=400) code = str(body.get("code", "")).strip() if not code: return web.json_response({"ok": False, "error": "Thiếu Discord OAuth code."}, status=400) token_payload = { "client_id": DISCORD_OAUTH_CLIENT_ID, "client_secret": DISCORD_OAUTH_CLIENT_SECRET, "grant_type": "authorization_code", "code": code, "redirect_uri": DISCORD_OAUTH_REDIRECT_URI, } headers = {"User-Agent": CATSTEAM_USER_AGENT} async with aiohttp.ClientSession(headers=headers) as session: async with session.post("https://discord.com/api/v10/oauth2/token", data=token_payload) as resp: raw = await resp.text() if resp.status >= 400: return web.json_response( {"ok": False, "error": _discord_api_error(raw, resp.status)}, status=502, ) token_data = json.loads(raw) access_token = token_data.get("access_token") refresh_token = token_data.get("refresh_token", "") if not access_token: return web.json_response({"ok": False, "error": "Discord không trả access_token."}, status=502) async with session.get( "https://discord.com/api/v10/users/@me", headers={"Authorization": f"Bearer {access_token}", "User-Agent": CATSTEAM_USER_AGENT}, ) as resp: raw = await resp.text() if resp.status >= 400: return web.json_response( {"ok": False, "error": _discord_api_error(raw, resp.status)}, status=502, ) user = json.loads(raw) user_id = str(user.get("id", "")) username = user.get("username", "") display_name = user.get("global_name") or username avatar_hash = user.get("avatar") avatar_url = ( f"https://cdn.discordapp.com/avatars/{user_id}/{avatar_hash}.png?size=128" if user_id and avatar_hash else f"https://cdn.discordapp.com/embed/avatars/{int(user_id or 0) % 5}.png" ) return web.json_response({ "ok": True, "user_id": user_id, "username": username, "display_name": display_name, "avatar_url": avatar_url, "refresh_token": refresh_token, }) def _discord_api_error(raw: str, status: int) -> str: try: data = json.loads(raw) if raw else {} return ( data.get("error_description") or data.get("message") or data.get("error") or f"HTTP {status}" ) except Exception: return raw[:180] or f"HTTP {status}" def _version_tuple(value: str) -> tuple[int, ...]: parts = re.findall(r"\d+", value or "") return tuple(int(part) for part in parts[:4]) or (0,) async def handle_launcher_update(request): latest_version = _clean_env(os.environ.get("CATSTEAM_LAUNCHER_VERSION")) current_version = _clean_env(request.query.get("version")) notes = _clean_env(os.environ.get("CATSTEAM_LAUNCHER_NOTES")) download_url = _clean_env(os.environ.get("CATSTEAM_LAUNCHER_DOWNLOAD_URL")) available = bool( latest_version and download_url and _version_tuple(latest_version) > _version_tuple(current_version) ) return web.json_response( { "ok": True, "available": available, "version": latest_version if available else current_version, "notes": notes if available else "", }, headers={"Cache-Control": "no-store, no-cache, max-age=0", "Pragma": "no-cache"}, ) async def handle_launcher_download(request): download_url = _clean_env(os.environ.get("CATSTEAM_LAUNCHER_DOWNLOAD_URL")) if not download_url: return web.json_response({"ok": False, "error": "No launcher update configured."}, status=404) try: async with aiohttp.ClientSession() as session: async with session.get(download_url, timeout=aiohttp.ClientTimeout(total=180)) as resp: if resp.status != 200: return web.json_response({"ok": False, "error": "Update unavailable."}, status=502) headers = { "Content-Type": resp.headers.get("Content-Type", "application/octet-stream"), "Content-Disposition": 'attachment; filename="Catsteam-update.exe"', "Cache-Control": "no-store, no-cache, max-age=0", } stream = web.StreamResponse(status=200, headers=headers) await stream.prepare(request) async for chunk in resp.content.iter_chunked(1024 * 256): await stream.write(chunk) await stream.write_eof() return stream except Exception: return web.json_response({"ok": False, "error": "Update download failed."}, status=502) async def start_web_server(): app = web.Application() app.add_routes([ web.get('/', handle_ping), web.get('/download/{appid}', handle_download), web.get('/api/hubcap/key', handle_hubcap_key), web.get('/api/hubcap/status', handle_hubcap_status), web.get('/api/launcher/update', handle_launcher_update), web.get('/api/launcher/download', handle_launcher_download), web.post('/api/discord/oauth/exchange', handle_discord_oauth_exchange), ]) # URL Shortener integration await shortener.load_from_hf() shortener.setup_routes(app) runner = web.AppRunner(app) await runner.setup() port = int(os.environ.get("PORT", 8080)) site = web.TCPSite(runner, '0.0.0.0', port) await site.start() print(f"Web server started on port {port}. Proxy is ready.") # ───────────────────────────────────────── # DATABASE # ───────────────────────────────────────── DB_FILE = "quota_db.json" def _load_db(): if not os.path.exists(DB_FILE): return {} try: with open(DB_FILE, "r") as f: return json.load(f) except: return {} def _save_db(data): try: with open(DB_FILE, "w") as f: json.dump(data, f) except Exception as e: print(f"[DB] Error saving DB: {e}") def quota_get(user_id: int) -> int: today = datetime.date.today().isoformat() db = _load_db() # Refresh nếu qua ngày mới if db.get("date") != today: db = {"date": today, "users": {}} _save_db(db) uid_str = str(user_id) return db["users"].get(uid_str, 0) def quota_increment(user_id: int): today = datetime.date.today().isoformat() db = _load_db() if db.get("date") != today: db = {"date": today, "users": {}} uid_str = str(user_id) current = db["users"].get(uid_str, 0) db["users"][uid_str] = current + 1 _save_db(db) # ───────────────────────────────────────── # STEAM HELPERS # ───────────────────────────────────────── async def steam_search(session: aiohttp.ClientSession, query: str) -> list[dict]: """Search Steam store using storesearch JSON API - fast and reliable.""" global _search_cache q = query.strip() now = time.time() # Return cached result if fresh if q.lower() in _search_cache: ts, cached = _search_cache[q.lower()] if now - ts < CACHE_TTL: return cached results = [] if q.isdigit(): # Direct AppID lookup url = f"https://store.steampowered.com/api/appdetails?appids={q}&cc=us&filters=basic" try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=8)) as r: data = await r.json(content_type=None) info = data.get(q, {}) if info.get("success") and "data" in info: results = [{"appid": int(q), "name": info["data"].get("name", f"App {q}")}] except Exception as e: print(f"[Steam Search] AppID lookup error: {e}") else: # storesearch returns proper JSON - this is the correct endpoint import urllib.parse encoded = urllib.parse.quote(q) url = f"https://store.steampowered.com/api/storesearch/?term={encoded}&l=english&cc=us" try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=8)) as r: if r.status == 200: data = await r.json(content_type=None) for item in data.get("items", []): appid = item.get("id") name = item.get("name", "") if appid and name: results.append({"appid": int(appid), "name": name}) if len(results) >= 10: break except Exception as e: print(f"[Steam Search] storesearch error: {e}") _search_cache[q.lower()] = (now, results) return results async def steam_app_details(session: aiohttp.ClientSession, appid: int) -> dict | None: url_us = f"https://store.steampowered.com/api/appdetails?appids={appid}&cc=us" async with session.get(url_us, timeout=aiohttp.ClientTimeout(total=15)) as r: if r.status == 200: data = await r.json(content_type=None) info = data.get(str(appid), {}) if info.get("success"): return info["data"] return None async def steam_reviews(session: aiohttp.ClientSession, appid: int) -> tuple[str, int]: url = f"https://store.steampowered.com/appreviews/{appid}?json=1&language=all" try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as r: data = await r.json(content_type=None) qs = data.get("query_summary", {}) return qs.get("review_score_desc", "No Reviews"), qs.get("total_reviews", 0) except: return "No Reviews", 0 async def steam_dlc_prices(session: aiohttp.ClientSession, dlc_ids: list[int]) -> float: total = 0.0 batch = dlc_ids[:50] if not batch: return 0.0 ids_str = ",".join(map(str, batch)) url = f"https://store.steampowered.com/api/appdetails?appids={ids_str}&cc=us&filters=price_overview" try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=15)) as r: data = await r.json(content_type=None) for v in data.values(): if v and v.get("success") and "data" in v: po = v["data"].get("price_overview", {}) total += po.get("final", 0) / 100 except: pass return total # ───────────────────────────────────────── # HUGGINGFACE HELPERS # ───────────────────────────────────────── def format_price(amount: float, currency: str) -> str: if currency == "VND": return f"{amount:,.0f}₫".replace(",", ".") return f"${amount:.2f}" async def shorten_url(long_url: str) -> str: """Rút gọn link qua TinyURL API (tự tạo session riêng).""" try: async with aiohttp.ClientSession() as s: api = f"https://tinyurl.com/api-create.php?url={long_url}" async with s.get(api, timeout=aiohttp.ClientTimeout(total=5)) as r: if r.status == 200: short = (await r.text()).strip() print(f"[SHORTEN] {long_url} -> {short}") return short except Exception as e: print(f"[SHORTEN] Error: {e}") return long_url # ───────────────────────────────────────── # HUBCAP MANIFEST API (Key Pool) # ───────────────────────────────────────── KEYS_FILE = "keys.json" def _load_env_hubcap_keys() -> list[str]: raw = _env_first("HUBCAP_KEYS", "CATSTEAM_HUBCAP_KEYS", default="")[0] if not raw: return [] parts = re.split(r"[\s,;]+", raw) return [part.strip() for part in parts if part.strip() and not part.strip().startswith("DÁN_")] _hubcap_key_index = 0 # Chỉ số key đang dùng _hubcap_usage_cache = {"time": 0.0, "data": None} def _load_hubcap_keys() -> list[str]: env_keys = _load_env_hubcap_keys() if env_keys: return env_keys """Đọc danh sách API Key từ keys.json.""" if not os.path.exists(KEYS_FILE): return [] try: with open(KEYS_FILE, "r") as f: data = json.load(f) keys = data.get("hubcap_keys", []) # Lọc bỏ key mẫu placeholder return [k for k in keys if k and not k.startswith("DÁN_")] except: return [] async def handle_hubcap_key(request): global _hubcap_key_index keys = _load_hubcap_keys() headers = { "Cache-Control": "no-store, no-cache, max-age=0", "Pragma": "no-cache", } if not keys: return web.json_response( {"ok": False, "error": "No Hubcap community key configured."}, status=503, headers=headers, ) key_index = _hubcap_key_index % len(keys) _hubcap_key_index += 1 return web.json_response( {"ok": True, "key": keys[key_index], "pool_size": len(keys), "key_index": key_index}, headers=headers, ) def _empty_hubcap_usage_summary() -> dict: return { "single": {"usage": 0, "limit": 0, "remaining": 0}, "bundle": {"usage": 0, "limit": 0, "remaining": 0}, "workshop": {"usage": 0, "limit": 0, "remaining": 0}, } async def _fetch_hubcap_usage_summary(keys: list[str]) -> dict: now = time.time() cached = _hubcap_usage_cache.get("data") if cached is not None and now - float(_hubcap_usage_cache.get("time") or 0) < 60: return cached summary = _empty_hubcap_usage_summary() if not keys: _hubcap_usage_cache.update({"time": now, "data": summary}) return summary async with aiohttp.ClientSession() as session: for key in keys: headers = {"Authorization": f"Bearer {key}"} try: async with session.get( "https://hubcapmanifest.com/api/v1/generate/usage", headers=headers, timeout=aiohttp.ClientTimeout(total=20), ) as resp: if resp.status != 200: continue payload = await resp.json(content_type=None) except Exception: continue if not isinstance(payload, dict): continue for bucket in ("single", "bundle", "workshop"): value = payload.get(bucket) if not isinstance(value, dict): continue summary[bucket]["usage"] += int(value.get("usage") or 0) summary[bucket]["limit"] += int(value.get("limit") or 0) summary[bucket]["remaining"] += int(value.get("remaining") or 0) _hubcap_usage_cache.update({"time": now, "data": summary}) return summary async def handle_hubcap_status(request): keys = _load_hubcap_keys() per_key_daily_limit = 25 usage = await _fetch_hubcap_usage_summary(keys) headers = { "Cache-Control": "no-store, no-cache, max-age=0", "Pragma": "no-cache", } return web.json_response( { "ok": bool(keys), "pool_size": len(keys), "per_key_daily_limit": per_key_daily_limit, "total_daily_limit": len(keys) * per_key_daily_limit, "usage": usage, }, headers=headers, ) USER_KEYS_FILE = "data/user_keys.json" def _get_user_key(user_id: int) -> str | None: try: with open(USER_KEYS_FILE, "r") as f: data = json.load(f) return data.get(str(user_id)) except: return None def _set_user_key(user_id: int, key: str): os.makedirs(os.path.dirname(USER_KEYS_FILE), exist_ok=True) data = {} try: if os.path.exists(USER_KEYS_FILE): with open(USER_KEYS_FILE, "r") as f: data = json.load(f) except: pass data[str(user_id)] = key with open(USER_KEYS_FILE, "w") as f: json.dump(data, f, indent=4) def _remove_user_key(user_id: int) -> bool: try: with open(USER_KEYS_FILE, "r") as f: data = json.load(f) if str(user_id) in data: del data[str(user_id)] with open(USER_KEYS_FILE, "w") as f: json.dump(data, f, indent=4) return True except: pass return False async def hubcap_api_call(session: aiohttp.ClientSession, endpoint: str, is_binary: bool = True, user_key: str = None) -> bytes | dict | None: """Gọi API Hubcap. Nếu có user_key, dùng duy nhất key đó, ngược lại dùng key rotation từ keys.json.""" url = f"https://hubcapmanifest.com{endpoint}" if user_key: headers = {"Authorization": f"Bearer {user_key}"} try: print(f"[HUBCAP] Gọi {endpoint} bằng User Key cá nhân...") async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=120)) as r: if r.status == 200: if is_binary: data = await r.read() if data.startswith(b"") or data.startswith(b""): print("[HUBCAP] Bị Cloudflare chặn (HTML response), thử cloudscraper...") return await _hubcap_cloudscraper_fallback(url, headers, is_binary) print(f"[HUBCAP] Thành công ({len(data)} bytes) (User Key)") return data else: try: data = await r.json(content_type=None) print(f"[HUBCAP] Thành công (JSON) (User Key)") return data except Exception as e: print(f"[HUBCAP] Lỗi parse JSON, thử cloudscraper fallback: {e}") return await _hubcap_cloudscraper_fallback(url, headers, is_binary) else: body = await r.text() print(f"[HUBCAP] Lỗi {r.status} (User Key): {body[:200]}") return None except Exception as e: print(f"[HUBCAP] Exception (User Key): {e}") return None global _hubcap_key_index keys = _load_hubcap_keys() if not keys: print("[HUBCAP] Không có API Key nào trong keys.json!") return None tried = 0 while tried < len(keys): key = keys[_hubcap_key_index % len(keys)] headers = {"Authorization": f"Bearer {key}"} try: print(f"[HUBCAP] Gọi {endpoint} bằng key #{_hubcap_key_index % len(keys) + 1}...") async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=120)) as r: if r.status == 200: if is_binary: data = await r.read() if data.startswith(b"") or data.startswith(b""): print("[HUBCAP] Bị Cloudflare chặn, thử cloudscraper...") return await _hubcap_cloudscraper_fallback(url, headers, is_binary) print(f"[HUBCAP] Thành công ({len(data)} bytes)") return data else: try: data = await r.json(content_type=None) print(f"[HUBCAP] Thành công (JSON)") return data except Exception as e: print(f"[HUBCAP] Lỗi parse JSON, thử cloudscraper fallback: {e}") return await _hubcap_cloudscraper_fallback(url, headers, is_binary) elif r.status == 429: print(f"[HUBCAP] Key #{_hubcap_key_index % len(keys) + 1} hết lượt (429). Thử key tiếp...") _hubcap_key_index += 1 tried += 1 continue elif r.status == 401: print(f"[HUBCAP] Key #{_hubcap_key_index % len(keys) + 1} không hợp lệ (401). Thử key tiếp...") _hubcap_key_index += 1 tried += 1 continue else: body = await r.text() print(f"[HUBCAP] Lỗi {r.status}: {body[:200]}") return None except Exception as e: print(f"[HUBCAP] Exception: {e}") _hubcap_key_index += 1 tried += 1 continue print(f"[HUBCAP] Đã duyệt hết {len(keys)} key, không thành công.") return None # Cloudscraper fallback - dùng khi aiohttp bị Cloudflare chặn _cf_scraper = None def _get_cf_scraper(): global _cf_scraper if _cf_scraper is None: _cf_scraper = cloudscraper.create_scraper() return _cf_scraper def _cloudscraper_sync(url: str, headers: dict, is_binary: bool): """Gọi Hubcap API bằng cloudscraper (đồng bộ), xuyên qua Cloudflare.""" try: scraper = _get_cf_scraper() r = scraper.get(url, headers=headers, timeout=120) if r.status_code == 200: if is_binary: return r.content else: return r.json() else: print(f"[CLOUDSCRAPER] Lỗi {r.status_code}: {r.text[:200]}") return None except Exception as e: print(f"[CLOUDSCRAPER] Exception: {e}") return None async def _hubcap_cloudscraper_fallback(url: str, headers: dict, is_binary: bool): """Async wrapper cho cloudscraper sync call.""" loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, _cloudscraper_sync, url, headers, is_binary) if result is not None: print(f"[CLOUDSCRAPER] Thành công! Xuyên qua Cloudflare.") else: print(f"[CLOUDSCRAPER] Thất bại, không xuyên được Cloudflare.") return result # Các hàm gọi API cụ thể theo từng endpoint async def hubcap_download_manifest(session, appid: int, user_key: str = None, force_update: bool = False) -> bytes | None: url = f"/api/v1/manifest/{appid}" if force_update: url += "?force_update=true" return await hubcap_api_call(session, url, user_key=user_key) async def hubcap_download_lua(session, appid: int, user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/lua/{appid}", user_key=user_key) async def hubcap_download_lua_basegame(session, appid: int, user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/lua/basegame/{appid}", user_key=user_key) async def hubcap_download_lua_dlc(session, appid: int, user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/lua/dlc/{appid}", user_key=user_key) async def hubcap_get_depot_keys(session, user_key: str = None) -> dict | None: return await hubcap_api_call(session, "/api/v1/depot-keys", is_binary=False, user_key=user_key) async def hubcap_generate_appmanifest(session, appid: int, branch: str = "public", user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/generate/appmanifest/{appid}?branch={branch}", user_key=user_key) async def hubcap_generate_workshop(session, workshop_id: str, user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/generate/workshopmanifest/{workshop_id}", user_key=user_key) async def hubcap_generate_depot(session, depot_id: str, manifest_id: str, user_key: str = None) -> bytes | None: return await hubcap_api_call(session, f"/api/v1/generate/manifest?depot_id={depot_id}&manifest_id={manifest_id}", user_key=user_key) async def hubcap_get_usage(session, user_key: str = None) -> dict | None: return await hubcap_api_call(session, "/api/v1/generate/usage", is_binary=False, user_key=user_key) async def hubcap_get_status(session, appid: int, user_key: str = None) -> dict | None: return await hubcap_api_call(session, f"/api/v1/status/{appid}", is_binary=False, user_key=user_key) def _hf_upload(file_bytes: bytes, path_in_repo: str) -> bool: """Upload file lên kho HuggingFace Dataset (đồng bộ, gọi từ async wrapper).""" try: from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) print(f"[HF-UPLOAD] Đang upload {path_in_repo} ({len(file_bytes)} bytes)...") api.upload_file( path_or_fileobj=io.BytesIO(file_bytes), path_in_repo=path_in_repo, repo_id=HF_REPO, repo_type="dataset", ) print(f"[HF-UPLOAD] Upload thành công {path_in_repo}!") return True except Exception as e: print(f"[HF-UPLOAD] Lỗi upload {path_in_repo}: {e}") return False async def upload_to_hf(zip_bytes: bytes, appid: int) -> bool: """Upload ZIP gộp (lua+manifest) lên lua-manifest games/""" return _hf_upload(zip_bytes, f"{HF_SUBFOLDER}/{appid}.zip") async def upload_lua_to_hf(lua_bytes: bytes, appid: int) -> bool: """Upload file .lua riêng lên lua/""" return _hf_upload(lua_bytes, f"{HF_LUA_FOLDER}/{appid}.lua") async def upload_manifest_to_hf(zip_bytes: bytes, appid: int) -> bool: """Upload manifest .zip riêng lên manifests/""" return _hf_upload(zip_bytes, f"{HF_MANIFEST_FOLDER}/{appid}.zip") async def upload_workshop_to_hf(manifest_bytes: bytes, workshop_id: str) -> bool: """Upload workshop manifest lên workshop/""" return _hf_upload(manifest_bytes, f"{HF_WORKSHOP_FOLDER}/{workshop_id}.manifest") async def upload_depot_to_hf(manifest_bytes: bytes, depot_id: str, manifest_id: str) -> bool: """Upload depot manifest lên depots//""" appid = depot_id[:-1] + "0" if len(depot_id) > 1 else depot_id return _hf_upload(manifest_bytes, f"{HF_DEPOT_FOLDER}/{appid}/{depot_id}_{manifest_id}.manifest") async def _hf_download(session: aiohttp.ClientSession, path: str) -> bytes | None: """Download file từ HuggingFace.""" encoded = path.replace(" ", "%20") url = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{encoded}" headers = {"Authorization": f"Bearer {HF_TOKEN}"} try: async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=60)) as r: if r.status == 200: return await r.read() except: pass return None async def hf_download_zip(session: aiohttp.ClientSession, appid: int) -> bytes | None: """Download ZIP gộp từ lua-manifest games/""" # Đã sửa lại để tải thẳng từ manifests/ thay vì lua-manifest games/ (bị lỗi thời) return await _hf_download(session, f"{HF_MANIFEST_FOLDER}/{appid}.zip") async def hf_download_lua_file(session: aiohttp.ClientSession, appid: int) -> bytes | None: """Download file .lua riêng từ lua/""" return await _hf_download(session, f"{HF_LUA_FOLDER}/{appid}.lua") async def _hf_peek_header(session: aiohttp.ClientSession, path: str, size: int = 512) -> bytes | None: """Chỉ đọc `size` bytes đầu tiên của file trên HF bằng HTTP Range, không tải hết.""" encoded = path.replace(" ", "%20") url = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{encoded}" headers = {"Authorization": f"Bearer {HF_TOKEN}", "Range": f"bytes=0-{size - 1}"} try: async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=15)) as r: if r.status in (200, 206): return await r.read() except: pass return None async def hf_download_manifest_zip(session: aiohttp.ClientSession, appid: int) -> bytes | None: """Download manifest .zip riêng từ manifests/""" return await _hf_download(session, f"{HF_MANIFEST_FOLDER}/{appid}.zip") async def hf_download_workshop(session: aiohttp.ClientSession, workshop_id: str) -> bytes | None: """Download workshop manifest từ workshop/""" return await _hf_download(session, f"{HF_WORKSHOP_FOLDER}/{workshop_id}.manifest") async def hf_download_depot(session: aiohttp.ClientSession, depot_id: str, manifest_id: str) -> bytes | None: """Download depot manifest từ depots// (với fallback về thư mục cũ)""" appid = depot_id[:-1] + "0" if len(depot_id) > 1 else depot_id data = await _hf_download(session, f"{HF_DEPOT_FOLDER}/{appid}/{depot_id}_{manifest_id}.manifest") if not data: data = await _hf_download(session, f"{HF_DEPOT_FOLDER}/{depot_id}_{manifest_id}.manifest") return data def parse_lua(lua_content: str, main_appid: int) -> dict: result = { "total_dlc_declared": 0, "dlc_appids": [], "depot_manifests": [], "main_appid": main_appid, } m = re.search(r"-- Total DLCs:\s*(\d+)", lua_content) if m: result["total_dlc_declared"] = int(m.group(1)) for m in re.finditer(r'setManifestid\((\d+),\s*"(\d+)"', lua_content): result["depot_manifests"].append((int(m.group(1)), m.group(2))) found_appids = set() for m in re.finditer(r'addappid\((\d+)', lua_content): found_appids.add(int(m.group(1))) for appid in found_appids: if appid != main_appid: result["dlc_appids"].append(appid) return result def check_manifests_in_zip(zip_bytes: bytes, depot_manifests: list) -> tuple[int, int]: try: with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: names = zf.namelist() except: return 0, len(depot_manifests) total = len(depot_manifests) existing = 0 for depot_id, manifest_id in depot_manifests: expected = f"{depot_id}_{manifest_id}.manifest" if any(os.path.basename(n) == expected for n in names): existing += 1 return existing, total # ───────────────────────────────────────── # BOT SETUP # ───────────────────────────────────────── intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): bot.add_view(SetupDichView()) bot.add_view(CloseTicketView()) print(f"Logged in as {bot.user} ({bot.user.id})") guild = discord.Object(id=GUILD_ID) bot.tree.copy_global_to(guild=guild) await bot.tree.sync(guild=guild) print("Commands synced.") # Start web server for streaming proxy & keep-alive bot.loop.create_task(start_web_server()) # Start HF background tasks hf_scanner_task.start() announcer_task.start() translator_task.start() print("[Bot] Ready. Using real-time Steam search (no bulk download).") # ───────────────────────────────────────── # VIEW: Nhận Link Tải (ẩn) # ───────────────────────────────────────── class DownloadView(discord.ui.View): def __init__(self, short_link: str, msg_text: str): super().__init__(timeout=600) # 10 phút timeout self.short_link = short_link self.msg_text = msg_text @discord.ui.button(label="📥 Tải xuống (Download)", style=discord.ButtonStyle.success, custom_id="dl_btn") async def download_btn(self, interaction: discord.Interaction, button: discord.ui.Button): content = f"{self.msg_text}\n📥 **[BẤM VÀO ĐÂY ĐỂ TẢI XUỐNG AN TOÀN]({self.short_link})**\n*(Link rút gọn bảo mật)*" await interaction.response.send_message(content=content, ephemeral=True) async def on_timeout(self): for child in self.children: child.disabled = True # Note: We can't easily edit the original message from on_timeout without the message object, so just free RAM. # ───────────────────────────────────────── # VIEW: Chọn game khi nhiều kết quả # ───────────────────────────────────────── class GameSelectView(discord.ui.View): def __init__(self, results: list[dict], interaction: discord.Interaction, check_dlc: bool, betabranch: str): super().__init__(timeout=60) self.results = results self.origin = interaction self.check_dlc = check_dlc self.betabranch = betabranch for app in results[:10]: btn = discord.ui.Button( label=app["name"][:80], style=discord.ButtonStyle.primary, custom_id=str(app["appid"]) ) btn.callback = self.make_callback(app["appid"]) self.add_item(btn) cancel = discord.ui.Button( label="❌ Cancel", style=discord.ButtonStyle.danger, custom_id="cancel" ) cancel.callback = self.cancel_callback self.add_item(cancel) def make_callback(self, appid: int): async def callback(interaction: discord.Interaction): await interaction.response.defer() self.stop() try: await self.origin.delete_original_response() except: pass await run_gen(interaction, appid, self.check_dlc, self.betabranch, followup=True) return callback async def cancel_callback(self, interaction: discord.Interaction): await interaction.response.defer() self.stop() try: await self.origin.delete_original_response() except: pass async def on_timeout(self): try: await self.origin.delete_original_response() except: pass # ───────────────────────────────────────── # UPDATE LOGIC # ───────────────────────────────────────── class UpdatePromptView(discord.ui.View): def __init__(self, timeout=60): super().__init__(timeout=timeout) self.value = None @discord.ui.button(label="Có", style=discord.ButtonStyle.success) async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.defer() self.value = True self.stop() @discord.ui.button(label="Không", style=discord.ButtonStyle.secondary) async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.defer() self.value = False self.stop() async def check_needs_update(session: aiohttp.ClientSession, appid: str, user_key: str, force: bool = False): hf_header = await _hf_peek_header(session, f"{HF_LUA_FOLDER}/{appid}.lua") hf_date = _parse_lua_date(hf_header) status_data = await hubcap_get_status(session, appid, user_key=user_key) hubcap_date = None if status_data and "file_modified" in status_data: try: hubcap_date = dateutil_parser.parse(status_data["file_modified"]) if hubcap_date.tzinfo is None: hubcap_date = hubcap_date.replace(tzinfo=timezone.utc) except Exception: pass needs_update = force reason = "Được yêu cầu ép cập nhật (force=True)." if not force: if hf_date is None: # Chưa có file trên HF → cần tải mới needs_update = True reason = "Không tìm thấy file trên HF hoặc không đọc được ngày giờ." elif hubcap_date is not None: # Có cả 2 ngày → so sánh thẳng if hubcap_date > hf_date: needs_update = True reason = f"Bản trên Hubcap mới hơn HF (Hubcap: {hubcap_date.strftime('%Y-%m-%d %H:%M')} > HF: {hf_date.strftime('%Y-%m-%d %H:%M')})." else: needs_update = False reason = "Bản trên HF đã là mới nhất." else: # Không lấy được ngày Hubcap (API lỗi/Cloudflare) → BỎ QUA, dùng bản hiện có needs_update = False reason = "Không lấy được thông tin từ Hubcap (API lỗi), dùng bản hiện có." return needs_update, reason, hf_date, hubcap_date async def perform_update(session: aiohttp.ClientSession, appid: str, user_key: str, proc_msg: discord.WebhookMessage, game_name: str): await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang ra lệnh ép Hubcap tải bản mới nhất cho **{game_name}** từ Steam... Vui lòng đợi!" ), view=None) manifest_bytes = await hubcap_download_manifest(session, appid, user_key=user_key, force_update=True) if not manifest_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không tải được Manifest mới cho `{appid}`.", color=0xff0000)) return False await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"✅ Đã tải Manifest mới ({len(manifest_bytes)/1024/1024:.2f} MB). Đang tải thêm Lua..." )) lua_bytes = await hubcap_download_lua(session, appid, user_key=user_key) if lua_bytes: now_str = datetime.datetime.now(timezone.utc).strftime("%B %d, %Y at %H:%M:%S UTC") try: lua_text = lua_bytes.decode('utf-8', errors='ignore') lua_text = f"-- Bot Last Updated: {now_str}\n" + lua_text lua_bytes = lua_text.encode('utf-8') except Exception: pass await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"☁️ Đang đồng bộ bản mới lên kho HuggingFace..." )) man_ok = await upload_manifest_to_hf(manifest_bytes, appid) lua_ok = False if lua_bytes: lua_ok = await upload_lua_to_hf(lua_bytes, appid) await proc_msg.edit(embed=discord.Embed( title=f"✅ Cập Nhật Thành Công: {game_name}", description=f"📦 **App ID:** `{appid}`\n" f"📁 **Manifest:** {'Thành công' if man_ok else 'Lỗi'}\n" f"📜 **Lua File:** {'Thành công' if lua_ok else 'Lỗi'}\n\n" f"🎉 Dữ liệu mới đã được đồng bộ lên kho!", color=0x00c851 )) return man_ok and lua_ok # ───────────────────────────────────────── # CORE LOGIC # ───────────────────────────────────────── async def run_gen(interaction: discord.Interaction, appid: int, check_dlc: bool, betabranch: str, followup: bool = False, gen_type: str = "game"): start_time = time.time() used = quota_get(interaction.user.id) if used >= MAX_GEN_PER_DAY: msg = f"❌ Bạn đã dùng hết {MAX_GEN_PER_DAY} lượt trong ngày hôm nay." if followup: await interaction.followup.send(msg, ephemeral=True) else: await interaction.response.send_message(msg, ephemeral=True) return processing_embed = discord.Embed(color=0x2b2d31) processing_embed.add_field(name="⏳ Processing...", value=f"**Game ID: {appid}**", inline=False) processing_embed.add_field(name="", value="Generating files, please wait...\nThis may take a few seconds depending on game size", inline=False) if followup: proc_msg = await interaction.followup.send(embed=processing_embed) else: await interaction.response.send_message(embed=processing_embed) proc_msg = await interaction.original_response() async with aiohttp.ClientSession() as session: app_task = asyncio.create_task(steam_app_details(session, appid)) review_task = asyncio.create_task(steam_reviews(session, appid)) app_data = await app_task review_str, review_count = await review_task if app_data is None: fallback_name = await _get_game_name(session, appid) if not fallback_name or fallback_name == f"App {appid}": fallback_name = f"Unknown Game ({appid})" app_data = { "name": fallback_name, "header_image": "", "drm_notice": "", "price_overview": {}, "dlc": [] } game_name = app_data.get("name", "Unknown") # --- NEW UPDATE PROMPT LOGIC --- user_key = _get_user_key(interaction.user.id) needs_update, reason, hf_date, hubcap_date = await check_needs_update(session, str(appid), user_key) if needs_update and hf_date is not None: view = UpdatePromptView(timeout=60) await proc_msg.edit( embed=discord.Embed( title="🔄 Cập Nhật Dữ Liệu", description=f"**{game_name}** có bản cập nhật mới trên kho Steam.\nLý do: {reason}\n\nBạn có muốn bot lấy bản mới nhất trước khi tải không? (Hết hạn sau 60 giây)", color=0xffff00 ), view=view ) await view.wait() if view.value is True: success = await perform_update(session, str(appid), user_key, proc_msg, game_name) if success: hf_date = datetime.datetime.now(timezone.utc) # Wait 1 second before continuing so they can read the success message await asyncio.sleep(1.0) elif view.value is False: await proc_msg.edit(embed=discord.Embed(color=0x2b2d31, description="⏭️ Bỏ qua cập nhật, đang lấy dữ liệu hiện tại..."), view=None) else: await proc_msg.edit(embed=discord.Embed(color=0x2b2d31, description="⏳ Đã hết thời gian chờ, tự động lấy dữ liệu hiện tại..."), view=None) elif needs_update and hf_date is None: # First time generation or file missing, auto update without asking success = await perform_update(session, str(appid), user_key, proc_msg, game_name) if success: hf_date = datetime.datetime.now(timezone.utc) # After potential update, fetch the file if gen_type == "lua": hf_task = asyncio.create_task(hf_download_lua_file(session, appid)) elif gen_type == "manifest": hf_task = asyncio.create_task(hf_download_manifest_zip(session, appid)) else: hf_task = asyncio.create_task(hf_download_zip(session, appid)) file_bytes = await hf_task # ------------------------------- thumbnail = app_data.get("header_image", "") drm_notice = app_data.get("drm_notice", "") has_denuvo = "denuvo" in drm_notice.lower() po = app_data.get("price_overview", {}) base_price = po.get("final", 0) / 100 if po else 0.0 currency = po.get("currency", "USD") if po else "USD" steam_dlcs: list[int] = app_data.get("dlc", []) total_steam_dlcs = len(steam_dlcs) dlc_price_total = 0.0 if 0 < total_steam_dlcs <= 50: dlc_price_task = asyncio.create_task(steam_dlc_prices(session, steam_dlcs)) dlc_price_total = await dlc_price_task total_price = base_price + dlc_price_total lua_data = None manifest_existing = 0 manifest_total = 0 # Parse metadata (lua/manifest) từ file đã tải if file_bytes and gen_type == "game": try: with zipfile.ZipFile(io.BytesIO(file_bytes)) as zf: lua_name = next((n for n in zf.namelist() if n.endswith(".lua")), None) if lua_name: lua_content = zf.read(lua_name).decode("utf-8", errors="ignore") lua_data = parse_lua(lua_content, appid) manifest_existing, manifest_total = check_manifests_in_zip( file_bytes, lua_data["depot_manifests"] ) except Exception as e: print(f"[ZIP] Error parsing: {e}") elif file_bytes and gen_type == "lua": try: lua_content = file_bytes.decode("utf-8", errors="ignore") lua_data = parse_lua(lua_content, appid) except Exception as e: print(f"[LUA] Error parsing: {e}") if check_dlc: local_dlcs = set(lua_data["dlc_appids"]) if lua_data else set() declared_total = lua_data.get("total_dlc_declared", 0) if lua_data else 0 # existing_dlc = số DLC thực sự có trong nội dung Lua (nguồn chuẩn) existing_dlc = declared_total if existing_dlc == 0 and len(local_dlcs) > 0: existing_dlc = len(local_dlcs) valid_dlc = existing_dlc # total = con số lớn nhất giữa: Lua declared, Lua thực tế đếm được, Steam API # Vì Steam API hay giấu DLC ẩn/pre-order, còn Lua thì quét sâu hơn real_total = max(declared_total, existing_dlc, total_steam_dlcs) total_steam_dlcs = real_total # Gán lại cho hiển thị missing_dlc = max(0, real_total - existing_dlc) completion = (existing_dlc / real_total * 100) if real_total > 0 else 100.0 else: valid_dlc = total_steam_dlcs existing_dlc = total_steam_dlcs missing_dlc = 0 completion = 100.0 elapsed = time.time() - start_time color = 0x00c851 if missing_dlc == 0 else 0xffbb33 manifest_status_str = ( f"✅ All {manifest_total} up to date" if manifest_total > 0 and manifest_existing == manifest_total else f"⚠️ {manifest_existing}/{manifest_total} found" if manifest_total > 0 else "⚠️ No files on HF" ) if hf_date: manifest_status_str += f"\nLast Updated: " embed = discord.Embed( title=f" Manifest Generated: {game_name}", color=color ) embed.add_field( name="Links", value=f"[Steam Store](https://store.steampowered.com/app/{appid})\n[SteamDB](https://steamdb.info/app/{appid})", inline=True ) embed.add_field( name="Reviews", value=f"{review_str}\n({review_count:,} reviews)", inline=True ) if gen_type == "game": embed.add_field( name="Manifest Status", value=manifest_status_str, inline=True ) embed.add_field(name="Base Game", value=format_price(base_price, currency), inline=True) embed.add_field(name="DLC Total", value=f"{format_price(dlc_price_total, currency)} ({total_steam_dlcs} DLC)", inline=True) embed.add_field(name=f"Price In {currency}", value=f"**{format_price(total_price, currency)}**", inline=True) dlc_status_val = ( f"{'✅' if missing_dlc == 0 else '⚠️'} **Total DLC:** {total_steam_dlcs}\n" f"**Valid DLC:** {valid_dlc}\n" f"**Existing:** {existing_dlc} | **Missing:** {missing_dlc}\n" f"**Completion:** {completion:.1f}%" ) embed.add_field(name="DLC Status", value=dlc_status_val, inline=False) if has_denuvo: embed.add_field( name="Important Notes", value="⚠️ NOTICE: Denuvo Anti-tamper detected. Game requires additional configuration for offline play.", inline=False ) # Online-Fix only applies if the game is multiplayer categories = app_data.get("categories", []) is_multiplayer = any(c.get("id") in [1, 9, 36, 38] for c in categories) if is_multiplayer: import urllib.parse safe_name = urllib.parse.quote_plus(game_name) of_link = f"https://online-fix.me/index.php?do=search&subaction=search&story={safe_name}" embed.add_field(name="🌐 Online Fix", value=f"[Search on Online-Fix.me]({of_link})", inline=False) if thumbnail: embed.set_image(url=thumbnail) view = None if file_bytes: file_size = len(file_bytes) base_url = os.environ.get("RENDER_EXTERNAL_URL", "http://localhost:8080") dl_link = f"{base_url}/download/{appid}" short_link = "" msg_text = f"Here is your **{gen_type}** file for **{game_name}**:\n" if gen_type == "game": if manifest_total > 0 and manifest_existing == manifest_total: msg_text += f"✅ All {manifest_total} manifests are up to date.\n" elif manifest_total > 0: msg_text += f"⚠️ {manifest_existing}/{manifest_total} manifests found.\n" else: msg_text += "⚠️ No manifest files found.\n" msg_text += f"📚 **DLC Status:** {existing_dlc}/{total_steam_dlcs} DLC available\n" if file_size > 10 * 1024 * 1024: # File lớn hơn 10MB -> rút gọn link và dùng View short_link = await shorten_url(dl_link) view = DownloadView(short_link, msg_text) quota_increment(interaction.user.id) new_used = used + 1 remaining = MAX_GEN_PER_DAY - new_used embed.set_footer(text=f"App ID: {appid} • Quota: {remaining}/{MAX_GEN_PER_DAY} • Processed in {elapsed:.2f}s") if view: await proc_msg.edit(embed=embed, view=view) else: await proc_msg.edit(embed=embed) ext = ".lua" if gen_type == "lua" else ".zip" if not file_bytes: await interaction.followup.send( content=f"⚠️ **Lỗi:** Không có file `{appid}{ext}` trong kho.\n👉 Nếu game có trên Steam nhưng chưa có trong kho, hãy dùng lệnh `/get update` hoặc `/get {gen_type}` để bot tạo và tải file mới về kho nhé!" ) elif len(file_bytes) <= 10 * 1024 * 1024: file_obj = discord.File( fp=io.BytesIO(file_bytes), filename=f"{appid}{ext}" ) await interaction.followup.send( content=msg_text, file=file_obj, ephemeral=True ) # Send quota remaining message (ephemeral) for both >10MB and <10MB cases if file_bytes: await interaction.followup.send( content=f"📊 You have **{remaining}/{MAX_GEN_PER_DAY}** manifest generations remaining today.", ephemeral=True ) # ───────────────────────────────────────── # ERROR HANDLER & LIMIT COMMAND # ───────────────────────────────────────── @bot.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): msg = f"⏳ Vui lòng đợi {error.retry_after:.1f} giây trước khi gửi lệnh tiếp theo." if interaction.response.is_done(): await interaction.followup.send(msg, ephemeral=True) else: await interaction.response.send_message(msg, ephemeral=True) else: print(f"Command Error: {error}") @bot.tree.command(name="help", description="Hiển thị hướng dẫn sử dụng bot") @app_commands.guilds(discord.Object(id=GUILD_ID)) async def help_cmd(interaction: discord.Interaction): help_text = """ **🤖 HƯỚNG DẪN SỬ DỤNG 0xoLemon-BOT** **🎮 1. LỆNH TẢI & TẠO GAME TỪ KHO (`/gen`)** Nhóm lệnh này dùng để lấy các file Manifest hoặc Lua đã được lưu sẵn trong kho lưu trữ của server (không tốn giới hạn API của bot). • `/gen game `: Tải file ZIP tổng hợp bao gồm cả Lua và Manifest của game. (Khuyên dùng) • `/gen manifest `: Chỉ tải riêng file ZIP chứa Manifest của game. • `/gen lua `: Chỉ tải riêng file .lua cấu hình game. • `/gen workshop `: Tải manifest dành cho 1 mục Workshop cụ thể. • `/gen depot `: Tải file manifest dành riêng cho 1 Depot cụ thể. **☁️ 2. LỆNH YÊU CẦU TRỰC TIẾP (`/get`)** Nếu game bạn cần tìm chưa có sẵn trong kho `/gen`, bạn có thể dùng nhóm lệnh `/get` để yêu cầu kéo game mới về và ném thẳng lên kho của tui. • `/get all `: Bot sẽ lấy cả Lua và Manifest về, tự động nén lại và đưa lên kho lưu trữ. • `/get generate [nhánh beta]`: Yêu cầu chủ động tạo mới Manifest cho game này (dành cho game mới update hoặc game chưa từng có). Quá trình mất khoảng 30-60 giây. • `/get lua `: Chỉ kéo riêng file Lua về. • `/get manifest `: Chỉ kéo riêng file Manifest về. • `/get status `: Kiểm tra xem game này hiện có sẵn hay không. **🔑 3. DÙNG API KEY CÁ NHÂN (KHÔNG GIỚI HẠN)** Bot của server sử dụng Key chung, đôi khi có thể bị nghẽn hoặc cạn lượt nếu quá nhiều người dùng `/get`. Để không phải chờ đợi, bạn có thể tự dùng API Key của riêng mình! Để biết xem lấy api key như nào, ở đâu, các bạn đọc tại đây 📢┇𝒊𝒎𝒑𝒐𝒓𝒕𝒂𝒏𝒕-𝒂𝒏𝒏𝒐𝒖𝒏𝒄𝒆𝒎𝒆𝒏𝒕… • `/key `: Lưu API Key cá nhân của bạn vào Bot. Từ giờ, mọi lệnh `/get` bạn gõ sẽ dùng Key của bạn (Key được bảo mật hoàn toàn và người khác không thể dùng ké). • `/key` (để trống): Xoá API Key cá nhân của bạn khỏi hệ thống và quay lại dùng Key chung của server. **📊 4. KIỂM TRA HẠN MỨC** • `/limit`: Xem số lượt tạo/tải game trong ngày của bạn. Mỗi người dùng có tối đa 20 lượt tạo (`/gen`) mỗi ngày. **🚨 TÓM LẠI:** Đây là bot free cho nên **tuyệt đối không**: - Spam - Lợi dụng bot - Dùng vào mục đích không chính đáng (như kiếm tiền .vv..v) - Không tag ACN nếu không anh ấy sẽ đéo để yên cho bạn """ embed = discord.Embed( title="Bảng Điều Khiển Bot", description=help_text.strip(), color=0x00c851 ) await interaction.response.send_message(embed=embed, ephemeral=True) @bot.tree.command(name="limit", description="Kiểm tra hạn mức tạo manifest trong ngày") @app_commands.guilds(discord.Object(id=GUILD_ID)) async def limit_cmd(interaction: discord.Interaction): used = quota_get(interaction.user.id) remaining = max(0, MAX_GEN_PER_DAY - used) await interaction.response.send_message( f"📊 **Hạn mức hôm nay:**\n" f"Đã dùng: **{used}/{MAX_GEN_PER_DAY}** lượt\n" f"Còn lại: **{remaining}** lượt", ephemeral=True ) # ───────────────────────────────────────── # SLASH COMMAND GROUP /gen # ───────────────────────────────────────── gen_group = app_commands.Group(name="gen", description="Generate manifest or lua files from repository", guild_ids=[GUILD_ID]) async def _handle_gen(interaction: discord.Interaction, appid: str, check_dlc: bool, betabranch: str, gen_type: str): if interaction.channel_id != CHANNEL_ID: await interaction.response.send_message( f"❌ Lệnh này chỉ dùng được trong <#{CHANNEL_ID}>.", ephemeral=True ) return appid = appid.strip() resolved_appid: int | None = None if appid.isdigit(): resolved_appid = int(appid) else: async with aiohttp.ClientSession() as session: results = await steam_search(session, appid) if not results: await interaction.response.send_message( f"❌ Không tìm thấy game nào khớp với `{appid}`.", ephemeral=True ) return if len(results) == 1: resolved_appid = results[0]["appid"] else: desc_lines = [] for i, app in enumerate(results[:10], 1): desc_lines.append(f"**{i}. {app['name']}**\nApp ID: {app['appid']}") extra = len(results) - 10 if extra > 0: desc_lines.append(f"*...and {extra} more games*") desc_lines.append("\nClick a button below to select a game, or use 'Cancel' to abort.") search_embed = discord.Embed( title="🔍 Game Search Results", description=f"Found **{len(results)}** games matching **{appid}**\n\nSelect a game to continue:\n\n" + "\n\n".join(desc_lines), color=0x5865F2 ) class CustomGenSelectView(discord.ui.View): def __init__(self, res, interaction: discord.Interaction, check, beta, gtype): super().__init__(timeout=60) self.results = res self.origin = interaction self.check_dlc = check self.betabranch = beta self.gen_type = gtype for app in res[:10]: btn = discord.ui.Button(label=app["name"][:80], style=discord.ButtonStyle.primary, custom_id=str(app["appid"])) btn.callback = self.make_callback(app["appid"]) self.add_item(btn) cancel = discord.ui.Button(label="❌ Cancel", style=discord.ButtonStyle.danger, custom_id="cancel") cancel.callback = self.cancel_callback self.add_item(cancel) def make_callback(self, a_id: int): async def callback(interaction: discord.Interaction): await interaction.response.defer() self.stop() try: await self.origin.delete_original_response() except: pass await run_gen(interaction, a_id, self.check_dlc, self.betabranch, followup=True, gen_type=self.gen_type) return callback async def cancel_callback(self, interaction: discord.Interaction): await interaction.response.defer() self.stop() try: await self.origin.delete_original_response() except: pass async def on_timeout(self): try: await self.origin.delete_original_response() except: pass view = CustomGenSelectView(results, interaction, check_dlc, betabranch, gen_type) await interaction.response.send_message(embed=search_embed, view=view) return await run_gen(interaction, resolved_appid, check_dlc, betabranch, followup=False, gen_type=gen_type) @gen_group.command(name="game", description="Tải file ZIP tổng hợp (lua+manifest) từ kho") @app_commands.describe(appid="The Steam App ID or game name", check_dlc="Check DLC (default: True)", betabranch="Beta branch (e.g. 'public')") async def gen_game_cmd(interaction: discord.Interaction, appid: str, check_dlc: bool = True, betabranch: str = "public"): await _handle_gen(interaction, appid, check_dlc, betabranch, "game") @gen_group.command(name="lua", description="Tải file LUA từ kho (chỉ LUA)") @app_commands.describe(appid="The Steam App ID or game name", check_dlc="Check DLC (default: True)", betabranch="Beta branch (e.g. 'public')") async def gen_lua_cmd(interaction: discord.Interaction, appid: str, check_dlc: bool = True, betabranch: str = "public"): await _handle_gen(interaction, appid, check_dlc, betabranch, "lua") @gen_group.command(name="manifest", description="Tải file ZIP MANIFEST từ kho") @app_commands.describe(appid="The Steam App ID or game name", check_dlc="Check DLC (default: True)", betabranch="Beta branch (e.g. 'public')") async def gen_manifest_cmd(interaction: discord.Interaction, appid: str, check_dlc: bool = True, betabranch: str = "public"): await _handle_gen(interaction, appid, check_dlc, betabranch, "manifest") @gen_group.command(name="workshop", description="Tải file manifest Workshop từ kho") @app_commands.describe(workshop_id="Workshop Item ID") async def gen_workshop_cmd(interaction: discord.Interaction, workshop_id: str): await interaction.response.defer() workshop_id = workshop_id.strip() used = quota_get(interaction.user.id) if used >= MAX_GEN_PER_DAY: await interaction.followup.send(f"❌ Bạn đã dùng hết {MAX_GEN_PER_DAY} lượt trong ngày hôm nay.", ephemeral=True) return async with aiohttp.ClientSession() as session: file_bytes = await hf_download_workshop(session, workshop_id) if not file_bytes: await interaction.followup.send(f"⚠️ Không tìm thấy file manifest cho Workshop `{workshop_id}` trên kho lưu trữ.", ephemeral=True) return quota_increment(interaction.user.id) remaining = MAX_GEN_PER_DAY - (used + 1) file_obj = discord.File(fp=io.BytesIO(file_bytes), filename=f"{workshop_id}.manifest") await interaction.followup.send( content=f"Here is your Workshop manifest file for **{workshop_id}**:\n📊 You have **{remaining}/{MAX_GEN_PER_DAY}** generations remaining.", file=file_obj, ephemeral=True ) @gen_group.command(name="depot", description="Tải file manifest Depot từ kho") @app_commands.describe(depot_id="Depot ID", manifest_id="Manifest ID") async def gen_depot_cmd(interaction: discord.Interaction, depot_id: str, manifest_id: str): await interaction.response.defer() depot_id = depot_id.strip() manifest_id = manifest_id.strip() used = quota_get(interaction.user.id) if used >= MAX_GEN_PER_DAY: await interaction.followup.send(f"❌ Bạn đã dùng hết {MAX_GEN_PER_DAY} lượt trong ngày hôm nay.", ephemeral=True) return async with aiohttp.ClientSession() as session: file_bytes = await hf_download_depot(session, depot_id, manifest_id) if not file_bytes: await interaction.followup.send(f"⚠️ Không tìm thấy file manifest cho Depot `{depot_id}` ({manifest_id}) trên kho lưu trữ.", ephemeral=True) return quota_increment(interaction.user.id) remaining = MAX_GEN_PER_DAY - (used + 1) file_obj = discord.File(fp=io.BytesIO(file_bytes), filename=f"{depot_id}_{manifest_id}.manifest") await interaction.followup.send( content=f"Here is your Depot manifest file for **{depot_id}**:\n📊 You have **{remaining}/{MAX_GEN_PER_DAY}** generations remaining.", file=file_obj, ephemeral=True ) # ───────────────────────────────────────── # SLASH COMMAND GROUP /get (Hubcap API) # ───────────────────────────────────────── # ───────────────────────────────────────── # /KEY COMMAND (Personal Hubcap Key) # ───────────────────────────────────────── @bot.tree.command(name="key", description="Lưu Hubcap API Key cá nhân của bạn để sử dụng không giới hạn") @app_commands.describe(api_key="Nhập Hubcap API Key của bạn (Bỏ trống để xoá key hiện tại)") async def key_cmd(interaction: discord.Interaction, api_key: str = None): if not api_key: removed = _remove_user_key(interaction.user.id) if removed: await interaction.response.send_message("✅ Đã xoá API Key cá nhân của bạn. Bot sẽ quay lại dùng key mặc định.", ephemeral=True) else: await interaction.response.send_message("⚠️ Bạn chưa lưu API Key cá nhân nào.", ephemeral=True) else: _set_user_key(interaction.user.id, api_key.strip()) await interaction.response.send_message("✅ Đã lưu API Key cá nhân của bạn! Từ giờ các lệnh `/get` sẽ dùng key này.", ephemeral=True) get_group = app_commands.Group(name="get", description="Tải dữ liệu từ Hubcap Manifest API", guild_ids=[GUILD_ID]) async def _resolve_appid(interaction: discord.Interaction, appid_str: str) -> int | None: """Helper: resolve tên game thành App ID.""" appid_str = appid_str.strip() if appid_str.isdigit(): return int(appid_str) async with aiohttp.ClientSession() as session: results = await steam_search(session, appid_str) if not results: return None if len(results) == 1: return results[0]["appid"] return results[0]["appid"] # Lấy kết quả đầu tiên async def _get_game_name(session, appid: int) -> str: app_data = await steam_app_details(session, appid) return app_data.get("name", f"App {appid}") if app_data else f"App {appid}" # ── /get lua ── @get_group.command(name="lua", description="Tải file Lua từ Hubcap và upload lên kho") @app_commands.describe(appid="Steam App ID hoặc tên game") @app_commands.checks.cooldown(1, 10.0, key=lambda i: i.user.id) async def get_lua_cmd(interaction: discord.Interaction, appid: str): await interaction.response.defer() resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return async with aiohttp.ClientSession() as session: game_name = await _get_game_name(session, resolved) proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang tải **Lua file** cho **{game_name}** từ Hubcap..." )) user_key = _get_user_key(interaction.user.id) lua_bytes = await hubcap_download_lua(session, resolved, user_key=user_key) if not lua_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không tải được Lua cho `{resolved}`.", color=0xff0000)) return # Upload lên HF lua/ folder await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"✅ Tải Lua thành công! ({len(lua_bytes)/1024:.1f} KB)\nĐang upload lên kho `lua/`..." )) upload_ok = await upload_lua_to_hf(lua_bytes, resolved) status_text = "✅ Đã upload lên kho `lua/`" if upload_ok else "⚠️ Upload thất bại" await proc_msg.edit(embed=discord.Embed( title=f"✅ Lua File: {game_name}", description=f"📦 **App ID:** `{resolved}`\n📁 **Kích thước:** {len(lua_bytes)/1024:.1f} KB\n☁️ **Nguồn:** kho lưu trữ\n{status_text}", color=0x00c851 if upload_ok else 0xffbb33 )) # Gửi file cho user file_obj = discord.File(fp=io.BytesIO(lua_bytes), filename=f"{resolved}.lua") await interaction.followup.send(file=file_obj, ephemeral=True) # ── /get manifest ── @get_group.command(name="manifest", description="Tải manifest ZIP từ Hubcap và upload lên kho") @app_commands.describe(appid="Steam App ID hoặc tên game") @app_commands.checks.cooldown(1, 10.0, key=lambda i: i.user.id) async def get_manifest_cmd(interaction: discord.Interaction, appid: str): await interaction.response.defer() resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return async with aiohttp.ClientSession() as session: game_name = await _get_game_name(session, resolved) proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang tải **Manifest ZIP** cho **{game_name}** từ Hubcap..." )) user_key = _get_user_key(interaction.user.id) zip_bytes = await hubcap_download_manifest(session, resolved, user_key=user_key) if not zip_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không tải được Manifest cho `{resolved}`.", color=0xff0000)) return # Upload lên HF manifests/ folder size_mb = len(zip_bytes) / 1024 / 1024 await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"✅ Tải Manifest thành công! ({size_mb:.2f} MB)\nĐang upload lên kho `manifests/`..." )) upload_ok = await upload_manifest_to_hf(zip_bytes, resolved) status_text = "✅ Đã upload lên kho `manifests/`" if upload_ok else "⚠️ Upload thất bại" await proc_msg.edit(embed=discord.Embed( title=f"✅ Manifest ZIP: {game_name}", description=f"📦 **App ID:** `{resolved}`\n📁 **Kích thước:** {size_mb:.2f} MB\n☁️ **Nguồn:** kho lưu trữ\n{status_text}", color=0x00c851 if upload_ok else 0xffbb33 )) # Gửi file cho user if len(zip_bytes) <= 10 * 1024 * 1024: file_obj = discord.File(fp=io.BytesIO(zip_bytes), filename=f"{resolved}.zip") await interaction.followup.send(file=file_obj, ephemeral=True) else: base_url = os.environ.get("RENDER_EXTERNAL_URL", "http://localhost:8080") dl_link = f"{base_url}/download/{resolved}" short_link = await shorten_url(dl_link) await interaction.followup.send( content=f"📥 **[BẤM VÀO ĐÂY ĐỂ TẢI XUỐNG]({short_link})**\n*(File quá lớn để gửi trực tiếp)*", ephemeral=True ) # ── /get all ── @get_group.command(name="all", description="Tải manifest + lua từ Hubcap, upload lên tất cả kho") @app_commands.describe(appid="Steam App ID hoặc tên game") @app_commands.checks.cooldown(1, 10.0, key=lambda i: i.user.id) async def get_all_cmd(interaction: discord.Interaction, appid: str): await interaction.response.defer() resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return start_time = time.time() async with aiohttp.ClientSession() as session: game_name = await _get_game_name(session, resolved) proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang tải **manifest + lua** cho **{game_name}** từ Hubcap...\n⚠️ Quá trình này có thể mất 10-30 giây." )) user_key = _get_user_key(interaction.user.id) # Tải cả manifest và lua song song manifest_task = asyncio.create_task(hubcap_download_manifest(session, resolved, user_key=user_key)) lua_task = asyncio.create_task(hubcap_download_lua(session, resolved, user_key=user_key)) manifest_bytes = await manifest_task lua_bytes = await lua_task if not manifest_bytes and not lua_bytes: elapsed = time.time() - start_time await proc_msg.edit(embed=discord.Embed( title="❌ Không tải được từ Hubcap", description=f"Không thể tải manifest/lua cho `{resolved}`.\n• Game chưa có trên Hubcap\n• API Key hết lượt/không hợp lệ", color=0xff0000 ).set_footer(text=f"Failed after {elapsed:.2f}s")) return # Upload lên từng thư mục riêng results = [] await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"✅ Tải xong! Đang upload lên kho lưu trữ..." )) if manifest_bytes: ok1 = await upload_manifest_to_hf(manifest_bytes, resolved) results.append(f"{'\u2705' if ok1 else '\u274c'} `manifests/{resolved}.zip` ({len(manifest_bytes)/1024/1024:.2f} MB)") # Upload cả vào thư mục gộp nếu có ok_hf = await upload_to_hf(manifest_bytes, resolved) if ok_hf: _add_to_announce_queue(resolved) else: results.append("❌ Manifest: Không tải được") if lua_bytes: ok2 = await upload_lua_to_hf(lua_bytes, resolved) results.append(f"{'\u2705' if ok2 else '\u274c'} `lua/{resolved}.lua` ({len(lua_bytes)/1024:.1f} KB)") else: results.append("❌ Lua: Không tải được") elapsed = time.time() - start_time await proc_msg.edit(embed=discord.Embed( title=f"✅ Đã thêm vào kho: {game_name}", description=f"📦 **App ID:** `{resolved}`\n☁️ **Nguồn:** kho lưu trữ\n\n**Kết quả upload:**\n" + "\n".join(results) + f"\n\nTừ giờ dùng `/gen game {resolved}` để tải về.", color=0x00c851 ).set_footer(text=f"Completed in {elapsed:.2f}s")) # ── /get generate ── @get_group.command(name="generate", description="Tạo manifest mới trực tiếp từ Steam (qua Hubcap)") @app_commands.describe(appid="Steam App ID hoặc tên game", branch="Branch (mặc định: public)") @app_commands.checks.cooldown(1, 15.0, key=lambda i: i.user.id) async def get_generate_cmd(interaction: discord.Interaction, appid: str, branch: str = "public"): await interaction.response.defer() resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return async with aiohttp.ClientSession() as session: game_name = await _get_game_name(session, resolved) proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang yêu cầu Hubcap **generate manifest mới** cho **{game_name}**...\n⚠️ Quá trình này có thể mất 30-60 giây." )) user_key = _get_user_key(interaction.user.id) gen_bytes = await hubcap_generate_appmanifest(session, resolved, branch, user_key=user_key) if not gen_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không generate được manifest cho `{resolved}`.", color=0xff0000)) return # Upload luôn lên HF upload_ok = await upload_to_hf(gen_bytes, resolved) size_mb = len(gen_bytes) / 1024 / 1024 if upload_ok: _add_to_announce_queue(resolved) await proc_msg.edit(embed=discord.Embed( title=f"✅ Generate & Upload: {game_name}", description=f"📦 **App ID:** `{resolved}`\n📁 **Kích thước:** {size_mb:.2f} MB\n🌿 **Branch:** {branch}\n\nManifest mới đã được tạo và upload lên kho!\nDùng `/gen {resolved}` để tải về.", color=0x00c851 )) else: await proc_msg.edit(embed=discord.Embed( title=f"⚠️ Generate OK nhưng Upload thất bại", description=f"Manifest đã tạo thành công ({size_mb:.2f} MB) nhưng không upload được lên kho.", color=0xffbb33 )) # ── /get generate_workshop ── @get_group.command(name="generate_workshop", description="Tạo manifest mới cho item Workshop từ Steam (qua Hubcap)") @app_commands.describe(workshop_id="Workshop Item ID") @app_commands.checks.cooldown(1, 15.0, key=lambda i: i.user.id) async def get_generate_workshop_cmd(interaction: discord.Interaction, workshop_id: str): await interaction.response.defer() workshop_id = workshop_id.strip() async with aiohttp.ClientSession() as session: proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang yêu cầu Hubcap **generate manifest mới** cho Workshop ID **{workshop_id}**...\n⚠️ Quá trình này có thể mất 15-30 giây." )) user_key = _get_user_key(interaction.user.id) gen_bytes = await hubcap_generate_workshop(session, workshop_id, user_key=user_key) if not gen_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không generate được manifest cho Workshop `{workshop_id}`.", color=0xff0000)) return # Upload luôn lên HF upload_ok = await upload_workshop_to_hf(gen_bytes, workshop_id) size_mb = len(gen_bytes) / 1024 / 1024 if upload_ok: await proc_msg.edit(embed=discord.Embed( title=f"✅ Generate Workshop & Upload: {workshop_id}", description=f"📦 **Workshop ID:** `{workshop_id}`\n📁 **Kích thước:** {size_mb:.2f} MB\n\nManifest mới đã được tạo và upload lên kho!\nDùng `/gen workshop {workshop_id}` để tải về.", color=0x00c851 )) else: await proc_msg.edit(embed=discord.Embed( title=f"⚠️ Generate Workshop OK nhưng Upload thất bại", description=f"Manifest đã tạo thành công ({size_mb:.2f} MB) nhưng không upload được lên kho.", color=0xffbb33 )) # ── /get generate_depot ── @get_group.command(name="generate_depot", description="Tạo manifest mới cho một Depot từ Steam (qua Hubcap)") @app_commands.describe(depot_id="Depot ID", manifest_id="Manifest ID") @app_commands.checks.cooldown(1, 15.0, key=lambda i: i.user.id) async def get_generate_depot_cmd(interaction: discord.Interaction, depot_id: str, manifest_id: str): await interaction.response.defer() depot_id = depot_id.strip() manifest_id = manifest_id.strip() async with aiohttp.ClientSession() as session: proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"⏳ Đang yêu cầu Hubcap **generate manifest mới** cho Depot **{depot_id}** ({manifest_id})...\n⚠️ Quá trình này có thể mất 15-30 giây." )) user_key = _get_user_key(interaction.user.id) gen_bytes = await hubcap_generate_depot(session, depot_id, manifest_id, user_key=user_key) if not gen_bytes: await proc_msg.edit(embed=discord.Embed(title="❌ Thất bại", description=f"Không generate được manifest cho Depot `{depot_id}`.", color=0xff0000)) return # Upload luôn lên HF upload_ok = await upload_depot_to_hf(gen_bytes, depot_id, manifest_id) size_mb = len(gen_bytes) / 1024 / 1024 if upload_ok: await proc_msg.edit(embed=discord.Embed( title=f"✅ Generate Depot & Upload: {depot_id}", description=f"📦 **Depot ID:** `{depot_id}`\n🔖 **Manifest ID:** `{manifest_id}`\n📁 **Kích thước:** {size_mb:.2f} MB\n\nManifest mới đã được tạo và upload lên kho!\nDùng `/gen depot {depot_id} {manifest_id}` để tải về.", color=0x00c851 )) else: await proc_msg.edit(embed=discord.Embed( title=f"⚠️ Generate Depot OK nhưng Upload thất bại", description=f"Manifest đã tạo thành công ({size_mb:.2f} MB) nhưng không upload được lên kho.", color=0xffbb33 )) # ── /get depotkeys ── @get_group.command(name="depotkeys", description="Xem danh sách Depot ID có sẵn trên Hubcap") @app_commands.checks.cooldown(1, 10.0, key=lambda i: i.user.id) async def get_depotkeys_cmd(interaction: discord.Interaction): await interaction.response.defer(ephemeral=True) user_key = _get_user_key(interaction.user.id) async with aiohttp.ClientSession() as session: data = await hubcap_get_depot_keys(session, user_key=user_key) if not data: await interaction.followup.send("❌ Không lấy được danh sách Depot Keys.", ephemeral=True) return total = data.get("total_depot_ids", 0) existing = data.get("existing_count", 0) pending = data.get("pending_count", 0) await interaction.followup.send(embed=discord.Embed( title="🔑 Hubcap Depot Keys", description=f"📊 **Tổng Depot IDs:** {total:,}\n" f"✅ **Đã có:** {existing:,}\n" f"⏳ **Đang chờ:** {pending:,}", color=0x5865F2 ), ephemeral=True) # ── /get usage ── @get_group.command(name="usage", description="Xem số lượt dùng API còn lại của Hubcap") @app_commands.checks.cooldown(1, 5.0, key=lambda i: i.user.id) async def get_usage_cmd(interaction: discord.Interaction): await interaction.response.defer(ephemeral=True) user_key = _get_user_key(interaction.user.id) async with aiohttp.ClientSession() as session: data = await hubcap_get_usage(session, user_key=user_key) if not data: await interaction.followup.send("❌ Không lấy được thông tin usage.", ephemeral=True) return single = data.get("single", {}) bundle = data.get("bundle", {}) workshop = data.get("workshop", {}) ready = data.get("steam_service_ready", False) await interaction.followup.send(embed=discord.Embed( title="📊 Hubcap API Usage", description=f"**Single Manifest:**\n" f"└ Đã dùng: {single.get('usage', 0)}/{single.get('limit', 0)} • Còn: {single.get('remaining', 0)}\n\n" f"**Bundle (App Manifest):**\n" f"└ Đã dùng: {bundle.get('usage', 0)}/{bundle.get('limit', 0)} • Còn: {bundle.get('remaining', 0)}\n\n" f"**Workshop:**\n" f"└ Đã dùng: {workshop.get('usage', 0)}/{workshop.get('limit', 0)} • Còn: {workshop.get('remaining', 0)}\n\n" f"**Steam Service:** {'🟢 Sẵn sàng' if ready else '🔴 Không khả dụng'}", color=0x00c851 if ready else 0xff0000 ), ephemeral=True) # ── /get status ── @get_group.command(name="status", description="Kiểm tra trạng thái manifest của game trên Hubcap") @app_commands.describe(appid="Steam App ID hoặc tên game") @app_commands.checks.cooldown(1, 5.0, key=lambda i: i.user.id) async def get_status_cmd(interaction: discord.Interaction, appid: str): await interaction.response.defer(ephemeral=True) resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return user_key = _get_user_key(interaction.user.id) async with aiohttp.ClientSession() as session: data = await hubcap_get_status(session, resolved, user_key=user_key) if not data: await interaction.followup.send(f"❌ Không lấy được trạng thái cho `{resolved}`.", ephemeral=True) return status = data.get("status", "unknown") exists = data.get("manifest_file_exists", False) size = data.get("file_size", 0) modified = data.get("file_modified", "N/A") age = data.get("file_age_days", 0) needs_update = data.get("needs_update", False) game_name = data.get("game_name", f"App {resolved}") color = 0x00c851 if exists and not needs_update else 0xffbb33 if exists else 0xff0000 await interaction.followup.send(embed=discord.Embed( title=f"📋 Status: {game_name}", description=f"📦 **App ID:** `{resolved}`\n" f"📌 **Trạng thái:** {status}\n" f"{'✅' if exists else '❌'} **File tồn tại:** {'Có' if exists else 'Không'}\n" f"📁 **Kích thước:** {size / 1024:.1f} KB\n" f"📅 **Cập nhật lần cuối:** {modified}\n" f"⏰ **Tuổi file:** {age:.1f} ngày\n" f"{'🔄' if needs_update else '✅'} **Cần cập nhật:** {'Có' if needs_update else 'Không'}", color=color ), ephemeral=True) @get_group.command(name="update", description="So sánh ngày tạo trong Lua HF và ép cập nhật nếu Hubcap có bản mới") @app_commands.describe(appid="Steam App ID hoặc tên game", force="Ép cập nhật bỏ qua so sánh") @app_commands.checks.cooldown(1, 15.0, key=lambda i: i.user.id) async def get_update_cmd(interaction: discord.Interaction, appid: str, force: bool = False): await interaction.response.defer() resolved = await _resolve_appid(interaction, appid) if not resolved: await interaction.followup.send(f"❌ Không tìm thấy game `{appid}`.", ephemeral=True) return user_key = _get_user_key(interaction.user.id) async with aiohttp.ClientSession() as session: game_name = await _get_game_name(session, resolved) proc_msg = await interaction.followup.send(embed=discord.Embed( color=0x2b2d31, description=f"🔍 Đang kiểm tra trạng thái trên Hubcap và HuggingFace cho **{game_name}**..." )) needs_update, reason, hf_date, hubcap_date = await check_needs_update(session, resolved, user_key, force=force) if not needs_update: msg = f"Game `{game_name}` không có cập nhật mới.\n\n📅 **HF Lua Created:** {hf_date.strftime('%Y-%m-%d %H:%M:%S') if hf_date else 'N/A'}\n📅 **Hubcap Modified:** {hubcap_date.strftime('%Y-%m-%d %H:%M:%S') if hubcap_date else 'N/A'}" await proc_msg.edit(embed=discord.Embed(title="✅ Đã là bản mới nhất", description=msg, color=0x00c851)) return await proc_msg.edit(embed=discord.Embed( color=0x2b2d31, description=f"⏳ **Cần Cập Nhật!** {reason}\nĐang ra lệnh ép Hubcap tải bản mới nhất cho **{game_name}** từ Steam... Vui lòng đợi!" )) await perform_update(session, resolved, user_key, proc_msg, game_name) def _parse_lua_date(lua_bytes: bytes): """Parse dòng '-- Bot Last Updated:' hoặc '-- Created:' từ nội dung file Lua.""" if not lua_bytes: return None try: text = lua_bytes.decode('utf-8', errors='ignore') date_str = None m_bot = re.search(r'--\s*Bot Last Updated:\s*(.+)', text) if m_bot: date_str = m_bot.group(1).strip() else: m_created = re.search(r'--\s*Created:\s*(.+)', text) if m_created: date_str = m_created.group(1).strip().replace(' at ', ' ') if date_str: tzinfos = {"EDT": -4*3600, "EST": -5*3600, "PDT": -7*3600, "PST": -8*3600, "UTC": 0, "GMT": 0} dt = dateutil_parser.parse(date_str, tzinfos=tzinfos) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt except Exception: pass return None # Autocomplete cho các lệnh /get có appid async def _get_autocomplete(interaction: discord.Interaction, current: str): if not current or len(current) < 2: return [] try: async with aiohttp.ClientSession() as session: apps = await steam_search(session, current.strip()) return [ app_commands.Choice(name=f"{app['name']} ({app['appid']})", value=str(app["appid"])) for app in apps[:25] ] except: return [] # ───────────────────────────────────────── # TICKET UI CLASSES # ───────────────────────────────────────── class CloseTicketView(discord.ui.View): def __init__(self): super().__init__(timeout=None) @discord.ui.button(label="Đóng Ticket", style=discord.ButtonStyle.danger, custom_id="close_translate_ticket", emoji="🔒") async def close_ticket(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message("Kênh sẽ tự động xoá sau 5 giây...") import asyncio await asyncio.sleep(5) try: await interaction.channel.delete() except: pass class CancelJobView(discord.ui.View): def __init__(self, job_id: str, input_path: str): super().__init__(timeout=None) self.job_id = job_id self.input_path = input_path @discord.ui.button(label="Huỷ Dịch Thuật", style=discord.ButtonStyle.danger, custom_id="cancel_translate_job", emoji="🛑") async def cancel_job(self, interaction: discord.Interaction, button: discord.ui.Button): queue = _load_json_list(TRANSLATE_QUEUE_FILE) new_queue = [j for j in queue if j.get("job_id") != self.job_id] if len(new_queue) == len(queue): # Job is not in queue (already translating or finished) await interaction.response.send_message("❌ Không thể huỷ! File này đã bắt đầu được dịch hoặc đã dịch xong.", ephemeral=True) return _save_json_list(TRANSLATE_QUEUE_FILE, new_queue) if os.path.exists(self.input_path): try: os.remove(self.input_path) except: pass # Disable button for child in self.children: child.disabled = True await interaction.response.edit_message(content="🛑 **ĐÃ HUỶ DỊCH THUẬT!**", view=self) class GoogleTranslateModal(discord.ui.Modal, title='Dịch bằng Google Translate'): def __init__(self, attachment, engine): super().__init__() self.attachment = attachment self.engine = engine target_lang = discord.ui.TextInput( label='Ngôn ngữ đích (Target Language)', default='vi', placeholder='Nhập mã ngôn ngữ (vi, en, ja...)', required=True, max_length=10 ) source_lang = discord.ui.TextInput( label='Ngôn ngữ gốc (VD: English)', default='English', placeholder='Nhập ngôn ngữ gốc cần dịch...', required=True, max_length=20 ) async def on_submit(self, interaction: discord.Interaction): await interaction.response.defer() file = self.attachment ext = os.path.splitext(file.filename)[1].lower() job_id = f"{interaction.user.id}_{int(time.time())}" input_path = os.path.join(TRANSLATE_WORK_DIR, f"{job_id}{ext}") await file.save(input_path) queue = _load_json_list(TRANSLATE_QUEUE_FILE) queue.append({ "job_id": job_id, "user_id": interaction.user.id, "channel_id": interaction.channel_id, "filename": file.filename, "input_path": input_path, "engine": self.engine, "api_key": "", "prompt": "", "target_lang": self.target_lang.value, "source_lang": self.source_lang.value, "game_format": interaction.channel.name.split("-")[1] if "-" in interaction.channel.name else "auto" }) _save_json_list(TRANSLATE_QUEUE_FILE, queue) await interaction.followup.send( f"⏳ Đã đưa file `{file.filename}` vào hàng đợi dịch bằng **{self.engine.capitalize()}** (Ngôn ngữ: {self.target_lang.value})! Vui lòng chờ tôi một lát...", view=CancelJobView(job_id, input_path) ) class APIKeyModal(discord.ui.Modal, title='Nhập Thông Tin Dịch Thuật AI'): def __init__(self, attachment, engine): super().__init__() self.attachment = attachment self.engine = engine target_lang = discord.ui.TextInput( label='Ngôn ngữ đích (Target Language)', default='vi', placeholder='Nhập mã ngôn ngữ (vi, en, ja...)', required=True, max_length=10 ) source_lang = discord.ui.TextInput( label='Ngôn ngữ gốc (VD: English)', default='English', placeholder='Nhập ngôn ngữ gốc cần dịch...', required=True, max_length=20 ) api_key = discord.ui.TextInput( label='API Key', placeholder='Nhập API Key của bạn vào đây...', required=True ) prompt = discord.ui.TextInput( label='Prompt bổ sung (Tuỳ chọn)', placeholder='VD: Dịch theo văn phong kiếm hiệp, giữ nguyên format', required=False, style=discord.TextStyle.paragraph ) async def on_submit(self, interaction: discord.Interaction): await interaction.response.defer() file = self.attachment ext = os.path.splitext(file.filename)[1].lower() job_id = f"{interaction.user.id}_{int(time.time())}" input_path = os.path.join(TRANSLATE_WORK_DIR, f"{job_id}{ext}") await file.save(input_path) queue = _load_json_list(TRANSLATE_QUEUE_FILE) queue.append({ "job_id": job_id, "user_id": interaction.user.id, "channel_id": interaction.channel_id, "filename": file.filename, "input_path": input_path, "engine": self.engine, "api_key": self.api_key.value, "prompt": self.prompt.value, "target_lang": self.target_lang.value, "source_lang": self.source_lang.value, "game_format": interaction.channel.name.split("-")[1] if "-" in interaction.channel.name else "auto" }) _save_json_list(TRANSLATE_QUEUE_FILE, queue) await interaction.followup.send( f"⏳ Đã đưa file `{file.filename}` vào hàng đợi dịch bằng **{self.engine.capitalize()}** (Ngôn ngữ: {self.target_lang.value})! Vui lòng chờ tôi một lát...", view=CancelJobView(job_id, input_path) ) class EngineSelectView(discord.ui.View): def __init__(self, attachment: discord.Attachment): super().__init__(timeout=300) self.attachment = attachment @discord.ui.select(placeholder="Chọn Công Cụ Dịch Thuật", options=[ discord.SelectOption(label="Google Translate", value="google", description="Miễn phí, không cần key"), discord.SelectOption(label="OpenAI (GPT-4o-mini)", value="openai", description="Cần API Key"), discord.SelectOption(label="Gemini (Google)", value="gemini", description="Cần API Key"), discord.SelectOption(label="Claude (Anthropic)", value="claude", description="Cần API Key"), discord.SelectOption(label="Grok (xAI)", value="grok", description="Cần API Key"), ]) async def select_engine(self, interaction: discord.Interaction, select: discord.ui.Select): engine = select.values[0] if engine == "google": await interaction.response.send_modal(GoogleTranslateModal(self.attachment, engine)) else: await interaction.response.send_modal(APIKeyModal(self.attachment, engine)) class SetupDichView(discord.ui.View): def __init__(self): super().__init__(timeout=None) @discord.ui.select( placeholder="Mở Phòng Dịch: Chọn Định Dạng Game", custom_id="open_translate_ticket", options=[ discord.SelectOption(label="Tự Động (Auto Detect)", value="auto", description="Tự động nhận diện định dạng file", emoji="🤖"), discord.SelectOption(label="Capcom (RE Engine)", value="capcom", description="Hỗ trợ file RE Engine", emoji="🦖"), discord.SelectOption(label="Ubisoft", value="ubisoft", description="Sắp ra mắt", emoji="🗡️"), discord.SelectOption(label="Unity / Unreal", value="unity", description="Sắp ra mắt", emoji="🎮") ] ) async def select_format(self, interaction: discord.Interaction, select: discord.ui.Select): game_format = select.values[0] guild = interaction.guild category = interaction.channel.category if not category: try: category = await guild.create_category("DỊCH THUẬT GAME") except discord.Forbidden: await interaction.response.send_message("❌ Bot không có quyền tạo danh mục.", ephemeral=True) return safe_name = "".join([c for c in interaction.user.name.lower() if c.isalnum()]) channel_name = f"dich-{game_format}-{safe_name}" # Check if user already has a ticket existing_channel = discord.utils.get(guild.text_channels, name=channel_name) if existing_channel: await interaction.response.send_message(f"✅ Bạn đã có một phòng dịch đang mở: {existing_channel.mention}", ephemeral=True) return overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True), guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True) } try: ticket_channel = await guild.create_text_channel( name=channel_name, category=category, overwrites=overwrites, topic=f"Phòng dịch {game_format.upper()} của {interaction.user.name}. Đóng bằng nút bên dưới." ) embed = discord.Embed( title=f"🎫 Phòng Dịch {game_format.upper()} Riêng Tư", description=f"Chào <@{interaction.user.id}>!\n\n" "Để bắt đầu dịch, bạn chỉ cần **KÉO THẢ FILE** (.zip, .json, .txt, .xml, .csv) vào kênh này.\n" "Sau đó một menu sẽ hiện ra để bạn chọn công cụ dịch!\n\n" "Khi hoàn tất, hãy bấm nút bên dưới để đóng kênh này.", color=0x2ECC71 ) await ticket_channel.send(content=f"<@{interaction.user.id}>", embed=embed, view=CloseTicketView()) await interaction.response.send_message(f"✅ Đã tạo phòng dịch cho bạn: {ticket_channel.mention}", ephemeral=True) except Exception as e: await interaction.response.send_message(f"❌ Lỗi khi tạo phòng: {e}", ephemeral=True) @discord.ui.button(label="Làm Mới Panel", style=discord.ButtonStyle.secondary, custom_id="refresh_panel", emoji="🔄", row=1) async def refresh_panel(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message("✅ Panel đã được làm mới! Hãy dùng menu bên trên để chọn định dạng game.", ephemeral=True) @bot.tree.command(name="setup_dich", description="[Admin] Tạo bảng điều khiển ticket dịch thuật") @app_commands.default_permissions(administrator=True) async def setup_dich_cmd(interaction: discord.Interaction): embed = discord.Embed( title="🌐 HỆ THỐNG VIỆT HOÁ GAME", description="""Chào mừng bạn đến với công cụ dịch thuật tự động! Hệ thống hỗ trợ dịch các file ngôn ngữ game (`.zip, .json, .xml, .csv, .txt`) với các AI hàng đầu (Google, OpenAI, Gemini, Claude). Bấm vào nút bên dưới để mở một **Phòng Kín Riêng Tư**. Chỉ có bạn và Bot nhìn thấy nội dung bạn gửi, hoàn toàn bảo mật và an toàn!""", color=0x2b2d31 ) embed.set_image(url="attachment://panel_image.png") await interaction.response.send_message("Đang tạo bảng điều khiển...", ephemeral=True) import os if os.path.exists("panel_image.png"): file = discord.File("panel_image.png", filename="panel_image.png") await interaction.channel.send(file=file, embed=embed, view=SetupDichView()) else: await interaction.channel.send(embed=embed, view=SetupDichView()) # ───────────────────────────────────────── # /DỊCH COMMAND (Việt Hoá) # ───────────────────────────────────────── @bot.tree.command(name="dich", description="Dịch file ngôn ngữ game sang Tiếng Việt (hỗ trợ AI)") @app_commands.describe( file="File cần dịch (.zip, .txt, .json, .xml, .csv)", engine="Công cụ dịch thuật", api_key="API Key (bắt buộc nếu dùng AI, bỏ trống nếu dùng Google)", prompt="Hướng dẫn thêm cho AI (tuỳ chọn)" ) @app_commands.choices(engine=[ app_commands.Choice(name="Google Translate (Miễn phí)", value="google"), app_commands.Choice(name="OpenAI (GPT-4o-mini)", value="openai"), app_commands.Choice(name="Gemini (Google)", value="gemini"), app_commands.Choice(name="Claude (Anthropic)", value="claude"), app_commands.Choice(name="Grok (xAI)", value="grok") ]) async def dich_cmd(interaction: discord.Interaction, file: discord.Attachment, engine: app_commands.Choice[str], api_key: str = "", prompt: str = ""): engine_val = engine.value if engine_val != "google" and not api_key: await interaction.response.send_message("❌ **Lỗi:** Bạn phải nhập `api_key` nếu chọn công cụ AI!", ephemeral=True) return ext = os.path.splitext(file.filename)[1].lower() if ext not in translator.SUPPORTED_EXTS and ext != ".zip": await interaction.response.send_message("❌ **Lỗi:** Chỉ hỗ trợ file `.zip`, `.txt`, `.json`, `.xml`, `.csv`", ephemeral=True) return if file.size > 25 * 1024 * 1024: await interaction.response.send_message("❌ **Lỗi:** File quá lớn! Vui lòng gửi file dưới 25MB.", ephemeral=True) return await interaction.response.defer(ephemeral=False) # Save file to work dir job_id = f"{interaction.user.id}_{int(time.time())}" input_path = os.path.join(TRANSLATE_WORK_DIR, f"{job_id}{ext}") await file.save(input_path) # Add to queue queue = _load_json_list(TRANSLATE_QUEUE_FILE) queue.append({ "job_id": job_id, "user_id": interaction.user.id, "channel_id": interaction.channel_id, "filename": file.filename, "input_path": input_path, "engine": engine_val, "api_key": api_key, "prompt": prompt }) _save_json_list(TRANSLATE_QUEUE_FILE, queue) await interaction.followup.send(f"✅ Đã đưa file `{file.filename}` vào hàng đợi dịch thuật bằng **{engine.name}**.\n⏳ Vui lòng chờ, tôi sẽ tag bạn khi hoàn tất!") get_lua_cmd.autocomplete("appid")(_get_autocomplete) get_manifest_cmd.autocomplete("appid")(_get_autocomplete) get_all_cmd.autocomplete("appid")(_get_autocomplete) get_generate_cmd.autocomplete("appid")(_get_autocomplete) get_status_cmd.autocomplete("appid")(_get_autocomplete) gen_game_cmd.autocomplete("appid")(_get_autocomplete) gen_lua_cmd.autocomplete("appid")(_get_autocomplete) gen_manifest_cmd.autocomplete("appid")(_get_autocomplete) bot.tree.add_command(gen_group) bot.tree.add_command(get_group) # ───────────────────────────────────────── # STATE MANAGEMENT (Scanner & Announcer) # ───────────────────────────────────────── DATA_DIR = os.path.join(os.path.dirname(__file__), "data") KNOWN_GAMES_FILE = os.path.join(DATA_DIR, "known_games.json") ANNOUNCE_QUEUE_FILE = os.path.join(DATA_DIR, "announce_queue.json") TRANSLATE_QUEUE_FILE = os.path.join(DATA_DIR, "translate_queue.json") TRANSLATE_WORK_DIR = os.path.join(DATA_DIR, "translate_work") os.makedirs(DATA_DIR, exist_ok=True) os.makedirs(TRANSLATE_WORK_DIR, exist_ok=True) def _load_json_list(filepath: str) -> list: try: if os.path.exists(filepath): with open(filepath, "r") as f: return json.load(f) except: pass return [] def _save_json_list(filepath: str, data: list): os.makedirs(os.path.dirname(filepath), exist_ok=True) with open(filepath, "w") as f: json.dump(data, f, indent=4) def _add_to_announce_queue(appid: str): appid_str = str(appid) known = _load_json_list(KNOWN_GAMES_FILE) if appid_str not in known: known.append(appid_str) _save_json_list(KNOWN_GAMES_FILE, known) queue = _load_json_list(ANNOUNCE_QUEUE_FILE) if appid_str not in queue: queue.append(appid_str) _save_json_list(ANNOUNCE_QUEUE_FILE, queue) # ───────────────────────────────────────── # BACKGROUND TASKS # ───────────────────────────────────────── @tasks.loop(minutes=15) async def hf_scanner_task(): try: url = f"https://huggingface.co/api/datasets/{HF_REPO}/tree/main/{HF_SUBFOLDER.replace(' ', '%20')}" headers = {"Authorization": f"Bearer {HF_TOKEN}"} async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as r: if r.status != 200: return data = await r.json() current_appids = [] for item in data: if item.get("type") == "file" and item.get("path", "").endswith(".zip"): filename = item["path"].split("/")[-1] appid = filename.replace(".zip", "") if appid.isdigit(): current_appids.append(appid) if not os.path.exists(KNOWN_GAMES_FILE): _save_json_list(KNOWN_GAMES_FILE, current_appids) print(f"[SCANNER] Lần chạy đầu tiên: Đã nạp {len(current_appids)} games.") return known_games = _load_json_list(KNOWN_GAMES_FILE) queue = _load_json_list(ANNOUNCE_QUEUE_FILE) new_count = 0 for appid in current_appids: if appid not in known_games: known_games.append(appid) if appid not in queue: queue.append(appid) new_count += 1 if new_count > 0: _save_json_list(KNOWN_GAMES_FILE, known_games) _save_json_list(ANNOUNCE_QUEUE_FILE, queue) print(f"[SCANNER] Đã thêm {new_count} games mới vào hàng đợi.") except Exception as e: print(f"[SCANNER] Lỗi khi quét HF: {e}") @tasks.loop(seconds=40) async def announcer_task(): try: queue = _load_json_list(ANNOUNCE_QUEUE_FILE) if not queue: return appid = queue[0] channel = bot.get_channel(1509974925127979008) if channel: async with aiohttp.ClientSession() as session: details = await steam_app_details(session, appid) review_desc, review_count = await steam_reviews(session, appid) if details: game_name = details.get("name", f"App {appid}") developers = ", ".join(details.get("developers", ["N/A"])) header_image = details.get("header_image", "") else: game_name = f"App {appid}" developers = "N/A" header_image = "" review_str = f"{review_count:,} user reviews ({review_desc})" if review_count > 0 else "No reviews" from datetime import datetime today = datetime.now().strftime("%Y-%m-%d") embed = discord.Embed( title=f"{game_name} ({appid}) Added", description=f"**Links**\n[Steam Store](https://store.steampowered.com/app/{appid}/) | [SteamDB](https://steamdb.info/app/{appid}/)", color=0x2b2d31 ) embed.add_field(name="Developer", value=developers, inline=True) embed.add_field(name="Reviews", value=review_str, inline=True) if header_image: embed.set_image(url=header_image) embed.set_footer(text=f"Upload date: {today} • Updated date: {today}") await channel.send(embed=embed) print(f"[ANNOUNCER] Đã gửi thông báo cho {appid}") queue.pop(0) _save_json_list(ANNOUNCE_QUEUE_FILE, queue) except Exception as e: print(f"[ANNOUNCER] Lỗi: {e}") async def delete_hf_file_later(path_in_repo: str, delay: int = 1800): await asyncio.sleep(delay) try: def _delete(): from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) api.delete_file(path_in_repo=path_in_repo, repo_id=HF_REPO, repo_type="dataset") await asyncio.to_thread(_delete) print(f"[HF] Đã xoá file tạm thời: {path_in_repo}") except Exception as e: print(f"[HF] Lỗi xoá file tạm thời {path_in_repo}: {e}") @tasks.loop(seconds=15) async def translator_task(): try: queue = _load_json_list(TRANSLATE_QUEUE_FILE) if not queue: return job = queue[0] job_id = job["job_id"] user_id = job["user_id"] channel_id = job["channel_id"] filename = job["filename"] input_path = job["input_path"] engine = job["engine"] api_key = job["api_key"] prompt = job.get("prompt", "") target_lang = job.get("target_lang", "vi") source_lang = job.get("source_lang", "English") game_format = job.get("game_format", "auto") channel = bot.get_channel(channel_id) if not channel: queue.pop(0) _save_json_list(TRANSLATE_QUEUE_FILE, queue) return print(f"[TRANSLATOR] Bắt đầu xử lý {job_id}") output_zip = os.path.join(TRANSLATE_WORK_DIR, f"translated_{job_id}.zip") target_channel = channel # Gửi kết quả vào đúng kênh ticket của user user = bot.get_user(user_id) try: await translator.process_translation_job(input_path, output_zip, engine, api_key, target_lang, prompt, game_format, source_lang) embed = discord.Embed( title="🎉 Hoàn Tất Dịch Thuật", description=f"File `{filename}` của bạn đã được dịch xong!", color=0x00c851 ) embed.add_field(name="Engine", value=engine.capitalize(), inline=True) # Chuẩn bị tin nhắn msg_kwargs = {} if os.path.exists(output_zip): size = os.path.getsize(output_zip) if size <= 10 * 1024 * 1024: msg_kwargs = {"embed": embed, "file": discord.File(output_zip, filename=f"viethoa_{filename}.zip")} else: embed.description += "\n\n⚠️ **Lưu ý:** File của bạn lớn hơn 10MB nên tôi đang đẩy nó lên máy chủ đám mây..." # Cập nhật thông báo tạm thời temp_msg = None try: if user: temp_msg = await user.send(embed=embed) except: if target_channel: temp_msg = await target_channel.send(content=f"<@{user_id}>", embed=embed) # Upload to HF hf_path = f"temp_translations/{job_id}_viethoa_{filename}.zip" with open(output_zip, "rb") as f: file_bytes = f.read() def _do_upload(): return _hf_upload(file_bytes, hf_path) success = await asyncio.to_thread(_do_upload) if success: long_link = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{hf_path}?download=true" dl_link = await shortener.create_internal_shortlink(long_link) embed.description = f"File `{filename}` của bạn đã được dịch xong!\n\n🔗 [**BẤM VÀO ĐÂY ĐỂ TẢI FILE**]({dl_link})\n\n⏳ *Lưu ý: Do dung lượng file lớn (>10MB), file này được lưu trên máy chủ đám mây và sẽ **tự động bị xoá vĩnh viễn sau 30 phút** để bảo vệ dữ liệu của bạn. Hãy tải ngay nhé!*" bot.loop.create_task(delete_hf_file_later(hf_path, 1800)) else: embed.title = "⚠️ Lỗi Upload" embed.description = "File dịch xong nhưng đẩy lên đám mây thất bại. Hãy thử với file nhỏ hơn." embed.color = 0xffbb33 # Edit the temporary message with the final link if temp_msg: await temp_msg.edit(embed=embed) msg_kwargs = None # Skip sending below else: embed.title = "⚠️ Lỗi Đầu Ra" embed.description = f"Đã dịch xong file `{filename}` nhưng không tìm thấy file zip đầu ra." embed.color = 0xffbb33 msg_kwargs = {"embed": embed} # Thử gửi DM trước if msg_kwargs: try: if user: await user.send(**msg_kwargs) if target_channel: await target_channel.send(f"✅ Đã gửi file dịch `{filename}` qua Tin Nhắn Riêng (DM) cho <@{user_id}>.") else: raise Exception("Không lấy được user object") except: # Nếu không thể DM, gửi vào kênh chỉ định if target_channel: msg_kwargs["content"] = f"<@{user_id}>" await target_channel.send(**msg_kwargs) except Exception as e: print(f"[TRANSLATOR] Lỗi khi dịch: {e}") err_embed = discord.Embed(title="❌ Lỗi Dịch Thuật", description=f"Đã xảy ra lỗi khi dịch file `{filename}`:\n```\n{e}\n```", color=0xff4444) if target_channel: await target_channel.send(content=f"<@{user_id}>", embed=err_embed) finally: if os.path.exists(input_path): os.remove(input_path) if os.path.exists(output_zip): os.remove(output_zip) queue.pop(0) _save_json_list(TRANSLATE_QUEUE_FILE, queue) print(f"[TRANSLATOR] Xong {job_id}") except Exception as e: print(f"[TRANSLATOR] Lỗi vòng lặp: {e}") @hf_scanner_task.before_loop async def before_scanner(): await bot.wait_until_ready() @announcer_task.before_loop async def before_announcer(): await bot.wait_until_ready() @bot.event async def on_message(message: discord.Message): if message.author.bot: return if message.channel.name.startswith("dich-") and message.attachments: file = message.attachments[0] ext = os.path.splitext(file.filename)[1].lower() if ext in translator.SUPPORTED_EXTS or ext == ".zip": if file.size > 10 * 1024 * 1024: await message.channel.send("❌ File quá lớn! Vui lòng gửi file dưới 10MB.") return # Anti-spam: Kiểm tra xem user này đã có job trong queue chưa queue = _load_json_list(TRANSLATE_QUEUE_FILE) if any(job.get("user_id") == message.author.id for job in queue): await message.channel.send("⚠️ **Cảnh báo Spam:** Bạn đang có 1 file trong hàng đợi dịch thuật! Vui lòng chờ file đó hoàn tất trước khi gửi thêm.") return await message.channel.send(f"✅ Đã nhận file `{file.filename}`. Vui lòng chọn Công cụ dịch thuật bên dưới:", view=EngineSelectView(file)) return await bot.process_commands(message) if __name__ == "__main__": _log_startup_config() if not TOKEN: raise SystemExit("Missing Discord bot token env. Supported names: DISCORD_BOT_TOKEN, BOT_TOKEN, TOKEN.") try: bot.run(TOKEN) except Exception: print("[Startup] bot.run failed:", flush=True) traceback.print_exc() raise