import asyncio import time import logging import aiohttp from aiohttp import web from khl import Bot, Message from khl.card import CardMessage, Card, Module, Element, Types from huggingface_hub import HfApi from core.config import BOT_TOKEN, SPACE_ID from core.database import db from services.data_manager import data_mgr from utils.cs2_logic import generate_random_case_drops, prewarm_price_index from utils.card_builder import build_open_case_card, build_help_card, build_me_card from utils.rate_limiter import rate_limiter logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) _hf_api = HfApi() bot = Bot(token=BOT_TOKEN) _start_time = time.monotonic() try: import psutil as _psutil except Exception: _psutil = None @bot.command(name='help', prefixes=['/']) async def show_help(msg: Message): await msg.reply(CardMessage(build_help_card())) @bot.command(name='open', prefixes=['/']) async def handle_open(msg: Message, *args): is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "cs2_open", 2.0) if is_limited: return await msg.reply(f"❌ 别点太快!冷却剩余 {remaining} 秒...") if not data_mgr.is_price_ready: return await msg.reply("⏳ 系统正在同步最新价格,请稍后再试...") count = max(1, min(10, int(args[0]))) if args and args[0].isdigit() else 1 try: items, cost, earned = generate_random_case_drops( count, data_mgr.affordable_cases, data_mgr.affordable_capsules, data_mgr.price_cn_map, data_mgr.price_dict ) profit = earned - cost user_id, name = str(msg.author.id), msg.author.username upd = await db.eco.find_one_and_update( {"_id": user_id}, {"$set": {"name": name}, "$inc": {"spent": cost, "earned": earned, "profit": profit, "opens": count}}, upsert=True, return_document=True ) card = build_open_case_card( count, items, profit, upd['profit'], upd['opens'], cost, earned, name ) await msg.reply(CardMessage(card)) except Exception as e: logger.error(f"[Open] 异常: {e}", exc_info=True) await msg.reply("❌ 计算引擎意外终止。") @bot.command(name='me', prefixes=['/']) async def handle_me(msg: Message): user_id = str(msg.author.id) doc = await db.eco.find_one({"_id": user_id}) if not doc: return await msg.reply("📭 你还没开过箱!输入 /open 开始吧。") card = build_me_card( doc.get('name', msg.author.username), doc.get('profit', 0), doc.get('spent', 0), doc.get('earned', 0), doc.get('opens', 0) ) await msg.reply(CardMessage(card)) @bot.command(name='status', prefixes=['/']) async def handle_status(msg: Message): uptime = int(time.time() - _start_time) h, m = uptime // 3600, (uptime % 3600) // 60 space_info = "未知" try: runtime = _hf_api.get_space_runtime(SPACE_ID) stage = runtime.stage hw = runtime.hardware if runtime.hardware else "?" space_info = f"{stage} ({hw})" except Exception: pass cpu_str = "N/A" if _psutil is not None: try: cpu_str = f"{(await asyncio.to_thread(_psutil.cpu_percent, interval=0.3))}%" except Exception: pass total_opens = 0 total_users = 0 db_status = "✅ 在线" try: # 聚合管道:一次查询完成统计,避免两次全表扫描 pipeline = [ {"$group": { "_id": None, "total_opens": {"$sum": "$opens"}, "total_users": {"$sum": 1} }} ] async for agg in db.eco.aggregate(pipeline): total_opens = agg.get('total_opens', 0) total_users = agg.get('total_users', 0) except Exception: db_status = "❌ 异常" lines = [ f"**Space**:{space_info}", f"**运行时长**:{h}小时{m}分", f"**CPU**:{cpu_str}", f"**MongoDB**:{db_status}", f"**用户数**:{total_users} 人", f"**武器箱**:{len(data_mgr.affordable_cases)} 个", f"**价格**:{len(data_mgr.price_dict)} 条", f"**总开箱**:{total_opens} 次", ] card = Card(color="#4B69FF") card.append(Module.Header("📊 系统状态")) card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD))) await msg.reply(CardMessage(card)) async def health_check(request): return web.json_response({ "status": "ok", "database": "connected" if db.client else "disconnected" }) async def main(): db_ok = await db.connect() if not db_ok: logger.error("[System] MongoDB 连接失败,请检查 MONGO_URI") return session = aiohttp.ClientSession() try: await data_mgr.init_crates_data(session) # 预热价格索引,消除首次 /open 冷启动延迟 prewarm_price_index(data_mgr.price_dict) webapp = web.Application() webapp.router.add_get('/health', health_check) runner = web.AppRunner(webapp) await runner.setup() await web.TCPSite(runner, '0.0.0.0', 7860).start() logger.info("[init] MongoDB 版已上线 (%d cases, %d capsules)", len(data_mgr.affordable_cases), len(data_mgr.affordable_capsules)) await bot.start() finally: await session.close() if __name__ == '__main__': asyncio.run(main())