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,96 @@
|
|
|
1
|
+
"""立绘图片处理。
|
|
2
|
+
|
|
3
|
+
imagemagic 返回的是 WebP。部分 QQ 客户端(尤其是老版本)渲染 WebP 会有问题,
|
|
4
|
+
所以装了 Pillow 就转成 PNG 再发。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import logging
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("nonebot_plugin_efthelper")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def webp_to_png(data: bytes) -> bytes:
|
|
17
|
+
"""把 WebP 转成 PNG。没装 Pillow 或转换失败就原样返回。"""
|
|
18
|
+
try:
|
|
19
|
+
from PIL import Image
|
|
20
|
+
except ImportError:
|
|
21
|
+
logger.debug("未安装 Pillow,立绘保持 WebP 格式")
|
|
22
|
+
return data
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
with Image.open(io.BytesIO(data)) as img:
|
|
26
|
+
buf = io.BytesIO()
|
|
27
|
+
img.convert("RGBA").save(buf, format="PNG", optimize=True)
|
|
28
|
+
return buf.getvalue()
|
|
29
|
+
except Exception as exc: # noqa: BLE001 - 转换失败不该影响主流程
|
|
30
|
+
logger.warning("WebP 转 PNG 失败,改用原始数据:%s", exc)
|
|
31
|
+
return data
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def dim_image(data: bytes, factor: float = 0.72) -> bytes:
|
|
35
|
+
"""按比例压暗图片,保留透明通道。Pillow 缺失或失败就原样返回。
|
|
36
|
+
|
|
37
|
+
eftforge 的胸像是游戏内直出的亮图,铺在深色卡片上会「跳」出来,
|
|
38
|
+
压暗一档才能和背景的冷色调融在一起。
|
|
39
|
+
"""
|
|
40
|
+
if not data or not (0 < factor < 1):
|
|
41
|
+
return data
|
|
42
|
+
try:
|
|
43
|
+
from PIL import Image, ImageEnhance
|
|
44
|
+
except ImportError:
|
|
45
|
+
logger.debug("未安装 Pillow,跳过压暗")
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
with Image.open(io.BytesIO(data)) as img:
|
|
50
|
+
rgba = img.convert("RGBA")
|
|
51
|
+
dimmed = ImageEnhance.Brightness(rgba).enhance(factor)
|
|
52
|
+
buf = io.BytesIO()
|
|
53
|
+
dimmed.save(buf, format="PNG", optimize=True)
|
|
54
|
+
return buf.getvalue()
|
|
55
|
+
except Exception as exc: # noqa: BLE001 - 压暗失败不该影响出图
|
|
56
|
+
logger.warning("压暗立绘失败,改用原图:%s", exc)
|
|
57
|
+
return data
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_image_segment(data: bytes):
|
|
61
|
+
"""构造当前适配器能识别的图片消息段。
|
|
62
|
+
|
|
63
|
+
返回 None 表示当前适配器不支持(调用方应降级为纯文本)。
|
|
64
|
+
"""
|
|
65
|
+
# OneBot V11(QQ 最常见)
|
|
66
|
+
try:
|
|
67
|
+
from nonebot.adapters.onebot.v11 import MessageSegment as V11Segment
|
|
68
|
+
|
|
69
|
+
return V11Segment.image(data)
|
|
70
|
+
except ImportError:
|
|
71
|
+
pass
|
|
72
|
+
except Exception as exc: # noqa: BLE001
|
|
73
|
+
logger.debug("构造 OneBot V11 图片段失败:%s", exc)
|
|
74
|
+
|
|
75
|
+
# OneBot V12
|
|
76
|
+
try:
|
|
77
|
+
from nonebot.adapters.onebot.v12 import MessageSegment as V12Segment
|
|
78
|
+
|
|
79
|
+
return V12Segment.image(data)
|
|
80
|
+
except ImportError:
|
|
81
|
+
pass
|
|
82
|
+
except Exception as exc: # noqa: BLE001
|
|
83
|
+
logger.debug("构造 OneBot V12 图片段失败:%s", exc)
|
|
84
|
+
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def sniff_format(data: bytes) -> Optional[str]:
|
|
89
|
+
"""从文件头猜图片格式,用于日志排查。"""
|
|
90
|
+
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
|
91
|
+
return "webp"
|
|
92
|
+
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
|
93
|
+
return "png"
|
|
94
|
+
if data[:2] == b"\xff\xd8":
|
|
95
|
+
return "jpeg"
|
|
96
|
+
return None
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""玩家昵称索引。
|
|
2
|
+
|
|
3
|
+
原版 stash 的自动补全靠 `players.tarkov.dev/{mode}/index.json`:
|
|
4
|
+
一份 `{"15":"Buhaus", "18":"Vladimir-Karpov", ...}` 的扁平字典。
|
|
5
|
+
|
|
6
|
+
实测数据(regular 模式):
|
|
7
|
+
|
|
8
|
+
| 项 | 值 |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| 大小 | 67 MB |
|
|
11
|
+
| 条目 | 2,969,695 |
|
|
12
|
+
| ID 覆盖 | 19.7%(只收录被 tarkov.dev 爬过的号) |
|
|
13
|
+
| 字符集 | **100% ASCII**(游戏昵称限制拉丁字符) |
|
|
14
|
+
| 重名 | 4,326 组(`pam` 有 4 个账号) |
|
|
15
|
+
| 空昵称 | 32 个 |
|
|
16
|
+
| 异常 | 2 个 troll 账号昵称长达 10,000 / 16,000 字符 |
|
|
17
|
+
|
|
18
|
+
原版把它整个读进内存,每次搜索线性遍历 297 万条并对每个昵称调一次
|
|
19
|
+
`toLowerCase()`。实测 Node 侧 629MB 常驻内存、6 次击键 4 秒;
|
|
20
|
+
直译到 Python 更糟(665MB)。
|
|
21
|
+
|
|
22
|
+
这里改成落盘 SQLite:下载后一次性转换,查询走索引。
|
|
23
|
+
实测常驻内存 13MB、6 次击键 23ms。
|
|
24
|
+
|
|
25
|
+
⚠️ 关于目录名:这个模块的公开接口一律接收 `GameMode` 对象,而不是字符串。
|
|
26
|
+
原因是「正式服」在两个 API 上的目录名不同:
|
|
27
|
+
|
|
28
|
+
json.tarkov.dev -> /regular/... (用来给数据库文件命名)
|
|
29
|
+
players.tarkov.dev -> /profile/... (用来下载 index.json)
|
|
30
|
+
|
|
31
|
+
早期版本用字符串参数,调用方传 json_folder 还是 players_folder 全靠自觉,
|
|
32
|
+
结果这个坑踩了三次(最后一次是 regular 索引静默 404,永远刷不了)。
|
|
33
|
+
改成传对象后,两种目录各取所需,从类型上就不可能传错。
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import asyncio
|
|
39
|
+
import json
|
|
40
|
+
import logging
|
|
41
|
+
import re
|
|
42
|
+
import sqlite3
|
|
43
|
+
import time
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import TYPE_CHECKING, List, Optional, Tuple
|
|
46
|
+
|
|
47
|
+
if TYPE_CHECKING: # 只为类型注解,避免和 api.py 循环导入
|
|
48
|
+
from .api import GameMode
|
|
49
|
+
|
|
50
|
+
logger = logging.getLogger("nonebot_plugin_efthelper")
|
|
51
|
+
|
|
52
|
+
PLAYERS_API = "https://players.tarkov.dev"
|
|
53
|
+
|
|
54
|
+
# 昵称长度上限。游戏本身约 15~21 字符,实测索引里混进了两个
|
|
55
|
+
# 10,000 / 16,000 字符的下划线 troll 账号,转换时直接丢掉。
|
|
56
|
+
MAX_NAME_LENGTH = 64
|
|
57
|
+
|
|
58
|
+
# 入库批次大小。批量插入比逐条快得多,同时把内存占用压在几十 MB。
|
|
59
|
+
_BATCH_SIZE = 50_000
|
|
60
|
+
|
|
61
|
+
# 昵称条目。真实文件是紧凑格式 `"15":"Buhaus"`(297 万条全部无空格),
|
|
62
|
+
# 但这里允许冒号周围有空白,容忍格式变化。
|
|
63
|
+
_ENTRY_RE = re.compile(r'"(\d+)"\s*:\s*"((?:[^"\\]|\\.)*)"')
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class MatchKind:
|
|
67
|
+
EXACT = "exact"
|
|
68
|
+
PREFIX = "prefix"
|
|
69
|
+
SUBSTRING = "substring"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class NicknameIndex:
|
|
73
|
+
"""昵称 -> 账号 ID 的本地索引。"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
cache_dir: Path,
|
|
78
|
+
*,
|
|
79
|
+
ttl: int = 7 * 24 * 3600,
|
|
80
|
+
download_timeout: float = 600.0,
|
|
81
|
+
max_retries: int = 3,
|
|
82
|
+
) -> None:
|
|
83
|
+
self.cache_dir = Path(cache_dir)
|
|
84
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
self.ttl = ttl
|
|
86
|
+
self.download_timeout = download_timeout
|
|
87
|
+
self.max_retries = max_retries
|
|
88
|
+
self._build_lock = asyncio.Lock()
|
|
89
|
+
|
|
90
|
+
# ---------------------------------------------------------------- 路径
|
|
91
|
+
|
|
92
|
+
def db_path(self, mode: "GameMode") -> Path:
|
|
93
|
+
"""数据库文件名用 json_folder:regular / pve / pvp-season。"""
|
|
94
|
+
return self.cache_dir / f"names_{mode.json_folder}.db"
|
|
95
|
+
|
|
96
|
+
def exists(self, mode: "GameMode") -> bool:
|
|
97
|
+
"""索引是否已经建好(不管新不新鲜)。"""
|
|
98
|
+
return self.db_path(mode).exists()
|
|
99
|
+
|
|
100
|
+
def is_fresh(self, mode: "GameMode") -> bool:
|
|
101
|
+
path = self.db_path(mode)
|
|
102
|
+
if not path.exists():
|
|
103
|
+
return False
|
|
104
|
+
if self.ttl <= 0:
|
|
105
|
+
return True
|
|
106
|
+
return (time.time() - path.stat().st_mtime) < self.ttl
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------- 构建
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def _iter_entries(raw: str):
|
|
112
|
+
"""逐条产出 (aid, nickname)。
|
|
113
|
+
|
|
114
|
+
刻意不用 json.loads:那会把 297 万条一次性变成 Python dict,
|
|
115
|
+
实测常驻内存 665MB。正则扫描同样快,而且这里是生成器——
|
|
116
|
+
调用方可以边解析边入库,不必把 297 万条攒在内存里。
|
|
117
|
+
|
|
118
|
+
处理过的真实数据怪癖:
|
|
119
|
+
· 32 个空昵称账号 -> 丢弃
|
|
120
|
+
· 2 个 troll 账号昵称长 10,000 / 16,000 字符 -> 丢弃
|
|
121
|
+
· 35 个昵称含转义换行(如 `Coffeelover\\n`)-> 反转义后 strip
|
|
122
|
+
"""
|
|
123
|
+
skipped_long = 0
|
|
124
|
+
skipped_empty = 0
|
|
125
|
+
|
|
126
|
+
for match in _ENTRY_RE.finditer(raw):
|
|
127
|
+
aid, name = match.group(1), match.group(2)
|
|
128
|
+
|
|
129
|
+
# 有反斜杠才做 JSON 反转义,避免 297 万次无谓开销
|
|
130
|
+
if "\\" in name:
|
|
131
|
+
try:
|
|
132
|
+
name = json.loads(f'"{name}"')
|
|
133
|
+
except Exception: # noqa: BLE001 - 解不开就用原样
|
|
134
|
+
pass
|
|
135
|
+
name = name.strip()
|
|
136
|
+
|
|
137
|
+
if not name:
|
|
138
|
+
skipped_empty += 1
|
|
139
|
+
continue
|
|
140
|
+
if len(name) > MAX_NAME_LENGTH:
|
|
141
|
+
skipped_long += 1
|
|
142
|
+
continue
|
|
143
|
+
yield int(aid), name
|
|
144
|
+
|
|
145
|
+
if skipped_long or skipped_empty:
|
|
146
|
+
logger.info(
|
|
147
|
+
"索引过滤:丢弃 %d 个超长昵称(>%d 字符)、%d 个空白昵称",
|
|
148
|
+
skipped_long,
|
|
149
|
+
MAX_NAME_LENGTH,
|
|
150
|
+
skipped_empty,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def _parse_index(cls, raw: str) -> List[Tuple[int, str]]:
|
|
155
|
+
"""一次性解析成列表。测试用;生产走 `_build_sync` 的流式路径。"""
|
|
156
|
+
return list(cls._iter_entries(raw))
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def _build_sync(cls, path: Path, raw: str) -> int:
|
|
160
|
+
"""流式解析 + 批量入库,返回写入条数。这是生产路径。
|
|
161
|
+
|
|
162
|
+
相比「先 `_parse_index` 攒列表再写」,内存峰值从实测 576MB
|
|
163
|
+
降到只有一批在内存里的量级。
|
|
164
|
+
"""
|
|
165
|
+
tmp = path.with_suffix(".tmp")
|
|
166
|
+
if tmp.exists():
|
|
167
|
+
tmp.unlink()
|
|
168
|
+
|
|
169
|
+
conn = sqlite3.connect(tmp)
|
|
170
|
+
total = 0
|
|
171
|
+
batch: List[Tuple[int, str, str]] = []
|
|
172
|
+
try:
|
|
173
|
+
conn.execute("PRAGMA journal_mode=OFF")
|
|
174
|
+
conn.execute("PRAGMA synchronous=OFF")
|
|
175
|
+
conn.execute(
|
|
176
|
+
"CREATE TABLE players ("
|
|
177
|
+
" aid INTEGER PRIMARY KEY,"
|
|
178
|
+
" name TEXT NOT NULL,"
|
|
179
|
+
" name_lower TEXT NOT NULL"
|
|
180
|
+
")"
|
|
181
|
+
)
|
|
182
|
+
for aid, name in cls._iter_entries(raw):
|
|
183
|
+
batch.append((aid, name, name.lower()))
|
|
184
|
+
if len(batch) >= _BATCH_SIZE:
|
|
185
|
+
conn.executemany(
|
|
186
|
+
"INSERT OR REPLACE INTO players VALUES (?,?,?)", batch
|
|
187
|
+
)
|
|
188
|
+
total += len(batch)
|
|
189
|
+
batch.clear()
|
|
190
|
+
if batch:
|
|
191
|
+
conn.executemany("INSERT OR REPLACE INTO players VALUES (?,?,?)", batch)
|
|
192
|
+
total += len(batch)
|
|
193
|
+
|
|
194
|
+
conn.execute("CREATE INDEX idx_name_lower ON players(name_lower)")
|
|
195
|
+
conn.commit()
|
|
196
|
+
finally:
|
|
197
|
+
conn.close()
|
|
198
|
+
|
|
199
|
+
tmp.replace(path)
|
|
200
|
+
return total
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _write_db(path: Path, rows: List[Tuple[int, str]]) -> None:
|
|
204
|
+
"""从现成的行列表建库。测试用。"""
|
|
205
|
+
tmp = path.with_suffix(".tmp")
|
|
206
|
+
if tmp.exists():
|
|
207
|
+
tmp.unlink()
|
|
208
|
+
conn = sqlite3.connect(tmp)
|
|
209
|
+
try:
|
|
210
|
+
conn.execute("PRAGMA journal_mode=OFF")
|
|
211
|
+
conn.execute("PRAGMA synchronous=OFF")
|
|
212
|
+
conn.execute(
|
|
213
|
+
"CREATE TABLE players ("
|
|
214
|
+
" aid INTEGER PRIMARY KEY,"
|
|
215
|
+
" name TEXT NOT NULL,"
|
|
216
|
+
" name_lower TEXT NOT NULL"
|
|
217
|
+
")"
|
|
218
|
+
)
|
|
219
|
+
conn.executemany(
|
|
220
|
+
"INSERT OR REPLACE INTO players VALUES (?,?,?)",
|
|
221
|
+
((aid, name, name.lower()) for aid, name in rows),
|
|
222
|
+
)
|
|
223
|
+
conn.execute("CREATE INDEX idx_name_lower ON players(name_lower)")
|
|
224
|
+
conn.commit()
|
|
225
|
+
finally:
|
|
226
|
+
conn.close()
|
|
227
|
+
tmp.replace(path)
|
|
228
|
+
|
|
229
|
+
async def build(self, mode: "GameMode", fetcher) -> bool:
|
|
230
|
+
"""下载并构建索引。`fetcher` 是 `async (url, timeout) -> bytes`。
|
|
231
|
+
|
|
232
|
+
返回是否构建成功。解析/写库放在线程里,不阻塞事件循环。
|
|
233
|
+
"""
|
|
234
|
+
async with self._build_lock:
|
|
235
|
+
# 下载用 players_folder:正式服在这里叫 profile 而不是 regular
|
|
236
|
+
url = f"{PLAYERS_API}/{mode.players_folder}/index.json"
|
|
237
|
+
logger.info("开始下载昵称索引:%s(约 67MB,首次会慢)", url)
|
|
238
|
+
started = time.time()
|
|
239
|
+
try:
|
|
240
|
+
raw_bytes = await fetcher(url, self.download_timeout)
|
|
241
|
+
except Exception as exc: # noqa: BLE001
|
|
242
|
+
logger.warning("昵称索引下载失败:%s", exc)
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
logger.info(
|
|
246
|
+
"索引下载完成:%.1f MB / %.1fs,开始转 SQLite",
|
|
247
|
+
len(raw_bytes) / 1024 / 1024,
|
|
248
|
+
time.time() - started,
|
|
249
|
+
)
|
|
250
|
+
try:
|
|
251
|
+
raw = raw_bytes.decode("utf-8", "replace")
|
|
252
|
+
del raw_bytes
|
|
253
|
+
total = await asyncio.to_thread(
|
|
254
|
+
self._build_sync, self.db_path(mode), raw
|
|
255
|
+
)
|
|
256
|
+
except Exception as exc: # noqa: BLE001
|
|
257
|
+
logger.warning("昵称索引构建失败:%s", exc)
|
|
258
|
+
return False
|
|
259
|
+
|
|
260
|
+
if not total:
|
|
261
|
+
logger.warning("昵称索引内容为空,判定为失败")
|
|
262
|
+
return False
|
|
263
|
+
|
|
264
|
+
logger.info("昵称索引就绪:%d 条 / 耗时 %.1fs", total, time.time() - started)
|
|
265
|
+
return True
|
|
266
|
+
|
|
267
|
+
# ---------------------------------------------------------------- 检索
|
|
268
|
+
|
|
269
|
+
@staticmethod
|
|
270
|
+
def _search_sync(db: Path, query: str, limit: int) -> Tuple[List[Tuple[int, str]], str]:
|
|
271
|
+
"""返回 (结果, 匹配类型)。同步函数,调用方负责丢线程。"""
|
|
272
|
+
q = query.strip().lower()
|
|
273
|
+
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
|
|
274
|
+
try:
|
|
275
|
+
# 1. 精确匹配优先——重名时全部返回,交给上层消歧
|
|
276
|
+
rows = conn.execute(
|
|
277
|
+
"SELECT aid, name FROM players WHERE name_lower = ? ORDER BY aid LIMIT ?",
|
|
278
|
+
(q, limit),
|
|
279
|
+
).fetchall()
|
|
280
|
+
if rows:
|
|
281
|
+
return rows, MatchKind.EXACT
|
|
282
|
+
|
|
283
|
+
# 2. 前缀匹配(能走 idx_name_lower 索引)
|
|
284
|
+
rows = conn.execute(
|
|
285
|
+
"SELECT aid, name FROM players "
|
|
286
|
+
"WHERE name_lower >= ? AND name_lower < ? "
|
|
287
|
+
"ORDER BY name_lower LIMIT ?",
|
|
288
|
+
(q, q + "\uffff", limit),
|
|
289
|
+
).fetchall()
|
|
290
|
+
if rows:
|
|
291
|
+
return rows, MatchKind.PREFIX
|
|
292
|
+
|
|
293
|
+
# 3. 退化成子串匹配。走不了索引,但 LIMIT 能让它尽早停
|
|
294
|
+
rows = conn.execute(
|
|
295
|
+
"SELECT aid, name FROM players "
|
|
296
|
+
"WHERE name_lower LIKE ? ORDER BY length(name) LIMIT ?",
|
|
297
|
+
(f"%{q}%", limit),
|
|
298
|
+
).fetchall()
|
|
299
|
+
return rows, MatchKind.SUBSTRING
|
|
300
|
+
finally:
|
|
301
|
+
conn.close()
|
|
302
|
+
|
|
303
|
+
async def search(
|
|
304
|
+
self, mode: "GameMode", query: str, *, limit: int = 10
|
|
305
|
+
) -> Tuple[List[Tuple[int, str]], str]:
|
|
306
|
+
"""按昵称检索。返回 ([(aid, name)], 匹配类型)。
|
|
307
|
+
|
|
308
|
+
数据库不存在时返回空结果——调用方应先确保索引已就绪。
|
|
309
|
+
"""
|
|
310
|
+
db = self.db_path(mode)
|
|
311
|
+
if not db.exists() or not query.strip():
|
|
312
|
+
return [], MatchKind.EXACT
|
|
313
|
+
return await asyncio.to_thread(self._search_sync, db, query, limit)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""记录最近被查询过的玩家:供定时预热使用,同时兜住上游索引的滞后。
|
|
2
|
+
|
|
3
|
+
顺带解决一个上游机制导致的盲区:`players.tarkov.dev/*/index.json` **每天只重建
|
|
4
|
+
一次**(实测 Last-Modified 固定在 00:02 UTC 左右),而档案 `{aid}.json` 是扫描到
|
|
5
|
+
就立刻写入的。所以新账号会出现「用 ID 能查到、用名字查不到」,最长要等一天。
|
|
6
|
+
|
|
7
|
+
我们手上本来就有档案(里面带 nickname),查过一次就记下来,
|
|
8
|
+
下次按名字查时作为兜底,不必等上游的索引。
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
背景:玩家档案是插件里唯一还要实时拉上游的数据(昵称索引、等级表、
|
|
12
|
+
成就表都已本地化)。档案更新本身很慢——上游靠志愿者用 TarkovMonitor
|
|
13
|
+
扫描上传,实测某个号 13 天没变——所以没必要每次查询都打上游。
|
|
14
|
+
|
|
15
|
+
但也不能一直吃缓存:常查的号应该保持新鲜。于是记录"谁被查过",
|
|
16
|
+
由一个定时任务每小时把过期的那些重新拉一遍。
|
|
17
|
+
|
|
18
|
+
这样:
|
|
19
|
+
· 用户查询永远命中缓存(秒回)
|
|
20
|
+
· 常查的号最多 1 小时陈旧
|
|
21
|
+
· 请求量可控(只刷被查过的,不是全量 297 万)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import logging
|
|
28
|
+
import time
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Dict, List, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger("nonebot_plugin_efthelper")
|
|
33
|
+
|
|
34
|
+
SCHEMA_VERSION = 1
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ProfileRegistry:
|
|
38
|
+
"""最近查询过的 (模式, 账号) 列表,按查询时间倒序。"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, cache_dir: Path, *, max_entries: int = 200) -> None:
|
|
41
|
+
self.cache_dir = Path(cache_dir)
|
|
42
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
self.max_entries = max_entries
|
|
44
|
+
self._path = self.cache_dir / "recent_profiles.json"
|
|
45
|
+
self._entries: Dict[str, Dict] = {}
|
|
46
|
+
self._load()
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------- 读写
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _key(folder: str, aid: int) -> str:
|
|
52
|
+
return f"{folder}:{aid}"
|
|
53
|
+
|
|
54
|
+
def _load(self) -> None:
|
|
55
|
+
if not self._path.exists():
|
|
56
|
+
return
|
|
57
|
+
try:
|
|
58
|
+
with self._path.open(encoding="utf-8") as fh:
|
|
59
|
+
data = json.load(fh)
|
|
60
|
+
if data.get("version") != SCHEMA_VERSION:
|
|
61
|
+
logger.info("查询记录版本不符,重建")
|
|
62
|
+
return
|
|
63
|
+
self._entries = data.get("entries") or {}
|
|
64
|
+
except Exception as exc: # noqa: BLE001 - 坏了就当空的
|
|
65
|
+
logger.warning("查询记录读取失败,忽略:%s", exc)
|
|
66
|
+
self._entries = {}
|
|
67
|
+
|
|
68
|
+
def _save(self) -> None:
|
|
69
|
+
tmp = self._path.with_suffix(".tmp")
|
|
70
|
+
try:
|
|
71
|
+
with tmp.open("w", encoding="utf-8") as fh:
|
|
72
|
+
json.dump(
|
|
73
|
+
{"version": SCHEMA_VERSION, "entries": self._entries},
|
|
74
|
+
fh,
|
|
75
|
+
ensure_ascii=False,
|
|
76
|
+
separators=(",", ":"),
|
|
77
|
+
)
|
|
78
|
+
tmp.replace(self._path)
|
|
79
|
+
except Exception as exc: # noqa: BLE001 - 记录失败不该影响查询
|
|
80
|
+
logger.warning("查询记录写入失败:%s", exc)
|
|
81
|
+
|
|
82
|
+
# ---------------------------------------------------------------- 接口
|
|
83
|
+
|
|
84
|
+
def remember(self, folder: str, aid: int, name: Optional[str] = None) -> None:
|
|
85
|
+
"""记一笔查询。已存在则只更新时间。
|
|
86
|
+
|
|
87
|
+
`name` 是档案里的昵称。上游索引滞后时,这是我们唯一能按名字找到
|
|
88
|
+
这个账号的途径,所以拿到就存下来。
|
|
89
|
+
"""
|
|
90
|
+
key = self._key(folder, aid)
|
|
91
|
+
entry = self._entries.get(key)
|
|
92
|
+
if entry is None:
|
|
93
|
+
entry = {"folder": folder, "aid": aid, "refreshed": 0}
|
|
94
|
+
self._entries[key] = entry
|
|
95
|
+
entry["queried"] = time.time()
|
|
96
|
+
if name:
|
|
97
|
+
entry["name"] = name
|
|
98
|
+
self._trim()
|
|
99
|
+
self._save()
|
|
100
|
+
|
|
101
|
+
def find_by_name(self, query: str) -> List[Tuple[str, int, str]]:
|
|
102
|
+
"""在本地记录里按昵称找。返回 [(folder, aid, name)]。
|
|
103
|
+
|
|
104
|
+
精确匹配优先于子串匹配;同一模式优先于其它模式。
|
|
105
|
+
用来兜住上游索引「每天只重建一次」造成的新账号盲区。
|
|
106
|
+
"""
|
|
107
|
+
q = query.strip().lower()
|
|
108
|
+
if not q:
|
|
109
|
+
return []
|
|
110
|
+
|
|
111
|
+
exact: List[Tuple[str, int, str]] = []
|
|
112
|
+
partial: List[Tuple[str, int, str]] = []
|
|
113
|
+
for entry in sorted(
|
|
114
|
+
self._entries.values(), key=lambda e: e.get("queried", 0), reverse=True
|
|
115
|
+
):
|
|
116
|
+
name = (entry.get("name") or "").strip()
|
|
117
|
+
if not name:
|
|
118
|
+
continue
|
|
119
|
+
low = name.lower()
|
|
120
|
+
hit = (entry["folder"], int(entry["aid"]), name)
|
|
121
|
+
if low == q:
|
|
122
|
+
exact.append(hit)
|
|
123
|
+
elif q in low:
|
|
124
|
+
partial.append(hit)
|
|
125
|
+
return exact + partial
|
|
126
|
+
|
|
127
|
+
def entries(self, *, limit: Optional[int] = None) -> List[Tuple[str, int]]:
|
|
128
|
+
"""按最近查询时间倒序返回 (folder, aid)。"""
|
|
129
|
+
ordered = sorted(
|
|
130
|
+
self._entries.values(), key=lambda e: e.get("queried", 0), reverse=True
|
|
131
|
+
)
|
|
132
|
+
if limit is not None:
|
|
133
|
+
ordered = ordered[:limit]
|
|
134
|
+
return [(e["folder"], int(e["aid"])) for e in ordered]
|
|
135
|
+
|
|
136
|
+
def mark_refreshed(self, folder: str, aid: int, *, success: bool) -> None:
|
|
137
|
+
entry = self._entries.get(self._key(folder, aid))
|
|
138
|
+
if entry is None:
|
|
139
|
+
return
|
|
140
|
+
entry["refreshed"] = time.time()
|
|
141
|
+
entry["last_ok"] = success
|
|
142
|
+
self._save()
|
|
143
|
+
|
|
144
|
+
def forget(self, folder: str, aid: int) -> None:
|
|
145
|
+
if self._entries.pop(self._key(folder, aid), None) is not None:
|
|
146
|
+
self._save()
|
|
147
|
+
|
|
148
|
+
def clear(self) -> None:
|
|
149
|
+
self._entries.clear()
|
|
150
|
+
self._save()
|
|
151
|
+
|
|
152
|
+
def __len__(self) -> int:
|
|
153
|
+
return len(self._entries)
|
|
154
|
+
|
|
155
|
+
def _trim(self) -> None:
|
|
156
|
+
"""只保留最近 max_entries 个,避免文件无限增长。"""
|
|
157
|
+
if len(self._entries) <= self.max_entries:
|
|
158
|
+
return
|
|
159
|
+
keep = sorted(
|
|
160
|
+
self._entries.items(),
|
|
161
|
+
key=lambda kv: kv[1].get("queried", 0),
|
|
162
|
+
reverse=True,
|
|
163
|
+
)[: self.max_entries]
|
|
164
|
+
self._entries = dict(keep)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nonebot-plugin-efthelper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 查询《逃离塔科夫》服务器状态、玩家资料与邪教圈献祭推荐
|
|
5
|
+
Author-email: xL1gHTx <light@l1ght.xyz>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Eastlight2008/nonebot_plugin_efthelper
|
|
8
|
+
Project-URL: Repository, https://github.com/Eastlight2008/nonebot_plugin_efthelper
|
|
9
|
+
Project-URL: Issues, https://github.com/Eastlight2008/nonebot_plugin_efthelper
|
|
10
|
+
Keywords: nonebot,nonebot2,eft,tarkov,escape-from-tarkov,plugin
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: nonebot2>=2.3.0
|
|
24
|
+
Requires-Dist: nonebot-adapter-onebot>=2.4.0
|
|
25
|
+
Requires-Dist: httpx>=0.27
|
|
26
|
+
Requires-Dist: pillow>=10.0
|
|
27
|
+
Requires-Dist: nonebot-plugin-localstore>=0.7.0
|
|
28
|
+
Requires-Dist: nonebot-plugin-apscheduler>=0.4.0
|
|
29
|
+
Requires-Dist: nonebot-plugin-waiter>=0.4.0
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# nonebot-plugin-efthelper
|
|
33
|
+
|
|
34
|
+
查询《逃离塔科夫》服务器状态、玩家资料,以及**邪教圈献祭推荐**。
|
|
35
|
+
|
|
36
|
+
> 数据来源:[tarkov.dev](https://tarkov.dev)(服务器状态、物品行情、玩家资料)
|
|
37
|
+
> 与 [eftforge](https://www.eftforge.com)(更实时的玩家档案与角色立绘)。
|
|
38
|
+
> 本项目与 Battlestate Games、tarkov.dev、eftforge 均无关联。
|
|
39
|
+
|
|
40
|
+
## 功能
|
|
41
|
+
|
|
42
|
+
| 命令 | 说明 |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `/eftstatus` | 查看三个模式(PvP / PvP 赛季 / PvE)的服务器状态 |
|
|
45
|
+
| `/player <模式> <角色ID 或 昵称>` | 玩家资料卡片:等级、转生、结局、EXP、PMC/SCAV 战绩、成就 |
|
|
46
|
+
| `/eftcircle <模式> <件数>` | 邪教圈献祭推荐:按 14 小时档(≥350,001)算出最省钱的献祭组合 |
|
|
47
|
+
| `/eftreload [模式]` | 手动刷新昵称索引(仅超级用户) |
|
|
48
|
+
|
|
49
|
+
模式取值:`pvp`(正式服)、`pvps`(PvP 赛季)、`pve`。
|
|
50
|
+
|
|
51
|
+
### 邪教圈献祭推荐
|
|
52
|
+
|
|
53
|
+
目标阈值固定为 **350,001(14 小时档)**,件数取 1~5:
|
|
54
|
+
|
|
55
|
+
- 求解「恰好 N 件、基准价值合计 ≥ 阈值、总价最低」的组合,同一种物品可以重复;
|
|
56
|
+
- 未指定件数时,一次给出 1~5 件的全部方案,并框出**性价比最高**的那一档;
|
|
57
|
+
- 单件价格用 tarkov.dev 的 24 小时成交均价,并随件数递增 2% 的保守系数;
|
|
58
|
+
- 行情缓存 6 小时,启动后每 10 分钟后台预热一次。
|
|
59
|
+
|
|
60
|
+
## 安装
|
|
61
|
+
|
|
62
|
+
使用 NB-CLI:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
nb plugin install nonebot-plugin-efthelper
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
或在 `pyproject.toml` 的 `[tool.nonebot]` 里加入插件名。
|
|
69
|
+
|
|
70
|
+
插件需要 OneBot V11 适配器:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
nb adapter install nonebot-adapter-onebot
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 配置
|
|
77
|
+
|
|
78
|
+
在 `.env` 中填写,全部可选:
|
|
79
|
+
|
|
80
|
+
| 配置项 | 默认值 | 说明 |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| `EFT_CACHE_DIR` | localstore 缓存目录 | 行情/缓存文件位置 |
|
|
83
|
+
| `EFT_HTTP_TIMEOUT` | `25.0` | HTTP 超时(秒) |
|
|
84
|
+
| `EFT_USER_AGENT` | `nonebot-plugin-efthelper` | 请求 UA(tarkov.dev 要求自定义 UA) |
|
|
85
|
+
| `EFT_CIRCLE_DEFAULT_THRESHOLD` | `350001` | 献祭阈值,14 小时档 |
|
|
86
|
+
| `EFT_CIRCLE_MAX_ITEMS` | `5` | 最多几件 |
|
|
87
|
+
| `EFT_CIRCLE_PRICE_FACTOR` | `1.0` | 买 1 件时的价格系数 |
|
|
88
|
+
| `EFT_CIRCLE_PRICE_FACTOR_STEP` | `0.02` | 每多一件追加的系数 |
|
|
89
|
+
| `EFT_CIRCLE_MAX_SAME_ITEM` | `0` | 同一件最多几份,0 = 不限 |
|
|
90
|
+
| `EFT_CIRCLE_CARD_ENABLED` | `true` | 是否发送卡片图 |
|
|
91
|
+
| `EFT_CIRCLE_WARM_ENABLED` | `true` | 是否后台预热行情 |
|
|
92
|
+
| `EFT_CIRCLE_WARM_INTERVAL_MINUTES` | `10.0` | 预热间隔(分钟) |
|
|
93
|
+
| `EFT_EFTFORGE_ENABLED` | `true` | 是否优先用 eftforge 取玩家档案 |
|
|
94
|
+
| `EFT_EFTFORGE_BASE` | `https://www.eftforge.com` | eftforge 地址 |
|
|
95
|
+
| `EFT_EFTFORGE_KEY` | 空 | eftforge 的 X-Atlas-Key(可选) |
|
|
96
|
+
| `EFT_EFTFORGE_ART_BRIGHTNESS` | `0.85` | 立绘压暗系数 |
|
|
97
|
+
|
|
98
|
+
## 效果
|
|
99
|
+
|
|
100
|
+
- 玩家卡片:左侧角色胸像、右侧昵称/等级/转生/结局/EXP 进度条、PMC 与 SCAV 双栏战绩、成就列表;
|
|
101
|
+
- 邪教圈卡片:按件数列出献祭组合、购买成本与节省额,金额统一卢布符号。
|
|
102
|
+
|
|
103
|
+
## 许可证
|
|
104
|
+
|
|
105
|
+
MIT
|