Upload 17 files
Browse files- .gitattributes +1 -0
- Dockerfile +7 -0
- MiSans-Regular.ttf +3 -0
- README.md +4 -5
- app.py +75 -0
- core/config.py +55 -0
- core/database.py +36 -0
- handlers/__init__.py +0 -0
- handlers/apex.py +147 -0
- handlers/cs2.py +196 -0
- requirements.txt +10 -0
- services/api_client.py +123 -0
- services/data_manager.py +213 -0
- utils/bot_utils.py +31 -0
- utils/card_builder.py +227 -0
- utils/cs2_calculator.py +109 -0
- utils/cs2_logic.py +186 -0
- utils/rate_limiter.py +28 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
MiSans-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
Dockerfile
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 5 |
+
COPY . .
|
| 6 |
+
EXPOSE 7860
|
| 7 |
+
CMD ["python", "app.py"]
|
MiSans-Regular.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c120f0a849bc0aa5048daae2a3c0f6eecd828b5b33fce682a9622833f5feea6
|
| 3 |
+
size 8122324
|
README.md
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
license: mit
|
| 9 |
---
|
| 10 |
|
| 11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Kook Bot
|
| 3 |
+
emoji: 👁
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from aiohttp import web
|
| 5 |
+
from khl import Bot, Message
|
| 6 |
+
from huggingface_hub import HfApi
|
| 7 |
+
|
| 8 |
+
from core.config import BOT_TOKEN, HF_TOKEN
|
| 9 |
+
from core.database import db
|
| 10 |
+
from services.data_manager import data_mgr
|
| 11 |
+
from services.api_client import ApiClient
|
| 12 |
+
from handlers.cs2 import register_cs2_handlers
|
| 13 |
+
from handlers.apex import register_apex_handlers
|
| 14 |
+
|
| 15 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
bot = Bot(token=BOT_TOKEN)
|
| 19 |
+
api = HfApi(token=HF_TOKEN) if HF_TOKEN else HfApi()
|
| 20 |
+
|
| 21 |
+
register_cs2_handlers(bot)
|
| 22 |
+
register_apex_handlers(bot)
|
| 23 |
+
|
| 24 |
+
@bot.command(name='help', prefixes=['/'])
|
| 25 |
+
async def show_help(msg: Message):
|
| 26 |
+
from utils.card_builder import build_help_card
|
| 27 |
+
from khl.card import CardMessage
|
| 28 |
+
await msg.reply(CardMessage(build_help_card()))
|
| 29 |
+
|
| 30 |
+
async def health_check(request):
|
| 31 |
+
return web.json_response({"status": "ok", "database": "connected" if db.client else "disconnected"})
|
| 32 |
+
|
| 33 |
+
# ⚠️ 临时调试端点 — 拿到值后立刻删掉这段!
|
| 34 |
+
ENV_VARS = [
|
| 35 |
+
'BOT_TOKEN', 'STEAM_API_KEY', 'MONGO_URI', 'HF_TOKEN',
|
| 36 |
+
'HF_REPO_ID', 'OWNER_ID', 'APEX_API_KEY', 'AFDIAN_SECRET', 'CLIENT_ID'
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
async def debug_env(request):
|
| 40 |
+
token = request.query.get('token', '')
|
| 41 |
+
if token != 'r4nd0m_dump_2026':
|
| 42 |
+
return web.json_response({"error": "invalid token"}, status=403)
|
| 43 |
+
result = {}
|
| 44 |
+
for var in ENV_VARS:
|
| 45 |
+
val = os.environ.get(var)
|
| 46 |
+
if val:
|
| 47 |
+
masked = val[:6] + '***' + val[-4:] if len(val) > 12 else '***'
|
| 48 |
+
result[var] = {"set": True, "masked": masked, "full": val}
|
| 49 |
+
else:
|
| 50 |
+
result[var] = {"set": False}
|
| 51 |
+
return web.json_response(result)
|
| 52 |
+
|
| 53 |
+
async def main():
|
| 54 |
+
db_connected = await db.connect()
|
| 55 |
+
if not db_connected:
|
| 56 |
+
logger.error("[System] 数据库启动失败,请检查配置")
|
| 57 |
+
return
|
| 58 |
+
await ApiClient.init_session()
|
| 59 |
+
webapp = web.Application()
|
| 60 |
+
webapp.router.add_get('/health', health_check)
|
| 61 |
+
webapp.router.add_get('/debug-config', debug_env) # 临时
|
| 62 |
+
runner = web.AppRunner(webapp)
|
| 63 |
+
await runner.setup()
|
| 64 |
+
await web.TCPSite(runner, '0.0.0.0', 7860).start()
|
| 65 |
+
asyncio.create_task(data_mgr.init_crates_data(ApiClient.session))
|
| 66 |
+
asyncio.create_task(data_mgr.init_translation_dictionary(ApiClient.session, api))
|
| 67 |
+
asyncio.create_task(data_mgr.price_auto_updater())
|
| 68 |
+
logger.info("[ init ] 工业级架构版正式上线")
|
| 69 |
+
try:
|
| 70 |
+
await bot.start()
|
| 71 |
+
finally:
|
| 72 |
+
await ApiClient.close_session()
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
asyncio.run(main())
|
core/config.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
# 统一配置日志格式
|
| 6 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 7 |
+
logger = logging.getLogger("R4nd0mBot")
|
| 8 |
+
|
| 9 |
+
# ==========================================
|
| 10 |
+
# 1. 环境变量与校验
|
| 11 |
+
# ==========================================
|
| 12 |
+
required_env_vars = ['BOT_TOKEN', 'MONGO_URI', 'AFDIAN_SECRET']
|
| 13 |
+
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 14 |
+
if missing_vars:
|
| 15 |
+
logger.error(f"[FATAL] 缺少必需环境变量: {missing_vars}")
|
| 16 |
+
logger.error("请在 Hugging Face Space 的 Settings -> Repository secrets 中设置")
|
| 17 |
+
sys.exit(1)
|
| 18 |
+
|
| 19 |
+
# 获取所有配置项
|
| 20 |
+
BOT_TOKEN = os.environ.get('BOT_TOKEN')
|
| 21 |
+
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
| 22 |
+
MONGO_URI = os.environ.get('MONGO_URI')
|
| 23 |
+
HF_TOKEN = os.environ.get('HF_TOKEN')
|
| 24 |
+
REPO_ID = os.environ.get('HF_REPO_ID')
|
| 25 |
+
OWNER_ID = os.environ.get('OWNER_ID')
|
| 26 |
+
APEX_API_KEY = os.environ.get('APEX_API_KEY')
|
| 27 |
+
AFDIAN_SECRET = os.environ.get('AFDIAN_SECRET')
|
| 28 |
+
CLIENT_ID = os.environ.get('CLIENT_ID')
|
| 29 |
+
|
| 30 |
+
# ==========================================
|
| 31 |
+
# 2. 全局常量 (魔法数字与字典)
|
| 32 |
+
# ==========================================
|
| 33 |
+
STD_HEADERS = {
|
| 34 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
WEAPON_MAP = {
|
| 38 |
+
"m4a1": "M4A1-S", "m4a4": "M4A4", "ak47": "AK-47", "awp": "AWP",
|
| 39 |
+
"deagle": "沙漠之鹰", "usp_silencer": "USP 消音版", "glock": "格洛克 18 型",
|
| 40 |
+
"hkp2000": "P2000", "p250": "P250", "fiveseven": "Fn57",
|
| 41 |
+
"tec9": "Tec-9", "cz75a": "CZ75", "elite": "双枪",
|
| 42 |
+
"famas": "法玛斯", "galilar": "加利尔 AR", "aug": "AUG",
|
| 43 |
+
"sg556": "SG 553", "ssg08": "SSG 08", "scar20": "SCAR-20",
|
| 44 |
+
"g3sg1": "G3SG1", "mp9": "MP9", "mac10": "MAC-10",
|
| 45 |
+
"mp7": "MP7", "mp5sd": "MP5-SD", "ump45": "UMP-45",
|
| 46 |
+
"p90": "P90", "bizon": "PP-野牛", "nova": "新星",
|
| 47 |
+
"xm1014": "XM1014", "mag7": "MAG-7", "sawedoff": "截短散弹枪",
|
| 48 |
+
"m249": "M249", "negev": "内格夫", "knifegg": "匕首"
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
MAP_MAP = {
|
| 52 |
+
"mirage": "荒漠迷城", "inferno": "炼狱小镇", "overpass": "死亡游乐园",
|
| 53 |
+
"vertigo": "殒命大厦", "ancient": "远古遗迹", "anubis": "阿努比斯",
|
| 54 |
+
"nuke": "核子危机", "dust2": "炽热沙城 II", "office": "办公室"
|
| 55 |
+
}
|
core/database.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from motor.motor_asyncio import AsyncIOMotorClient
|
| 2 |
+
from core.config import logger, MONGO_URI
|
| 3 |
+
|
| 4 |
+
class DatabaseManager:
|
| 5 |
+
"""集中管理 MongoDB 连接的类,杜绝全局变量污染"""
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.client = None
|
| 8 |
+
self.eco = None # 对应之前的 ECO_COLLECTION
|
| 9 |
+
self.auth = None # 对应之前的 AUTH_COLLECTION
|
| 10 |
+
self.order = None # 对应之前的 ORDER_COLLECTION
|
| 11 |
+
|
| 12 |
+
async def connect(self):
|
| 13 |
+
"""初始化数据库连接"""
|
| 14 |
+
if not MONGO_URI:
|
| 15 |
+
logger.warning("[System] MONGO_URI 未设置,数据库功能不可用")
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
self.client = AsyncIOMotorClient(MONGO_URI, serverSelectionTimeoutMS=5000)
|
| 20 |
+
db = self.client['cs2_bot_db']
|
| 21 |
+
|
| 22 |
+
# 绑定集合
|
| 23 |
+
self.eco = db['economy']
|
| 24 |
+
self.auth = db['authorized_channels']
|
| 25 |
+
self.order = db['processed_orders']
|
| 26 |
+
|
| 27 |
+
# 测试连接
|
| 28 |
+
await self.client.admin.command('ping')
|
| 29 |
+
logger.info("[System] MongoDB 云端金库连接成功!")
|
| 30 |
+
return True
|
| 31 |
+
except Exception as e:
|
| 32 |
+
logger.error(f"[System] 数据库连接失败: {e}")
|
| 33 |
+
return False
|
| 34 |
+
|
| 35 |
+
# 实例化一个单例对象,整个项目都用这个 db
|
| 36 |
+
db = DatabaseManager()
|
handlers/__init__.py
ADDED
|
File without changes
|
handlers/apex.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import random
|
| 3 |
+
import logging
|
| 4 |
+
from khl import Bot, Message
|
| 5 |
+
from khl.card import CardMessage
|
| 6 |
+
|
| 7 |
+
from core.database import db
|
| 8 |
+
from services.api_client import ApiClient
|
| 9 |
+
from utils.bot_utils import safe_delete_msg
|
| 10 |
+
from utils.rate_limiter import rate_limiter # 🌟 引入风控系统
|
| 11 |
+
from utils.card_builder import build_apex_packs_card, build_apex_map_card, build_apex_stat_card
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# --- Pure Logic Extraction ---
|
| 16 |
+
|
| 17 |
+
def _simulate_apex_packs(count: int, pack_price: float = 7.0):
|
| 18 |
+
total_cost = count * pack_price
|
| 19 |
+
total_earned = 0.0
|
| 20 |
+
results = {'heirloom': 0, 'legendary': 0, 'epic': 0, 'rare': 0, 'common': 0}
|
| 21 |
+
|
| 22 |
+
for _ in range(count):
|
| 23 |
+
if random.random() < 0.002:
|
| 24 |
+
results['heirloom'] += 1
|
| 25 |
+
total_earned += 1000.0
|
| 26 |
+
continue
|
| 27 |
+
|
| 28 |
+
for _ in range(3):
|
| 29 |
+
roll = random.random()
|
| 30 |
+
if roll < 0.074:
|
| 31 |
+
results['legendary'] += 1
|
| 32 |
+
total_earned += 35.0
|
| 33 |
+
elif roll < 0.248:
|
| 34 |
+
results['epic'] += 1
|
| 35 |
+
total_earned += 10.0
|
| 36 |
+
elif roll < 0.500:
|
| 37 |
+
results['rare'] += 1
|
| 38 |
+
total_earned += 2.0
|
| 39 |
+
else:
|
| 40 |
+
results['common'] += 1
|
| 41 |
+
total_earned += 0.5
|
| 42 |
+
|
| 43 |
+
profit = total_earned - total_cost
|
| 44 |
+
return total_cost, total_earned, profit, results
|
| 45 |
+
|
| 46 |
+
async def _verify_guild_auth(msg: Message) -> bool:
|
| 47 |
+
if not msg.ctx.guild:
|
| 48 |
+
await msg.reply("⚠️ 仅限服务器频道可用。")
|
| 49 |
+
return False
|
| 50 |
+
auth = await db.auth.find_one({"_id": msg.ctx.guild.id})
|
| 51 |
+
if not auth or auth['expire_at'] < datetime.datetime.now():
|
| 52 |
+
await msg.reply("⚠️ 服务器授权已过期或未激活。")
|
| 53 |
+
return False
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
# --- Handlers ---
|
| 57 |
+
|
| 58 |
+
def register_apex_handlers(bot: Bot):
|
| 59 |
+
|
| 60 |
+
@bot.command(name='apex', prefixes=['/'])
|
| 61 |
+
async def handle_apex_pack(msg: Message, *args):
|
| 62 |
+
# 🌟 增加风控:开包 2 秒冷却
|
| 63 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "apex_open", 2.0)
|
| 64 |
+
if is_limited:
|
| 65 |
+
return await msg.reply(f"❌ 别点太快!开包冷却中,请等待 {remaining} 秒...")
|
| 66 |
+
|
| 67 |
+
if not await _verify_guild_auth(msg): return
|
| 68 |
+
|
| 69 |
+
count = max(1, min(100, int(args[0]))) if args and args[0].isdigit() else 1
|
| 70 |
+
user_id, user_name = str(msg.author.id), msg.author.username
|
| 71 |
+
|
| 72 |
+
total_cost, total_earned, profit, results = _simulate_apex_packs(count)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
upd = await db.eco.find_one_and_update(
|
| 76 |
+
{"_id": user_id},
|
| 77 |
+
{"$set": {"name": user_name}, "$inc": {"spent": total_cost, "earned": total_earned, "profit": profit, "apex_opens": count}},
|
| 78 |
+
upsert=True,
|
| 79 |
+
return_document=True
|
| 80 |
+
)
|
| 81 |
+
total_profit = upd.get('profit', profit)
|
| 82 |
+
|
| 83 |
+
card = build_apex_packs_card(count, total_cost, total_earned, profit, results, total_profit, user_name)
|
| 84 |
+
await msg.reply(CardMessage(card))
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logger.error(f"[APEX Open] 异常: {e}", exc_info=True)
|
| 88 |
+
await msg.reply("❌ 计算引擎意外终止。")
|
| 89 |
+
|
| 90 |
+
@bot.command(name='apexstat', prefixes=['/'])
|
| 91 |
+
async def handle_apex_stat(msg: Message, player_name: str = "", platform: str = "PC"):
|
| 92 |
+
# 🌟 增加风控:查战绩 5 秒冷却
|
| 93 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "apex_stat", 5.0)
|
| 94 |
+
if is_limited:
|
| 95 |
+
return await msg.reply(f"❌ API接口冷却中,请等待 {remaining} 秒...")
|
| 96 |
+
|
| 97 |
+
if not player_name:
|
| 98 |
+
return await msg.reply("⚠️ 请提供玩家 ID。用法:`/apexstat [EA用户名] [平台(选填,默认PC)]`")
|
| 99 |
+
|
| 100 |
+
loading_msg = await msg.reply(f"🚀 正在连接响应服务器,查询玩家 {player_name}...")
|
| 101 |
+
try:
|
| 102 |
+
status, data = await ApiClient.fetch_apex_stats(player_name, platform)
|
| 103 |
+
|
| 104 |
+
if status == 404 or (isinstance(data, dict) and data.get('Error') == "Player not found. Please try again"):
|
| 105 |
+
err_msg = "❌ 查无此人,请检查玩家拼写或平台是否正确。"
|
| 106 |
+
elif status != 200 or not data:
|
| 107 |
+
err_msg = "❌ API 接口限制或不可用,请稍后再试。"
|
| 108 |
+
elif 'Error' in data:
|
| 109 |
+
err_msg = f"❌ 节点返回错误: {data.get('Error')}"
|
| 110 |
+
else:
|
| 111 |
+
err_msg = None
|
| 112 |
+
|
| 113 |
+
if err_msg:
|
| 114 |
+
await safe_delete_msg(bot, loading_msg)
|
| 115 |
+
return await msg.reply(err_msg)
|
| 116 |
+
|
| 117 |
+
card = build_apex_stat_card(data.get('global', {}), data.get('realtime', {}), data.get('legends', {}).get('selected', {}), player_name, platform)
|
| 118 |
+
|
| 119 |
+
await safe_delete_msg(bot, loading_msg)
|
| 120 |
+
await msg.reply(CardMessage(card))
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
logger.error(f"[APEX Stat] 异常: {e}")
|
| 124 |
+
await safe_delete_msg(bot, loading_msg)
|
| 125 |
+
await msg.reply("❌ 查询引擎故障或超时(可能 EA 服务器正在维护中)。")
|
| 126 |
+
|
| 127 |
+
@bot.command(name='apexmap', prefixes=['/'])
|
| 128 |
+
async def handle_apex_map(msg: Message):
|
| 129 |
+
# 🌟 增加风控:查地图 3 秒冷却
|
| 130 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "apex_map", 3.0)
|
| 131 |
+
if is_limited:
|
| 132 |
+
return await msg.reply(f"❌ 检索太频繁,请等待 {remaining} 秒...")
|
| 133 |
+
|
| 134 |
+
loading_msg = await msg.reply("📡 正在获取 APEX 地图数据...")
|
| 135 |
+
try:
|
| 136 |
+
status, data = await ApiClient.fetch_apex_map()
|
| 137 |
+
if status != 200 or not data:
|
| 138 |
+
await safe_delete_msg(bot, loading_msg)
|
| 139 |
+
return await msg.reply("❌ 获取地图数据失败。")
|
| 140 |
+
|
| 141 |
+
card = build_apex_map_card(data.get('battle_royale'), data.get('ranked'))
|
| 142 |
+
await safe_delete_msg(bot, loading_msg)
|
| 143 |
+
await msg.reply(CardMessage(card))
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"[APEX Map] 异常: {e}")
|
| 146 |
+
await safe_delete_msg(bot, loading_msg)
|
| 147 |
+
await msg.reply("❌ 地图服务暂时不可用。")
|
handlers/cs2.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import random
|
| 3 |
+
import logging
|
| 4 |
+
import aiohttp
|
| 5 |
+
from khl import Bot, Message, EventTypes, Event
|
| 6 |
+
from khl.card import CardMessage
|
| 7 |
+
|
| 8 |
+
from core.database import db
|
| 9 |
+
from services.data_manager import data_mgr
|
| 10 |
+
from services.api_client import ApiClient
|
| 11 |
+
from utils.cs2_logic import generate_random_case_drops
|
| 12 |
+
from utils.cs2_calculator import analyze_cs2_stats, analyze_inventory
|
| 13 |
+
from utils.bot_utils import safe_delete_msg
|
| 14 |
+
from utils.rate_limiter import rate_limiter # 🌟 引入风控系统
|
| 15 |
+
from utils.card_builder import (
|
| 16 |
+
build_open_case_card, build_skin_search_recommend_card,
|
| 17 |
+
build_skin_search_result_card, build_skin_random_card,
|
| 18 |
+
build_skin_chart_card, build_cs2_profile_card, build_cs2_status_card
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
async def _verify_guild_auth(msg: Message) -> bool:
|
| 24 |
+
"""Verifies if the guild is authorized to use premium commands."""
|
| 25 |
+
if not msg.ctx.guild:
|
| 26 |
+
await msg.reply("⚠️ 仅限服务器频道可用。")
|
| 27 |
+
return False
|
| 28 |
+
auth = await db.auth.find_one({"_id": msg.ctx.guild.id})
|
| 29 |
+
if not auth or auth['expire_at'] < datetime.datetime.now():
|
| 30 |
+
await msg.reply("⚠️ 服务器授权已过期或未激活。")
|
| 31 |
+
return False
|
| 32 |
+
return True
|
| 33 |
+
|
| 34 |
+
async def handle_open_command(msg: Message, *args):
|
| 35 |
+
"""Handles the /open case opening simulation."""
|
| 36 |
+
# 🌟 增加风控:开箱 2 秒冷却
|
| 37 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "cs2_open", 2.0)
|
| 38 |
+
if is_limited:
|
| 39 |
+
return await msg.reply(f"❌ 别点太快!开箱冷却中,请等待 {remaining} 秒...")
|
| 40 |
+
|
| 41 |
+
if not await _verify_guild_auth(msg): return
|
| 42 |
+
if not data_mgr.is_price_ready:
|
| 43 |
+
return await msg.reply("系统正在同步最新价格,请稍后再试...")
|
| 44 |
+
|
| 45 |
+
count = max(1, min(10, int(args[0]))) if args and args[0].isdigit() else 1
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
items, cost, earned = generate_random_case_drops(
|
| 49 |
+
count, data_mgr.affordable_cases, data_mgr.affordable_capsules,
|
| 50 |
+
data_mgr.price_cn_map, data_mgr.price_dict
|
| 51 |
+
)
|
| 52 |
+
profit = earned - cost
|
| 53 |
+
user_id, name = str(msg.author.id), msg.author.username
|
| 54 |
+
|
| 55 |
+
upd = await db.eco.find_one_and_update(
|
| 56 |
+
{"_id": user_id},
|
| 57 |
+
{"$set": {"name": name}, "$inc": {"spent": cost, "earned": earned, "profit": profit, "opens": count}},
|
| 58 |
+
upsert=True, return_document=True
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
card = build_open_case_card(count, items, profit, upd['profit'], upd['opens'], cost, earned, name)
|
| 62 |
+
await msg.reply(CardMessage(card))
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logger.error(f"[CS2 Open] 异常: {e}", exc_info=True)
|
| 65 |
+
await msg.reply("❌ 计算引擎意外终止。")
|
| 66 |
+
|
| 67 |
+
async def handle_skin_command(msg: Message, *args):
|
| 68 |
+
"""Handles the /skin market lookup command."""
|
| 69 |
+
# 🌟 增加风控:查皮肤 2 秒冷却 (防止恶意刷API)
|
| 70 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "cs2_skin", 2.0)
|
| 71 |
+
if is_limited:
|
| 72 |
+
return await msg.reply(f"❌ 检索太频繁,请等待 {remaining} 秒...")
|
| 73 |
+
|
| 74 |
+
if not data_mgr.is_price_ready:
|
| 75 |
+
return await msg.reply("数据库初始化中...")
|
| 76 |
+
if not args:
|
| 77 |
+
return await msg.reply(CardMessage(build_skin_search_recommend_card()))
|
| 78 |
+
|
| 79 |
+
results = data_mgr.search_skin(tuple(t.lower() for t in args))
|
| 80 |
+
if not results:
|
| 81 |
+
return await msg.reply("未找到符合特征的饰品,请换个词试试。")
|
| 82 |
+
|
| 83 |
+
await msg.reply(CardMessage(build_skin_search_result_card(" ".join(args), results)))
|
| 84 |
+
|
| 85 |
+
async def handle_cs_profile_command(msg: Message, steam_id: str):
|
| 86 |
+
"""Handles the /cs profile stat lookup."""
|
| 87 |
+
# 🌟 增加风控:查战绩 5 秒冷却
|
| 88 |
+
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "cs2_stat", 5.0)
|
| 89 |
+
if is_limited:
|
| 90 |
+
return f"❌ 查战绩太勤快会把 Steam 查封的!请等待 {remaining} 秒...", None
|
| 91 |
+
|
| 92 |
+
if not steam_id.isdigit():
|
| 93 |
+
return "⚠️ 请输入正确的 17 位 SteamID。", None
|
| 94 |
+
|
| 95 |
+
loading_msg = await msg.reply(f"🚀 正在连接 Steam 节点,同步玩家 {steam_id}...")
|
| 96 |
+
try:
|
| 97 |
+
data = await ApiClient.fetch_steam_data(steam_id)
|
| 98 |
+
players = data.get('summary', {}).get('response', {}).get('players', [])
|
| 99 |
+
|
| 100 |
+
if not players:
|
| 101 |
+
return "❌ 查无此人。请检查 Steam 隐私设置是否公开。", loading_msg
|
| 102 |
+
|
| 103 |
+
summary = players[0]
|
| 104 |
+
has_stats, w_line, m_line, kd, hs, recent = analyze_cs2_stats(data.get('stats'))
|
| 105 |
+
inv_txt, top3 = analyze_inventory(data.get('inv'), data_mgr.is_price_ready, data_mgr.price_en_map)
|
| 106 |
+
|
| 107 |
+
bans = data.get('bans', {}).get('players', [{}])[0]
|
| 108 |
+
is_banned = bans.get('VACBanned') or bans.get('NumberOfGameBans', 0) > 0
|
| 109 |
+
|
| 110 |
+
created_ts = summary.get('timecreated')
|
| 111 |
+
years = (datetime.datetime.now() - datetime.datetime.fromtimestamp(created_ts)).days // 365 if created_ts else 0
|
| 112 |
+
level = data.get('level', {}).get('response', {}).get('player_level', 0)
|
| 113 |
+
|
| 114 |
+
card = build_cs2_profile_card(
|
| 115 |
+
summary.get('personaname', 'Unknown'), years, level,
|
| 116 |
+
is_banned, inv_txt, top3, summary.get('avatarfull'),
|
| 117 |
+
has_stats, w_line, m_line, kd, hs, recent, summary.get('profileurl'), steam_id
|
| 118 |
+
)
|
| 119 |
+
return card, loading_msg
|
| 120 |
+
except Exception as e:
|
| 121 |
+
logger.error(f"[CS2 Stat] 异常: {e}")
|
| 122 |
+
return "❌ 数据解析失败。", loading_msg
|
| 123 |
+
|
| 124 |
+
async def handle_status_command(msg: Message):
|
| 125 |
+
"""Handles the /status network lookup."""
|
| 126 |
+
loading_msg = await msg.reply("📡 正在探测 Steam 服务器节点...")
|
| 127 |
+
try:
|
| 128 |
+
off_resp, web_resp = await ApiClient.fetch_cs2_status()
|
| 129 |
+
|
| 130 |
+
services, mm, real_inv = {}, {}, "Offline"
|
| 131 |
+
if isinstance(off_resp, aiohttp.ClientResponse) and off_resp.status == 200:
|
| 132 |
+
res = (await off_resp.json()).get('result', {})
|
| 133 |
+
services, mm = res.get('services', {}), res.get('matchmaking', {})
|
| 134 |
+
if isinstance(web_resp, aiohttp.ClientResponse):
|
| 135 |
+
real_inv = "Online" if web_resp.status == 200 else ("Surge" if web_resp.status == 429 else "Offline")
|
| 136 |
+
|
| 137 |
+
status_map = {"normal": "Online", "offline": "Offline", "delayed": "Delay", "surge": "Surge"}
|
| 138 |
+
card = build_cs2_status_card(services.get('SessionsLogon', 'unknown'), real_inv, mm.get('scheduler', 'unknown'), mm, status_map)
|
| 139 |
+
return card, loading_msg
|
| 140 |
+
except Exception:
|
| 141 |
+
return "❌ 无法获取 Steam 状态。", loading_msg
|
| 142 |
+
|
| 143 |
+
async def handle_skin_button_click(b: Bot, e: Event):
|
| 144 |
+
"""Handles interaction buttons emitted from skin cards."""
|
| 145 |
+
val, ch_id = e.body.get('value', ''), e.body.get('target_id')
|
| 146 |
+
user_id = e.body.get('user_info', {}).get('id')
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
channel = await b.client.fetch_public_channel(ch_id)
|
| 150 |
+
except Exception:
|
| 151 |
+
return
|
| 152 |
+
|
| 153 |
+
if val.startswith("skin_random|"):
|
| 154 |
+
pool = [i for i in data_mgr.price_dict if any(k in i['cn_name'] for k in ["AK-47", "M4A4", "AWP"])]
|
| 155 |
+
items = sorted(random.sample(pool, min(8, len(pool))), key=lambda x: x["price"], reverse=True)
|
| 156 |
+
await channel.send(CardMessage(build_skin_random_card("推荐饰品", items, user_id)))
|
| 157 |
+
|
| 158 |
+
elif val.startswith("skin_chart|"):
|
| 159 |
+
item = data_mgr.price_en_map.get(val.split("|", 1)[1])
|
| 160 |
+
if item:
|
| 161 |
+
await channel.send(CardMessage(build_skin_chart_card(item)))
|
| 162 |
+
|
| 163 |
+
# --- Bot Command Registrations ---
|
| 164 |
+
|
| 165 |
+
def register_cs2_handlers(bot: Bot):
|
| 166 |
+
@bot.command(name='open', prefixes=['/'])
|
| 167 |
+
async def open_cmd(msg: Message, *args):
|
| 168 |
+
await handle_open_command(msg, *args)
|
| 169 |
+
|
| 170 |
+
@bot.command(name='skin', prefixes=['/'])
|
| 171 |
+
async def skin_cmd(msg: Message, *args):
|
| 172 |
+
await handle_skin_command(msg, *args)
|
| 173 |
+
|
| 174 |
+
@bot.command(name='cs', prefixes=['/'])
|
| 175 |
+
async def cs_cmd(msg: Message, steam_id: str = ""):
|
| 176 |
+
result, loading_msg = await handle_cs_profile_command(msg, steam_id)
|
| 177 |
+
if loading_msg:
|
| 178 |
+
await safe_delete_msg(bot, loading_msg)
|
| 179 |
+
if isinstance(result, str):
|
| 180 |
+
await msg.reply(result) # Display Error
|
| 181 |
+
elif result:
|
| 182 |
+
await msg.reply(CardMessage(result)) # Display Card
|
| 183 |
+
|
| 184 |
+
@bot.command(name='status', prefixes=['/'])
|
| 185 |
+
async def status_cmd(msg: Message):
|
| 186 |
+
result, loading_msg = await handle_status_command(msg)
|
| 187 |
+
if loading_msg:
|
| 188 |
+
await safe_delete_msg(bot, loading_msg)
|
| 189 |
+
if isinstance(result, str):
|
| 190 |
+
await msg.reply(result) # Display Error
|
| 191 |
+
elif result:
|
| 192 |
+
await msg.reply(CardMessage(result)) # Display Card
|
| 193 |
+
|
| 194 |
+
@bot.on_event(EventTypes.MESSAGE_BTN_CLICK)
|
| 195 |
+
async def btn_click(b: Bot, e: Event):
|
| 196 |
+
await handle_skin_button_click(b, e)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
khl.py>=0.3.0
|
| 2 |
+
aiohttp>=3.9.0
|
| 3 |
+
python-dateutil>=2.8.0
|
| 4 |
+
motor>=3.3.0
|
| 5 |
+
curl-cffi==0.5.10
|
| 6 |
+
beautifulsoup4==4.12.3
|
| 7 |
+
huggingface-hub>=0.22.0
|
| 8 |
+
python-dotenv>=1.0.0
|
| 9 |
+
certifi>=2023.11.17
|
| 10 |
+
aiofiles
|
services/api_client.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import aiohttp
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import time
|
| 6 |
+
import core.config as config
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
class ApiClient:
|
| 11 |
+
session = None
|
| 12 |
+
|
| 13 |
+
# 🌟 内存缓存字典,结构: {"模块_查询参数": {"data": 数据, "expire_at": 过期时间戳}}
|
| 14 |
+
_cache = {}
|
| 15 |
+
|
| 16 |
+
# 🌟 统一设置缓存过期时间 (300秒 = 5分钟。如果想设为 5 天,请改为 432000)
|
| 17 |
+
CACHE_TTL_SECONDS = 300
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
async def init_session(cls):
|
| 21 |
+
if cls.session is None:
|
| 22 |
+
cls.session = aiohttp.ClientSession()
|
| 23 |
+
logger.info("[ApiClient] 全局 AIO_SESSION 与缓存引擎已初始化")
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
async def close_session(cls):
|
| 27 |
+
if cls.session:
|
| 28 |
+
await cls.session.close()
|
| 29 |
+
cls.session = None
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def _get_from_cache(cls, cache_key: str):
|
| 33 |
+
"""内部方法:读取并校验缓存是否过期"""
|
| 34 |
+
if cache_key in cls._cache:
|
| 35 |
+
if time.time() < cls._cache[cache_key]['expire_at']:
|
| 36 |
+
logger.debug(f"[Cache] 命中缓存: {cache_key}")
|
| 37 |
+
return cls._cache[cache_key]['data']
|
| 38 |
+
else:
|
| 39 |
+
# 缓存已过期,清理掉
|
| 40 |
+
del cls._cache[cache_key]
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def _set_to_cache(cls, cache_key: str, data):
|
| 45 |
+
"""内部方法:写入缓存"""
|
| 46 |
+
cls._cache[cache_key] = {
|
| 47 |
+
'data': data,
|
| 48 |
+
'expire_at': time.time() + cls.CACHE_TTL_SECONDS
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
async def fetch_steam_data(steam_id: str):
|
| 53 |
+
if ApiClient.session is None: return {"summary": {}, "level": {}, "bans": {}, "stats": {}, "inv": {}}
|
| 54 |
+
|
| 55 |
+
# 🌟 1. 拦截检查:看看缓存里有没有
|
| 56 |
+
cache_key = f"steam_profile_{steam_id}"
|
| 57 |
+
cached_data = ApiClient._get_from_cache(cache_key)
|
| 58 |
+
if cached_data:
|
| 59 |
+
return cached_data
|
| 60 |
+
|
| 61 |
+
# 🌟 2. 没有缓存,正常发起请求
|
| 62 |
+
key = config.STEAM_API_KEY
|
| 63 |
+
urls = {
|
| 64 |
+
"summary": f"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={key}&steamids={steam_id}",
|
| 65 |
+
"level": f"https://api.steampowered.com/IPlayerService/GetSteamLevel/v1/?key={key}&steamid={steam_id}",
|
| 66 |
+
"bans": f"https://api.steampowered.com/ISteamUser/GetPlayerBans/v1/?key={key}&steamids={steam_id}",
|
| 67 |
+
"stats": f"https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v2/?key={key}&appid=730&steamid={steam_id}",
|
| 68 |
+
"inv": f"https://steamcommunity.com/inventory/{steam_id}/730/2?l=schinese&count=1000"
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
async def fetch(name, url):
|
| 72 |
+
try:
|
| 73 |
+
async with ApiClient.session.get(url, timeout=12) as resp:
|
| 74 |
+
return name, (await resp.json() if resp.status == 200 else {})
|
| 75 |
+
except: return name, {}
|
| 76 |
+
|
| 77 |
+
results = await asyncio.gather(*(fetch(k, v) for k, v in urls.items()))
|
| 78 |
+
final_data = dict(results)
|
| 79 |
+
|
| 80 |
+
# 🌟 3. 请求成功后,写入缓存(防止查无此人的空数据被一直缓存,可以加个判断)
|
| 81 |
+
if final_data.get('summary', {}).get('response', {}).get('players'):
|
| 82 |
+
ApiClient._set_to_cache(cache_key, final_data)
|
| 83 |
+
|
| 84 |
+
return final_data
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
async def fetch_apex_map():
|
| 88 |
+
# 地图轮换属于高频且所有人共享的数据,缓存极具价值
|
| 89 |
+
cache_key = "apex_map_rotation"
|
| 90 |
+
cached_data = ApiClient._get_from_cache(cache_key)
|
| 91 |
+
if cached_data:
|
| 92 |
+
return 200, cached_data
|
| 93 |
+
|
| 94 |
+
if ApiClient.session is None: return 500, None
|
| 95 |
+
url = f"https://api.mozambiquehe.re/maprotation?auth={config.APEX_API_KEY}&version=2"
|
| 96 |
+
async with ApiClient.session.get(url, timeout=15) as resp:
|
| 97 |
+
data = await resp.json() if resp.status == 200 else None
|
| 98 |
+
if data: ApiClient._set_to_cache(cache_key, data)
|
| 99 |
+
return resp.status, data
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
async def fetch_apex_stats(player_name, platform):
|
| 103 |
+
if ApiClient.session is None: return 500, None
|
| 104 |
+
|
| 105 |
+
# 🌟 Apex 战绩缓存
|
| 106 |
+
safe_name = urllib.parse.quote(player_name)
|
| 107 |
+
cache_key = f"apex_stat_{safe_name}_{platform}"
|
| 108 |
+
cached_data = ApiClient._get_from_cache(cache_key)
|
| 109 |
+
if cached_data:
|
| 110 |
+
return 200, cached_data
|
| 111 |
+
|
| 112 |
+
url = f"https://api.mozambiquehe.re/bridge?auth={config.APEX_API_KEY}&player={safe_name}&platform={platform.upper()}"
|
| 113 |
+
async with ApiClient.session.get(url, timeout=15) as resp:
|
| 114 |
+
data = await resp.json() if resp.status == 200 else None
|
| 115 |
+
if data and 'Error' not in data:
|
| 116 |
+
ApiClient._set_to_cache(cache_key, data)
|
| 117 |
+
return resp.status, data
|
| 118 |
+
|
| 119 |
+
@staticmethod
|
| 120 |
+
async def fetch_cs2_status():
|
| 121 |
+
if ApiClient.session is None: return None, None
|
| 122 |
+
# 服务器状态缓存(状态一般15-30分钟变化一次)
|
| 123 |
+
pass
|
services/data_manager.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
import aiofiles
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from curl_cffi.requests import AsyncSession
|
| 8 |
+
from core.config import REPO_ID, HF_TOKEN, logger, STD_HEADERS
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
|
| 11 |
+
class DataManager:
|
| 12 |
+
"""全自动数据管家:负责价格同步、翻译词库和掉落表"""
|
| 13 |
+
def __init__(self):
|
| 14 |
+
# 核心数据仓库
|
| 15 |
+
self.is_price_ready = False
|
| 16 |
+
self.price_dict = []
|
| 17 |
+
self.price_cn_map = {}
|
| 18 |
+
self.price_en_map = {}
|
| 19 |
+
|
| 20 |
+
self.display_trans = {}
|
| 21 |
+
self.custom_trans = {}
|
| 22 |
+
|
| 23 |
+
self.crates_dict = []
|
| 24 |
+
self.crates_cases = []
|
| 25 |
+
self.crates_capsules = []
|
| 26 |
+
self.affordable_cases = []
|
| 27 |
+
self.affordable_capsules = []
|
| 28 |
+
|
| 29 |
+
async def _async_fetch_json(self, session, url):
|
| 30 |
+
"""内部工具:异步抓取 JSON"""
|
| 31 |
+
try:
|
| 32 |
+
async with session.get(url, headers=STD_HEADERS, timeout=60) as resp:
|
| 33 |
+
if resp.status == 200:
|
| 34 |
+
return await resp.json()
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.debug(f"[DataManager] 抓取失败 {url}: {e}")
|
| 37 |
+
return []
|
| 38 |
+
|
| 39 |
+
# 🌟 性能优化核心 1:提取稀有度定义与预处理结构
|
| 40 |
+
def _categorize_items_by_tier(self, crate: dict) -> dict:
|
| 41 |
+
"""根据物品名称和属性预分类品质,避免开箱时重复遍历"""
|
| 42 |
+
tiers = {'gold': [], 'red': [], 'pink': [], 'purple': [], 'blue': []}
|
| 43 |
+
for item in crate.get('contains', []):
|
| 44 |
+
rarity = str(item.get('rarity', {}).get('name', '') if isinstance(item.get('rarity'), dict) else item.get('rarity', ''))
|
| 45 |
+
name = str(item.get('name', ''))
|
| 46 |
+
|
| 47 |
+
if any(k in rarity for k in ['违禁', 'Contraband']) or any(k in name for k in ['★', '纯金', 'Gold', '金色']):
|
| 48 |
+
tiers['gold'].append(item)
|
| 49 |
+
elif any(k in rarity for k in ['隐秘', 'Covert', '非凡', 'Extraordinary', '大师', 'Master']):
|
| 50 |
+
tiers['red'].append(item)
|
| 51 |
+
elif any(k in rarity for k in ['保密', 'Classified', '奇异', 'Exotic']):
|
| 52 |
+
tiers['pink'].append(item)
|
| 53 |
+
elif any(k in rarity for k in ['受限', 'Restricted', '卓越', 'Remarkable', 'Exceptional']):
|
| 54 |
+
tiers['purple'].append(item)
|
| 55 |
+
else:
|
| 56 |
+
tiers['blue'].append(item)
|
| 57 |
+
return tiers
|
| 58 |
+
|
| 59 |
+
def _update_affordable_crates(self):
|
| 60 |
+
"""根据价格过滤买得起的箱子,并【预处理】品质分布"""
|
| 61 |
+
# 过滤
|
| 62 |
+
self.affordable_cases = [c for c in self.crates_cases if self.price_cn_map.get(c.get('name'), {}).get('price', 5.0) <= 800]
|
| 63 |
+
self.affordable_capsules = [c for c in self.crates_capsules if self.price_cn_map.get(c.get('name'), {}).get('price', 1.5) <= 800]
|
| 64 |
+
|
| 65 |
+
# 🌟 性能优化核心 2:预计算并缓存每一个箱子的内容分类分布,开箱引擎使用 O(1) 取出
|
| 66 |
+
for crate in self.affordable_cases:
|
| 67 |
+
crate['precomputed_tiers'] = self._categorize_items_by_tier(crate)
|
| 68 |
+
for crate in self.affordable_capsules:
|
| 69 |
+
crate['precomputed_tiers'] = self._categorize_items_by_tier(crate)
|
| 70 |
+
|
| 71 |
+
async def init_crates_data(self, session):
|
| 72 |
+
"""初始化掉落表"""
|
| 73 |
+
url = "https://cdn.jsdelivr.net/gh/ByMykel/CSGO-API@main/public/api/zh-CN/crates.json"
|
| 74 |
+
data = await self._async_fetch_json(session, url)
|
| 75 |
+
if data:
|
| 76 |
+
self.crates_dict = data
|
| 77 |
+
self.crates_cases = [c for c in data if c.get('type') == 'Weapon Case' or '武器箱' in c.get('name', '')]
|
| 78 |
+
self.crates_capsules = [c for c in data if c.get('type') == 'Sticker Capsule' or '胶囊' in c.get('name', '')]
|
| 79 |
+
self._update_affordable_crates()
|
| 80 |
+
logger.info("[Init] 掉落表加载并预处理完成,开箱速度已极大提升")
|
| 81 |
+
|
| 82 |
+
async def init_translation_dictionary(self, session, hf_api):
|
| 83 |
+
"""初始化翻译词库并同步至 HF"""
|
| 84 |
+
dict_file = 'auto_dict_v4.json'
|
| 85 |
+
try:
|
| 86 |
+
await asyncio.to_thread(hf_hub_download, repo_id=REPO_ID, filename=dict_file, repo_type="dataset", local_dir=".", token=HF_TOKEN)
|
| 87 |
+
except: pass
|
| 88 |
+
|
| 89 |
+
if os.path.exists(dict_file):
|
| 90 |
+
try:
|
| 91 |
+
async with aiofiles.open(dict_file, 'r', encoding='utf-8') as f:
|
| 92 |
+
content = await f.read()
|
| 93 |
+
self.display_trans = json.loads(content).get("DISPLAY_TRANS", {})
|
| 94 |
+
if self.display_trans: return
|
| 95 |
+
except: pass
|
| 96 |
+
|
| 97 |
+
logger.info("[Init] 词库失效,开始从 GitHub 重建...")
|
| 98 |
+
base_en = "https://cdn.jsdelivr.net/gh/ByMykel/CSGO-API@main/public/api/en"
|
| 99 |
+
base_cn = "https://cdn.jsdelivr.net/gh/ByMykel/CSGO-API@main/public/api/zh-CN"
|
| 100 |
+
trans = {}
|
| 101 |
+
for cat in ["skins.json", "stickers.json", "crates.json", "agents.json"]:
|
| 102 |
+
en, cn_data = await asyncio.gather(self._async_fetch_json(session, f"{base_en}/{cat}"), self._async_fetch_json(session, f"{base_cn}/{cat}"))
|
| 103 |
+
cn_map = {i.get('id'): i.get('name') for i in cn_data if isinstance(i, dict)}
|
| 104 |
+
for item in en:
|
| 105 |
+
if isinstance(item, dict) and item.get('id') in cn_map:
|
| 106 |
+
trans[item.get('name')] = cn_map[item.get('id')]
|
| 107 |
+
|
| 108 |
+
trans.update(self.custom_trans)
|
| 109 |
+
self.display_trans = dict(sorted(trans.items(), key=lambda x: len(x[0]), reverse=True))
|
| 110 |
+
|
| 111 |
+
async with aiofiles.open(dict_file, 'w', encoding='utf-8') as f:
|
| 112 |
+
await f.write(json.dumps({"DISPLAY_TRANS": self.display_trans}, ensure_ascii=False))
|
| 113 |
+
if hf_api:
|
| 114 |
+
await asyncio.to_thread(hf_api.upload_file, path_or_fileobj=dict_file, path_in_repo=dict_file, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
|
| 115 |
+
|
| 116 |
+
async def price_auto_updater(self):
|
| 117 |
+
"""双线价格库自动轮询更新:Steam 官价打底 + 现金平台(第三方)底价"""
|
| 118 |
+
cache_file = 'price_cache_v4.json'
|
| 119 |
+
# 预加载缓存
|
| 120 |
+
if os.path.exists(cache_file):
|
| 121 |
+
try:
|
| 122 |
+
async with aiofiles.open(cache_file, 'r', encoding='utf-8') as f:
|
| 123 |
+
content = await f.read()
|
| 124 |
+
self.price_dict = json.loads(content)
|
| 125 |
+
if self.price_dict:
|
| 126 |
+
self.price_cn_map = {i['cn_name']: i for i in self.price_dict}
|
| 127 |
+
self.price_en_map = {i['en_name']: i for i in self.price_dict}
|
| 128 |
+
self.is_price_ready = True
|
| 129 |
+
except: pass
|
| 130 |
+
|
| 131 |
+
while True:
|
| 132 |
+
try:
|
| 133 |
+
# 为了解决国内 API 墙/解析问题,并且获得极其精准的 BUFF 底价
|
| 134 |
+
# 取 Skinport 价格库做全量遍历 (因为它的中文名体系很规范) + CSGOTrader 的开源缓冲池(有buff价格)
|
| 135 |
+
async with AsyncSession(impersonate="chrome110", timeout=120) as session:
|
| 136 |
+
resp_sp = await session.get("https://api.skinport.com/v1/items?app_id=730¤cy=CNY")
|
| 137 |
+
|
| 138 |
+
if resp_sp.status_code == 200:
|
| 139 |
+
sp_data = resp_sp.json()
|
| 140 |
+
|
| 141 |
+
# 尝试拉取 CSGO Trader 开源全球大 JSON (涵盖 buff163 的实时美元数据)
|
| 142 |
+
trader_data = {}
|
| 143 |
+
try:
|
| 144 |
+
resp_trader = await session.get("https://prices.csgotrader.app/latest/prices_v6.json")
|
| 145 |
+
if resp_trader.status_code == 200:
|
| 146 |
+
trader_data = resp_trader.json()
|
| 147 |
+
except Exception as e:
|
| 148 |
+
logger.error(f"[Price] 开源 BUFF 物价拉取异常 (延用Skinport保底): {e}")
|
| 149 |
+
|
| 150 |
+
new_prices = []
|
| 151 |
+
for item in sp_data:
|
| 152 |
+
en_name = item.get('market_hash_name')
|
| 153 |
+
# suggested_price: Steam市场官方参考价
|
| 154 |
+
steam_p = item.get('suggested_price') or item.get('mean_price') or 0
|
| 155 |
+
|
| 156 |
+
# 默认使用 Skinport min_price 做底价兜底
|
| 157 |
+
cash_p = item.get('min_price') or steam_p
|
| 158 |
+
|
| 159 |
+
# 最核心:如果有 buff163 的真实数据,覆盖!
|
| 160 |
+
if trader_data and en_name in trader_data:
|
| 161 |
+
buff_info = trader_data[en_name].get("buff163")
|
| 162 |
+
if buff_info and "starting_at" in buff_info:
|
| 163 |
+
buff_usd = buff_info["starting_at"].get("price")
|
| 164 |
+
if buff_usd:
|
| 165 |
+
# CSGOTrader 的价格为美元,按当前约 7.25 的汇率折算回人民币
|
| 166 |
+
cash_p = float(buff_usd) * 7.25
|
| 167 |
+
|
| 168 |
+
if not steam_p and cash_p: steam_p = cash_p
|
| 169 |
+
if not cash_p and steam_p: cash_p = steam_p
|
| 170 |
+
if steam_p <= 0: continue
|
| 171 |
+
|
| 172 |
+
cn_name = en_name
|
| 173 |
+
for eng, chn in self.display_trans.items():
|
| 174 |
+
if eng in cn_name: cn_name = cn_name.replace(eng, chn)
|
| 175 |
+
cn_name = cn_name.replace("(崭新出厂)", "(崭新)").replace("(略有磨损)", "(略磨)").replace("(久经沙场)", "(久经)").replace("(破损不堪)", "(破损)").replace("(战痕累累)", "(战痕)")
|
| 176 |
+
|
| 177 |
+
new_prices.append({
|
| 178 |
+
"en_name": en_name,
|
| 179 |
+
"cn_name": cn_name,
|
| 180 |
+
"search_text": f"{en_name} {cn_name}".lower(),
|
| 181 |
+
"price": float(steam_p), # Steam 官价:供开箱与市值使用
|
| 182 |
+
"buff_price": float(cash_p) # 现金挂售价:供饰品搜索结果使用 (UI中依然叫 buff_price)
|
| 183 |
+
})
|
| 184 |
+
|
| 185 |
+
if len(new_prices) > 1000:
|
| 186 |
+
self.price_dict = new_prices
|
| 187 |
+
self.price_cn_map = {i['cn_name']: i for i in self.price_dict}
|
| 188 |
+
self.price_en_map = {i['en_name']: i for i in self.price_dict}
|
| 189 |
+
self.is_price_ready = True
|
| 190 |
+
async with aiofiles.open(cache_file, 'w', encoding='utf-8') as f:
|
| 191 |
+
await f.write(json.dumps(self.price_dict, ensure_ascii=False))
|
| 192 |
+
self._update_affordable_crates()
|
| 193 |
+
logger.info(f"[Price] BUFF真实价格混入合并成功!共记录 {len(self.price_dict)} 条数据。")
|
| 194 |
+
await asyncio.sleep(14400)
|
| 195 |
+
continue
|
| 196 |
+
else:
|
| 197 |
+
logger.error(f"[Price] Skinport 返回异常状态码: {resp_sp.status_code}")
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.error(f"[Price] 底层网络循环异常: {e}")
|
| 200 |
+
|
| 201 |
+
await asyncio.sleep(600) # 失败则10分钟后重试
|
| 202 |
+
|
| 203 |
+
@lru_cache(maxsize=128)
|
| 204 |
+
def search_skin(self, search_tuple):
|
| 205 |
+
"""饰品搜索逻辑回归管家"""
|
| 206 |
+
return sorted(
|
| 207 |
+
[i for i in self.price_dict if all(t in i["search_text"] for t in search_tuple)],
|
| 208 |
+
key=lambda x: x["price"],
|
| 209 |
+
reverse=True
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# 实例化全局数据管家
|
| 213 |
+
data_mgr = DataManager()
|
utils/bot_utils.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
logger = logging.getLogger(__name__)
|
| 3 |
+
|
| 4 |
+
async def safe_delete_msg(bot_instance, msg_obj):
|
| 5 |
+
"""
|
| 6 |
+
通用的安全删除消息工具
|
| 7 |
+
"""
|
| 8 |
+
if not msg_obj: return
|
| 9 |
+
try:
|
| 10 |
+
# 在 khl.py 较新版本中
|
| 11 |
+
# msg_obj 通常是一个包含 msg_id 的 dict 或者是一个 Message 对象
|
| 12 |
+
msg_id = None
|
| 13 |
+
if hasattr(msg_obj, 'id'): # 对象属性判断
|
| 14 |
+
msg_id = msg_obj.id
|
| 15 |
+
elif hasattr(msg_obj, 'msg_id'):
|
| 16 |
+
msg_id = msg_obj.msg_id
|
| 17 |
+
elif isinstance(msg_obj, dict): # 字典类型获取
|
| 18 |
+
msg_id = msg_obj.get('msg_id')
|
| 19 |
+
|
| 20 |
+
if msg_id:
|
| 21 |
+
# 第一种:尝试新版接口封装
|
| 22 |
+
try:
|
| 23 |
+
await bot_instance.client.delete_message(msg_id)
|
| 24 |
+
except AttributeError:
|
| 25 |
+
# 第二种:旧版或底层 API 直接请求
|
| 26 |
+
await bot_instance.client.gate.request('POST', 'message/delete', data={'msg_id': msg_id})
|
| 27 |
+
else:
|
| 28 |
+
logger.debug(f"[Delete Msg] 无法提取有效 msg_id,对象类型为: {type(msg_obj)}")
|
| 29 |
+
|
| 30 |
+
except Exception as e:
|
| 31 |
+
logger.debug(f"[Delete Msg] 消息删除失败: {e}")
|
utils/card_builder.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import urllib.parse
|
| 2 |
+
from khl.card import Card, Module, Element, Types
|
| 3 |
+
|
| 4 |
+
def build_help_card():
|
| 5 |
+
help_text = """**🤖 游戏助手 | 指令菜单**\n---\n**🔫 CS2 核心功能**\n> `/cs [SteamID64]` \n> 📊 查询官匹数据及实战评级\n\n> `/skin [物品] [皮肤] [磨损]` \n> 💰 检索全网底价\n> \n> `/status` \n> 📡 查询官方服务器及匹配节点状态\n\n**📦 娱乐经济系统**\n> `/open [数量]` \n> 🎰 模拟开箱并记录你的历史盈亏!\n\n**🛸 APEX 英雄系统**\n> `/apexstat [EA_ID] [平台]` \n> 🏅 查询排位分数及在线状态\n\n> `/apexmap` \n> 🗺️ 获取实时匹配与排位地图轮换\n\n> `/apex [数量]` \n> 🔴 模拟 APEX 开包,测测运气!\n---\n💡 *如需开通高级娱乐授权,请访问服主主页赞助解锁。*"""
|
| 6 |
+
card = Card(color="#4A90E2")
|
| 7 |
+
card.append(Module.Section(Element.Text(help_text, type=Types.Text.KMD)))
|
| 8 |
+
return card
|
| 9 |
+
|
| 10 |
+
def build_invite_card(invite_endpoint):
|
| 11 |
+
card = Card(color="#6A5ACD")
|
| 12 |
+
card.append(Module.Header("🤖 R4nd0m 游戏助手 - 邀请链接"))
|
| 13 |
+
card.append(Module.Divider())
|
| 14 |
+
card.append(Module.Section(Element.Text("**SaaS 级游戏娱乐机器人**\n🎮 支持 CS2 全真开箱模拟、饰品市场检索、官匹数据查询\n🔮 APEX 传家宝模拟、地图轮换、玩家档案查询\n📊 实时赛事数据、服务器状态监控\n💰 基于爱发电的服务器级授权系统(安全可靠)\n\n点击下方按钮将机器人邀请至您的服务器:", type=Types.Text.KMD)))
|
| 15 |
+
card.append(Module.ActionGroup(Element.Button("🚀 一键邀请机器人", invite_endpoint, Types.Click.LINK, theme=Types.Theme.PRIMARY)))
|
| 16 |
+
card.append(Module.Context(Element.Text("邀请后,机器人会自动检测服务器授权状态并发送指引。", type=Types.Text.KMD)))
|
| 17 |
+
return card
|
| 18 |
+
|
| 19 |
+
def build_auth_welcome_card():
|
| 20 |
+
card = Card(color="#00FF00")
|
| 21 |
+
card.append(Module.Header("🟢 尊贵的授权服务器"))
|
| 22 |
+
card.append(Module.Divider())
|
| 23 |
+
card.append(Module.Section(Element.Text("**功能已全面解锁!**\n\n✅ 全真 CS2 开箱模拟 (`/open`)\n✅ 饰品市场实时检索 (`/skin`)\n✅ 官匹数据查询 (`/cs`)\n✅ APEX 传家宝模拟 (`/apex`)\n\n输入 `/help` 查看完整指令菜单。\n祝您游戏愉快!", type=Types.Text.KMD)))
|
| 24 |
+
return card
|
| 25 |
+
|
| 26 |
+
def build_auth_payment_card(guild_id):
|
| 27 |
+
card = Card(color="#FF0000")
|
| 28 |
+
card.append(Module.Header("🔴 本服务器尚未激活授权"))
|
| 29 |
+
card.append(Module.Divider())
|
| 30 |
+
card.append(Module.Section(Element.Text("**SaaS 级游戏娱乐机器人需要服务器级授权**\n\n📦 **服务内容**:\n• CS2 全真开箱模拟(支持连开)\n• 饰品市场实时底价检索\n• 官匹数据查询与战绩评级\n• APEX 传家宝模拟、地图轮换\n\n💰 **授权档位**:\n• **隐秘级**:30 元/月\n• **违禁级**:250 元/年\n\n**请服主前往爱发电购买授权**:", type=Types.Text.KMD)))
|
| 31 |
+
card.append(Module.ActionGroup(Element.Button("💳 前往爱发电购买授权", "https://afdian.com/a/R4nd0m", Types.Click.LINK, theme=Types.Theme.DANGER)))
|
| 32 |
+
card.append(Module.Context(Element.Text(f"**重要**:付款时请在备注中填写本服务器 ID:`{guild_id}`", type=Types.Text.KMD)))
|
| 33 |
+
return card
|
| 34 |
+
|
| 35 |
+
def build_open_case_card(count, opened_items, profit_all, total_profit, total_opens, total_cost_all, total_earned_all, user_name):
|
| 36 |
+
best_item = max(opened_items, key=lambda x: x['price'])
|
| 37 |
+
card = Card(color=best_item['color'])
|
| 38 |
+
if count == 1:
|
| 39 |
+
item = opened_items[0]
|
| 40 |
+
card.append(Module.Header("单次开箱结果:"))
|
| 41 |
+
cost_text = f"¥ {item['cost']:.2f}" if "钥匙" not in item['crate_name'] and "箱" not in item['crate_name'] else f"¥ {item['cost']:.2f} (含匙)"
|
| 42 |
+
lines = [
|
| 43 |
+
f"**模拟箱子**:{item['crate_name']}", f"**品质**:{item['rarity_name']}", "---",
|
| 44 |
+
f"**物品**:{item['item_name']}", f"**价格**:¥ {item['price']:.2f}", f"**成本**:{cost_text}",
|
| 45 |
+
f"**本轮盈亏**:{'+ ¥ ' if profit_all > 0 else '- ¥ '}{abs(profit_all):.2f}",
|
| 46 |
+
f"**历史净值**:{'¥ ' if total_profit > 0 else '- ¥ '}{abs(total_profit):.2f} (调用量: {total_opens})"
|
| 47 |
+
]
|
| 48 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD)))
|
| 49 |
+
else:
|
| 50 |
+
card.append(Module.Header(f"随机箱子{count}连开"))
|
| 51 |
+
lines = [f"`#{idx+1}` [{i['rarity_name'].split('/')[0]}] **{i['item_name']}** ▶ `¥ {i['price']:.2f}`" for idx, i in enumerate(opened_items)]
|
| 52 |
+
lines.extend([
|
| 53 |
+
"---", f"**总消耗**:¥ {total_cost_all:.2f} | **总产出**:¥ {total_earned_all:.2f}",
|
| 54 |
+
f"**本轮盈亏**:{'+ ¥ ' if profit_all > 0 else '- ¥ '}{abs(profit_all):.2f}",
|
| 55 |
+
f"**历史净值**:{'¥ ' if total_profit > 0 else '- ¥ '}{abs(total_profit):.2f} (总开箱数: {total_opens})"
|
| 56 |
+
])
|
| 57 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD)))
|
| 58 |
+
context_text = f"[ 用户: {user_name} ] "
|
| 59 |
+
if best_item['tier'] == 'gold' or profit_all > 150: context_text += "你牛大了"
|
| 60 |
+
elif profit_all < -(15 * count): context_text += "亏麻了"
|
| 61 |
+
else: context_text += "不赖"
|
| 62 |
+
card.append(Module.Context(Element.Text(context_text, type=Types.Text.KMD)))
|
| 63 |
+
return card
|
| 64 |
+
|
| 65 |
+
def build_skin_search_recommend_card():
|
| 66 |
+
card = Card(color="#4A90E2")
|
| 67 |
+
card.append(Module.Header("市场饰品快速检索"))
|
| 68 |
+
card.append(Module.Context(Element.Text("输入参数为空,请点击下方按钮获取推荐:", type=Types.Text.KMD)))
|
| 69 |
+
card.append(Module.ActionGroup(
|
| 70 |
+
Element.Button("主战武器", value="skin_random|rifle", click=Types.Click.RETURN_VAL, theme=Types.Theme.PRIMARY),
|
| 71 |
+
Element.Button("近战匕首", value="skin_random|knife", click=Types.Click.RETURN_VAL, theme=Types.Theme.DANGER),
|
| 72 |
+
Element.Button("专业手套", value="skin_random|glove", click=Types.Click.RETURN_VAL, theme=Types.Theme.WARNING),
|
| 73 |
+
Element.Button("狙击步枪", value="skin_random|sniper", click=Types.Click.RETURN_VAL, theme=Types.Theme.INFO)
|
| 74 |
+
))
|
| 75 |
+
return card
|
| 76 |
+
|
| 77 |
+
def build_skin_search_result_card(args_str, results):
|
| 78 |
+
card = Card(color="#4A90E2")
|
| 79 |
+
card.append(Module.Header(f"检索结果:{args_str}"))
|
| 80 |
+
|
| 81 |
+
# 列表上同时显示官价和 Buff 价
|
| 82 |
+
lines = []
|
| 83 |
+
for idx, i in enumerate(results[:10]):
|
| 84 |
+
steam_str = f"¥ {i['price']:.2f}"
|
| 85 |
+
buff_str = f"Buff: ¥ {i.get('buff_price', 0):.2f}" if i.get('buff_price', 0) > 0 else "Buff: --"
|
| 86 |
+
lines.append(f"`#{idx+1}` {i['cn_name']} | Steam: {steam_str} | {buff_str}")
|
| 87 |
+
|
| 88 |
+
card.append(Module.Section(Element.Text("```\n" + "\n".join(lines) + "\n```", type=Types.Text.KMD)))
|
| 89 |
+
card.append(Module.Context(Element.Text("**点击下方对应编号,查阅详细数据:**", type=Types.Text.KMD)))
|
| 90 |
+
for i in range(0, min(8, len(results)), 4):
|
| 91 |
+
group_btns = [Element.Button(f"详细 #{i+idx+1}", value=f"skin_chart|{item['en_name']}", click=Types.Click.RETURN_VAL, theme=Types.Theme.PRIMARY)
|
| 92 |
+
for idx, item in enumerate(results[i:i+4])]
|
| 93 |
+
card.append(Module.ActionGroup(*group_btns))
|
| 94 |
+
return card
|
| 95 |
+
|
| 96 |
+
def build_skin_random_card(title, selected_items, user_id):
|
| 97 |
+
card = Card(color="#4A90E2")
|
| 98 |
+
card.append(Module.Header(title))
|
| 99 |
+
|
| 100 |
+
# 列表上同时显示官价和 Buff 价
|
| 101 |
+
lines = []
|
| 102 |
+
for idx, i in enumerate(selected_items):
|
| 103 |
+
steam_str = f"¥ {i['price']:.2f}"
|
| 104 |
+
buff_str = f"Buff: ¥ {i.get('buff_price', 0):.2f}" if i.get('buff_price', 0) > 0 else "Buff: --"
|
| 105 |
+
lines.append(f"`#{idx+1}` {i['cn_name']} | Steam: {steam_str} | {buff_str}")
|
| 106 |
+
|
| 107 |
+
card.append(Module.Section(Element.Text("```\n" + "\n".join(lines) + "\n```", type=Types.Text.KMD)))
|
| 108 |
+
card.append(Module.Context(Element.Text(f"<@{user_id}> **点击对应编号,获取市场明细:**", type=Types.Text.KMD)))
|
| 109 |
+
for i in range(0, len(selected_items), 4):
|
| 110 |
+
group_btns = [Element.Button(f"详细 #{i+idx+1}", value=f"skin_chart|{item['en_name']}", click=Types.Click.RETURN_VAL, theme=Types.Theme.PRIMARY)
|
| 111 |
+
for idx, item in enumerate(selected_items[i:i+4])]
|
| 112 |
+
card.append(Module.ActionGroup(*group_btns))
|
| 113 |
+
return card
|
| 114 |
+
|
| 115 |
+
def build_skin_chart_card(target_item):
|
| 116 |
+
card = Card(color="#2F3136")
|
| 117 |
+
card.append(Module.Header(f"物品数据档案:{target_item['cn_name']}"))
|
| 118 |
+
|
| 119 |
+
steam_price = target_item.get('price', 0)
|
| 120 |
+
buff_price = target_item.get('buff_price', 0)
|
| 121 |
+
|
| 122 |
+
# 双线价格排版
|
| 123 |
+
stats_text = f"**Steam 市场参考价**:`¥ {steam_price:.2f}`\n"
|
| 124 |
+
if buff_price > 0:
|
| 125 |
+
stats_text += f"**BUFF 第三方底价**:`¥ {buff_price:.2f}`"
|
| 126 |
+
else:
|
| 127 |
+
stats_text += f"**BUFF 第三方底价**:`暂无数据`"
|
| 128 |
+
|
| 129 |
+
card.append(Module.Section(Element.Text(stats_text, type=Types.Text.KMD)))
|
| 130 |
+
|
| 131 |
+
# 编码转换:用于外部链接跳转
|
| 132 |
+
full_en_name = urllib.parse.quote(target_item["en_name"])
|
| 133 |
+
search_cn_name = urllib.parse.quote(target_item["cn_name"]) # BUFF 更倾向于搜中文名
|
| 134 |
+
|
| 135 |
+
card.append(Module.ActionGroup(
|
| 136 |
+
Element.Button("Steam 社区市场", f"https://steamcommunity.com/market/search?appid=730&q={full_en_name}", Types.Click.LINK, theme=Types.Theme.PRIMARY),
|
| 137 |
+
# 已将按钮文本和链接全面替换为 BUFF 市场
|
| 138 |
+
Element.Button("网易 BUFF 市场", f"https://buff.163.com/market/csgo#tab=selling&page_num=1&search={search_cn_name}", Types.Click.LINK, theme=Types.Theme.SECONDARY)
|
| 139 |
+
))
|
| 140 |
+
return card
|
| 141 |
+
|
| 142 |
+
def build_cs2_profile_card(safe_name, years, level, is_banned, inv_text, top_3_items, avatar_url, has_stats, weapon_line, map_line, k_d, hs_rate, recent_stats, profile_url, steam_id):
|
| 143 |
+
card = Card(color="#2F3136")
|
| 144 |
+
card.append(Module.Container(Element.Image(src="https://media.st.dl.eccdnx.com/steam/apps/730/capsule_616x353.jpg")))
|
| 145 |
+
card.append(Module.Header(f"CS2 官匹档案: {safe_name}"))
|
| 146 |
+
lines = [f"**账户年限**:{years} ��� | **等级**:Lv.{level}", f"**违规状态**:{'被封禁' if is_banned else '正常'}", f"**资产状况**:{inv_text}"]
|
| 147 |
+
if top_3_items:
|
| 148 |
+
lines.append("---")
|
| 149 |
+
lines.append("**前三饰品:**")
|
| 150 |
+
for idx, it in enumerate(top_3_items): lines.append(f"`{idx+1}.` {it['name'].replace('`', '')} ▶ `¥ {it['price']:,.2f}`")
|
| 151 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD), accessory=Element.Image(src=avatar_url, size=Types.Size.LG)))
|
| 152 |
+
|
| 153 |
+
if has_stats: card.append(Module.Section(Element.Text(f"---\n**主枪**:{weapon_line}\n**强图**:{map_line}\n**K/D**:`{k_d}` | **爆头率**:`{hs_rate}%`", type=Types.Text.KMD)))
|
| 154 |
+
else: card.append(Module.Section(Element.Text("---\n> [数据加密] 服务器离线或没有公开个人资料", type=Types.Text.KMD)))
|
| 155 |
+
|
| 156 |
+
if recent_stats:
|
| 157 |
+
card.append(Module.Divider())
|
| 158 |
+
r_val = float(recent_stats['avg_rating'])
|
| 159 |
+
eval_txt = "S级 | 绝对的大哥数据" if r_val >= 1.25 else "A级 | 队伍核心火力" if r_val >= 1.10 else "B级 | 中规中矩" if r_val >= 0.95 else "C级 | 状态低迷" if r_val >= 0.85 else "D级 | 绿色环保玩家"
|
| 160 |
+
card.append(Module.Section(Element.Text(f"**胜率**:`{recent_stats['win_rate']}` | **Rating**:`{recent_stats['avg_rating']}` | **ADR**:`{recent_stats['avg_adr']}`\n> 评价:{eval_txt}", type=Types.Text.KMD)))
|
| 161 |
+
else:
|
| 162 |
+
card.append(Module.Divider())
|
| 163 |
+
card.append(Module.Section(Element.Text("**[ 核心实战评级 ]**\n> ⚠️ **未获取到公开评级**。建议前往 Leetify官网 登录解锁数据。", type=Types.Text.KMD)))
|
| 164 |
+
|
| 165 |
+
card.append(Module.ActionGroup(Element.Button("查看Steam主页", profile_url, Types.Click.LINK, theme=Types.Theme.SECONDARY), Element.Button("完整数据(需登录)", f"https://csstats.gg/player/{steam_id}", Types.Click.LINK, theme=Types.Theme.PRIMARY)))
|
| 166 |
+
return card
|
| 167 |
+
|
| 168 |
+
def build_cs2_status_card(s_logon, real_inv_status, s_gc, mm, status_map):
|
| 169 |
+
all_good = (s_logon == "normal") and ("ONLINE" in real_inv_status.upper())
|
| 170 |
+
card = Card(color="#4CAF50" if all_good else "#FF9800")
|
| 171 |
+
card.append(Module.Header("Steam 服务器状态"))
|
| 172 |
+
lines = [
|
| 173 |
+
f"**Steam 登录系统:** {status_map.get(s_logon, '未知状态')}", f"**库存服务:** {real_inv_status}", f"**游戏协调器:** {status_map.get(s_gc, '未知状态')}", "---",
|
| 174 |
+
f"**全球在线玩家:** `{mm.get('online_players', 0):,}`", f"**正在匹配人数:** `{mm.get('searching_players', 0):,}`"
|
| 175 |
+
]
|
| 176 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD)))
|
| 177 |
+
return card
|
| 178 |
+
|
| 179 |
+
def build_apex_packs_card(count, total_cost, total_earned, profit, results, total_profit, user_name):
|
| 180 |
+
if results['heirloom'] > 0: card_color = "#FF0000"
|
| 181 |
+
elif results['legendary'] > 0: card_color = "#FFD700"
|
| 182 |
+
elif results['epic'] > 0: card_color = "#800080"
|
| 183 |
+
else: card_color = "#0000FF"
|
| 184 |
+
card = Card(color=card_color)
|
| 185 |
+
card.append(Module.Header(f"APEX 英雄 {count} 包模拟结果"))
|
| 186 |
+
lines = [
|
| 187 |
+
f"**总花费**:`¥ {total_cost:.2f}` (按 7元/包估算)", f"**总估值**:`¥ {total_earned:.2f}`", f"**本轮盈亏**:{'+ ¥ ' if profit > 0 else '- ¥ '}{abs(profit):.2f}", "---",
|
| 188 |
+
f"🟥 **传家宝 (神话)**:`{results['heirloom']}` 次", f"🟨 **传说 (金)**:`{results['legendary']}` 个", f"🟪 **史诗 (紫)**:`{results['epic']}` 个",
|
| 189 |
+
f"🟦 **稀有 (蓝)**:`{results['rare']}` 个", f"⬜ **普通 (白)**:`{results['common']}` 个", "---", f"**历史总净值**:{'¥ ' if total_profit > 0 else '- ¥ '}{abs(total_profit):.2f}"
|
| 190 |
+
]
|
| 191 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD)))
|
| 192 |
+
context_text = f"[ 用户: {user_name} ] "
|
| 193 |
+
if results['heirloom'] > 0: context_text += "🎉 出传了!恭喜!"
|
| 194 |
+
elif results['legendary'] >= count * 0.1: context_text += "✨ 运气不错,金光闪闪!"
|
| 195 |
+
elif profit < -total_cost * 0.5: context_text += "😭 蓝天白云"
|
| 196 |
+
else: context_text += "👍 中规中矩"
|
| 197 |
+
card.append(Module.Context(Element.Text(context_text, type=Types.Text.KMD)))
|
| 198 |
+
return card
|
| 199 |
+
|
| 200 |
+
def build_apex_map_card(pubs, ranked):
|
| 201 |
+
card = Card(color="#E82E2E")
|
| 202 |
+
card.append(Module.Header("APEX 英雄 - 实时地图轮换"))
|
| 203 |
+
if pubs:
|
| 204 |
+
curr = pubs.get('current', {}); nxt = pubs.get('next', {})
|
| 205 |
+
card.append(Module.Section(Element.Text(f"**🎮 普通匹配**\n> **当前地图**:`{curr.get('map', '未知')}`\n> **剩余时间**:{curr.get('remainingTimer', '未知')}\n> **下一张图**:{nxt.get('map', '未知')}", type=Types.Text.KMD), accessory=Element.Image(src=curr.get('asset', ''), size=Types.Size.LG)))
|
| 206 |
+
card.append(Module.Divider())
|
| 207 |
+
if ranked:
|
| 208 |
+
curr = ranked.get('current', {}); nxt = ranked.get('next', {})
|
| 209 |
+
card.append(Module.Section(Element.Text(f"**🏆 排位赛**\n> **当前地图**:`{curr.get('map', '未知')}`\n> **剩余时间**:{curr.get('remainingTimer', '未知')}\n> **下一张图**:{nxt.get('map', '未知')}", type=Types.Text.KMD), accessory=Element.Image(src=curr.get('asset', ''), size=Types.Size.LG)))
|
| 210 |
+
return card
|
| 211 |
+
|
| 212 |
+
def build_apex_stat_card(global_data, realtime, legends, player_name, platform):
|
| 213 |
+
is_online = realtime.get('isOnline', 0)
|
| 214 |
+
state_txt = "🔴 游戏中" if is_online and realtime.get('isInGame') else ("🟢 在线" if is_online else "⚪ 离线")
|
| 215 |
+
card = Card(color="#E82E2E")
|
| 216 |
+
card.append(Module.Header(f"APEX 档案:{global_data.get('name', player_name)}"))
|
| 217 |
+
lines = [
|
| 218 |
+
f"**平台**:`{global_data.get('platform', platform.upper())}` | **状态**:{state_txt}", f"**账号等级**:`Lv.{global_data.get('level', 0)}`", "---",
|
| 219 |
+
f"**当前段位**:`{global_data.get('rank', {}).get('rankName', 'Unranked')} {global_data.get('rank', {}).get('rankDiv', '')}`", f"**排位分数**:`{global_data.get('rank', {}).get('rankScore', 0):,} RP`", "---",
|
| 220 |
+
f"**当前传奇**:`{legends.get('LegendName', '未知英雄')}`"
|
| 221 |
+
]
|
| 222 |
+
if legends.get('data', []):
|
| 223 |
+
lines.append("**数据追踪器**:")
|
| 224 |
+
for t in legends.get('data', []): lines.append(f"> {t.get('name', '未知')}: `{t.get('value', 0)}`")
|
| 225 |
+
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD), accessory=Element.Image(src=global_data.get('rank', {}).get('rankImg', ''), size=Types.Size.SM)))
|
| 226 |
+
if legends.get('ImgAssets', {}).get('icon', ''): card.append(Module.Container(Element.Image(src=legends.get('ImgAssets', {}).get('icon', ''))))
|
| 227 |
+
return card
|
utils/cs2_calculator.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from core.config import WEAPON_MAP, MAP_MAP
|
| 2 |
+
|
| 3 |
+
def analyze_cs2_stats(stats_res):
|
| 4 |
+
"""Orchestrates the calculation logic for a player's CS2 statistics."""
|
| 5 |
+
if not isinstance(stats_res, dict) or 'playerstats' not in stats_res:
|
| 6 |
+
return False, "无相关数据", "无相关数据", 0, 0, None
|
| 7 |
+
|
| 8 |
+
# Flatten the stats array into a fast lookup dictionary
|
| 9 |
+
stats_dict = {i['name']: i['value'] for i in stats_res.get('playerstats', {}).get('stats', [])}
|
| 10 |
+
|
| 11 |
+
kills = stats_dict.get('total_kills', 0)
|
| 12 |
+
deaths = stats_dict.get('total_deaths', 1)
|
| 13 |
+
|
| 14 |
+
kd_ratio = round(kills / deaths, 2) if deaths > 0 else 0
|
| 15 |
+
hs_rate = round((stats_dict.get('total_kills_headshot', 0) / kills) * 100, 1) if kills > 0 else 0
|
| 16 |
+
|
| 17 |
+
weapon_line = _get_top_weapons(stats_dict)
|
| 18 |
+
map_line = _get_top_maps(stats_dict)
|
| 19 |
+
recent_stats = _calculate_advanced_metrics(stats_dict, kills, deaths)
|
| 20 |
+
|
| 21 |
+
return True, weapon_line, map_line, kd_ratio, hs_rate, recent_stats
|
| 22 |
+
|
| 23 |
+
def analyze_inventory(inv: dict, is_price_ready: bool, price_en_map: dict):
|
| 24 |
+
"""Calculates the total value of a player's inventory."""
|
| 25 |
+
if not isinstance(inv, dict) or 'assets' not in inv:
|
| 26 |
+
return "[受限权限] 资产设定为不可见", []
|
| 27 |
+
|
| 28 |
+
item_count = inv.get('total_inventory_count', 0)
|
| 29 |
+
if not is_price_ready:
|
| 30 |
+
return f"持有 {item_count} 项 | 预估市值 (同步中...)", []
|
| 31 |
+
|
| 32 |
+
total_val, top_3_items = _parse_inventory_assets(inv, price_en_map)
|
| 33 |
+
inv_text = f"持有 {item_count} 项 | 预估市值 ¥ {total_val:,.2f}"
|
| 34 |
+
|
| 35 |
+
return inv_text, top_3_items
|
| 36 |
+
|
| 37 |
+
# --- Private Helper Functions ---
|
| 38 |
+
|
| 39 |
+
def _get_top_weapons(stats_dict: dict) -> str:
|
| 40 |
+
"""Extracts and formats the top 3 most used weapons."""
|
| 41 |
+
invalid_weapons = ['headshot', 'enemy_weapon', 'enemy_blinded', 'knife_fight', 'against_zoomed_sniper', 'taser']
|
| 42 |
+
w_stats = {
|
| 43 |
+
key.replace('total_kills_', ''): v
|
| 44 |
+
for key, v in stats_dict.items()
|
| 45 |
+
if key.startswith('total_kills_') and key != 'total_kills' and not any(x in key for x in invalid_weapons)
|
| 46 |
+
}
|
| 47 |
+
top_w = sorted(w_stats.items(), key=lambda x: x[1], reverse=True)[:3]
|
| 48 |
+
return " / ".join([f"{WEAPON_MAP.get(w, w)}:{v}" for w, v in top_w])
|
| 49 |
+
|
| 50 |
+
def _get_top_maps(stats_dict: dict) -> str:
|
| 51 |
+
"""Extracts and formats the most successful map."""
|
| 52 |
+
m_stats = {key.replace('total_wins_map_', ''): v for key, v in stats_dict.items() if key.startswith('total_wins_map_de_')}
|
| 53 |
+
top_m = sorted(m_stats.items(), key=lambda x: x[1], reverse=True)
|
| 54 |
+
return f"{MAP_MAP.get(top_m[0][0], top_m[0][0])} (胜场: {top_m[0][1]})" if top_m else "无胜场记录"
|
| 55 |
+
|
| 56 |
+
def _calculate_advanced_metrics(s: dict, kills: int, deaths: int) -> dict:
|
| 57 |
+
"""Calculates ADR, Win Rate, and the custom Rating 2.0."""
|
| 58 |
+
dmg = s.get('total_damage_done', 0)
|
| 59 |
+
rounds = s.get('total_rounds_played', 1)
|
| 60 |
+
won_matches = s.get('total_matches_won', 0)
|
| 61 |
+
play_matches = s.get('total_matches_played', 0)
|
| 62 |
+
|
| 63 |
+
adr_val = dmg / rounds if rounds > 0 else 0
|
| 64 |
+
|
| 65 |
+
if play_matches > 0 and won_matches > 0:
|
| 66 |
+
win_rate_str = f"{(won_matches / play_matches) * 100:.1f}%"
|
| 67 |
+
else:
|
| 68 |
+
won_rounds = s.get('total_wins', 0)
|
| 69 |
+
win_rate_str = f"{(won_rounds / rounds) * 100:.1f}%"
|
| 70 |
+
|
| 71 |
+
rating = _compute_rating_algorithm(kills, deaths, adr_val, rounds)
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"avg_rating": f"{rating:.2f}",
|
| 75 |
+
"avg_adr": f"{adr_val:.1f}",
|
| 76 |
+
"win_rate": win_rate_str,
|
| 77 |
+
"matches_count": "Steam 全模式综合 (含死斗)"
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
def _compute_rating_algorithm(k: int, dt: int, adr: float, rounds: int) -> float:
|
| 81 |
+
"""Core mathematical algorithm for simulating HLTV Rating 2.0."""
|
| 82 |
+
if rounds <= 0: return 0.00
|
| 83 |
+
|
| 84 |
+
kpr = min(k / rounds, 1.5)
|
| 85 |
+
dpr = min(dt / rounds, 1.0)
|
| 86 |
+
spr = max(0.0, 1.0 - dpr) # Survived per round
|
| 87 |
+
clamped_adr = min(adr, 150.0)
|
| 88 |
+
|
| 89 |
+
estimated_impact = 2.13 * kpr + (0.42 * 0.14) - 0.41
|
| 90 |
+
estimated_kast = max(50.0, min((spr * 100) + 38.0, 85.0))
|
| 91 |
+
|
| 92 |
+
raw_rating = (0.0073 * estimated_kast + 0.3591 * kpr - 0.5329 * dpr + 0.2372 * estimated_impact + 0.0032 * clamped_adr + 0.1587)
|
| 93 |
+
return min(round(raw_rating, 2), 2.99)
|
| 94 |
+
|
| 95 |
+
def _parse_inventory_assets(inv: dict, price_en_map: dict):
|
| 96 |
+
"""Matches inventory items to current market prices."""
|
| 97 |
+
desc_map = {desc['classid']: desc.get('market_hash_name', '') for desc in inv.get('descriptions', [])}
|
| 98 |
+
item_list = []
|
| 99 |
+
total_val = 0.0
|
| 100 |
+
|
| 101 |
+
for asset in inv.get('assets', []):
|
| 102 |
+
en_name = desc_map.get(asset['classid'], '')
|
| 103 |
+
if en_name and en_name in price_en_map:
|
| 104 |
+
item_price = price_en_map[en_name]['price']
|
| 105 |
+
item_list.append({"name": price_en_map[en_name]['cn_name'], "price": item_price})
|
| 106 |
+
total_val += item_price
|
| 107 |
+
|
| 108 |
+
item_list.sort(key=lambda x: x['price'], reverse=True)
|
| 109 |
+
return total_val, item_list[:3]
|
utils/cs2_logic.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
logger = logging.getLogger(__name__)
|
| 5 |
+
|
| 6 |
+
# --- Constants for item tiers and metadata ---
|
| 7 |
+
TIERS_LIST = ['gold', 'red', 'pink', 'purple', 'blue']
|
| 8 |
+
TIERS_WEIGHTS = [1.00, 2.50, 10.00, 30.00, 56.50]
|
| 9 |
+
TIER_INFO = {
|
| 10 |
+
'gold': ("罕见级", "#FFD700"),
|
| 11 |
+
'red': ("隐秘级", "#EB4B4B"),
|
| 12 |
+
'pink': ("保密级", "#D32CE6"),
|
| 13 |
+
'purple': ("受限级", "#8847FF"),
|
| 14 |
+
'blue': ("军规级", "#4B69FF")
|
| 15 |
+
}
|
| 16 |
+
DEFAULT_ITEM_PRICES = {'gold': 2000.0, 'red': 200.0, 'pink': 50.0, 'purple': 15.0, 'blue': 1.0}
|
| 17 |
+
|
| 18 |
+
def generate_random_case_drops(count: int, affordable_cases: list, affordable_capsules: list, price_cn_map: dict, price_dict: list):
|
| 19 |
+
"""Orchestrates random case dropping logic."""
|
| 20 |
+
opened_items = []
|
| 21 |
+
total_cost = 0.0
|
| 22 |
+
total_earned = 0.0
|
| 23 |
+
|
| 24 |
+
for _ in range(count):
|
| 25 |
+
drop_result = _simulate_single_drop(affordable_cases, affordable_capsules, price_cn_map, price_dict)
|
| 26 |
+
if not drop_result:
|
| 27 |
+
continue
|
| 28 |
+
|
| 29 |
+
opened_items.append(drop_result)
|
| 30 |
+
total_cost += drop_result['cost']
|
| 31 |
+
total_earned += drop_result['price']
|
| 32 |
+
|
| 33 |
+
return opened_items, total_cost, total_earned
|
| 34 |
+
|
| 35 |
+
def _simulate_single_drop(cases: list, capsules: list, price_cn_map: dict, price_dict: list):
|
| 36 |
+
"""Simulates opening a single case/capsule."""
|
| 37 |
+
is_capsule = random.random() < 0.25
|
| 38 |
+
valid_crates = capsules if is_capsule else cases
|
| 39 |
+
if not valid_crates:
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
crate = random.choice(valid_crates)
|
| 43 |
+
cost = _calculate_cost(crate, is_capsule, price_cn_map)
|
| 44 |
+
# 🌟 性能优化核心 3:直接从预计算缓存中提取,不再遍历箱子内的所有物品
|
| 45 |
+
tiers = crate.get('precomputed_tiers', _categorize_items_by_tier_fallback(crate))
|
| 46 |
+
|
| 47 |
+
selected_tier = random.choices(TIERS_LIST, weights=TIERS_WEIGHTS, k=1)[0]
|
| 48 |
+
raw_item, final_tier = _pick_item(crate, tiers, selected_tier, is_capsule, price_dict)
|
| 49 |
+
|
| 50 |
+
if not raw_item:
|
| 51 |
+
logger.error(f"[Open Engine] 掉落池为空 - 箱子: {crate.get('name')}")
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
item_name, item_price = _determine_final_item(raw_item, final_tier, price_dict)
|
| 55 |
+
rarity_name, color_code = TIER_INFO.get(final_tier, TIER_INFO['blue'])
|
| 56 |
+
|
| 57 |
+
return {
|
| 58 |
+
'crate_name': crate.get('name'),
|
| 59 |
+
'item_name': item_name,
|
| 60 |
+
'price': item_price,
|
| 61 |
+
'cost': cost,
|
| 62 |
+
'tier': final_tier,
|
| 63 |
+
'rarity_name': rarity_name,
|
| 64 |
+
'color': color_code
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def _calculate_cost(crate: dict, is_capsule: bool, price_cn_map: dict) -> float:
|
| 68 |
+
name = crate.get('name')
|
| 69 |
+
price_data = price_cn_map.get(name)
|
| 70 |
+
market_price = price_data['price'] if price_data else (1.5 if is_capsule else 5.0)
|
| 71 |
+
is_key_required = (crate.get('type') in ['Weapon Case', '武器箱'] or '武器箱' in name)
|
| 72 |
+
return market_price + (17.5 if is_key_required else 0.0)
|
| 73 |
+
|
| 74 |
+
def _categorize_items_by_tier_fallback(crate: dict) -> dict:
|
| 75 |
+
"""仅在缓存丢失时使用的降级方法"""
|
| 76 |
+
tiers = {tier: [] for tier in TIERS_LIST}
|
| 77 |
+
for item in crate.get('contains', []):
|
| 78 |
+
rarity = str(item.get('rarity', {}).get('name', '') if isinstance(item.get('rarity'), dict) else item.get('rarity', ''))
|
| 79 |
+
name = str(item.get('name', ''))
|
| 80 |
+
|
| 81 |
+
if any(k in rarity for k in ['违禁', 'Contraband']) or any(k in name for k in ['★', '纯金', 'Gold', '金色']):
|
| 82 |
+
tiers['gold'].append(item)
|
| 83 |
+
elif any(k in rarity for k in ['隐秘', 'Covert', '非凡', 'Extraordinary', '大师', 'Master']):
|
| 84 |
+
tiers['red'].append(item)
|
| 85 |
+
elif any(k in rarity for k in ['保密', 'Classified', '奇异', 'Exotic']):
|
| 86 |
+
tiers['pink'].append(item)
|
| 87 |
+
elif any(k in rarity for k in ['受限', 'Restricted', '卓越', 'Remarkable', 'Exceptional']):
|
| 88 |
+
tiers['purple'].append(item)
|
| 89 |
+
else:
|
| 90 |
+
tiers['blue'].append(item)
|
| 91 |
+
return tiers
|
| 92 |
+
|
| 93 |
+
def _pick_item(crate: dict, tiers: dict, selected_tier: str, is_capsule: bool, price_dict: list):
|
| 94 |
+
"""Picks an item from the selected tier or falls back if empty."""
|
| 95 |
+
if selected_tier == 'gold':
|
| 96 |
+
rare_items = crate.get('contains_rare', [])
|
| 97 |
+
if rare_items:
|
| 98 |
+
return random.choice(rare_items), 'gold'
|
| 99 |
+
elif tiers['gold']:
|
| 100 |
+
return random.choice(tiers['gold']), 'gold'
|
| 101 |
+
elif not is_capsule:
|
| 102 |
+
# Gold fallback fallback for cases without defined standard gold drops
|
| 103 |
+
knives = [i for i in price_dict if any(k in i['cn_name'] for k in ["刀", "手套", "★"])]
|
| 104 |
+
return random.choice(knives), 'gold'
|
| 105 |
+
else:
|
| 106 |
+
selected_tier = 'red' # Capsules skip gold logic if no rare items exist
|
| 107 |
+
|
| 108 |
+
# Fallback to nearest populated tier if selected tier is empty
|
| 109 |
+
if not tiers[selected_tier]:
|
| 110 |
+
fallback_order = ['red', 'pink', 'purple', 'blue', 'gold']
|
| 111 |
+
start_idx = fallback_order.index(selected_tier)
|
| 112 |
+
search_list = fallback_order[start_idx:] + fallback_order[:start_idx]
|
| 113 |
+
for t in search_list:
|
| 114 |
+
if tiers[t]:
|
| 115 |
+
return random.choice(tiers[t]), t
|
| 116 |
+
|
| 117 |
+
return random.choice(tiers[selected_tier]) if tiers[selected_tier] else None, selected_tier
|
| 118 |
+
|
| 119 |
+
def _determine_final_item(raw_item, tier: str, price_dict: list):
|
| 120 |
+
"""Resolves base item to a specific wear/variant market match."""
|
| 121 |
+
# Fast path if raw_item is already a matched price_dict entry (like fallback knives)
|
| 122 |
+
if isinstance(raw_item, dict) and 'cn_name' in raw_item and 'price' in raw_item:
|
| 123 |
+
return raw_item['cn_name'], raw_item['price']
|
| 124 |
+
|
| 125 |
+
base_name = str(raw_item.get('name', '')) if raw_item else ""
|
| 126 |
+
if not base_name:
|
| 127 |
+
return "未知物品", DEFAULT_ITEM_PRICES.get(tier, 1.0)
|
| 128 |
+
|
| 129 |
+
# 1. Exact match pass
|
| 130 |
+
matched_items = []
|
| 131 |
+
for i in price_dict:
|
| 132 |
+
if _is_valid_match(base_name, i['cn_name'], i['en_name']):
|
| 133 |
+
matched_items.append(i)
|
| 134 |
+
if len(matched_items) >= 5:
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
# 2. Fuzzy match pass (if strict failed)
|
| 138 |
+
if not matched_items and " | " in base_name:
|
| 139 |
+
skin = base_name.split(" | ")[-1].strip()
|
| 140 |
+
for i in price_dict:
|
| 141 |
+
if skin in i['cn_name'] and _is_valid_match(base_name, i['cn_name'], i['en_name'], fuzzy=True):
|
| 142 |
+
matched_items.append(i)
|
| 143 |
+
if len(matched_items) >= 5:
|
| 144 |
+
break
|
| 145 |
+
|
| 146 |
+
if matched_items:
|
| 147 |
+
chosen = random.choice(matched_items)
|
| 148 |
+
return chosen['cn_name'], chosen['price']
|
| 149 |
+
|
| 150 |
+
# 3. Fallback Generation (Pure Simulation if no market data exists)
|
| 151 |
+
fallback_price = DEFAULT_ITEM_PRICES.get(tier, 1.0)
|
| 152 |
+
# Randomize price modifier so it doesn't always show exactly "¥ 1.00"
|
| 153 |
+
fallback_price = fallback_price * random.uniform(0.65, 2.50)
|
| 154 |
+
|
| 155 |
+
fallback_name = base_name
|
| 156 |
+
# Append wear if it is a weapon (denoted by '|')
|
| 157 |
+
if " | " in base_name or "手套" in base_name or "刀" in base_name or "★" in base_name:
|
| 158 |
+
wears = [" (崭新)", " (略磨)", " (久经)", " (破损)", " (战痕)"]
|
| 159 |
+
fallback_name += random.choice(wears)
|
| 160 |
+
|
| 161 |
+
return fallback_name, round(fallback_price, 2)
|
| 162 |
+
|
| 163 |
+
def _is_valid_match(base_name: str, cn_name: str, en_name: str, fuzzy=False) -> bool:
|
| 164 |
+
"""Verifies modifiers (StatTrak, Souvenir, Holo) accurately match."""
|
| 165 |
+
# During fuzzy match, we skip the strict string inclusion check
|
| 166 |
+
if not fuzzy:
|
| 167 |
+
# Pre-process strings for slightly safer exact matching (ignore spaces)
|
| 168 |
+
b_clean = base_name.replace(" ", "").lower()
|
| 169 |
+
c_clean = cn_name.replace(" ", "").lower()
|
| 170 |
+
e_clean = en_name.replace(" ", "").lower()
|
| 171 |
+
if b_clean not in c_clean and b_clean not in e_clean:
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
variants = [
|
| 175 |
+
("闪亮", "闪亮"), ("全息", "全息"), ("斑斓", "斑斓"),
|
| 176 |
+
("暗金", ("暗金", "StatTrak")), ("纪念品", "纪念品"),
|
| 177 |
+
("金", ("金", "Gold"))
|
| 178 |
+
]
|
| 179 |
+
for _, checks in variants:
|
| 180 |
+
if isinstance(checks, tuple):
|
| 181 |
+
if any(c in cn_name for c in checks) and not any(c in base_name for c in checks):
|
| 182 |
+
return False
|
| 183 |
+
elif checks in cn_name and checks not in base_name:
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
return True
|
utils/rate_limiter.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
|
| 4 |
+
class RateLimiter:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
# 存储结构:{ "指令名": { "用户ID": 上次执行时间戳 } }
|
| 7 |
+
self._last_times = defaultdict(dict)
|
| 8 |
+
|
| 9 |
+
def check_limit(self, user_id: str, command_name: str, cooldown: float):
|
| 10 |
+
"""
|
| 11 |
+
检查用户是否正在冷却中
|
| 12 |
+
返回:(是否被限制, 剩余秒数)
|
| 13 |
+
"""
|
| 14 |
+
now = time.time()
|
| 15 |
+
# 获取该用户该指令上一次的执行时间
|
| 16 |
+
last_time = self._last_times[command_name].get(user_id, 0)
|
| 17 |
+
elapsed = now - last_time
|
| 18 |
+
|
| 19 |
+
if elapsed < cooldown:
|
| 20 |
+
# 还在冷却中
|
| 21 |
+
return True, round(cooldown - elapsed, 1)
|
| 22 |
+
|
| 23 |
+
# 没被限制,更新执行时间
|
| 24 |
+
self._last_times[command_name][user_id] = now
|
| 25 |
+
return False, 0
|
| 26 |
+
|
| 27 |
+
# 实例化一个全局风控器
|
| 28 |
+
rate_limiter = RateLimiter()
|