tmp
Browse files
app.py
DELETED
|
@@ -1,165 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import time
|
| 3 |
-
import logging
|
| 4 |
-
import aiohttp
|
| 5 |
-
from aiohttp import web
|
| 6 |
-
from khl import Bot, Message
|
| 7 |
-
from khl.card import CardMessage, Card, Module, Element, Types
|
| 8 |
-
|
| 9 |
-
from core.config import BOT_TOKEN, SPACE_ID
|
| 10 |
-
from core.database import db
|
| 11 |
-
from services.data_manager import data_mgr
|
| 12 |
-
from utils.cs2_logic import generate_random_case_drops
|
| 13 |
-
from utils.card_builder import build_open_case_card, build_help_card, build_me_card
|
| 14 |
-
from utils.rate_limiter import rate_limiter
|
| 15 |
-
|
| 16 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
-
logger = logging.getLogger(__name__)
|
| 18 |
-
|
| 19 |
-
bot = Bot(token=BOT_TOKEN)
|
| 20 |
-
_start_time = time.time()
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
@bot.command(name='help', prefixes=['/'])
|
| 24 |
-
async def show_help(msg: Message):
|
| 25 |
-
await msg.reply(CardMessage(build_help_card()))
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
@bot.command(name='open', prefixes=['/'])
|
| 29 |
-
async def handle_open(msg: Message, *args):
|
| 30 |
-
is_limited, remaining = rate_limiter.check_limit(str(msg.author.id), "cs2_open", 2.0)
|
| 31 |
-
if is_limited:
|
| 32 |
-
return await msg.reply(f"❌ 别点太快!冷却剩余 {remaining} 秒...")
|
| 33 |
-
if not data_mgr.is_price_ready:
|
| 34 |
-
return await msg.reply("⏳ 系统正在同步最新价格,请稍后再试...")
|
| 35 |
-
|
| 36 |
-
count = max(1, min(10, int(args[0]))) if args and args[0].isdigit() else 1
|
| 37 |
-
try:
|
| 38 |
-
items, cost, earned = generate_random_case_drops(
|
| 39 |
-
count, data_mgr.affordable_cases, data_mgr.affordable_capsules,
|
| 40 |
-
data_mgr.price_cn_map, data_mgr.price_dict
|
| 41 |
-
)
|
| 42 |
-
profit = earned - cost
|
| 43 |
-
user_id, name = str(msg.author.id), msg.author.username
|
| 44 |
-
|
| 45 |
-
upd = await db.eco.find_one_and_update(
|
| 46 |
-
{"_id": user_id},
|
| 47 |
-
{"$set": {"name": name},
|
| 48 |
-
"$inc": {"spent": cost, "earned": earned, "profit": profit, "opens": count}},
|
| 49 |
-
upsert=True, return_document=True
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
card = build_open_case_card(
|
| 53 |
-
count, items, profit,
|
| 54 |
-
upd['profit'], upd['opens'],
|
| 55 |
-
cost, earned, name
|
| 56 |
-
)
|
| 57 |
-
await msg.reply(CardMessage(card))
|
| 58 |
-
except Exception as e:
|
| 59 |
-
logger.error(f"[Open] 异常: {e}", exc_info=True)
|
| 60 |
-
await msg.reply("❌ 计算引擎意外终止。")
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
@bot.command(name='me', prefixes=['/'])
|
| 64 |
-
async def handle_me(msg: Message):
|
| 65 |
-
user_id = str(msg.author.id)
|
| 66 |
-
doc = await db.eco.find_one({"_id": user_id})
|
| 67 |
-
if not doc:
|
| 68 |
-
return await msg.reply("📭 你还没开过箱!输入 `/open` 开始吧。")
|
| 69 |
-
card = build_me_card(
|
| 70 |
-
doc.get('name', msg.author.username),
|
| 71 |
-
doc.get('profit', 0),
|
| 72 |
-
doc.get('spent', 0),
|
| 73 |
-
doc.get('earned', 0),
|
| 74 |
-
doc.get('opens', 0)
|
| 75 |
-
)
|
| 76 |
-
await msg.reply(CardMessage(card))
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
@bot.command(name='status', prefixes=['/'])
|
| 80 |
-
async def handle_status(msg: Message):
|
| 81 |
-
uptime = int(time.time() - _start_time)
|
| 82 |
-
h, m = uptime // 3600, (uptime % 3600) // 60
|
| 83 |
-
|
| 84 |
-
space_info = "未知"
|
| 85 |
-
try:
|
| 86 |
-
from huggingface_hub import HfApi
|
| 87 |
-
runtime = HfApi().get_space_runtime(SPACE_ID)
|
| 88 |
-
stage = runtime.stage
|
| 89 |
-
hw = runtime.hardware if runtime.hardware else "?"
|
| 90 |
-
space_info = f"{stage} ({hw})"
|
| 91 |
-
except Exception:
|
| 92 |
-
pass
|
| 93 |
-
|
| 94 |
-
# 系统资源
|
| 95 |
-
cpu_str = "N/A"
|
| 96 |
-
mem_str = "N/A"
|
| 97 |
-
try:
|
| 98 |
-
import psutil
|
| 99 |
-
psutil.cpu_percent(interval=0.1) # warm up
|
| 100 |
-
cpu_str = f"{psutil.cpu_percent(interval=0.5)}%"
|
| 101 |
-
mem = psutil.virtual_memory()
|
| 102 |
-
mem_str = f"{mem.used // 1048576}MB/{mem.total // 1048576}MB ({mem.percent}%)"
|
| 103 |
-
except Exception:
|
| 104 |
-
pass
|
| 105 |
-
|
| 106 |
-
total_opens = 0
|
| 107 |
-
db_status = "✅ 在线"
|
| 108 |
-
try:
|
| 109 |
-
count = await db.eco.count_documents({})
|
| 110 |
-
async for user in db.eco.find({}):
|
| 111 |
-
total_opens += user.get('opens', 0)
|
| 112 |
-
except Exception:
|
| 113 |
-
db_status = "❌ 异常"
|
| 114 |
-
|
| 115 |
-
lines = [
|
| 116 |
-
f"**R4nd0m 开箱 Bot**",
|
| 117 |
-
f"---",
|
| 118 |
-
f"**Space**:{space_info}",
|
| 119 |
-
f"**运行时长**:{h}小时{m}分",
|
| 120 |
-
f"**CPU**:{cpu_str}",
|
| 121 |
-
f"**内存**:{mem_str}",
|
| 122 |
-
f"**MongoDB**:{db_status}",
|
| 123 |
-
f"**武器箱**:{len(data_mgr.affordable_cases)} 个",
|
| 124 |
-
f"**价格**:{len(data_mgr.price_dict)} 条",
|
| 125 |
-
f"**总开箱**:{total_opens} 次",
|
| 126 |
-
]
|
| 127 |
-
|
| 128 |
-
card = Card(color="#4B69FF")
|
| 129 |
-
card.append(Module.Header("📊 系统状态"))
|
| 130 |
-
card.append(Module.Section(Element.Text("\n".join(lines), type=Types.Text.KMD)))
|
| 131 |
-
await msg.reply(CardMessage(card))
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
async def health_check(request):
|
| 135 |
-
return web.json_response({
|
| 136 |
-
"status": "ok",
|
| 137 |
-
"database": "connected" if db.client else "disconnected"
|
| 138 |
-
})
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
async def main():
|
| 142 |
-
db_ok = await db.connect()
|
| 143 |
-
if not db_ok:
|
| 144 |
-
logger.error("[System] MongoDB 连接失败,请检查 MONGO_URI")
|
| 145 |
-
return
|
| 146 |
-
|
| 147 |
-
session = aiohttp.ClientSession()
|
| 148 |
-
try:
|
| 149 |
-
await data_mgr.init_crates_data(session)
|
| 150 |
-
|
| 151 |
-
webapp = web.Application()
|
| 152 |
-
webapp.router.add_get('/health', health_check)
|
| 153 |
-
runner = web.AppRunner(webapp)
|
| 154 |
-
await runner.setup()
|
| 155 |
-
await web.TCPSite(runner, '0.0.0.0', 7860).start()
|
| 156 |
-
|
| 157 |
-
logger.info("[init] MongoDB 版已上线 (%d cases, %d capsules)",
|
| 158 |
-
len(data_mgr.affordable_cases), len(data_mgr.affordable_capsules))
|
| 159 |
-
await bot.start()
|
| 160 |
-
finally:
|
| 161 |
-
await session.close()
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
if __name__ == '__main__':
|
| 165 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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