nonebot-plugin-bugu 0.2.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.
Files changed (35) hide show
  1. nonebot_plugin_bugu/__init__.py +31 -0
  2. nonebot_plugin_bugu/api.py +282 -0
  3. nonebot_plugin_bugu/collection.py +166 -0
  4. nonebot_plugin_bugu/commands.py +234 -0
  5. nonebot_plugin_bugu/config.py +91 -0
  6. nonebot_plugin_bugu/draw.py +406 -0
  7. nonebot_plugin_bugu/features/__init__.py +0 -0
  8. nonebot_plugin_bugu/features/collection.py +247 -0
  9. nonebot_plugin_bugu/features/common.py +100 -0
  10. nonebot_plugin_bugu/features/flowers/__init__.py +0 -0
  11. nonebot_plugin_bugu/features/flowers/data.py +167 -0
  12. nonebot_plugin_bugu/features/flowers/render.py +300 -0
  13. nonebot_plugin_bugu/features/flowers/reply.py +123 -0
  14. nonebot_plugin_bugu/features/neighbors/__init__.py +0 -0
  15. nonebot_plugin_bugu/features/neighbors/data.py +143 -0
  16. nonebot_plugin_bugu/features/neighbors/render.py +225 -0
  17. nonebot_plugin_bugu/features/neighbors/reply.py +149 -0
  18. nonebot_plugin_bugu/features/recipes/__init__.py +0 -0
  19. nonebot_plugin_bugu/features/recipes/data.py +313 -0
  20. nonebot_plugin_bugu/features/recipes/render.py +371 -0
  21. nonebot_plugin_bugu/features/recipes/reply.py +219 -0
  22. nonebot_plugin_bugu/features/recipes/search.py +151 -0
  23. nonebot_plugin_bugu/features/starsea/__init__.py +0 -0
  24. nonebot_plugin_bugu/features/starsea/data.py +267 -0
  25. nonebot_plugin_bugu/features/starsea/render.py +579 -0
  26. nonebot_plugin_bugu/features/starsea/reply.py +356 -0
  27. nonebot_plugin_bugu/features/starsea/search.py +271 -0
  28. nonebot_plugin_bugu/fonts.py +152 -0
  29. nonebot_plugin_bugu/runtime.py +109 -0
  30. nonebot_plugin_bugu/values.py +87 -0
  31. nonebot_plugin_bugu-0.2.0.dist-info/METADATA +257 -0
  32. nonebot_plugin_bugu-0.2.0.dist-info/RECORD +35 -0
  33. nonebot_plugin_bugu-0.2.0.dist-info/WHEEL +4 -0
  34. nonebot_plugin_bugu-0.2.0.dist-info/entry_points.txt +3 -0
  35. nonebot_plugin_bugu-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,406 @@
1
+ """图片卡片的共用绘制工具。
2
+
3
+ 背景渐变、圆角裁剪、文字截断 / 折行、胶囊、编号徽章、页脚……四个模块的卡片
4
+ (星海 / 菜谱 / 友邻 / 鲜花)都靠这一层,保证视觉一致。
5
+
6
+ 所有函数都是同步的,调用方负责丢进线程池。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import io
12
+ import math
13
+ from typing import Any, List, Optional, Sequence, Tuple
14
+
15
+ try: # 没装 Pillow 时插件仍要能导入,具体报错留给渲染阶段
16
+ from PIL import Image, ImageDraw
17
+ except ImportError: # pragma: no cover - 依赖已写在 pyproject 里
18
+ Image = None # type: ignore[assignment]
19
+ ImageDraw = None # type: ignore[assignment]
20
+
21
+ from .fonts import FontError, FontSet, resolve_fonts
22
+
23
+ RESAMPLE = getattr(getattr(Image, "Resampling", None), "LANCZOS", None)
24
+
25
+ # ImageDraw.ImageDraw 的别名:渲染函数签名用它,模块没装 Pillow 时也不会炸
26
+ Draw = Any
27
+
28
+ # 布谷工具箱的深色星空主题
29
+ BG_TOP = (24, 34, 76)
30
+ BG_BOTTOM = (11, 16, 36)
31
+ CREAM = (252, 248, 225)
32
+ DIM = (138, 155, 186)
33
+ FAINT = (92, 107, 138)
34
+ YELLOW = (246, 204, 82)
35
+ LINE = (43, 59, 99)
36
+ TILE_BG = (30, 41, 78)
37
+ BADGE_BLUE = (32, 52, 92)
38
+ BADGE_BLUE_LINE = (108, 148, 210)
39
+ TYPE_CHIP_INK = (42, 33, 24)
40
+ SPECIALTY_BLUE = (59, 130, 196)
41
+ GREEN = (76, 175, 98)
42
+
43
+ GRADE_COLORS = {
44
+ "S": (198, 158, 58),
45
+ "A": (156, 134, 162),
46
+ "B": (133, 181, 187),
47
+ "C": (198, 193, 173),
48
+ }
49
+ GRADE_UNKNOWN = (158, 154, 139)
50
+
51
+ SOURCE_TEXT = "数据来源:布谷工具箱 · bugu.nsun200512.cc"
52
+
53
+
54
+ class DrawError(RuntimeError):
55
+ """图片渲染失败(缺字体 / 图片坏掉 / 没装 Pillow)。"""
56
+
57
+
58
+ def require_pillow() -> None:
59
+ if Image is None or ImageDraw is None:
60
+ raise DrawError("未安装 Pillow,无法渲染图片(pip install pillow)")
61
+
62
+
63
+ def grade_color(grade: str) -> Tuple[int, int, int]:
64
+ return GRADE_COLORS.get((grade or "").upper(), GRADE_UNKNOWN)
65
+
66
+
67
+ def resolve_fontset(fonts: Optional[FontSet]) -> FontSet:
68
+ if fonts is not None:
69
+ return fonts
70
+ try:
71
+ return resolve_fonts()
72
+ except FontError as exc:
73
+ raise DrawError(str(exc)) from exc
74
+
75
+
76
+ # ------------------------------------------------------------------ 图像
77
+
78
+
79
+ def resize(image: Image.Image, size: Tuple[int, int]) -> Image.Image:
80
+ return image.resize((max(1, size[0]), max(1, size[1])), RESAMPLE or Image.BICUBIC)
81
+
82
+
83
+ def open_image(raw: Optional[bytes], label: str = "图片") -> Optional[Image.Image]:
84
+ if not raw:
85
+ return None
86
+ try:
87
+ image = Image.open(io.BytesIO(raw))
88
+ image.load()
89
+ return image.convert("RGBA")
90
+ except Exception as exc: # Pillow 对坏图会抛各种异常
91
+ raise DrawError(f"{label}无法解析:{exc}") from exc
92
+
93
+
94
+ def background(width: int, height: int) -> Image.Image:
95
+ """竖向渐变底:上深蓝下近黑。"""
96
+ width = max(1, width)
97
+ height = max(1, height)
98
+ strip = Image.new("RGBA", (1, height))
99
+ for y in range(height):
100
+ t = y / max(1, height - 1)
101
+ color = tuple(int(a + (b - a) * t) for a, b in zip(BG_TOP, BG_BOTTOM))
102
+ strip.putpixel((0, y), (*color, 255))
103
+ return resize(strip, (width, height))
104
+
105
+
106
+ def rounded(image: Image.Image, radius: int) -> Image.Image:
107
+ mask = Image.new("L", image.size, 0)
108
+ ImageDraw.Draw(mask).rounded_rectangle(
109
+ [0, 0, image.size[0] - 1, image.size[1] - 1], radius, fill=255
110
+ )
111
+ out = image.convert("RGBA")
112
+ out.putalpha(mask)
113
+ return out
114
+
115
+
116
+ def cover(image: Image.Image, size: Tuple[int, int]) -> Image.Image:
117
+ """等比缩放铺满目标框,居中裁切(不拉伸)。"""
118
+ target_w, target_h = max(1, size[0]), max(1, size[1])
119
+ scale = max(target_w / image.width, target_h / image.height)
120
+ new_size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
121
+ scaled = resize(image, new_size)
122
+ left = (scaled.width - target_w) // 2
123
+ top = (scaled.height - target_h) // 2
124
+ return scaled.crop((left, top, left + target_w, top + target_h))
125
+
126
+
127
+ # ------------------------------------------------------------------ 文字
128
+
129
+
130
+ def text_width(draw: ImageDraw.ImageDraw, text: str, font) -> float:
131
+ return draw.textlength(text, font=font)
132
+
133
+
134
+ def fit_text(draw: ImageDraw.ImageDraw, text: str, font, max_width: float) -> str:
135
+ """单行放不下就截断加省略号。"""
136
+ text = text or ""
137
+ if max_width <= 0 or text_width(draw, text, font) <= max_width:
138
+ return text
139
+ ellipsis = "…"
140
+ while text and text_width(draw, text + ellipsis, font) > max_width:
141
+ text = text[:-1]
142
+ return (text + ellipsis) if text else ellipsis
143
+
144
+
145
+ def wrap_text(
146
+ draw: ImageDraw.ImageDraw,
147
+ text: str,
148
+ font,
149
+ max_width: float,
150
+ max_lines: int = 2,
151
+ *,
152
+ paragraph_gap: bool = False,
153
+ ) -> List[str]:
154
+ """按宽度折行,最多 ``max_lines`` 行,最后一行超出就省略号。
155
+
156
+ ``paragraph_gap`` 决定原文换行怎么处理:``True`` 时空一行(人物介绍这种分段文字),
157
+ ``False`` 时紧贴下一行(菜谱描述这种逐行排版)。
158
+ """
159
+ text = (text or "").replace("\r", "")
160
+ if not text.strip() or max_width <= 0:
161
+ return []
162
+ lines: List[str] = []
163
+ paragraphs = text.split("\n")
164
+ for index, paragraph in enumerate(paragraphs):
165
+ paragraph = paragraph.strip()
166
+ if not paragraph:
167
+ continue
168
+ if index and lines and paragraph_gap:
169
+ lines.append("")
170
+ rest = paragraph
171
+ while rest and len(lines) < max_lines:
172
+ if text_width(draw, rest, font) <= max_width:
173
+ lines.append(rest)
174
+ rest = ""
175
+ break
176
+ cut = len(rest)
177
+ while cut > 1 and text_width(draw, rest[:cut], font) > max_width:
178
+ cut -= 1
179
+ break_at = max(rest.rfind(sep, 0, cut) for sep in (":", ",", "、", "(")) + 1
180
+ if 3 < break_at < cut:
181
+ cut = break_at
182
+ lines.append(rest[:cut])
183
+ rest = rest[cut:]
184
+ if rest and lines:
185
+ lines[-1] = fit_text(draw, lines[-1] + rest, font, max_width)
186
+ if len(lines) >= max_lines:
187
+ break
188
+ return lines
189
+
190
+
191
+ def draw_paragraph(
192
+ draw: ImageDraw.ImageDraw,
193
+ text: str,
194
+ font,
195
+ x: int,
196
+ y: int,
197
+ max_width: int,
198
+ *,
199
+ line_height: int,
200
+ fill=DIM,
201
+ max_lines: int = 8,
202
+ paragraph_gap: bool = False,
203
+ ) -> int:
204
+ """画一段自动折行的文字,返回占用高度。"""
205
+ lines = wrap_text(
206
+ draw, text, font, max_width, max_lines=max_lines, paragraph_gap=paragraph_gap
207
+ )
208
+ for i, line in enumerate(lines):
209
+ if not line:
210
+ continue
211
+ draw.text((x, y + i * line_height), line, font=font, fill=fill)
212
+ return len(lines) * line_height
213
+
214
+
215
+ def bold_text(draw, xy, text: str, font, fonts: FontSet, fill=CREAM, anchor=None) -> None:
216
+ """统一的「粗体」:真粗体直接用,模拟粗体加一圈同色描边。"""
217
+ draw.text(
218
+ xy,
219
+ text,
220
+ font=font,
221
+ fill=fill,
222
+ anchor=anchor,
223
+ stroke_width=fonts.stroke(True),
224
+ stroke_fill=fill,
225
+ )
226
+
227
+
228
+ # ------------------------------------------------------------------ 组件
229
+
230
+
231
+ def star(draw: ImageDraw.ImageDraw, cx: float, cy: float, r: float, fill) -> None:
232
+ points = []
233
+ for i in range(10):
234
+ angle = -math.pi / 2 + i * math.pi / 5
235
+ radius = r if i % 2 == 0 else r * 0.45
236
+ points.append((cx + radius * math.cos(angle), cy + radius * math.sin(angle)))
237
+ draw.polygon(points, fill=fill)
238
+
239
+
240
+ def chip(
241
+ draw: ImageDraw.ImageDraw,
242
+ x: float,
243
+ y: float,
244
+ text: str,
245
+ font,
246
+ *,
247
+ fill=YELLOW,
248
+ ink=TYPE_CHIP_INK,
249
+ pad_x: int = 14,
250
+ height: int = 34,
251
+ radius: int = 17,
252
+ ) -> int:
253
+ """画一个胶囊标签,返回占用宽度。"""
254
+ width = int(text_width(draw, text, font)) + pad_x * 2
255
+ draw.rounded_rectangle([x, y, x + width, y + height], radius, fill=fill)
256
+ bbox = draw.textbbox((0, 0), text, font=font)
257
+ text_h = bbox[3] - bbox[1]
258
+ draw.text((x + pad_x, y + (height - text_h) / 2 - bbox[1]), text, font=font, fill=ink)
259
+ return width
260
+
261
+
262
+ def chip_row(
263
+ draw: ImageDraw.ImageDraw,
264
+ x: int,
265
+ y: int,
266
+ items: Sequence[Tuple[str, Tuple[int, int, int], Tuple[int, int, int]]],
267
+ font,
268
+ max_width: int,
269
+ *,
270
+ height: int = 30,
271
+ gap: int = 8,
272
+ line_gap: int = 36,
273
+ ) -> int:
274
+ """把若干 ``(文字, 底色, 字色)`` 胶囊按行流式排好,返回占用高度。"""
275
+ cursor_x = x
276
+ cursor_y = y
277
+ for text, fill, ink in items:
278
+ width = int(text_width(draw, text, font)) + 24
279
+ if cursor_x > x and cursor_x + width > x + max_width:
280
+ cursor_x = x
281
+ cursor_y += line_gap
282
+ chip(
283
+ draw,
284
+ cursor_x,
285
+ cursor_y,
286
+ text,
287
+ font,
288
+ fill=fill,
289
+ ink=ink,
290
+ pad_x=12,
291
+ height=height,
292
+ radius=height // 2,
293
+ )
294
+ cursor_x += width + gap
295
+ return cursor_y - y + height
296
+
297
+
298
+ def number_badge(
299
+ draw: ImageDraw.ImageDraw,
300
+ cx: float,
301
+ cy: float,
302
+ number: int,
303
+ font,
304
+ *,
305
+ special: bool,
306
+ radius: Optional[int] = None,
307
+ ) -> None:
308
+ r = radius or (15 if number < 10 else 17)
309
+ if special:
310
+ fill, outline, ink = YELLOW, YELLOW, TYPE_CHIP_INK
311
+ else:
312
+ fill, outline, ink = BADGE_BLUE, BADGE_BLUE_LINE, CREAM
313
+ draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=2)
314
+ draw.text((cx, cy), str(number), font=font, fill=ink, anchor="mm")
315
+
316
+
317
+ def check_mark(
318
+ draw: ImageDraw.ImageDraw,
319
+ cx: float,
320
+ cy: float,
321
+ radius: int,
322
+ *,
323
+ fill=GREEN,
324
+ outline=(11, 16, 36),
325
+ ) -> None:
326
+ """右上角的绿色对勾(收集进度)。"""
327
+ draw.ellipse(
328
+ [cx - radius, cy - radius, cx + radius, cy + radius],
329
+ fill=fill,
330
+ outline=outline,
331
+ width=2,
332
+ )
333
+ r = radius * 0.5
334
+ draw.line(
335
+ [(cx - r * 0.8, cy + r * 0.1), (cx - r * 0.2, cy + r * 0.7), (cx + r, cy - r * 0.68)],
336
+ fill=(255, 255, 255),
337
+ width=max(2, radius // 5),
338
+ )
339
+
340
+
341
+ def icon_disc(
342
+ canvas: Image.Image,
343
+ draw: ImageDraw.ImageDraw,
344
+ icon: Optional[Image.Image],
345
+ cx: float,
346
+ cy: float,
347
+ radius: int,
348
+ *,
349
+ ring: Tuple[int, int, int] = TILE_BG,
350
+ fill=TILE_BG,
351
+ placeholder: str = "?",
352
+ font=None,
353
+ placeholder_fill=DIM,
354
+ ) -> None:
355
+ """画一个圆形图标位:有图就按对角线内切放进圆里,没图画占位字。"""
356
+ draw.ellipse(
357
+ [cx - radius, cy - radius, cx + radius, cy + radius],
358
+ fill=fill,
359
+ outline=ring,
360
+ width=3,
361
+ )
362
+ if icon is not None:
363
+ scale = 2 * radius * 0.90 / math.hypot(max(1, icon.width), max(1, icon.height))
364
+ scaled = resize(
365
+ icon,
366
+ (max(1, round(icon.width * scale)), max(1, round(icon.height * scale))),
367
+ )
368
+ canvas.alpha_composite(
369
+ scaled, (round(cx - scaled.width / 2), round(cy - scaled.height / 2))
370
+ )
371
+ elif font is not None:
372
+ draw.text((cx, cy), placeholder, font=font, fill=placeholder_fill, anchor="mm")
373
+
374
+
375
+ def encode(image: Image.Image) -> bytes:
376
+ buffer = io.BytesIO()
377
+ image.convert("RGB").save(buffer, format="PNG", optimize=True)
378
+ return buffer.getvalue()
379
+
380
+
381
+ def finish(
382
+ content: Image.Image,
383
+ width: int,
384
+ *,
385
+ fonts: FontSet,
386
+ pad: int,
387
+ left_text: str = SOURCE_TEXT,
388
+ right_text: str = "",
389
+ ) -> bytes:
390
+ """按内容实际高度裁切,贴到渐变底上,再补页脚。"""
391
+ bbox = content.getbbox()
392
+ content_h = bbox[3] if bbox else 1
393
+ content_h = max(1, min(content_h, content.height))
394
+ height = content_h + 56
395
+
396
+ canvas = background(width, height)
397
+ canvas.alpha_composite(content.crop((0, 0, width, content_h)))
398
+ draw = ImageDraw.Draw(canvas)
399
+
400
+ footer_y = height - 34
401
+ draw.line([(pad, footer_y - 12), (width - pad, footer_y - 12)], fill=LINE, width=1)
402
+ footer_font = fonts.get(15)
403
+ draw.text((pad, footer_y), left_text, font=footer_font, fill=FAINT)
404
+ if right_text:
405
+ draw.text((width - pad, footer_y), right_text, font=footer_font, fill=FAINT, anchor="rt")
406
+ return encode(canvas)
File without changes
@@ -0,0 +1,247 @@
1
+ """收集进度的命令逻辑。
2
+
3
+ 三类进度:星海物种 / 鲜花 / 菜谱。进度存在 bot 本地(按 QQ 号),
4
+ 和站点账号无关——站点同步要邮箱密码,插件不保存用户密码。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Dict, List, Sequence, Tuple
11
+
12
+ from ..collection import KIND_FLOWER, KIND_LABELS, KIND_RECIPE, KIND_STARSEA
13
+ from .common import Reply, ReplyEnv, usage
14
+
15
+ # 命令里用的类型前缀(比 KIND_LABELS 短,方便手打)
16
+ KIND_HINTS = {KIND_STARSEA: "星海", KIND_FLOWER: "鲜花", KIND_RECIPE: "菜谱"}
17
+
18
+
19
+ @dataclass
20
+ class Candidate:
21
+ kind: str
22
+ key: str
23
+ label: str
24
+ detail: str = ""
25
+
26
+
27
+ async def _candidates(env: ReplyEnv, text: str, hint: str = "") -> List[Candidate]:
28
+ """在三个图鉴里找这个名字,返回所有可能的条目(精确优先)。"""
29
+ out: List[Candidate] = []
30
+ want_starsea = hint in {"", "星海", "物种", "采集"}
31
+ want_flower = hint in {"", "鲜花", "花"}
32
+ want_recipe = hint in {"", "菜谱", "料理"}
33
+
34
+ if want_starsea:
35
+ data = await env.client.get_starsea()
36
+ exact = [
37
+ sp for sp in data.species.values() if text in (sp.name, sp.display_name)
38
+ ] or [sp for sp in data.species.values() if text in sp.label]
39
+ for species in exact:
40
+ out.append(
41
+ Candidate(
42
+ KIND_STARSEA,
43
+ str(species.id),
44
+ species.label,
45
+ f"{species.kind_name} · {species.grade or '?'}",
46
+ )
47
+ )
48
+
49
+ if want_flower:
50
+ book = await env.client.get_flowers()
51
+ exact = [f for f in book.flowers if f.name == text] or [
52
+ f for f in book.flowers if text in f.name
53
+ ]
54
+ for flower in exact:
55
+ out.append(
56
+ Candidate(
57
+ KIND_FLOWER,
58
+ flower.name,
59
+ flower.name,
60
+ f"{flower.species} · {flower.grade or '?'}",
61
+ )
62
+ )
63
+
64
+ if want_recipe:
65
+ book = await env.client.get_recipes()
66
+ exact = [
67
+ r
68
+ for r in book.recipes
69
+ if text in (r.display_name, r.number_text, str(r.number))
70
+ ] or [r for r in book.recipes if text in r.display_name]
71
+ for recipe in exact:
72
+ out.append(
73
+ Candidate(
74
+ KIND_RECIPE,
75
+ str(recipe.number),
76
+ recipe.display_name,
77
+ f"#{recipe.number_text}" + (f" · {recipe.type}" if recipe.type else ""),
78
+ )
79
+ )
80
+
81
+ return out
82
+
83
+
84
+ async def overview_text(env: ReplyEnv) -> str:
85
+ stars = await env.client.get_starsea()
86
+ recipes = await env.client.get_recipes()
87
+ flowers = await env.client.get_flowers()
88
+ totals = env.collected_totals
89
+ lines = [
90
+ "收藏进度(只存在本机,按 QQ 号区分)",
91
+ "",
92
+ f"星海物种:{totals.get(KIND_STARSEA, 0)} / {len(stars.species)}",
93
+ f"鲜花:{totals.get(KIND_FLOWER, 0)} / {len(flowers.flowers)}",
94
+ f"菜谱:{totals.get(KIND_RECIPE, 0)} / {len(recipes.recipes)}",
95
+ "",
96
+ usage(
97
+ "收藏 <名字> —— 标记 / 取消,例如 收藏 疆星步甲",
98
+ "收藏 星海 —— 看每个点位的收集进度",
99
+ "收藏 鲜花 —— 看每个品种的收集进度",
100
+ "收藏 菜谱 —— 看各类菜谱的收集进度",
101
+ "收藏 清空 —— 清空自己的进度",
102
+ ),
103
+ ]
104
+ return "\n".join(lines)
105
+
106
+
107
+ async def starsea_progress_text(env: ReplyEnv) -> str:
108
+ data = await env.client.get_starsea()
109
+ collected = env.collected(KIND_STARSEA)
110
+ total = len(data.species)
111
+ done = sum(1 for sp in data.species.values() if str(sp.id) in collected)
112
+ lines = [f"星海收集进度:{done} / {total}(按物种去重)", ""]
113
+ for sea_map in data.maps:
114
+ distinct: Dict[int, bool] = {}
115
+ rows: List[Tuple[str, int, int]] = []
116
+ for point in sea_map.ordered_points():
117
+ species = data.species_of(point)
118
+ if not species:
119
+ continue
120
+ point_done = 0
121
+ for sp in species:
122
+ got = str(sp.id) in collected
123
+ distinct[sp.id] = distinct.get(sp.id, False) or got
124
+ if got:
125
+ point_done += 1
126
+ if point_done:
127
+ rows.append((point.name, point_done, len(species)))
128
+ map_done = sum(1 for got in distinct.values() if got)
129
+ lines.append(f"【{sea_map.display_name}】已收 {map_done} / {len(distinct)} 种")
130
+ for name, point_done, point_total in rows:
131
+ lines.append(f"· {name} {point_done}/{point_total}")
132
+ if not rows:
133
+ lines.append("· (还没记录)")
134
+ if done == 0:
135
+ lines.append("")
136
+ lines.append("还没记录任何物种,发「收藏 <物种名>」试试。")
137
+ return "\n".join(lines)
138
+
139
+
140
+ async def flower_progress_text(env: ReplyEnv) -> str:
141
+ book = await env.client.get_flowers()
142
+ collected = env.collected(KIND_FLOWER)
143
+ lines = [f"鲜花收集进度:{len(collected)} / {len(book.flowers)}", ""]
144
+ for item in book.species:
145
+ names = [flower.name for flower in book.flowers_of(item.name)]
146
+ done = sum(1 for name in names if name in collected)
147
+ lines.append(f"· {item.name} {done}/{len(names)}")
148
+ return "\n".join(lines)
149
+
150
+
151
+ async def recipe_progress_text(env: ReplyEnv) -> str:
152
+ book = await env.client.get_recipes()
153
+ collected = env.collected(KIND_RECIPE)
154
+ lines = [f"菜谱收集进度:{len(collected)} / {len(book.recipes)}", ""]
155
+ by_type: Dict[str, Tuple[int, int]] = {}
156
+ for recipe in book.recipes:
157
+ key = recipe.type or "未分类"
158
+ total, done = by_type.get(key, (0, 0))
159
+ by_type[key] = (total + 1, done + (1 if str(recipe.number) in collected else 0))
160
+ for key, (total, done) in by_type.items():
161
+ lines.append(f"· {key} {done}/{total}")
162
+ return "\n".join(lines)
163
+
164
+
165
+ def _choice_text(candidates: Sequence[Candidate], text: str) -> str:
166
+ kinds = {candidate.kind for candidate in candidates}
167
+ if len(kinds) > 1:
168
+ lines = [f"「{text}」在多个图鉴里都有,按类型再发一次:"]
169
+ for candidate in candidates:
170
+ hint = KIND_HINTS.get(candidate.kind, candidate.kind)
171
+ label = KIND_LABELS.get(candidate.kind, candidate.kind)
172
+ lines.append(f"· 收藏 {hint} {candidate.label}({label} · {candidate.detail})")
173
+ return "\n".join(lines)
174
+
175
+ label = KIND_LABELS.get(candidates[0].kind, candidates[0].kind)
176
+ lines = [f"{label}里匹配到 {len(candidates)} 个条目,写全一点:"]
177
+ for candidate in candidates[:12]:
178
+ lines.append(f"· {candidate.label}({candidate.detail})")
179
+ return "\n".join(lines)
180
+
181
+
182
+ async def toggle_text(env: ReplyEnv, candidates: Sequence[Candidate], text: str) -> Reply:
183
+ if not candidates:
184
+ return f"没找到「{text}」。可以发「收藏 星海」「收藏 鲜花」「收藏 菜谱」先看看图鉴。"
185
+
186
+ if len({candidate.kind for candidate in candidates}) > 1:
187
+ return _choice_text(candidates, text)
188
+
189
+ if len(candidates) > 1:
190
+ exact = [candidate for candidate in candidates if candidate.label == text]
191
+ if len(exact) != 1:
192
+ return _choice_text(candidates, text)
193
+ candidates = exact
194
+
195
+ candidate = candidates[0]
196
+ assert env.store is not None
197
+ new_state = await env.store.toggle(env.user_id, candidate.kind, candidate.key)
198
+ label = KIND_LABELS.get(candidate.kind, candidate.kind)
199
+ mark = "✓ 已标记收集" if new_state else "✗ 已取消收集"
200
+ done = env.collected_totals.get(candidate.kind, 0)
201
+ return (
202
+ f"{mark}:{candidate.label}({label} · {candidate.detail})\n"
203
+ f"{label}进度:{done} / {await _kind_total(env, candidate.kind)}"
204
+ )
205
+
206
+
207
+ async def _kind_total(env: ReplyEnv, kind: str) -> int:
208
+ if kind == KIND_STARSEA:
209
+ return len((await env.client.get_starsea()).species)
210
+ if kind == KIND_FLOWER:
211
+ return len((await env.client.get_flowers()).flowers)
212
+ if kind == KIND_RECIPE:
213
+ return len((await env.client.get_recipes()).recipes)
214
+ return 0
215
+
216
+
217
+ async def reply_collection(arg: str, env: ReplyEnv) -> Reply:
218
+ arg = (arg or "").strip()
219
+ if not arg:
220
+ return await overview_text(env)
221
+
222
+ parts = arg.split(None, 1)
223
+ head = parts[0]
224
+ rest = parts[1].strip() if len(parts) > 1 else ""
225
+
226
+ if not rest:
227
+ if head in {"星海", "物种", "采集", "星海物种"}:
228
+ return await starsea_progress_text(env)
229
+ if head in {"鲜花", "花"}:
230
+ return await flower_progress_text(env)
231
+ if head in {"菜谱", "料理"}:
232
+ return await recipe_progress_text(env)
233
+ if head in {"清空", "重置"}:
234
+ assert env.store is not None
235
+ removed = await env.store.clear(env.user_id)
236
+ return f"已清空你的收藏进度(共 {removed} 项)。"
237
+
238
+ hint = ""
239
+ text = arg
240
+ if head in {"星海", "物种", "采集", "星海物种"} and rest:
241
+ hint, text = "星海", rest
242
+ elif head in {"鲜花", "花"} and rest:
243
+ hint, text = "鲜花", rest
244
+ elif head in {"菜谱", "料理"} and rest:
245
+ hint, text = "菜谱", rest
246
+
247
+ return await toggle_text(env, await _candidates(env, text, hint), text)