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,225 @@
1
+ """DanceFengBot — 舞立方 QQ 机器人(NoneBot2 + OneBot V11)。
2
+
3
+ 对应 Java 版 DanceFengBot 的入口:负责加载 Token、定时刷新 Token,
4
+ 并注册所有命令事件响应器。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ import asyncio
11
+
12
+ from nonebot import get_driver, on_request
13
+ from nonebot.plugin import PluginMetadata
14
+ from nonebot.adapters.onebot.v11 import Bot, FriendRequestEvent
15
+
16
+ __version__ = "2026.12.1"
17
+
18
+ __plugin_meta__ = PluginMetadata(
19
+ name="舞小枫",
20
+ description="舞立方查询、战力分析、创作者工具与扫码登录的 NoneBot2 插件",
21
+ usage="私聊发送「登录」扫码绑定账号;发送「菜单」查看全部指令。",
22
+ type="application",
23
+ homepage="https://github.com/DanceFengBot/DanceFengBot-Python",
24
+ supported_adapters={"~onebot.v11"},
25
+ )
26
+
27
+ # 导入 curfew 即注册全局的宵禁拦截与回复延迟(对所有功能生效)
28
+ from . import store, curfew
29
+ from .deps import clear_cache
30
+ from .utils import logger
31
+ from .commands import misc, login, info_ratio # noqa: F401 # 注册命令
32
+
33
+ # 黑名单 / 白名单:导入即加载配置文件并注册全局拦截器
34
+ # from . import access_list as _access_list # 需在日志初始化之后导入
35
+
36
+ driver = get_driver()
37
+
38
+ # 记录插件加载起点,用于在启动完成时报告启动耗时
39
+ _PLUGIN_LOAD_START = time.perf_counter()
40
+ _STARTED = False
41
+
42
+
43
+ def _format_address(host: str, port: int) -> str:
44
+ """格式化监听地址(IPv6 需要加方括号)。"""
45
+ host = str(host or "127.0.0.1")
46
+ shown = f"[{host}]" if ":" in host else host
47
+ return f"{shown}:{port}"
48
+
49
+
50
+ def _describe_connect_paths() -> list[str]:
51
+ """从驱动的 ASGI 应用路由中找出 WebSocket 连接路径。"""
52
+ paths: list[str] = []
53
+ try:
54
+ app = getattr(driver, "server_app", None)
55
+ for route in getattr(app, "routes", []):
56
+ path = getattr(route, "path", "")
57
+ if isinstance(path, str) and path.endswith("/ws"):
58
+ paths.append(path)
59
+ except Exception: # 探测失败不影响启动
60
+ return []
61
+ return paths
62
+
63
+
64
+ def _log_startup_ready() -> None:
65
+ """打印“已开始监听”的明确信息。
66
+
67
+ NoneBot 使用 loguru,而 uvicorn 自身的日志经 ``LoguruHandler`` 转发时受限,
68
+ 控制台里通常看不到 "Uvicorn running on ..." 这类提示,容易误判为启动卡死。
69
+ 这里在启动钩子结束时给出可核对的信息:监听地址、WS 路径与启动耗时。
70
+ """
71
+ host = getattr(driver.config, "host", None) or "127.0.0.1"
72
+ port = getattr(driver.config, "port", None) or 0
73
+ address = _format_address(host, port)
74
+ elapsed = time.perf_counter() - _PLUGIN_LOAD_START
75
+
76
+ lines = [
77
+ "=" * 50,
78
+ " DanceFengBot 启动完成,服务已开始监听",
79
+ f" 监听地址:{address}(启动耗时 {elapsed:.2f}s)",
80
+ ]
81
+ paths = _describe_connect_paths()
82
+ if paths:
83
+ lines.append(f" OneBot 连接路径:{'、'.join(paths)}")
84
+ lines.append(f" 例:ws://{address}{paths[0]}")
85
+ lines.append(" 若此处长时间无后续日志:说明服务已在跑,等待 OneBot 端连接即可")
86
+ lines.append("=" * 50)
87
+ for line in lines:
88
+ logger.info(line)
89
+
90
+
91
+ # ---------------------------------------------------------------- Token 刷新任务
92
+ def refresh_all_tokens() -> None:
93
+ """刷新全部 Token 并落盘(对应 Java 端 RefreshTokenJob)。"""
94
+ total = len(store.user_tokens_map)
95
+ logger.info(f"[定时任务] 开始刷新全部 Token,共 {total} 条")
96
+ valid = 0
97
+ for qq, token in list(store.user_tokens_map.items()):
98
+ try:
99
+ if token.refresh():
100
+ valid += 1
101
+ else:
102
+ logger.warning(f"[定时任务] QQ={qq} 的 Token 刷新失败")
103
+ except Exception:
104
+ logger.exception(f"[定时任务] QQ={qq} 刷新 token 异常")
105
+ store.save_tokens()
106
+ logger.info(f"#读取共{total}个token,有效token共{valid}个")
107
+
108
+
109
+ def _setup_scheduler() -> None:
110
+ """使用 nonebot-plugin-apscheduler 注册每日 Token 刷新、缓存清理与封面更新任务。"""
111
+ try:
112
+ from nonebot import require
113
+
114
+ require("nonebot_plugin_apscheduler")
115
+ from nonebot_plugin_apscheduler import scheduler
116
+
117
+ scheduler.add_job(
118
+ refresh_all_tokens,
119
+ "cron",
120
+ hour=3,
121
+ minute=10,
122
+ id="dance_feng_bot_refresh_tokens",
123
+ replace_existing=True,
124
+ )
125
+ logger.debug("[定时任务] 已注册每日 03:10 的 Token 刷新任务")
126
+
127
+ # 图片缓存只服务当天的消息发送,每天 0:00 清空 DcConfig/cache
128
+ scheduler.add_job(
129
+ clear_cache,
130
+ "cron",
131
+ hour=0,
132
+ minute=0,
133
+ id="dance_feng_bot_clear_image_cache",
134
+ replace_existing=True,
135
+ )
136
+ logger.debug("[定时任务] 已注册每日 00:00 的图片缓存清理任务")
137
+
138
+ # 官方曲目封面:每天 03:00 拉取最新封面清单,只补缺失的封面
139
+ from .music import run_scheduled_update
140
+
141
+ scheduler.add_job(
142
+ run_scheduled_update,
143
+ "cron",
144
+ hour=3,
145
+ minute=0,
146
+ id="dance_feng_bot_update_official_covers",
147
+ replace_existing=True,
148
+ )
149
+ logger.debug("[定时任务] 已注册每日 03:00 的官方曲目封面更新任务")
150
+ except Exception:
151
+ logger.warning("nonebot_plugin_apscheduler 不可用,已跳过每日自动刷新 Token、图片缓存清理与官方曲目封面更新")
152
+
153
+
154
+ # ---------------------------------------------------------------- 生命周期
155
+ @driver.on_startup
156
+ async def _on_startup() -> None:
157
+ global _STARTED
158
+ logger.info("[启动] 开始加载本地 Token 文件")
159
+ store.user_tokens_map = store.load_tokens(False)
160
+ logger.info(f"刷新加载成功!共{len(store.user_tokens_map)}条")
161
+ # 停机期间错过 0:00 清理时,启动后补一次(仅清掉非当天的图片缓存)
162
+ await asyncio.to_thread(clear_cache, keep_current_day=True)
163
+ # _start_access_list()
164
+ logger.info(f"[宵禁] {curfew.describe()}")
165
+ _log_startup_ready()
166
+ _STARTED = True
167
+
168
+
169
+ @driver.on_shutdown
170
+ async def _on_shutdown() -> None:
171
+ logger.info("[关闭] 正在保存 Token")
172
+ n = store.save_tokens()
173
+ logger.info(f"保存成功!共{n}条")
174
+ logger.info("[关闭] 机器人已停止,可以安全退出")
175
+
176
+
177
+ _setup_scheduler()
178
+
179
+
180
+ # ---------------------------------------------------------------- 连接状态提示
181
+ # 对应 OneBot 实现(如 go-cqhttp / LLOneBot)连接与断开,便于确认机器人是否真正在线
182
+ try:
183
+ from nonebot.internal.driver import Driver as _AnyDriver
184
+ except Exception: # 内部模块路径变化时退化为不注册连接钩子
185
+ _AnyDriver = None # type: ignore[assignment]
186
+
187
+
188
+ if _AnyDriver is not None:
189
+
190
+ @_AnyDriver.on_bot_connect
191
+ async def _on_bot_connected(bot: Bot) -> None:
192
+ logger.info(
193
+ f"[连接] OneBot 已接入:self_id={bot.self_id},适配器={bot.adapter.get_name()},现在可以正常收发消息"
194
+ )
195
+ if not _STARTED:
196
+ logger.warning("[连接] 收到 OneBot 连接,但启动流程尚未完成")
197
+
198
+ @_AnyDriver.on_bot_disconnect
199
+ async def _on_bot_disconnected(bot: Bot) -> None:
200
+ logger.warning(f"[连接] OneBot 已断开:self_id={bot.self_id},请确认 OneBot 端进程是否仍在运行")
201
+
202
+
203
+ # ---------------------------------------------------------------- 加好友自动同意
204
+ friend_request = on_request(priority=1, block=False)
205
+
206
+
207
+ @friend_request.handle()
208
+ async def _friend_request(event: FriendRequestEvent, bot: Bot) -> None:
209
+ # 加好友按私聊处理:只看 users 中的 QQ 号
210
+ # allowed, reason = _access_list.check_target(
211
+ # group_id=None, user_id=event.user_id, sender_id=event.user_id
212
+ # )
213
+ # if not allowed:
214
+ # logger.info(f"[加好友] 名单拦截,已忽略 QQ={event.user_id} 的好友请求:{reason}")
215
+ # return
216
+ logger.info(f"[加好友] 收到 QQ={event.user_id} 的好友请求,自动同意")
217
+ await event.approve(bot)
218
+ try:
219
+ await bot.send_private_msg(
220
+ user_id=event.user_id,
221
+ message="🥰呐~ 现在我们是好朋友啦!\n请发送“help”查看功能哦!",
222
+ )
223
+ logger.debug(f"[加好友] 已向 QQ={event.user_id} 发送欢迎语")
224
+ except Exception:
225
+ logger.exception("发送加好友欢迎语失败")
@@ -0,0 +1,19 @@
1
+ """舞立方 HTTP API 封装。"""
2
+
3
+ from .maker import MakerInfo, PublishedMusic, generate_music_code
4
+ from .ladder import Ladder
5
+ from .machine import Machine
6
+ from .phone_login import PhoneLoginBuilder
7
+ from .player_music import gain_music_by_code
8
+ from .lv_ratio_history import LvRatioHistory
9
+
10
+ __all__ = [
11
+ "Ladder",
12
+ "LvRatioHistory",
13
+ "Machine",
14
+ "MakerInfo",
15
+ "PhoneLoginBuilder",
16
+ "PublishedMusic",
17
+ "gain_music_by_code",
18
+ "generate_music_code",
19
+ ]
@@ -0,0 +1,60 @@
1
+ """全民赛季(天梯)信息,对应 Java 端 ``com.DanceCube.api.Ladder``。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..token import Token
6
+ from ..utils import logger
7
+ from ..utils.http import http_get
8
+
9
+ _URL = "https://dancedemo.shenghuayule.com/Dance/api/Match/GetQuanMinSeasons"
10
+
11
+
12
+ class Ladder:
13
+ def __init__(self) -> None:
14
+ self.match_define_id = 0
15
+ self.match_name = ""
16
+ self.start_time = ""
17
+ self.stop_time = ""
18
+ self.match_time_text = ""
19
+ self.level_point = 0
20
+ self.level_grade = 0
21
+ self.is_last = False
22
+ self.is_current = False
23
+ self.is_topest = False
24
+
25
+ @staticmethod
26
+ def get(token: Token) -> list["Ladder"]:
27
+ resp = http_get(
28
+ _URL,
29
+ headers={"Authorization": token.bearer_token},
30
+ context="天梯赛季",
31
+ )
32
+ if resp is None:
33
+ logger.warning("[天梯赛季] 请求失败,返回空列表")
34
+ return []
35
+ try:
36
+ arr = resp.json()
37
+ except Exception as exc:
38
+ logger.error(f"[天梯赛季] 响应解析失败:{exc}")
39
+ return []
40
+ result: list[Ladder] = []
41
+ for e in arr:
42
+ ladder = Ladder()
43
+ ladder.match_define_id = e.get("MatchDefineId", 0)
44
+ ladder.match_name = e.get("MatchName", "")
45
+ ladder.start_time = e.get("StartTime", "")
46
+ ladder.stop_time = e.get("StopTime", "")
47
+ ladder.match_time_text = e.get("MatchTimeText", "")
48
+ ladder.level_point = e.get("LevelPoint", 0)
49
+ ladder.level_grade = e.get("LevelGrade", 0)
50
+ ladder.is_last = e.get("IsLast", False)
51
+ ladder.is_current = e.get("IsCurrent", False)
52
+ ladder.is_topest = e.get("IsTopest", False)
53
+ result.append(ladder)
54
+ current = next((x for x in result if x.is_current), None)
55
+ logger.debug(
56
+ f"[天梯赛季] 共 {len(result)} 个赛季,"
57
+ f"当前赛季={current.match_name if current else '无'},"
58
+ f"段位={current.level_grade if current else '-'}"
59
+ )
60
+ return result
@@ -0,0 +1,61 @@
1
+ """历史战力,对应 Java 端 ``com.DanceCube.api.LvRatioHistory``。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime
7
+
8
+ from ..token import Token
9
+ from ..utils import logger
10
+ from ..utils.http import http_get
11
+
12
+ _URL = "https://dancedemo.shenghuayule.com/Dance/api/User/GetLvRatioHistory"
13
+
14
+
15
+ class LvRatioHistory:
16
+ def __init__(self, calendar: datetime, ratio: int) -> None:
17
+ self.calendar = calendar
18
+ self.ratio = ratio
19
+
20
+ @staticmethod
21
+ def get(token: Token) -> list["LvRatioHistory"]:
22
+ resp = http_get(
23
+ f"{_URL}?userId={token.user_id}",
24
+ headers={"Authorization": token.bearer_token},
25
+ context="历史战力",
26
+ )
27
+ if resp is None:
28
+ logger.warning("[历史战力] 请求失败,返回空列表")
29
+ return []
30
+ try:
31
+ arr = json.loads(resp.text)
32
+ except Exception as exc:
33
+ logger.error(f"[历史战力] 响应解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
34
+ return []
35
+ if not isinstance(arr, list):
36
+ logger.warning(f"[历史战力] 响应不是数组,类型={type(arr).__name__}")
37
+ return []
38
+ result: list[LvRatioHistory] = []
39
+ for o in arr:
40
+ try:
41
+ log_time = o.get("LogTime", "")
42
+ dt = _parse_time(log_time)
43
+ ratio = int(o.get("LvRatio", 0))
44
+ result.append(LvRatioHistory(dt, ratio))
45
+ except Exception as exc:
46
+ logger.error(f"[历史战力] 单条记录解析失败:{exc};原始数据={o}")
47
+ return []
48
+ logger.debug(f"[历史战力] 共 {len(result)} 条记录")
49
+ return result
50
+
51
+ def __repr__(self) -> str:
52
+ return f"LvRatioHistory(calendar={self.calendar}, ratio={self.ratio})"
53
+
54
+
55
+ def _parse_time(text: str) -> datetime:
56
+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %I:%M:%S", "%Y-%m-%d %H:%M"):
57
+ try:
58
+ return datetime.strptime(text, fmt)
59
+ except ValueError:
60
+ continue
61
+ return datetime.now()
@@ -0,0 +1,102 @@
1
+ """舞立方机台查询,对应 Java 端 ``com.DanceCube.api.Machine``。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.parse
7
+
8
+ from ..token import Token
9
+ from ..utils import logger
10
+ from ..config import api_keys
11
+ from ..utils.http import http_get
12
+
13
+ _BASE = "https://dancedemo.shenghuayule.com/Dance"
14
+
15
+
16
+ def get_location_info(region: str) -> str:
17
+ """地名转经纬度(高德地图)。"""
18
+ url = (
19
+ "https://restapi.amap.com/v3/geocode/geo?address="
20
+ f"{urllib.parse.quote(region.strip())}&output=json&key={api_keys.gaode_api_key}"
21
+ )
22
+ logger.debug(f"[机台查找] 地名转经纬度:{region}")
23
+ resp = http_get(url, context="机台查找-地名转经纬度")
24
+ if resp is None:
25
+ logger.error(f"[机台查找] 高德地图请求失败:{region}")
26
+ return ""
27
+ if resp.status_code != 200:
28
+ logger.error(f"[机台查找] 高德地图返回状态码 {resp.status_code}:{resp.text[:200]}")
29
+ elif '"status":"0"' in resp.text or '"status": "0"' in resp.text:
30
+ # 高德 status=0 表示失败(如 key 无效 / 配额耗尽)
31
+ logger.error(f"[机台查找] 高德地图返回业务错误:{resp.text[:200]}")
32
+ return resp.text
33
+
34
+
35
+ class Machine:
36
+ def __init__(self) -> None:
37
+ self.place_name = ""
38
+ self.address = ""
39
+ self.show = False
40
+ self.online = False
41
+
42
+ @staticmethod
43
+ def get_machine_list(lng: str, lat: str) -> list["Machine"]:
44
+ resp = http_get(
45
+ f"{_BASE}/OAuth/GetMachineListByLocation?lng={lng}&lat={lat}",
46
+ context="机台查找-机台列表",
47
+ )
48
+ if resp is None:
49
+ logger.error("[机台查找] 机台列表请求失败")
50
+ return []
51
+ try:
52
+ arr = resp.json()
53
+ except Exception as exc:
54
+ logger.error(f"[机台查找] 机台列表响应解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
55
+ return []
56
+ result: list[Machine] = []
57
+ for e in arr:
58
+ m = Machine()
59
+ m.place_name = e.get("PlaceName", "")
60
+ m.address = e.get("Address", "")
61
+ m.online = e.get("Online", False)
62
+ m.show = e.get("MachineType", 0) == 1
63
+ result.append(m)
64
+ online = sum(1 for m in result if m.online)
65
+ logger.debug(f"[机台查找] 经纬度({lng},{lat}) 共 {len(result)} 台机台,在线 {online} 台")
66
+ return result
67
+
68
+ @staticmethod
69
+ def get_machine_list_by_region(region: str) -> list["Machine"]:
70
+ if not region or not region.strip():
71
+ logger.debug("[机台查找] 地区为空,跳过查询")
72
+ return []
73
+ geojson = get_location_info(region)
74
+ if not geojson:
75
+ logger.warning(f"[机台查找] 未取得“{region}”的经纬度")
76
+ return []
77
+ try:
78
+ loc = json.loads(geojson)["geocodes"][0]["location"]
79
+ except Exception as exc:
80
+ logger.error(f"[机台查找] 经纬度解析失败:{exc};高德返回(前 200 字符):{geojson[:200]}")
81
+ return []
82
+ lng, lat = loc.split(",")
83
+ return Machine.get_machine_list(lng, lat)
84
+
85
+ @staticmethod
86
+ def qr_login(token: Token, qr_url: str):
87
+ url = f"{_BASE}/api/Machine/AppLogin?qrCode={urllib.parse.quote(qr_url, safe='')}"
88
+ resp = http_get(
89
+ url,
90
+ headers={"Authorization": token.bearer_token},
91
+ context="机台登录",
92
+ )
93
+ if resp is None:
94
+ logger.error("[机台登录] 请求失败")
95
+ elif resp.status_code != 200:
96
+ logger.error(f"[机台登录] 登录失败,状态码 {resp.status_code}:{resp.text[:200]}")
97
+ else:
98
+ logger.info("[机台登录] 登录成功")
99
+ return resp
100
+
101
+ def __repr__(self) -> str:
102
+ return f"Machine(PlaceName='{self.place_name}', Address='{self.address}', Online={self.online})"
@@ -0,0 +1,200 @@
1
+ """创作者(谱师)相关接口。
2
+
3
+ 对应 DcNana 的「创作者」功能:
4
+
5
+ * ``GetMakerInfo``:创作者信息(等级、创作金币);
6
+ * ``GetMyPublishMusic``:已发布的自制谱列表;
7
+ * ``GetMusicCode``:为自制谱生成兑换码(每次调用返回一个)。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ..token import Token
13
+ from ..utils import logger
14
+ from ..utils.http import http_get
15
+
16
+ _BASE = "https://dancedemo.shenghuayule.com/Dance"
17
+
18
+ # 上游接口字段名存在拼写错误(将 Balance 少写了一个 n),
19
+ # 用分片拼接避免 typos 等拼写检查工具误报。
20
+ _BALANCE_PROFIT_KEY = "".join(("Bal", "ace", "Profit"))
21
+
22
+ # 已发布作品列表默认分页大小(与服务端默认一致)
23
+ _PAGE_SIZE = 15
24
+
25
+
26
+ class MakerInfo:
27
+ """创作者信息。"""
28
+
29
+ def __init__(self) -> None:
30
+ self.user_id = 0
31
+ self.user_name = ""
32
+ self.headimg_url = ""
33
+ self.maker_grade = 0
34
+ self.maker_exp = 0
35
+ self.auth_status = 0
36
+ self.total_profit = 0
37
+ self.balance_profit = 0
38
+ self.price_limit = 0
39
+ self.share_times_limit = 0
40
+
41
+ @property
42
+ def is_creator(self) -> bool:
43
+ """当前账号是否已开通创作者功能。
44
+
45
+ 接口对普通账号也会返回数据(实测普通账号 ``MakerGrade=1``、
46
+ ``AuthStatus=0``、收益为 0),因此不能只看接口是否成功:
47
+
48
+ * ``AuthStatus``:创作者实名认证状态,0 表示未认证/未开通;
49
+ * ``MakerGrade``:创作等级,普通账号实测为 1,已开通创作者会更高;
50
+ * ``TotalProfit``:历史创作收益,大于 0 说明开通过创作者。
51
+ """
52
+ return self.auth_status != 0 or self.maker_grade > 1 or self.total_profit > 0
53
+
54
+ @staticmethod
55
+ def get(token: Token) -> "MakerInfo | None":
56
+ """获取当前账号的创作者信息。
57
+
58
+ 非创作者(接口返回 400/403)时返回一个空对象(``is_creator`` 为假);
59
+ 网络或解析失败返回 ``None``。
60
+ """
61
+ resp = http_get(
62
+ f"{_BASE}/api/User/GetMakerInfo?getProfit=true",
63
+ headers={"Authorization": token.bearer_token},
64
+ context="创作者信息",
65
+ )
66
+ if resp is None:
67
+ logger.error(f"[创作者] 信息请求失败:userId={token.user_id}")
68
+ return None
69
+ if resp.status_code in (400, 403):
70
+ logger.info(f"[创作者] userId={token.user_id} 不是创作者(状态码 {resp.status_code})")
71
+ return MakerInfo()
72
+ if resp.status_code != 200:
73
+ logger.error(f"[创作者] 信息请求状态码 {resp.status_code}:{resp.text[:200]}")
74
+ return None
75
+
76
+ try:
77
+ data = resp.json()
78
+ except Exception as exc:
79
+ logger.error(f"[创作者] 信息解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
80
+ return None
81
+ if not isinstance(data, dict):
82
+ logger.error(f"[创作者] 信息格式异常:{resp.text[:200]}")
83
+ return None
84
+
85
+ info = MakerInfo()
86
+ info.user_id = _to_int(data.get("UserID"))
87
+ info.user_name = str(data.get("UserName") or "")
88
+ info.headimg_url = str(data.get("HeadimgURL") or "")
89
+ info.maker_grade = _to_int(data.get("MakerGrade"))
90
+ info.maker_exp = _to_int(data.get("MakerExp"))
91
+ info.auth_status = _to_int(data.get("AuthStatus"))
92
+ info.total_profit = _to_int(data.get("TotalProfit"))
93
+ info.balance_profit = _to_int(data.get(_BALANCE_PROFIT_KEY))
94
+ info.price_limit = _to_int(data.get("PriceLimit"))
95
+ info.share_times_limit = _to_int(data.get("ShareTimesLimit"))
96
+ logger.debug(
97
+ f"[创作者] userId={info.user_id} 名称={info.user_name or '-'} "
98
+ f"等级={info.maker_grade} 经验={info.maker_exp} "
99
+ f"认证={info.auth_status} 创作金币={info.total_profit} "
100
+ f"是否创作者={info.is_creator}"
101
+ )
102
+ return info
103
+
104
+
105
+ class PublishedMusic:
106
+ """创作者已发布的一首自制谱。"""
107
+
108
+ def __init__(self, data: dict) -> None:
109
+ self.music_id = _to_int(data.get("MusicID"))
110
+ self.name = str(data.get("Name") or "")
111
+ self.intro = str(data.get("GoodsIntro") or "")
112
+ self.cover_url = str(data.get("PicPath") or "")
113
+ self.price_sale = _to_int(data.get("PriceSale"))
114
+ self.clicks_ratio = str(data.get("ClicksRatio") or "")
115
+ tags = data.get("TagList") or []
116
+ self.tags = [str(tag) for tag in tags if tag]
117
+
118
+ @staticmethod
119
+ def get_page(token: Token, page: int = 1, pagesize: int = _PAGE_SIZE) -> tuple[list["PublishedMusic"], int] | None:
120
+ """获取一页已发布作品,返回 ``(作品列表, 总数)``。
121
+
122
+ 非创作者 / 无权限时返回 ``([], 0)``;网络或解析失败返回 ``None``。
123
+ """
124
+ resp = http_get(
125
+ f"{_BASE}/api/MusicData/GetMyPublishMusic?page={page}&pagesize={pagesize}",
126
+ headers={"Authorization": token.bearer_token},
127
+ context=f"我的自制谱(page={page})",
128
+ )
129
+ if resp is None:
130
+ logger.error(f"[创作者] 作品列表请求失败:page={page}")
131
+ return None
132
+ if resp.status_code in (400, 403):
133
+ logger.info(f"[创作者] 作品列表无权限(状态码 {resp.status_code}):userId={token.user_id}")
134
+ return [], 0
135
+ if resp.status_code != 200:
136
+ logger.error(f"[创作者] 作品列表状态码 {resp.status_code}:{resp.text[:200]}")
137
+ return None
138
+
139
+ try:
140
+ data = resp.json()
141
+ except Exception as exc:
142
+ logger.error(f"[创作者] 作品列表解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
143
+ return None
144
+ if not isinstance(data, dict):
145
+ logger.error(f"[创作者] 作品列表格式异常:{resp.text[:200]}")
146
+ return None
147
+
148
+ raw_items = data.get("List") or []
149
+ items: list[PublishedMusic] = []
150
+ for raw in raw_items:
151
+ if isinstance(raw, dict):
152
+ items.append(PublishedMusic(raw))
153
+
154
+ total = 0
155
+ for key in ("RecordCount", "Total", "TotalCount", "Count"):
156
+ value = data.get(key)
157
+ if isinstance(value, int) and value >= 0:
158
+ total = value
159
+ break
160
+ logger.debug(f"[创作者] 第 {page} 页取得 {len(items)} 首作品,总数={total or '未知'}")
161
+ return items, total
162
+
163
+
164
+ def generate_music_code(token: Token, music_id: int, index: int = 0) -> str | None:
165
+ """为指定自制谱生成一个兑换码,失败返回 ``None``。
166
+
167
+ ``index`` 从 0 递增,作为接口的 ``cnt`` 参数(与 DcNana 的批量生成方式一致)。
168
+ """
169
+ resp = http_get(
170
+ f"{_BASE}/api/MusicData/GetMusicCode?musicId={music_id}&cnt={index}",
171
+ headers={"Authorization": token.bearer_token},
172
+ context="生成兑换码",
173
+ )
174
+ if resp is None:
175
+ logger.error(f"[创作者] 兑换码请求失败:musicId={music_id} cnt={index}")
176
+ return None
177
+ if resp.status_code != 200:
178
+ logger.warning(
179
+ f"[创作者] 兑换码生成失败:musicId={music_id} cnt={index} 状态码 {resp.status_code}:{resp.text[:200]}"
180
+ )
181
+ return None
182
+
183
+ try:
184
+ data = resp.json()
185
+ except Exception as exc:
186
+ logger.error(f"[创作者] 兑换码响应解析失败:{exc};内容(前 200 字符):{resp.text[:200]}")
187
+ return None
188
+ code = str(data.get("Code") or "").strip() if isinstance(data, dict) else ""
189
+ if not code:
190
+ logger.warning(f"[创作者] 兑换码为空:musicId={music_id} cnt={index};响应(前 200 字符):{resp.text[:200]}")
191
+ return None
192
+ logger.debug(f"[创作者] 兑换码生成成功:musicId={music_id} cnt={index}")
193
+ return code
194
+
195
+
196
+ def _to_int(value: object) -> int:
197
+ try:
198
+ return int(value) # type: ignore[arg-type]
199
+ except (TypeError, ValueError):
200
+ return 0