nonebot-plugin-efthelper 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nonebot_plugin_efthelper/__init__.py +1195 -0
- nonebot_plugin_efthelper/api.py +668 -0
- nonebot_plugin_efthelper/assets/README.md +27 -0
- nonebot_plugin_efthelper/assets/bear.png +0 -0
- nonebot_plugin_efthelper/assets/usec.png +0 -0
- nonebot_plugin_efthelper/card.py +1112 -0
- nonebot_plugin_efthelper/circle.py +380 -0
- nonebot_plugin_efthelper/config.py +310 -0
- nonebot_plugin_efthelper/eftforge.py +177 -0
- nonebot_plugin_efthelper/endings.py +86 -0
- nonebot_plugin_efthelper/format.py +339 -0
- nonebot_plugin_efthelper/image.py +96 -0
- nonebot_plugin_efthelper/index.py +313 -0
- nonebot_plugin_efthelper/registry.py +164 -0
- nonebot_plugin_efthelper-0.1.0.dist-info/METADATA +105 -0
- nonebot_plugin_efthelper-0.1.0.dist-info/RECORD +19 -0
- nonebot_plugin_efthelper-0.1.0.dist-info/WHEEL +5 -0
- nonebot_plugin_efthelper-0.1.0.dist-info/licenses/LICENSE +21 -0
- nonebot_plugin_efthelper-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
"""tarkov.dev 数据访问层。
|
|
2
|
+
|
|
3
|
+
职责划分与原版 stash 的对应关系:
|
|
4
|
+
- `modules/json-api.mjs` + `commands/status.mjs` -> `get_status()`
|
|
5
|
+
- `commands/player.mjs` -> `get_profile()` / `build_render_url()`
|
|
6
|
+
- `modules/game-data.mjs` 的 playerLevels/achievements -> `get_level_table()` / `get_achievement_names()`
|
|
7
|
+
|
|
8
|
+
与原版的差异(都是刻意的):
|
|
9
|
+
1. 不下载 67MB 的玩家昵称索引 —— 按角色 ID 查询不需要它。
|
|
10
|
+
2. 等级表不再每次从 17MB 的 items 端点现取,而是抽出来落盘缓存。
|
|
11
|
+
3. 立绘 URL 不再受原版硬编码的 2048 字符上限限制。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import re
|
|
20
|
+
import time
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, List, Optional
|
|
24
|
+
from urllib.parse import quote
|
|
25
|
+
|
|
26
|
+
from .eftforge import MODES as EFTFORGE_MODES
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("nonebot_plugin_efthelper")
|
|
31
|
+
|
|
32
|
+
JSON_API = "https://json.tarkov.dev"
|
|
33
|
+
PLAYERS_API = "https://players.tarkov.dev"
|
|
34
|
+
IMAGEMAGIC = "https://imagemagic.tarkov.dev"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class GameMode:
|
|
39
|
+
"""一个游戏模式。
|
|
40
|
+
|
|
41
|
+
注意两个 API 的目录命名规则**不一样**,这是原版 player.mjs:62-65 里的隐藏细节:
|
|
42
|
+
|
|
43
|
+
json.tarkov.dev -> /regular/... /pve/... /pvp-season/...
|
|
44
|
+
players.tarkov.dev -> /profile/... /pve/... /pvp-season/...
|
|
45
|
+
|
|
46
|
+
正式服(regular)在 json.tarkov.dev 上叫 regular,
|
|
47
|
+
但在 players.tarkov.dev 上叫 profile。搞错就会一直 404。
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
key: str
|
|
51
|
+
json_folder: str
|
|
52
|
+
players_folder: str
|
|
53
|
+
label: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_PVP = GameMode("regular", "regular", "profile", "PvP")
|
|
57
|
+
_PVE = GameMode("pve", "pve", "pve", "PvE")
|
|
58
|
+
_PVP_SEASON = GameMode("pvp-season", "pvp-season", "pvp-season", "PvP 赛季")
|
|
59
|
+
|
|
60
|
+
# 用户输入 -> GameMode
|
|
61
|
+
MODE_ALIASES: Dict[str, GameMode] = {
|
|
62
|
+
"pvp": _PVP,
|
|
63
|
+
"regular": _PVP,
|
|
64
|
+
"pve": _PVE,
|
|
65
|
+
"pvps": _PVP_SEASON,
|
|
66
|
+
"pvp-season": _PVP_SEASON,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
# 展示用,按顺序列出所有模式
|
|
70
|
+
ALL_MODES: List[GameMode] = [_PVP, _PVE, _PVP_SEASON]
|
|
71
|
+
|
|
72
|
+
# stash commands/status.mjs 里的状态码表,索引即 status 字段
|
|
73
|
+
STATUS_LABELS = ["🟢 正常", "🔄 更新中", "🟡 不稳定", "🔴 宕机"]
|
|
74
|
+
|
|
75
|
+
# player.mjs:96-111 的装备过滤规则
|
|
76
|
+
_SKIP_SLOTS = {
|
|
77
|
+
"FirstPrimaryWeapon",
|
|
78
|
+
"SecondPrimaryWeapon",
|
|
79
|
+
"Holster",
|
|
80
|
+
"Scabbard",
|
|
81
|
+
"Pockets",
|
|
82
|
+
"SecuredContainer",
|
|
83
|
+
"ArmBand",
|
|
84
|
+
}
|
|
85
|
+
_ARMOR_SLOT_PATTERNS = [
|
|
86
|
+
re.compile(r"_plate$"),
|
|
87
|
+
re.compile(r"^[Ss]oft_armor_"),
|
|
88
|
+
re.compile(r"^Collar$"),
|
|
89
|
+
re.compile(r"^Groin$"),
|
|
90
|
+
re.compile(r"^[Hh]elmet_"),
|
|
91
|
+
]
|
|
92
|
+
_SKIP_PROPS = {"Repairable", "Sight", "StackObjectsCount"}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class TarkovError(Exception):
|
|
96
|
+
"""数据获取失败。message 可以直接展示给用户。"""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def resolve_mode(text: str) -> Optional[GameMode]:
|
|
100
|
+
"""把用户输入的模式别名解析成 GameMode。无法识别返回 None。"""
|
|
101
|
+
return MODE_ALIASES.get(text.strip().lower())
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _flea_estimate(item: Dict[str, Any]) -> int:
|
|
105
|
+
"""买入单价的估计:直接采用 24 小时成交均价。
|
|
106
|
+
|
|
107
|
+
为什么是均价而非最低价(2026-11-28 用 5 个游戏内样本拟合的结论):
|
|
108
|
+
· 最低价常是「已被抢掉」的幽灵挂单,按它估会系统性偏低
|
|
109
|
+
(如 TerraGroup 公寓钥匙 low24 28,999 / 实际 60,000);
|
|
110
|
+
· 高价对倒会污染 high24h 与部分成交,所以也不用最高价;
|
|
111
|
+
· 以 avg24h 为基准时,5 个样本的几何平均比值是 0.993,即基本无系统偏差。
|
|
112
|
+
|
|
113
|
+
拟合对比(剔除 20 万以上的贵物,因为它们实际不会被拿去献祭):
|
|
114
|
+
SJ9 avg 40,462 实际 40,000 +1.2%
|
|
115
|
+
公寓钥匙 avg 59,166 实际 60,000 -1.4%
|
|
116
|
+
棘轮扳手 avg 64,320 实际 60,000 +7.2%
|
|
117
|
+
平均绝对误差 3.3%——已经落在数据本身的噪声范围内(±10% 上下波动)。
|
|
118
|
+
|
|
119
|
+
件数带来的「越买越贵」由 circle 的 price_step 处理,不在这里重复。
|
|
120
|
+
"""
|
|
121
|
+
avg = int(item.get("avg24hPrice") or 0)
|
|
122
|
+
if avg > 0:
|
|
123
|
+
return avg
|
|
124
|
+
last = int(item.get("lastLowPrice") or 0)
|
|
125
|
+
if last > 0:
|
|
126
|
+
return last
|
|
127
|
+
return int(item.get("low24hPrice") or 0)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class TarkovClient:
|
|
131
|
+
"""带磁盘缓存的异步数据客户端。整个进程共用一个实例。"""
|
|
132
|
+
|
|
133
|
+
def __init__(
|
|
134
|
+
self,
|
|
135
|
+
cache_dir: Path,
|
|
136
|
+
*,
|
|
137
|
+
cache_ttl: int = 7 * 24 * 3600,
|
|
138
|
+
connect_timeout: float = 10.0,
|
|
139
|
+
read_timeout: float = 90.0,
|
|
140
|
+
render_timeout: float = 35.0,
|
|
141
|
+
max_retries: int = 3,
|
|
142
|
+
max_render_url: int = 8000,
|
|
143
|
+
interactive_timeout: float = 25.0,
|
|
144
|
+
static_timeout: float = 150.0,
|
|
145
|
+
interactive_retries: int = 2,
|
|
146
|
+
render_retries: int = 1,
|
|
147
|
+
profile_cache_ttl: int = 3600,
|
|
148
|
+
profile_stale_ok: bool = True,
|
|
149
|
+
circle_ttl: int = 6 * 3600,
|
|
150
|
+
eftforge_base: str = "https://www.eftforge.com",
|
|
151
|
+
eftforge_key: str = "",
|
|
152
|
+
eftforge_ttl: int = 600,
|
|
153
|
+
eftforge_timeout: float = 20.0,
|
|
154
|
+
) -> None:
|
|
155
|
+
self.cache_dir = Path(cache_dir)
|
|
156
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
self.cache_ttl = cache_ttl
|
|
158
|
+
self.max_retries = max_retries
|
|
159
|
+
self.max_render_url = max_render_url
|
|
160
|
+
|
|
161
|
+
self._client = httpx.AsyncClient(
|
|
162
|
+
follow_redirects=True,
|
|
163
|
+
headers={"user-agent": "nonebot-plugin-efthelper"},
|
|
164
|
+
timeout=httpx.Timeout(
|
|
165
|
+
read_timeout, connect=connect_timeout, write=30.0, pool=10.0
|
|
166
|
+
),
|
|
167
|
+
)
|
|
168
|
+
self._render_timeout = render_timeout
|
|
169
|
+
self._interactive_timeout = interactive_timeout
|
|
170
|
+
self._static_timeout = static_timeout
|
|
171
|
+
self._interactive_retries = interactive_retries
|
|
172
|
+
self._render_retries = render_retries
|
|
173
|
+
self.profile_cache_ttl = profile_cache_ttl
|
|
174
|
+
self.profile_stale_ok = profile_stale_ok
|
|
175
|
+
# 邪教圈用的物品行情缓存(体积大、价格按天变,单独一个 TTL)
|
|
176
|
+
self.circle_ttl = circle_ttl
|
|
177
|
+
# eftforge:第三方玩家档案源,失败要能快速回退
|
|
178
|
+
self.eftforge_base = eftforge_base.rstrip("/")
|
|
179
|
+
self.eftforge_key = eftforge_key
|
|
180
|
+
self.eftforge_ttl = eftforge_ttl
|
|
181
|
+
self.eftforge_timeout = eftforge_timeout
|
|
182
|
+
# 同一份静态数据避免并发重复下载
|
|
183
|
+
self._locks: Dict[str, asyncio.Lock] = {}
|
|
184
|
+
|
|
185
|
+
async def aclose(self) -> None:
|
|
186
|
+
await self._client.aclose()
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------ 底层
|
|
189
|
+
|
|
190
|
+
def _lock(self, key: str) -> asyncio.Lock:
|
|
191
|
+
if key not in self._locks:
|
|
192
|
+
self._locks[key] = asyncio.Lock()
|
|
193
|
+
return self._locks[key]
|
|
194
|
+
|
|
195
|
+
async def _get(
|
|
196
|
+
self,
|
|
197
|
+
url: str,
|
|
198
|
+
*,
|
|
199
|
+
expect_json: bool = True,
|
|
200
|
+
timeout: Optional[float] = None,
|
|
201
|
+
retries: Optional[int] = None,
|
|
202
|
+
) -> Any:
|
|
203
|
+
"""带重试的 GET。tarkov.dev 的 CDN 会偶发抽风,重试是必要的。
|
|
204
|
+
|
|
205
|
+
`retries` 单独可调:交互类请求要压小,否则上游挂起时
|
|
206
|
+
用户会等「超时 × 重试次数」那么久。
|
|
207
|
+
"""
|
|
208
|
+
attempts = retries if retries is not None else self.max_retries
|
|
209
|
+
last: Optional[Exception] = None
|
|
210
|
+
for attempt in range(1, attempts + 1):
|
|
211
|
+
try:
|
|
212
|
+
resp = await self._client.get(
|
|
213
|
+
url, timeout=timeout if timeout is not None else httpx.USE_CLIENT_DEFAULT
|
|
214
|
+
)
|
|
215
|
+
resp.raise_for_status()
|
|
216
|
+
return resp.json() if expect_json else resp.content
|
|
217
|
+
except Exception as exc: # noqa: BLE001 - 统一重试
|
|
218
|
+
last = exc
|
|
219
|
+
if attempt < attempts:
|
|
220
|
+
wait = 1.5 * attempt
|
|
221
|
+
logger.warning(
|
|
222
|
+
"请求失败(%s/%s) %s: %s,%.1fs 后重试",
|
|
223
|
+
attempt,
|
|
224
|
+
attempts,
|
|
225
|
+
url[:120],
|
|
226
|
+
exc,
|
|
227
|
+
wait,
|
|
228
|
+
)
|
|
229
|
+
await asyncio.sleep(wait)
|
|
230
|
+
raise TarkovError(f"请求 {url[:120]} 失败:{last}") from last
|
|
231
|
+
|
|
232
|
+
def _cache_path(self, name: str) -> Path:
|
|
233
|
+
return self.cache_dir / name
|
|
234
|
+
|
|
235
|
+
def _cache_fresh(self, path: Path, ttl: Optional[int] = None) -> bool:
|
|
236
|
+
if not path.exists():
|
|
237
|
+
return False
|
|
238
|
+
ttl = self.cache_ttl if ttl is None else ttl
|
|
239
|
+
if ttl <= 0:
|
|
240
|
+
return True
|
|
241
|
+
return (time.time() - path.stat().st_mtime) < ttl
|
|
242
|
+
|
|
243
|
+
def _read_json(self, path: Path) -> Any:
|
|
244
|
+
with path.open(encoding="utf-8") as fh:
|
|
245
|
+
return json.load(fh)
|
|
246
|
+
|
|
247
|
+
def _write_json(self, path: Path, data: Any) -> None:
|
|
248
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
249
|
+
with tmp.open("w", encoding="utf-8") as fh:
|
|
250
|
+
json.dump(data, fh, ensure_ascii=False, separators=(",", ":"))
|
|
251
|
+
tmp.replace(path)
|
|
252
|
+
|
|
253
|
+
# ------------------------------------------------------------- status
|
|
254
|
+
|
|
255
|
+
async def get_status(self) -> Dict[str, Any]:
|
|
256
|
+
"""EFT 服务器状态。对应 commands/status.mjs。"""
|
|
257
|
+
payload = await self._get(
|
|
258
|
+
f"{JSON_API}/status",
|
|
259
|
+
timeout=self._interactive_timeout,
|
|
260
|
+
retries=self._interactive_retries,
|
|
261
|
+
)
|
|
262
|
+
data = payload.get("data")
|
|
263
|
+
if not isinstance(data, dict):
|
|
264
|
+
raise TarkovError("状态接口返回了意外的数据格式")
|
|
265
|
+
return data
|
|
266
|
+
|
|
267
|
+
# ------------------------------------------------------- 静态数据缓存
|
|
268
|
+
|
|
269
|
+
async def get_level_table(self, json_folder: str) -> List[Dict[str, Any]]:
|
|
270
|
+
"""等级经验表(79 条)。
|
|
271
|
+
|
|
272
|
+
原版每次都从 17MB 的 items 端点里取(game-data.mjs:565),
|
|
273
|
+
这里抽出来落盘,避免每次查询都下 17MB。
|
|
274
|
+
|
|
275
|
+
等级经验曲线是游戏全局常量,与模式无关,所以只缓存一份。
|
|
276
|
+
"""
|
|
277
|
+
path = self._cache_path("playerlevels.json")
|
|
278
|
+
async with self._lock("levels"):
|
|
279
|
+
if self._cache_fresh(path):
|
|
280
|
+
try:
|
|
281
|
+
table = self._read_json(path)
|
|
282
|
+
if table:
|
|
283
|
+
return table
|
|
284
|
+
except Exception: # noqa: BLE001 - 缓存损坏就重新拉
|
|
285
|
+
logger.warning("等级表缓存损坏,重新获取")
|
|
286
|
+
|
|
287
|
+
logger.info("首次获取等级经验表:需要下载 %s/items(约 17MB)", json_folder)
|
|
288
|
+
payload = await self._get(
|
|
289
|
+
f"{JSON_API}/{json_folder}/items", timeout=self._static_timeout
|
|
290
|
+
)
|
|
291
|
+
table = (payload.get("data") or {}).get("playerLevels")
|
|
292
|
+
if not table:
|
|
293
|
+
raise TarkovError("items 端点里没有 playerLevels")
|
|
294
|
+
self._write_json(path, table)
|
|
295
|
+
logger.info("等级经验表已缓存(%d 条)", len(table))
|
|
296
|
+
return table
|
|
297
|
+
|
|
298
|
+
async def get_achievement_names(self, json_folder: str) -> Dict[str, str]:
|
|
299
|
+
"""成就 id -> 名称。
|
|
300
|
+
|
|
301
|
+
坑:tasks 端点里成就的 `name` 字段是翻译占位符
|
|
302
|
+
(形如 "65141c80ec10ff011f17cc3e name"),
|
|
303
|
+
真实名字要用 tasks_en 这个 locale 文件查表翻译。
|
|
304
|
+
这也是原版 getAchievements() 里 jsonApi.translate 干的事。
|
|
305
|
+
"""
|
|
306
|
+
path = self._cache_path(f"achievements_{json_folder}.json")
|
|
307
|
+
async with self._lock(f"ach_{json_folder}"):
|
|
308
|
+
if self._cache_fresh(path):
|
|
309
|
+
try:
|
|
310
|
+
names = self._read_json(path)
|
|
311
|
+
if names:
|
|
312
|
+
return names
|
|
313
|
+
except Exception: # noqa: BLE001
|
|
314
|
+
logger.warning("成就表缓存损坏,重新获取")
|
|
315
|
+
|
|
316
|
+
logger.info("获取成就名称表:%s/tasks + %s/tasks_en", json_folder, json_folder)
|
|
317
|
+
tasks, locale = await asyncio.gather(
|
|
318
|
+
self._get(f"{JSON_API}/{json_folder}/tasks", timeout=self._static_timeout),
|
|
319
|
+
self._get(
|
|
320
|
+
f"{JSON_API}/{json_folder}/tasks_en",
|
|
321
|
+
timeout=self._interactive_timeout,
|
|
322
|
+
),
|
|
323
|
+
)
|
|
324
|
+
raw = (tasks.get("data") or {}).get("achievements") or {}
|
|
325
|
+
loc = locale.get("data") or {}
|
|
326
|
+
names: Dict[str, str] = {}
|
|
327
|
+
for ach_id, ach in raw.items():
|
|
328
|
+
key = (ach or {}).get("name") or ach_id
|
|
329
|
+
names[ach_id] = loc.get(key) or (ach or {}).get("normalizedName") or ach_id
|
|
330
|
+
self._write_json(path, names)
|
|
331
|
+
logger.info("成就名称表已缓存(%d 条)", len(names))
|
|
332
|
+
return names
|
|
333
|
+
|
|
334
|
+
# ------------------------------------------------------------ eftforge
|
|
335
|
+
|
|
336
|
+
async def get_eftforge_profile(
|
|
337
|
+
self, json_folder: str, account_id: int
|
|
338
|
+
) -> Optional[Dict[str, Any]]:
|
|
339
|
+
"""eftforge Atlas 的玩家档案(原始响应)。
|
|
340
|
+
|
|
341
|
+
一律失败返回 None:它是第三方服务,不能成为单点故障,
|
|
342
|
+
调用方拿到 None 就回去走 tarkov.dev。
|
|
343
|
+
"""
|
|
344
|
+
mode = EFTFORGE_MODES.get(json_folder)
|
|
345
|
+
if not mode:
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
path = self._cache_path(f"eftforge_{mode}_{account_id}.json")
|
|
349
|
+
if self._cache_fresh(path, self.eftforge_ttl):
|
|
350
|
+
cached = self._read_json_safe(path)
|
|
351
|
+
if isinstance(cached, dict) and cached.get("nickname"):
|
|
352
|
+
return cached
|
|
353
|
+
|
|
354
|
+
headers = {"X-Atlas-Key": self.eftforge_key} if self.eftforge_key else None
|
|
355
|
+
try:
|
|
356
|
+
resp = await self._client.get(
|
|
357
|
+
f"{self.eftforge_base}/atlas/api/lookup",
|
|
358
|
+
params={"accountId": account_id, "mode": mode},
|
|
359
|
+
headers=headers,
|
|
360
|
+
timeout=self.eftforge_timeout,
|
|
361
|
+
)
|
|
362
|
+
if resp.status_code == 404:
|
|
363
|
+
logger.info("eftforge 查无此号 aid=%s mode=%s", account_id, mode)
|
|
364
|
+
return None
|
|
365
|
+
resp.raise_for_status()
|
|
366
|
+
data = resp.json()
|
|
367
|
+
except Exception as exc: # noqa: BLE001 - 第三方,失败就回退
|
|
368
|
+
logger.warning("eftforge 查询失败 aid=%s mode=%s:%s", account_id, mode, exc)
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
if not isinstance(data, dict) or not data.get("nickname"):
|
|
372
|
+
logger.warning("eftforge 返回了意外的数据 aid=%s mode=%s", account_id, mode)
|
|
373
|
+
return None
|
|
374
|
+
self._write_json(path, data)
|
|
375
|
+
logger.info("eftforge 命中 %s(%s)", data.get("nickname"), mode)
|
|
376
|
+
return data
|
|
377
|
+
|
|
378
|
+
async def fetch_eftforge_art(self, path: Optional[str]) -> Optional[bytes]:
|
|
379
|
+
"""下载 eftforge 的立绘(character.full)。拿不到返回 None。"""
|
|
380
|
+
if not path:
|
|
381
|
+
return None
|
|
382
|
+
url = path if path.startswith("http") else f"{self.eftforge_base}{path}"
|
|
383
|
+
try:
|
|
384
|
+
resp = await self._client.get(url, timeout=self._render_timeout)
|
|
385
|
+
resp.raise_for_status()
|
|
386
|
+
return resp.content
|
|
387
|
+
except Exception as exc: # noqa: BLE001 - 图只是锦上添花
|
|
388
|
+
logger.warning("eftforge 立绘下载失败:%s", exc)
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
# -------------------------------------------------------- 邪教圈献祭
|
|
392
|
+
|
|
393
|
+
async def get_circle_items(self, json_folder: str) -> Dict[str, Any]:
|
|
394
|
+
"""邪教圈计算用的精简物品表 + 中文名。
|
|
395
|
+
|
|
396
|
+
items 端点有 17MB,这里只保留计算需要的字段落盘,
|
|
397
|
+
再取 items_zh 把 i18n 占位名换成中文,避免每次查询都下大文件。
|
|
398
|
+
|
|
399
|
+
可购性口径:**跳蚤市场有价格即可购**,不做额外白名单。
|
|
400
|
+
另加一道下限:跳蚤价 < 100 的视为无市场(tarkov.dev 对没有挂单的
|
|
401
|
+
物品会写 1),否则会推荐出一堆 1₽ 的假货。
|
|
402
|
+
"""
|
|
403
|
+
# v2:价格口径从「24h 最低」换成鲁棒值,旧缓存直接作废
|
|
404
|
+
path = self._cache_path(f"circle_items_v7_{json_folder}.json")
|
|
405
|
+
async with self._lock(f"circle_{json_folder}"):
|
|
406
|
+
if self._cache_fresh(path, self.circle_ttl):
|
|
407
|
+
try:
|
|
408
|
+
data = self._read_json(path)
|
|
409
|
+
if data and data.get("items"):
|
|
410
|
+
return data
|
|
411
|
+
except Exception: # noqa: BLE001 - 缓存坏了就重新拉
|
|
412
|
+
logger.warning("邪教圈物品缓存损坏,重新获取")
|
|
413
|
+
|
|
414
|
+
logger.info("获取邪教圈物品数据:%s/items + items_zh", json_folder)
|
|
415
|
+
payload = await self._get(
|
|
416
|
+
f"{JSON_API}/{json_folder}/items", timeout=self._static_timeout
|
|
417
|
+
)
|
|
418
|
+
raw = (payload.get("data") or {}).get("items") or {}
|
|
419
|
+
if not isinstance(raw, dict) or not raw:
|
|
420
|
+
raise TarkovError("items 端点返回了意外的数据格式")
|
|
421
|
+
|
|
422
|
+
try:
|
|
423
|
+
names_payload = await self._get(
|
|
424
|
+
f"{JSON_API}/{json_folder}/items_zh", timeout=self._static_timeout
|
|
425
|
+
)
|
|
426
|
+
names = names_payload.get("data") or {}
|
|
427
|
+
except Exception as exc: # noqa: BLE001 - 没中文名就退回占位名
|
|
428
|
+
logger.warning("中文名表获取失败,退回原始名:%s", exc)
|
|
429
|
+
names = {}
|
|
430
|
+
|
|
431
|
+
items: List[Dict[str, Any]] = []
|
|
432
|
+
for tpl, it in raw.items():
|
|
433
|
+
if not isinstance(it, dict):
|
|
434
|
+
continue
|
|
435
|
+
base_price = int(it.get("basePrice") or 0)
|
|
436
|
+
if base_price <= 0:
|
|
437
|
+
continue
|
|
438
|
+
# 武器预设(types == ["preset"])的 basePrice 是整套配件的和,
|
|
439
|
+
# 而它在跳蚤上的挂价往往是裸枪价,两者对不上会算出离谱的性价比,
|
|
440
|
+
# 所以这一类不参与推荐。
|
|
441
|
+
if "preset" in (it.get("types") or []):
|
|
442
|
+
continue
|
|
443
|
+
flea = _flea_estimate(it)
|
|
444
|
+
if flea < 100:
|
|
445
|
+
continue # 跳蚤无价 → 视为不可购
|
|
446
|
+
trader = 0
|
|
447
|
+
for offer in it.get("buyFromTrader") or []:
|
|
448
|
+
price = int(offer.get("priceRUB") or 0)
|
|
449
|
+
if price > 0 and (trader == 0 or price < trader):
|
|
450
|
+
trader = price
|
|
451
|
+
key = it.get("name") or ""
|
|
452
|
+
items.append(
|
|
453
|
+
{
|
|
454
|
+
"tpl": tpl,
|
|
455
|
+
"name": names.get(key) or key or tpl,
|
|
456
|
+
"base": base_price,
|
|
457
|
+
"flea": flea,
|
|
458
|
+
"trader": trader,
|
|
459
|
+
}
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
data = {"items": items, "built": int(time.time())}
|
|
463
|
+
self._write_json(path, data)
|
|
464
|
+
logger.info("邪教圈物品表已缓存(%d 件,%s)", len(items), json_folder)
|
|
465
|
+
return data
|
|
466
|
+
|
|
467
|
+
# ------------------------------------------------------------- player
|
|
468
|
+
|
|
469
|
+
async def get_profile(
|
|
470
|
+
self, players_folder: str, account_id: int
|
|
471
|
+
) -> Dict[str, Any]:
|
|
472
|
+
"""玩家资料,带本地磁盘缓存。
|
|
473
|
+
|
|
474
|
+
注意 `players_folder` 是 players.tarkov.dev 的目录名,
|
|
475
|
+
正式服是 `profile` 而不是 `regular`。
|
|
476
|
+
|
|
477
|
+
为什么要缓存:上游的玩家档案来自志愿者用 TarkovMonitor 扫描上传,
|
|
478
|
+
更新很慢(实测某个账号的资料 13 天没变)。而这块数据目前是插件里
|
|
479
|
+
唯一每次都要实时拉的——昵称索引、等级表、成就表都已经本地化了。
|
|
480
|
+
|
|
481
|
+
缓存策略:
|
|
482
|
+
· 新鲜(< ttl) -> 直接用,不发请求
|
|
483
|
+
· 过期 -> 拉上游;成功就更新,失败就用旧数据兜底
|
|
484
|
+
· 没有缓存 -> 只能拉上游,失败就报错
|
|
485
|
+
"""
|
|
486
|
+
cache_path = self._profile_cache_path(players_folder, account_id)
|
|
487
|
+
|
|
488
|
+
if self._cache_fresh(cache_path, self.profile_cache_ttl):
|
|
489
|
+
cached = self._read_json_safe(cache_path)
|
|
490
|
+
if cached is not None:
|
|
491
|
+
logger.debug("玩家资料命中缓存 aid=%s mode=%s", account_id, players_folder)
|
|
492
|
+
return cached
|
|
493
|
+
|
|
494
|
+
url = f"{PLAYERS_API}/{players_folder}/{account_id}.json"
|
|
495
|
+
try:
|
|
496
|
+
payload = await self._get(
|
|
497
|
+
url,
|
|
498
|
+
timeout=self._interactive_timeout,
|
|
499
|
+
retries=self._interactive_retries,
|
|
500
|
+
)
|
|
501
|
+
except Exception:
|
|
502
|
+
# 上游挂了:有旧数据就先用着,别让用户白等
|
|
503
|
+
if self.profile_stale_ok:
|
|
504
|
+
stale = self._read_json_safe(cache_path)
|
|
505
|
+
if stale is not None:
|
|
506
|
+
age = self._cache_age(cache_path)
|
|
507
|
+
logger.warning(
|
|
508
|
+
"玩家资料上游失败,回退到 %.1f 小时前的缓存 aid=%s",
|
|
509
|
+
age / 3600,
|
|
510
|
+
account_id,
|
|
511
|
+
)
|
|
512
|
+
return stale
|
|
513
|
+
raise
|
|
514
|
+
|
|
515
|
+
if not isinstance(payload, dict):
|
|
516
|
+
raise TarkovError("资料接口返回了意外的数据格式")
|
|
517
|
+
if payload.get("err") or payload.get("errmsg"):
|
|
518
|
+
raise TarkovError(str(payload.get("errmsg") or payload.get("err")))
|
|
519
|
+
if "info" not in payload:
|
|
520
|
+
# 「该模式没这个号」也算一种确定的结果,缓存起来免得反复问上游
|
|
521
|
+
self._write_json(cache_path, payload)
|
|
522
|
+
raise TarkovError("该账号在当前模式下没有资料")
|
|
523
|
+
|
|
524
|
+
self._write_json(cache_path, payload)
|
|
525
|
+
return payload
|
|
526
|
+
|
|
527
|
+
# ------------------------------------------------------- 资料缓存工具
|
|
528
|
+
|
|
529
|
+
def _profile_cache_path(self, players_folder: str, account_id: int) -> Path:
|
|
530
|
+
# 正式服的目录名是 profile,直接拿来当文件名有点歧义,统一成 regular
|
|
531
|
+
name = "regular" if players_folder == "profile" else players_folder
|
|
532
|
+
d = self.cache_dir / "profiles"
|
|
533
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
534
|
+
return d / f"{name}_{account_id}.json"
|
|
535
|
+
|
|
536
|
+
def _read_json_safe(self, path: Path) -> Optional[Any]:
|
|
537
|
+
if not path.exists():
|
|
538
|
+
return None
|
|
539
|
+
try:
|
|
540
|
+
return self._read_json(path)
|
|
541
|
+
except Exception as exc: # noqa: BLE001 - 缓存坏了当没有
|
|
542
|
+
logger.warning("缓存文件损坏,忽略:%s(%s)", path.name, exc)
|
|
543
|
+
return None
|
|
544
|
+
|
|
545
|
+
@staticmethod
|
|
546
|
+
def _cache_age(path: Path) -> float:
|
|
547
|
+
return time.time() - path.stat().st_mtime if path.exists() else 0.0
|
|
548
|
+
|
|
549
|
+
# ------------------------------------------------------- 立绘
|
|
550
|
+
|
|
551
|
+
@staticmethod
|
|
552
|
+
def _build_equipment(equipment: Dict[str, Any]) -> Dict[str, Any]:
|
|
553
|
+
"""逐行复刻 player.mjs:96-145 的装备裁剪。
|
|
554
|
+
|
|
555
|
+
目的:把发往 imagemagic 的 JSON 压小。原版不裁剪的话 URL 会长到不可用。
|
|
556
|
+
"""
|
|
557
|
+
eq_id = (equipment or {}).get("Id")
|
|
558
|
+
items = (equipment or {}).get("Items") or []
|
|
559
|
+
by_id = {it.get("_id"): it for it in items}
|
|
560
|
+
|
|
561
|
+
kept: List[Dict[str, Any]] = []
|
|
562
|
+
for original in items:
|
|
563
|
+
if original.get("_id") == eq_id:
|
|
564
|
+
kept.append(dict(original))
|
|
565
|
+
continue
|
|
566
|
+
|
|
567
|
+
slot = original.get("slotId") or ""
|
|
568
|
+
if any(p.search(slot) for p in _ARMOR_SLOT_PATTERNS):
|
|
569
|
+
continue
|
|
570
|
+
|
|
571
|
+
# 回溯到直接挂在根节点上的那件物品,用它的 slotId 判断
|
|
572
|
+
node = original
|
|
573
|
+
for _ in range(100):
|
|
574
|
+
if node.get("parentId") == eq_id:
|
|
575
|
+
break
|
|
576
|
+
parent = by_id.get(node.get("parentId"))
|
|
577
|
+
if parent is None:
|
|
578
|
+
break
|
|
579
|
+
node = parent
|
|
580
|
+
if (node.get("slotId") or "") in _SKIP_SLOTS:
|
|
581
|
+
continue
|
|
582
|
+
|
|
583
|
+
item = dict(original)
|
|
584
|
+
upd = item.get("upd")
|
|
585
|
+
if upd:
|
|
586
|
+
trimmed = {k: v for k, v in upd.items() if k not in _SKIP_PROPS}
|
|
587
|
+
if trimmed:
|
|
588
|
+
item["upd"] = trimmed
|
|
589
|
+
else:
|
|
590
|
+
item.pop("upd", None)
|
|
591
|
+
kept.append(item)
|
|
592
|
+
|
|
593
|
+
return {"Id": eq_id, "Items": kept}
|
|
594
|
+
|
|
595
|
+
def build_render_url(self, profile: Dict[str, Any]) -> Optional[str]:
|
|
596
|
+
"""构造 imagemagic 立绘 URL。超长则返回 None(由调用方决定是否放弃)。"""
|
|
597
|
+
equipment = self._build_equipment(profile.get("equipment") or {})
|
|
598
|
+
payload = json.dumps(
|
|
599
|
+
{
|
|
600
|
+
"aid": profile.get("aid"),
|
|
601
|
+
"customization": profile.get("customization") or {},
|
|
602
|
+
"equipment": equipment,
|
|
603
|
+
},
|
|
604
|
+
separators=(",", ":"),
|
|
605
|
+
)
|
|
606
|
+
url = f"{IMAGEMAGIC}/player/{profile.get('aid')}.webp?data={quote(payload, safe='')}"
|
|
607
|
+
if len(url) > self.max_render_url:
|
|
608
|
+
logger.warning(
|
|
609
|
+
"立绘 URL 长度 %d 超过上限 %d,跳过图片", len(url), self.max_render_url
|
|
610
|
+
)
|
|
611
|
+
return None
|
|
612
|
+
return url
|
|
613
|
+
|
|
614
|
+
async def fetch_raw(self, url: str, timeout: float = 600.0) -> bytes:
|
|
615
|
+
"""下载原始字节。给昵称索引(约 67MB)这类大文件用。"""
|
|
616
|
+
return await self._get(
|
|
617
|
+
url, expect_json=False, timeout=timeout, retries=self.max_retries
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
async def fetch_render(self, url: str) -> Optional[bytes]:
|
|
621
|
+
"""下载立绘。失败返回 None——图片只是锦上添花,不该让整条命令失败。"""
|
|
622
|
+
try:
|
|
623
|
+
return await self._get(
|
|
624
|
+
url,
|
|
625
|
+
expect_json=False,
|
|
626
|
+
timeout=self._render_timeout,
|
|
627
|
+
retries=self._render_retries,
|
|
628
|
+
)
|
|
629
|
+
except Exception as exc: # noqa: BLE001
|
|
630
|
+
logger.warning("立绘下载失败:%s", exc)
|
|
631
|
+
return None
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
# ---------------------------------------------------------------- 纯计算
|
|
635
|
+
|
|
636
|
+
def find_level(experience: int, levels: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
637
|
+
"""复刻 player.mjs:8-21 的 getPlayerLevel。
|
|
638
|
+
|
|
639
|
+
levels[i]["exp"] 是「从上一级升到该级」所需经验,
|
|
640
|
+
所以累加和才是到达该级的总经验。
|
|
641
|
+
"""
|
|
642
|
+
total = 0
|
|
643
|
+
for i, level_data in enumerate(levels):
|
|
644
|
+
total += level_data.get("exp", 0)
|
|
645
|
+
if total == experience:
|
|
646
|
+
return level_data
|
|
647
|
+
if total > experience:
|
|
648
|
+
return levels[i - 1]
|
|
649
|
+
return levels[-1]
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def level_progress(
|
|
653
|
+
experience: int, levels: List[Dict[str, Any]]
|
|
654
|
+
) -> tuple[Dict[str, Any], int, int]:
|
|
655
|
+
"""返回 (当前等级, 本级已获得经验, 本级所需经验)。
|
|
656
|
+
|
|
657
|
+
与 `find_level` 保持一致:当累加到 levels[i] 时总经验超过玩家经验,
|
|
658
|
+
说明玩家停在 levels[i-1]。所以本级已获得 = experience - 之前的累加和,
|
|
659
|
+
升级所需 = levels[i].exp。
|
|
660
|
+
"""
|
|
661
|
+
total = 0
|
|
662
|
+
for i, level_data in enumerate(levels):
|
|
663
|
+
need = level_data.get("exp", 0)
|
|
664
|
+
if total + need > experience:
|
|
665
|
+
current = levels[i - 1] if i > 0 else levels[0]
|
|
666
|
+
return current, experience - total, need
|
|
667
|
+
total += need
|
|
668
|
+
return levels[-1], 0, 0
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# 阵营图标资源
|
|
2
|
+
|
|
3
|
+
`usec.png` 和 `bear.png` 是 **USEC / BEAR 阵营徽章的 alpha 蒙版**(L 模式灰度图),
|
|
4
|
+
运行时按阵营配色重新染色,所以只需要存蒙版,体积很小。
|
|
5
|
+
|
|
6
|
+
| 文件 | 尺寸 | 体积 | 来源 |
|
|
7
|
+
| --- | --- | --- | --- |
|
|
8
|
+
| `usec.png` | 205×256 | ~7 KB | [USEC Emblem](https://static.wikia.nocookie.net/escapefromtarkov_gamepedia/images/b/bf/USEC_Emblem.png) |
|
|
9
|
+
| `bear.png` | 222×256 | ~12 KB | [BEAR Icon](https://static.wikia.nocookie.net/escapefromtarkov_gamepedia/images/a/a1/BEAR_Icon.png) |
|
|
10
|
+
|
|
11
|
+
两张图都来自 [Escape from Tarkov Wiki (Fandom)](https://escapefromtarkov.fandom.com/),
|
|
12
|
+
原始文件为 896px 高的 WebP,此处等比缩放到 256px 高并只保留 alpha 通道。
|
|
13
|
+
|
|
14
|
+
## 版权
|
|
15
|
+
|
|
16
|
+
USEC / BEAR 徽章是 **Battlestate Games** 的版权素材,此处按同人项目惯例用于
|
|
17
|
+
粉丝向机器人,与原项目 [the-hideout/stash](https://github.com/the-hideout/stash)
|
|
18
|
+
使用 tarkov.dev 物品图标、Boss 立绘等游戏素材的做法一致。
|
|
19
|
+
|
|
20
|
+
若版权方有异议,删除这两个文件即可——插件会自动退回纯文字徽章
|
|
21
|
+
(见 `card.py` 的 `faction_icon()`,找不到文件时返回 `None`)。
|
|
22
|
+
|
|
23
|
+
## 重新生成
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
python scripts/fetch_faction_icons.py
|
|
27
|
+
```
|