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,234 @@
1
+ """命令注册与分发。
2
+
3
+ 四个模块各自把业务写在 ``features/<模块>/reply.py`` 里,
4
+ 这里只负责:取参、跑环境、冷却、异常兜底、把 ``str`` / ``bytes`` 发出去。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from typing import Callable, Dict, Optional
11
+
12
+ from nonebot import on_command
13
+ from nonebot.adapters.onebot.v11 import Message, MessageEvent, MessageSegment
14
+ from nonebot.log import logger
15
+ from nonebot.params import CommandArg
16
+ from nonebot.permission import SUPERUSER
17
+
18
+ from .api import BuguError
19
+ from .features import collection as collection_feature
20
+ from .features.common import Reply, ReplyEnv, command_start
21
+ from .features.flowers import reply as flower_feature
22
+ from .features.neighbors import reply as neighbor_feature
23
+ from .features.recipes import reply as recipe_feature
24
+ from .features.starsea import reply as starsea_feature
25
+ from .fonts import FontError, FontSet
26
+ from .runtime import get_client, get_config, get_fonts, get_store
27
+
28
+ PRIORITY = 12
29
+
30
+ HELP_WORDS = {"帮助", "help", "?", "?", "菜单"}
31
+
32
+ bugu = on_command("布谷", priority=PRIORITY, block=True)
33
+ starsea = on_command("星海", priority=PRIORITY, block=True)
34
+ starsea_map = on_command("星海地图", aliases={"星图"}, priority=PRIORITY, block=True)
35
+ starsea_point = on_command("星海点位", aliases={"星点"}, priority=PRIORITY, block=True)
36
+ starsea_search = on_command("星海查", aliases={"星海搜索"}, priority=PRIORITY, block=True)
37
+ recipe = on_command("菜谱", priority=PRIORITY, block=True)
38
+ recipe_search = on_command("菜谱查", aliases={"菜谱搜索"}, priority=PRIORITY, block=True)
39
+ neighbor = on_command("友邻", aliases={"友邻备忘"}, priority=PRIORITY, block=True)
40
+ flower = on_command("鲜花", aliases={"花谱", "鲜花培育"}, priority=PRIORITY, block=True)
41
+ collection = on_command("收藏", aliases={"布谷收藏"}, priority=PRIORITY, block=True)
42
+ refresh = on_command("布谷刷新", priority=PRIORITY, block=True, permission=SUPERUSER)
43
+
44
+
45
+ # ------------------------------------------------------------------ 环境
46
+
47
+
48
+ class Cooldown:
49
+ """按用户 + 命令的简单冷却,防止连点把图渲爆。"""
50
+
51
+ def __init__(self) -> None:
52
+ self._last: Dict[str, float] = {}
53
+
54
+ def remaining(self, key: str, seconds: int) -> float:
55
+ now = time.monotonic()
56
+ last = self._last.get(key)
57
+ if seconds and last is not None and now - last < seconds:
58
+ return seconds - (now - last)
59
+ self._last[key] = now
60
+ if len(self._last) > 4096:
61
+ threshold = now - max(60, seconds * 4)
62
+ self._last = {k: v for k, v in self._last.items() if v >= threshold}
63
+ return 0.0
64
+
65
+
66
+ _cooldown = Cooldown()
67
+
68
+
69
+ def _env(event: Optional[MessageEvent]) -> ReplyEnv:
70
+ config = get_config()
71
+ client = get_client(config)
72
+ store = get_store(config)
73
+ fonts: Optional[FontSet] = None
74
+ if config.bugu_image_enabled:
75
+ try:
76
+ fonts = get_fonts(config)
77
+ except FontError as exc:
78
+ logger.warning(f"布谷工具箱没有可用字体,改为纯文字:{exc}")
79
+ user_id = event.get_user_id() if event is not None else ""
80
+ return ReplyEnv(client=client, config=config, fonts=fonts, user_id=user_id, store=store)
81
+
82
+
83
+ def _as_segment(reply: Reply):
84
+ return MessageSegment.image(reply) if isinstance(reply, bytes) else reply
85
+
86
+
87
+ # ------------------------------------------------------------------ 帮助
88
+
89
+
90
+ def help_text() -> str:
91
+ start = command_start()
92
+ return "\n".join(
93
+ [
94
+ "布谷工具箱 · 星布谷地小助手",
95
+ "",
96
+ "【星海地图】",
97
+ f" {start}星海 <词> 智能识别区域 / 点位 / 物种",
98
+ f" {start}星海地图 [区域] 区域地图卡片",
99
+ f" {start}星海点位 <点位名> 点位详情",
100
+ f" {start}星海查 <物种 / 大类> 跨区域搜索",
101
+ "",
102
+ "【菜谱】",
103
+ f" {start}菜谱 <菜名 / 编号> 菜谱卡片",
104
+ f" {start}菜谱查 <食材 / 类型 / 厨具> 搜索筛选",
105
+ f" {start}菜谱 随机 随手看一道",
106
+ "",
107
+ "【友邻备忘】",
108
+ f" {start}友邻 友邻名单",
109
+ f" {start}友邻 <名字> [喜爱/好感/反感/关于] 档案卡与词条",
110
+ "",
111
+ "【鲜花培育】",
112
+ f" {start}鲜花 品种列表",
113
+ f" {start}鲜花 <品种 / 花名> 杂交配方与花色",
114
+ "",
115
+ "【收集进度】",
116
+ f" {start}收藏 总览",
117
+ f" {start}收藏 <名字> 标记 / 取消",
118
+ f" {start}收藏 星海 / 鲜花 / 菜谱 分类进度",
119
+ "",
120
+ "数据来源:布谷工具箱 bugu.nsun200512.cc",
121
+ ]
122
+ )
123
+
124
+
125
+ # ------------------------------------------------------------------ 分发
126
+
127
+
128
+ async def _run(
129
+ matcher,
130
+ event: MessageEvent,
131
+ arg: Message,
132
+ handler: Callable[[str, ReplyEnv], object],
133
+ *,
134
+ matcher_name: str,
135
+ cooldown: bool = True,
136
+ ) -> None:
137
+ env = _env(event)
138
+ if env.store is not None:
139
+ await env.store.ensure_loaded()
140
+
141
+ if cooldown and env.config.bugu_cooldown_seconds:
142
+ left = _cooldown.remaining(f"{env.user_id}:{matcher_name}", env.config.bugu_cooldown_seconds)
143
+ if left > 0:
144
+ await matcher.finish(f"慢一点,{left:.0f} 秒后再试")
145
+
146
+ text = arg.extract_plain_text().strip()
147
+ try:
148
+ reply = await handler(text, env)
149
+ except BuguError as exc:
150
+ logger.warning(f"布谷数据获取失败:{exc.message} {exc.detail}")
151
+ await matcher.finish(f"获取数据失败:{exc.message}")
152
+ except Exception:
153
+ logger.opt(exception=True).error("布谷工具箱处理异常")
154
+ await matcher.finish("出错了,稍后再试一下")
155
+
156
+ await matcher.finish(_as_segment(reply))
157
+
158
+
159
+ async def _help_reply(text: str, env: ReplyEnv) -> Reply:
160
+ return help_text()
161
+
162
+
163
+ @bugu.handle()
164
+ async def _handle_bugu(event: MessageEvent, arg: Message = CommandArg()) -> None:
165
+ await _run(bugu, event, arg, _help_reply, matcher_name="help", cooldown=False)
166
+
167
+
168
+ @starsea.handle()
169
+ async def _handle_starsea(event: MessageEvent, arg: Message = CommandArg()) -> None:
170
+ await _run(starsea, event, arg, starsea_feature.reply_smart, matcher_name="starsea")
171
+
172
+
173
+ @starsea_map.handle()
174
+ async def _handle_starsea_map(event: MessageEvent, arg: Message = CommandArg()) -> None:
175
+ await _run(starsea_map, event, arg, starsea_feature.reply_map, matcher_name="starsea_map")
176
+
177
+
178
+ @starsea_point.handle()
179
+ async def _handle_starsea_point(event: MessageEvent, arg: Message = CommandArg()) -> None:
180
+ await _run(starsea_point, event, arg, starsea_feature.reply_point, matcher_name="starsea_point")
181
+
182
+
183
+ @starsea_search.handle()
184
+ async def _handle_starsea_search(event: MessageEvent, arg: Message = CommandArg()) -> None:
185
+ await _run(starsea_search, event, arg, starsea_feature.reply_search, matcher_name="starsea_search")
186
+
187
+
188
+ @recipe.handle()
189
+ async def _handle_recipe(event: MessageEvent, arg: Message = CommandArg()) -> None:
190
+ await _run(recipe, event, arg, recipe_feature.reply_recipes, matcher_name="recipe")
191
+
192
+
193
+ @recipe_search.handle()
194
+ async def _handle_recipe_search(event: MessageEvent, arg: Message = CommandArg()) -> None:
195
+ await _run(recipe_search, event, arg, recipe_feature.reply_search, matcher_name="recipe_search", cooldown=False)
196
+
197
+
198
+ @neighbor.handle()
199
+ async def _handle_neighbor(event: MessageEvent, arg: Message = CommandArg()) -> None:
200
+ await _run(neighbor, event, arg, neighbor_feature.reply_neighbors, matcher_name="neighbor")
201
+
202
+
203
+ @flower.handle()
204
+ async def _handle_flower(event: MessageEvent, arg: Message = CommandArg()) -> None:
205
+ await _run(flower, event, arg, flower_feature.reply_flowers, matcher_name="flower")
206
+
207
+
208
+ @collection.handle()
209
+ async def _handle_collection(event: MessageEvent, arg: Message = CommandArg()) -> None:
210
+ await _run(collection, event, arg, collection_feature.reply_collection, matcher_name="collection", cooldown=False)
211
+
212
+
213
+ @refresh.handle()
214
+ async def _handle_refresh() -> None:
215
+ config = get_config()
216
+ client = get_client(config)
217
+ try:
218
+ data = await client.preload_all(force=True)
219
+ except BuguError as exc:
220
+ await refresh.finish(f"刷新失败:{exc.message}")
221
+
222
+ removed = client.clear_image_cache()
223
+ stars = data["starsea"]
224
+ recipes = data["recipes"]
225
+ flowers = data["flowers"]
226
+ neighbors = data["neighbors"]
227
+ await refresh.finish(
228
+ "已刷新:"
229
+ f"菜谱 {recipes.count} 道 · "
230
+ f"星海 {len(stars.maps)} 图 {stars.point_count} 点位 {stars.species_count} 物种 · "
231
+ f"友邻 {len(neighbors.neighbors)} 位 · "
232
+ f"鲜花 {len(flowers.species)} 品种 {len(flowers.flowers)} 朵,"
233
+ f"清掉 {removed} 张缓存图片"
234
+ )
@@ -0,0 +1,91 @@
1
+ """插件配置项。
2
+
3
+ 所有字段都可以在 NoneBot 项目的 ``.env`` 里用大写字段名覆盖,例如::
4
+
5
+ BUGU_API_BASE=https://bugu.nsun200512.cc
6
+ BUGU_IMAGE_ENABLED=true
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pydantic import BaseModel, Field, field_validator
12
+
13
+
14
+ class Config(BaseModel):
15
+ """星海地图插件配置。"""
16
+
17
+ bugu_api_base: str = Field(
18
+ default="https://bugu.nsun200512.cc",
19
+ description="布谷工具箱站点地址(数据接口 + 图片都从这里取)",
20
+ )
21
+ bugu_request_timeout: float = Field(
22
+ default=15.0,
23
+ description="单次 HTTP 请求超时时间(秒)",
24
+ )
25
+ bugu_data_cache_ttl: int = Field(
26
+ default=6 * 60 * 60,
27
+ description="星海数据的内存缓存时长(秒),过短会拖慢响应",
28
+ )
29
+ bugu_image_cache_ttl: int = Field(
30
+ default=30 * 24 * 60 * 60,
31
+ description="底图 / 图标 / 头图的磁盘缓存时长(秒)",
32
+ )
33
+ bugu_image_enabled: bool = Field(
34
+ default=True,
35
+ description="是否渲染图片卡片;关闭后只回复文字",
36
+ )
37
+ bugu_cooldown_seconds: int = Field(
38
+ default=3,
39
+ description="同一用户两次出图的最小间隔(秒),0 表示不限制",
40
+ )
41
+ bugu_search_limit: int = Field(
42
+ default=12,
43
+ description="一次搜索最多展示多少个点位",
44
+ )
45
+ bugu_font_path: str = Field(
46
+ default="",
47
+ description="中文字体路径,留空则自动查找系统字体",
48
+ )
49
+ bugu_font_index: int = Field(
50
+ default=0,
51
+ description="字体文件内的索引(.ttc 集合文件用)",
52
+ )
53
+ bugu_bold_font_path: str = Field(
54
+ default="",
55
+ description="粗体中文字体路径,留空则用常规体加描边模拟",
56
+ )
57
+ bugu_bold_font_index: int = Field(
58
+ default=0,
59
+ description="粗体字体文件内的索引(.ttc 集合文件用)",
60
+ )
61
+ bugu_collection_path: str = Field(
62
+ default="",
63
+ description="收集进度文件路径,留空用 nonebot-plugin-localstore 的 data 目录",
64
+ )
65
+
66
+ @field_validator("bugu_api_base")
67
+ @classmethod
68
+ def _normalize_base(cls, value: str) -> str:
69
+ value = (value or "").strip().rstrip("/")
70
+ return value or "https://bugu.nsun200512.cc"
71
+
72
+ @field_validator("bugu_request_timeout")
73
+ @classmethod
74
+ def _check_timeout(cls, value: float) -> float:
75
+ if value <= 0:
76
+ raise ValueError("bugu_request_timeout 必须大于 0")
77
+ return value
78
+
79
+ @field_validator("bugu_data_cache_ttl", "bugu_image_cache_ttl", "bugu_cooldown_seconds")
80
+ @classmethod
81
+ def _check_non_negative(cls, value: int) -> int:
82
+ if value < 0:
83
+ raise ValueError("缓存时长 / 冷却时间不能是负数")
84
+ return value
85
+
86
+ @field_validator("bugu_search_limit")
87
+ @classmethod
88
+ def _check_limit(cls, value: int) -> int:
89
+ if value <= 0:
90
+ raise ValueError("bugu_search_limit 必须大于 0")
91
+ return min(value, 50)