nonebot-plugin-dancefengbot 2026.12.3__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 (59) hide show
  1. nonebot_plugin_dancefengbot/__init__.py +225 -0
  2. nonebot_plugin_dancefengbot/api/__init__.py +19 -0
  3. nonebot_plugin_dancefengbot/api/ladder.py +60 -0
  4. nonebot_plugin_dancefengbot/api/lv_ratio_history.py +61 -0
  5. nonebot_plugin_dancefengbot/api/machine.py +102 -0
  6. nonebot_plugin_dancefengbot/api/maker.py +200 -0
  7. nonebot_plugin_dancefengbot/api/phone_login.py +89 -0
  8. nonebot_plugin_dancefengbot/api/player_music.py +25 -0
  9. nonebot_plugin_dancefengbot/assets.py +201 -0
  10. nonebot_plugin_dancefengbot/command_list.py +82 -0
  11. nonebot_plugin_dancefengbot/commands/__init__.py +5 -0
  12. nonebot_plugin_dancefengbot/commands/creator.py +332 -0
  13. nonebot_plugin_dancefengbot/commands/info_ratio.py +272 -0
  14. nonebot_plugin_dancefengbot/commands/login.py +223 -0
  15. nonebot_plugin_dancefengbot/commands/misc.py +295 -0
  16. nonebot_plugin_dancefengbot/commands/server_status.py +30 -0
  17. nonebot_plugin_dancefengbot/config.py +228 -0
  18. nonebot_plugin_dancefengbot/curfew.py +344 -0
  19. nonebot_plugin_dancefengbot/deps.py +155 -0
  20. nonebot_plugin_dancefengbot/image/__init__.py +21 -0
  21. nonebot_plugin_dancefengbot/image/common.py +210 -0
  22. nonebot_plugin_dancefengbot/image/drawer.py +150 -0
  23. nonebot_plugin_dancefengbot/image/effect.py +41 -0
  24. nonebot_plugin_dancefengbot/image/level_scores.py +58 -0
  25. nonebot_plugin_dancefengbot/image/user_info.py +111 -0
  26. nonebot_plugin_dancefengbot/image/user_ratio.py +61 -0
  27. nonebot_plugin_dancefengbot/image/user_ratio_ap30.py +44 -0
  28. nonebot_plugin_dancefengbot/image/user_ratio_b30.py +44 -0
  29. nonebot_plugin_dancefengbot/info/__init__.py +17 -0
  30. nonebot_plugin_dancefengbot/info/account.py +39 -0
  31. nonebot_plugin_dancefengbot/info/reply_item.py +69 -0
  32. nonebot_plugin_dancefengbot/info/server_status.py +362 -0
  33. nonebot_plugin_dancefengbot/info/song_score.py +66 -0
  34. nonebot_plugin_dancefengbot/info/status.py +11 -0
  35. nonebot_plugin_dancefengbot/info/user.py +154 -0
  36. nonebot_plugin_dancefengbot/music/__init__.py +41 -0
  37. nonebot_plugin_dancefengbot/music/cover.py +242 -0
  38. nonebot_plugin_dancefengbot/music/cover_update.py +226 -0
  39. nonebot_plugin_dancefengbot/music/model.py +10 -0
  40. nonebot_plugin_dancefengbot/music/util.py +92 -0
  41. nonebot_plugin_dancefengbot/ratio/__init__.py +35 -0
  42. nonebot_plugin_dancefengbot/ratio/acc_grade.py +23 -0
  43. nonebot_plugin_dancefengbot/ratio/calculator.py +178 -0
  44. nonebot_plugin_dancefengbot/ratio/rank_music.py +32 -0
  45. nonebot_plugin_dancefengbot/ratio/recent_music.py +57 -0
  46. nonebot_plugin_dancefengbot/ratio/recorded.py +47 -0
  47. nonebot_plugin_dancefengbot/store.py +41 -0
  48. nonebot_plugin_dancefengbot/token/__init__.py +6 -0
  49. nonebot_plugin_dancefengbot/token/builder.py +140 -0
  50. nonebot_plugin_dancefengbot/token/token.py +120 -0
  51. nonebot_plugin_dancefengbot/utils/__init__.py +1 -0
  52. nonebot_plugin_dancefengbot/utils/crypto.py +55 -0
  53. nonebot_plugin_dancefengbot/utils/fonts.py +61 -0
  54. nonebot_plugin_dancefengbot/utils/http.py +286 -0
  55. nonebot_plugin_dancefengbot/utils/logger.py +557 -0
  56. nonebot_plugin_dancefengbot/utils/tencent.py +109 -0
  57. nonebot_plugin_dancefengbot-2026.12.3.dist-info/METADATA +120 -0
  58. nonebot_plugin_dancefengbot-2026.12.3.dist-info/RECORD +59 -0
  59. nonebot_plugin_dancefengbot-2026.12.3.dist-info/WHEEL +4 -0
@@ -0,0 +1,89 @@
1
+ """手机号登录,对应 Java 端 ``com.DanceCube.api.PhoneLoginBuilder``。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ import base64
7
+
8
+ from ..token import Token
9
+ from ..utils import logger
10
+ from ..utils.http import http_get, http_post
11
+
12
+ _BASE = "https://dancedemo.shenghuayule.com/Dance"
13
+
14
+
15
+ class PhoneLoginBuilder:
16
+ def __init__(self, phone_number: str) -> None:
17
+ self.phone_number = phone_number
18
+
19
+ def get_graph_code(self) -> bytes | None:
20
+ """获取图形验证码图片,返回 PNG 字节。"""
21
+ logger.debug(f"[手机号登录] 获取图形验证码:phone={self.phone_number}")
22
+ resp = http_get(
23
+ f"{_BASE}/api/Common/GetGraphCode?phone={self.phone_number}",
24
+ context="手机号登录-图形验证码",
25
+ )
26
+ if resp is None:
27
+ logger.error(f"[手机号登录] 图形验证码请求失败:phone={self.phone_number}")
28
+ return None
29
+ if resp.status_code != 200:
30
+ logger.error(f"[手机号登录] 图形验证码状态码 {resp.status_code}:{resp.text[:200]}")
31
+ return None
32
+ try:
33
+ raw = resp.text.strip().strip('"')
34
+ data = base64.b64decode(raw)
35
+ logger.debug(f"[手机号登录] 图形验证码获取成功,{len(data)} 字节")
36
+ return data
37
+ except Exception as exc:
38
+ logger.error(f"[手机号登录] 图形验证码解码失败:{exc};内容(前 200 字符):{resp.text[:200]}")
39
+ return None
40
+
41
+ def get_sms_code(self, graph_code: str) -> bool:
42
+ """通过图形验证码发送短信验证码。"""
43
+ logger.debug(f"[手机号登录] 请求短信验证码:phone={self.phone_number}")
44
+ resp = http_get(
45
+ f"{_BASE}/api/Common/GetSMSCode?phone={self.phone_number}&graphCode={graph_code}",
46
+ context="手机号登录-短信验证码",
47
+ )
48
+ if resp is None:
49
+ logger.error(f"[手机号登录] 短信验证码请求失败:phone={self.phone_number}")
50
+ return False
51
+ if resp.status_code != 200:
52
+ logger.error(f"[手机号登录] 短信验证码失败,状态码 {resp.status_code}:{resp.text[:200]}")
53
+ return False
54
+ logger.info(f"[手机号登录] 短信验证码已发送:phone={self.phone_number}")
55
+ return True
56
+
57
+ def login(self, sms_code: str) -> Token | None:
58
+ """手机号登录,返回 Token。"""
59
+ logger.debug(f"[手机号登录] 使用短信验证码登录:phone={self.phone_number}")
60
+ resp = http_post(
61
+ f"{_BASE}/token",
62
+ headers={"content-type": "application/x-www-form-urlencoded"},
63
+ data={
64
+ "client_type": "phone",
65
+ "grant_type": "client_credentials",
66
+ "client_id": self.phone_number,
67
+ "client_secret": sms_code,
68
+ },
69
+ context="手机号登录-换取Token",
70
+ )
71
+ if resp is None:
72
+ logger.error(f"[手机号登录] 登录请求失败:phone={self.phone_number}")
73
+ return None
74
+ if resp.status_code != 200:
75
+ logger.error(f"[手机号登录] 登录失败,状态码 {resp.status_code}:{resp.text[:200]}")
76
+ return None
77
+ try:
78
+ data = resp.json()
79
+ token = Token(
80
+ user_id=data.get("userId", 0),
81
+ access_token=data.get("access_token"),
82
+ refresh_token=data.get("refresh_token"),
83
+ rec_time=int(time.time() * 1000),
84
+ )
85
+ except Exception as exc:
86
+ logger.error(f"[手机号登录] Token 响应解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
87
+ return None
88
+ logger.info(f"[手机号登录] 登录成功,userId={token.user_id}")
89
+ return token
@@ -0,0 +1,25 @@
1
+ """玩家音乐相关接口,对应 Java 端 ``com.DanceCube.api.PlayerMusic``。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..token import Token
6
+ from ..utils import logger
7
+ from ..utils.http import http_post
8
+
9
+
10
+ def gain_music_by_code(token: Token, code: str):
11
+ """兑换自制谱兑换码。"""
12
+ logger.debug(f"[兑换码] 尝试兑换:code={code},userId={token.user_id}")
13
+ resp = http_post(
14
+ f"https://dancedemo.shenghuayule.com/Dance/api/MusicData/GainMusicByCode?code={code}",
15
+ headers={"Authorization": token.bearer_token},
16
+ data="",
17
+ context="兑换码",
18
+ )
19
+ if resp is None:
20
+ logger.error(f"[兑换码] 请求失败:code={code}")
21
+ elif resp.status_code != 200:
22
+ logger.error(f"[兑换码] 兑换失败,状态码 {resp.status_code}:{resp.text[:200]}")
23
+ else:
24
+ logger.info(f"[兑换码] 兑换成功:code={code}")
25
+ return resp
@@ -0,0 +1,201 @@
1
+ """DcConfig 图片/字体素材自动下载。
2
+
3
+ 素材仓库:https://github.com/DanceFengBot/dfb-miscellaneous
4
+
5
+ 首次运行且本地缺少关键素材时,会依次尝试 GitHub 直连和镜像源下载仓库
6
+ ZIP,只解压其中的 ``Fonts/`` 与 ``Images/``,并且不会覆盖本地已有文件。
7
+ 全部源失败时写入 ``DcConfig/ASSETS_DOWNLOAD_FAILED.txt``,提示手动下载。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import shutil
14
+ import zipfile
15
+ import urllib.error
16
+ import urllib.request
17
+ from pathlib import Path, PurePosixPath
18
+ from datetime import datetime
19
+
20
+ from .utils import logger
21
+
22
+ REPO_URL = "https://github.com/DanceFengBot/dfb-miscellaneous"
23
+ ARCHIVE_PATH = "archive/refs/heads/main.zip"
24
+ REPO_ZIP_URL = f"{REPO_URL}/{ARCHIVE_PATH}"
25
+
26
+ # 依次尝试:GitHub 直连 -> 镜像(镜像前缀 + 原始地址)
27
+ ASSET_SOURCES: tuple[tuple[str, str], ...] = (
28
+ ("GitHub", REPO_ZIP_URL),
29
+ ("ghfast.top", f"https://ghfast.top/{REPO_ZIP_URL}"),
30
+ ("gh-proxy.com", f"https://gh-proxy.com/{REPO_ZIP_URL}"),
31
+ ("ghproxy.net", f"https://ghproxy.net/{REPO_ZIP_URL}"),
32
+ )
33
+
34
+ # 只检查这些关键素材;缺任意一个就触发下载(不覆盖已有文件)
35
+ KEY_ASSETS: tuple[str, ...] = (
36
+ "Fonts/SmileySans-Oblique.ttf",
37
+ "Fonts/PANGMENZHENGDAOBIAOTITI-1.TTF",
38
+ "Fonts/SourceHanSans-Bold.otf",
39
+ "Fonts/MSYHBD.TTC",
40
+ "Images/UserInfoImage/Background2.png",
41
+ "Images/UserRatioImage/Background1.png",
42
+ "Images/Material/Background1.png",
43
+ "Images/LastPlayImage/background.png",
44
+ )
45
+
46
+ _MAX_DOWNLOAD_BYTES = 300 * 1024 * 1024
47
+ _SKIP_ENV = "DCF_SKIP_ASSETS_DOWNLOAD"
48
+ _TRUTHY = {"1", "true", "yes", "on"}
49
+
50
+
51
+ def _missing_assets(config_path: Path) -> list[str]:
52
+ return [rel for rel in KEY_ASSETS if not (config_path / rel).is_file()]
53
+
54
+
55
+ def _download(url: str, target: Path) -> None:
56
+ """下载 URL 到 target,带简单的进度日志。"""
57
+ logger.info(f"[素材] 开始下载:{url}")
58
+ request = urllib.request.Request(
59
+ url,
60
+ headers={"User-Agent": "DanceFengBot/1.0 (+https://github.com/DanceFengBot)"},
61
+ )
62
+ with urllib.request.urlopen(request, timeout=30) as response:
63
+ status = getattr(response, "status", 200)
64
+ if status != 200:
65
+ raise RuntimeError(f"HTTP {status}")
66
+ total = 0
67
+ raw_length = response.headers.get("Content-Length")
68
+ if raw_length and raw_length.isdigit():
69
+ total = int(raw_length)
70
+ downloaded = 0
71
+ last_log = 0
72
+ with target.open("wb") as handle:
73
+ while True:
74
+ chunk = response.read(1024 * 1024)
75
+ if not chunk:
76
+ break
77
+ handle.write(chunk)
78
+ downloaded += len(chunk)
79
+ if downloaded > _MAX_DOWNLOAD_BYTES:
80
+ raise RuntimeError("压缩包超过大小上限,已中止下载")
81
+ if downloaded - last_log >= 10 * 1024 * 1024:
82
+ last_log = downloaded
83
+ suffix = f"/{total / 1024 / 1024:.1f} MB" if total else ""
84
+ logger.info(f"[素材] 已下载 {downloaded / 1024 / 1024:.1f} MB{suffix}")
85
+ if downloaded == 0:
86
+ raise RuntimeError("下载内容为空")
87
+
88
+
89
+ def _extract(zip_path: Path, config_path: Path) -> int:
90
+ """只解压 Fonts/ 与 Images/,返回新增文件数量。"""
91
+ extracted = 0
92
+ with zipfile.ZipFile(zip_path) as archive:
93
+ for info in archive.infolist():
94
+ if info.is_dir():
95
+ continue
96
+ name = info.filename.replace("\\", "/")
97
+ parts = PurePosixPath(name).parts
98
+ try:
99
+ index = next(i for i, part in enumerate(parts) if part in ("Fonts", "Images"))
100
+ except StopIteration:
101
+ continue
102
+ rel = Path(*parts[index:])
103
+ if ".." in rel.parts:
104
+ continue
105
+ target = config_path / rel
106
+ if target.exists():
107
+ continue
108
+ try:
109
+ target.parent.mkdir(parents=True, exist_ok=True)
110
+ with archive.open(info) as src, target.open("wb") as dst:
111
+ shutil.copyfileobj(src, dst)
112
+ extracted += 1
113
+ except OSError as exc:
114
+ logger.warning(f"[素材] 解压文件失败,已跳过:{rel} | {exc}")
115
+ return extracted
116
+
117
+
118
+ def _write_failure_help(config_path: Path, missing: list[str], errors: list[str]) -> Path:
119
+ help_path = config_path / "ASSETS_DOWNLOAD_FAILED.txt"
120
+ lines = [
121
+ "DanceFengBot 图片/字体素材自动下载失败",
122
+ f"时间:{datetime.now():%Y-%m-%d %H:%M:%S}",
123
+ f"配置目录:{config_path}",
124
+ "",
125
+ "缺失的关键素材:",
126
+ *[f" - {item}" for item in missing],
127
+ "",
128
+ "已尝试的下载源及错误:",
129
+ *[f" - {item}" for item in errors],
130
+ "",
131
+ "请手动下载并安装素材:",
132
+ f" 1. 打开 {REPO_URL}",
133
+ " 2. 点击 Code -> Download ZIP(或在镜像站下载同一仓库的 ZIP)",
134
+ f" 镜像示例:https://ghfast.top/{REPO_ZIP_URL}",
135
+ " 3. 解压 ZIP,把其中的 Fonts/ 和 Images/ 两个目录合并到:",
136
+ f" {config_path}",
137
+ " 4. 确认以下文件存在(不区分大小写请按实际文件名):",
138
+ *[f" {item}" for item in missing],
139
+ " 5. 重新启动机器人;已有文件不会被覆盖。",
140
+ "",
141
+ "如果只是暂时无法访问 GitHub,也可以稍后重启机器人重试。",
142
+ ]
143
+ try:
144
+ help_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
145
+ except OSError as exc:
146
+ logger.warning(f"[素材] 无法写入手动下载说明:{help_path} | {exc}")
147
+ return help_path
148
+
149
+
150
+ def ensure_assets(config_path: Path) -> bool:
151
+ """确保关键图片/字体素材存在;返回是否已满足要求。
152
+
153
+ 失败不会抛出异常,也不会阻止机器人启动(文字功能仍可用)。
154
+ """
155
+ if os.environ.get(_SKIP_ENV, "").strip().lower() in _TRUTHY:
156
+ logger.info(f"[素材] 已设置 {_SKIP_ENV},跳过自动下载")
157
+ return False
158
+
159
+ missing = _missing_assets(config_path)
160
+ if not missing:
161
+ return True
162
+
163
+ logger.info(
164
+ f"[素材] 缺少 {len(missing)} 个关键素材,开始自动下载:"
165
+ f"{', '.join(missing[:3])}{' ...' if len(missing) > 3 else ''}"
166
+ )
167
+ errors: list[str] = []
168
+ for name, url in ASSET_SOURCES:
169
+ temp_zip = config_path / f".assets-download-{os.getpid()}.zip"
170
+ try:
171
+ _download(url, temp_zip)
172
+ added = _extract(temp_zip, config_path)
173
+ still_missing = _missing_assets(config_path)
174
+ if not still_missing:
175
+ logger.info(f"[素材] 下载完成(来源:{name}),新增 {added} 个文件:{config_path}")
176
+ return True
177
+ errors.append(f"{name}: 压缩包不完整,仍缺少 {', '.join(still_missing[:5])}")
178
+ logger.warning(f"[素材] {name} 下载完成但素材仍不完整:{', '.join(still_missing[:5])}")
179
+ except (
180
+ urllib.error.URLError,
181
+ TimeoutError,
182
+ OSError,
183
+ RuntimeError,
184
+ zipfile.BadZipFile,
185
+ ) as exc:
186
+ reason = f"{type(exc).__name__}: {exc}"
187
+ errors.append(f"{name}: {reason}")
188
+ logger.warning(f"[素材] 下载源 {name} 失败:{reason}")
189
+ finally:
190
+ try:
191
+ temp_zip.unlink(missing_ok=True)
192
+ except OSError:
193
+ pass
194
+
195
+ help_path = _write_failure_help(config_path, missing, errors)
196
+ logger.error(
197
+ "[素材] 所有下载源均失败,图片/字体功能暂不可用。\n"
198
+ f"请手动下载 {REPO_URL} 并将 Fonts/、Images/ 合并到 {config_path}\n"
199
+ f"详细说明已写入:{help_path}"
200
+ )
201
+ return False
@@ -0,0 +1,82 @@
1
+ """控制台可用指令列表打印。
2
+
3
+ NoneBot 启动完成后,枚举本插件注册的所有事件响应器(Matcher),
4
+ 将其触发词整理为可读的指令清单打印到控制台,方便运维确认指令是否正常加载。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from nonebot import get_plugin_by_module_name
10
+ from nonebot.rule import (
11
+ RegexRule,
12
+ CommandRule,
13
+ EndswithRule,
14
+ KeywordsRule,
15
+ FullmatchRule,
16
+ StartswithRule,
17
+ ShellCommandRule,
18
+ )
19
+ from nonebot.matcher import Matcher
20
+
21
+ from .utils import logger
22
+
23
+
24
+ def _call_of(checker) -> object | None:
25
+ """取出 RuleChecker 依赖背后的真实可调用对象。"""
26
+ return getattr(checker, "call", None)
27
+
28
+
29
+ def _extract_triggers(matcher: type[Matcher]) -> list[str]:
30
+ """从事件响应器规则中提取用户可输入的触发词。"""
31
+ triggers: list[str] = []
32
+ for checker in matcher.rule.checkers:
33
+ call = _call_of(checker)
34
+ if isinstance(call, (CommandRule, ShellCommandRule)):
35
+ # cmds 形如 (("手机号登录",), ("验证码登录",))
36
+ for cmd in call.cmds:
37
+ triggers.append(".".join(cmd))
38
+ elif isinstance(call, FullmatchRule):
39
+ triggers.extend(call.msg)
40
+ elif isinstance(call, StartswithRule):
41
+ triggers.extend(f"{prefix}…" for prefix in call.msg)
42
+ elif isinstance(call, EndswithRule):
43
+ triggers.extend(f"…{suffix}" for suffix in call.msg)
44
+ elif isinstance(call, KeywordsRule):
45
+ triggers.extend(call.keywords)
46
+ elif isinstance(call, RegexRule):
47
+ triggers.append(f"正则:{call.regex}")
48
+ return triggers
49
+
50
+
51
+ def collect_commands() -> dict[str, list[str]]:
52
+ """按模块名归类本插件的所有触发词(去重并排序)。"""
53
+ plugin = get_plugin_by_module_name(__name__)
54
+ if plugin is None:
55
+ return {}
56
+
57
+ grouped: dict[str, set[str]] = {}
58
+ for matcher in plugin.matcher:
59
+ module = (matcher.module_name or "").rsplit(".", 1)[-1]
60
+ for trigger in _extract_triggers(matcher):
61
+ grouped.setdefault(module, set()).add(trigger)
62
+
63
+ return {name: sorted(triggers) for name, triggers in sorted(grouped.items())}
64
+
65
+
66
+ def print_command_list() -> None:
67
+ """把可用指令列表打印到控制台。"""
68
+ grouped = collect_commands()
69
+ if not grouped:
70
+ logger.info("[DanceFengBot] 未收集到任何可用指令")
71
+ return
72
+
73
+ width = 50
74
+ lines = ["=" * width, " DanceFengBot 可用指令列表", "=" * width]
75
+ for module, triggers in grouped.items():
76
+ lines.append("")
77
+ lines.append(f"【{module}】")
78
+ lines.extend(f" · {trigger}" for trigger in triggers)
79
+ lines.append("=" * width)
80
+
81
+ for line in lines:
82
+ logger.info(line)
@@ -0,0 +1,5 @@
1
+ """命令处理器(NoneBot 事件响应器)。"""
2
+
3
+ from . import misc, login, creator, info_ratio, server_status
4
+
5
+ __all__ = ["creator", "info_ratio", "login", "misc", "server_status"]