nonebot-plugin-lyric-relay 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_lyric_relay/__init__.py +538 -0
- nonebot_plugin_lyric_relay/config.py +239 -0
- nonebot_plugin_lyric_relay/features.py +78 -0
- nonebot_plugin_lyric_relay/gate.py +306 -0
- nonebot_plugin_lyric_relay/judge.py +297 -0
- nonebot_plugin_lyric_relay/library.py +774 -0
- nonebot_plugin_lyric_relay/relay.py +795 -0
- nonebot_plugin_lyric_relay/rhyme.py +122 -0
- nonebot_plugin_lyric_relay/search.py +496 -0
- nonebot_plugin_lyric_relay/state.py +118 -0
- nonebot_plugin_lyric_relay/store.py +231 -0
- nonebot_plugin_lyric_relay/text.py +294 -0
- nonebot_plugin_lyric_relay-0.1.0.dist-info/METADATA +312 -0
- nonebot_plugin_lyric_relay-0.1.0.dist-info/RECORD +16 -0
- nonebot_plugin_lyric_relay-0.1.0.dist-info/WHEEL +4 -0
- nonebot_plugin_lyric_relay-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""群聊歌词接龙插件(nonebot-plugin-lyric-relay)。
|
|
2
|
+
|
|
3
|
+
群里有人发了一句歌词,机器人接着唱下一句 —— 像个记得歌词的群友。
|
|
4
|
+
|
|
5
|
+
- **自然触发**:群友随手打一句「从前从前有个人爱你很久」,bot 认出是《晴天》,
|
|
6
|
+
就接「但故事的最后你好像还是说了拜拜」;@机器人 或引用某条消息时同样会响应;
|
|
7
|
+
- **连续接**:接过之后 2 分钟内,别人(哪怕是另一个人)再发同首歌的某一句,
|
|
8
|
+
bot 继续往下接,不会突然换歌;接的时候**只发下一句**,不带歌名;
|
|
9
|
+
- **对唱**:一句一句轮流发也能接 —— 窗口内会把上一条(别人发的)拼进候选;
|
|
10
|
+
- **查歌**:``/什么歌 <歌词片段>``(别名 ``/歌词``)直接回答这是哪首歌;
|
|
11
|
+
- **按群开关**(可选):默认全群可用;设 ``lyric_relay_per_group_switch=true``
|
|
12
|
+
后群管用 ``/歌词开关 on|off`` 单独开关。
|
|
13
|
+
|
|
14
|
+
判定分两层:先按「歌词长什么样」做本地版式闸门(长度/分行/押韵/口语词),
|
|
15
|
+
再把拿不准的交给模型确认;确认是歌词后,再用曲库(lrclib 为主,网易云搜索兜底)
|
|
16
|
+
定位到具体某首歌的某一行,接出下一句。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
from typing import Optional
|
|
24
|
+
|
|
25
|
+
import nonebot
|
|
26
|
+
from nonebot import get_driver, get_plugin_config, on_command, on_message, require
|
|
27
|
+
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent, MessageSegment
|
|
28
|
+
from nonebot.log import logger
|
|
29
|
+
from nonebot.params import CommandArg
|
|
30
|
+
from nonebot.plugin import PluginMetadata
|
|
31
|
+
from nonebot.rule import Rule
|
|
32
|
+
|
|
33
|
+
require("nonebot_plugin_localstore")
|
|
34
|
+
|
|
35
|
+
from nonebot_plugin_localstore import get_plugin_data_dir # noqa: E402
|
|
36
|
+
|
|
37
|
+
from . import features # noqa: E402
|
|
38
|
+
from .config import Config, plugin_config # noqa: E402
|
|
39
|
+
from .judge import LLMJudge # noqa: E402
|
|
40
|
+
from .library import Library # noqa: E402
|
|
41
|
+
from .relay import RelayEngine, plan_text, render, render_title_only # noqa: E402
|
|
42
|
+
from .search import SearchContext, search # noqa: E402
|
|
43
|
+
from .state import RelayStore # noqa: E402
|
|
44
|
+
from .store import IndexStore # noqa: E402
|
|
45
|
+
from .text import clean_text, is_noise, lyric_lines # noqa: E402
|
|
46
|
+
|
|
47
|
+
__plugin_meta__ = PluginMetadata(
|
|
48
|
+
name="歌词接龙",
|
|
49
|
+
description="群友发歌词,机器人接下一句;也可用 /什么歌 查这是哪首歌",
|
|
50
|
+
usage="""\
|
|
51
|
+
(无需命令:群里发一句歌词,bot 认出歌名后自动接下一句;
|
|
52
|
+
@机器人 发歌词、或引用 bot 接的那句再 @机器人,也会接)
|
|
53
|
+
/什么歌 <歌词片段> 查这句是哪首歌(也可直接给歌名)
|
|
54
|
+
/歌词 <歌词片段> 同上(别名)
|
|
55
|
+
/歌词开关 on|off 按群开关(需 lyric_relay_per_group_switch=true,群管可用)""",
|
|
56
|
+
type="application",
|
|
57
|
+
homepage="https://github.com/EricScottLin/nonebot-plugin-lyric-relay",
|
|
58
|
+
config=Config,
|
|
59
|
+
supported_adapters={"~onebot.v11"},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
DATA_DIR = get_plugin_data_dir()
|
|
63
|
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _ai_value(name: str) -> str:
|
|
67
|
+
"""读可选的通用模型配置(``llm_api_base`` / ``llm_api_key`` / ``llm_model``)。
|
|
68
|
+
|
|
69
|
+
留空就用插件自己的 ``lyric_relay_llm_*``;两边都没配且开了
|
|
70
|
+
``lyric_relay_use_llm`` 时,判定会退回纯本地规则。
|
|
71
|
+
"""
|
|
72
|
+
try:
|
|
73
|
+
return str(getattr(get_driver().config, name, "") or "")
|
|
74
|
+
except Exception: # noqa: BLE001
|
|
75
|
+
return ""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------- 组件装配
|
|
79
|
+
library = Library(
|
|
80
|
+
lrclib_base=plugin_config.lyric_relay_lrclib_base,
|
|
81
|
+
timeout=plugin_config.lyric_relay_timeout_seconds,
|
|
82
|
+
max_song_lines=plugin_config.lyric_relay_max_song_lines,
|
|
83
|
+
cache_songs=plugin_config.lyric_relay_cache_songs,
|
|
84
|
+
cache_line_index=plugin_config.lyric_relay_cache_line_index,
|
|
85
|
+
netease_enabled=plugin_config.lyric_relay_netease_fallback,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
index_store = IndexStore(DATA_DIR / "library.json")
|
|
89
|
+
index_store.load_into(library.index)
|
|
90
|
+
|
|
91
|
+
judge = LLMJudge(
|
|
92
|
+
api_base=plugin_config.lyric_relay_llm_api_base or _ai_value("llm_api_base"),
|
|
93
|
+
api_key=plugin_config.lyric_relay_llm_api_key or _ai_value("llm_api_key"),
|
|
94
|
+
model=plugin_config.lyric_relay_llm_model or _ai_value("llm_model"),
|
|
95
|
+
timeout=plugin_config.lyric_relay_llm_timeout_seconds,
|
|
96
|
+
max_tokens=plugin_config.lyric_relay_llm_max_tokens,
|
|
97
|
+
batch_size=plugin_config.lyric_relay_llm_batch_size,
|
|
98
|
+
batch_wait=plugin_config.lyric_relay_llm_batch_wait,
|
|
99
|
+
disabled=not plugin_config.lyric_relay_use_llm,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
store = RelayStore()
|
|
103
|
+
cfg = plugin_config.model_copy(deep=True)
|
|
104
|
+
engine = RelayEngine(cfg, library, judge, store)
|
|
105
|
+
|
|
106
|
+
# 每群一个串行锁:同一群里两条消息同时处理会互相打乱「连续接」状态
|
|
107
|
+
_group_locks: dict[int, asyncio.Lock] = {}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _lock_for(group_id: int) -> asyncio.Lock:
|
|
111
|
+
lock = _group_locks.get(group_id)
|
|
112
|
+
if lock is None:
|
|
113
|
+
lock = asyncio.Lock()
|
|
114
|
+
_group_locks[group_id] = lock
|
|
115
|
+
return lock
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------- 上下文重置
|
|
119
|
+
def reset_group(group_id: int) -> None:
|
|
120
|
+
"""清空某群的全部接龙上下文(测试与 /歌词 重置用)。"""
|
|
121
|
+
engine.reset_group(group_id)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ---------------------------------------------------------------- 权限 / 开关
|
|
125
|
+
ADMIN_ROLES = frozenset({"owner", "admin"})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _is_admin(bot: Bot, event: MessageEvent) -> bool:
|
|
129
|
+
if isinstance(event, GroupMessageEvent):
|
|
130
|
+
if getattr(event.sender, "role", None) in ADMIN_ROLES:
|
|
131
|
+
return True
|
|
132
|
+
uid = event.get_user_id()
|
|
133
|
+
try:
|
|
134
|
+
superusers = {str(x) for x in getattr(getattr(bot, "config", None), "superusers", set())}
|
|
135
|
+
except Exception: # noqa: BLE001
|
|
136
|
+
superusers = set()
|
|
137
|
+
return uid in superusers
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _enabled(group_id: int) -> bool:
|
|
141
|
+
return plugin_config.lyric_relay_enabled and features.is_enabled(group_id)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ---------------------------------------------------------------- 自然触发
|
|
145
|
+
async def _relay_rule(event: GroupMessageEvent) -> bool:
|
|
146
|
+
"""只处理:本群已开启 + 纯文本 + 不像命令 + 不是噪音。"""
|
|
147
|
+
if not _enabled(event.group_id):
|
|
148
|
+
return False
|
|
149
|
+
if not _text_of(event):
|
|
150
|
+
return False
|
|
151
|
+
return True
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _text_of(event: MessageEvent) -> str:
|
|
155
|
+
"""取消息里的文字(去掉 @ 段、回复段),非纯文本返回空串。
|
|
156
|
+
|
|
157
|
+
「—— 歌名 - 歌手」这类署名行会被剔掉:群友常把 bot 接的那句连同署名
|
|
158
|
+
整段复制回来,署名混进歌词里会让匹配失败。
|
|
159
|
+
"""
|
|
160
|
+
segs = [s for s in event.get_message() if s.type not in ("at", "reply", "face")]
|
|
161
|
+
if not segs:
|
|
162
|
+
return ""
|
|
163
|
+
if any(s.type != "text" for s in segs):
|
|
164
|
+
return ""
|
|
165
|
+
raw = "".join(str(s.data.get("text") or "") for s in segs).strip()
|
|
166
|
+
if is_noise(raw):
|
|
167
|
+
return ""
|
|
168
|
+
lines = lyric_lines(raw)
|
|
169
|
+
if not lines:
|
|
170
|
+
return ""
|
|
171
|
+
return "\n".join(lines)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# 明显是「在跟机器人说话」的口语/指令词:@机器人 后带这些字,就不是在发歌词
|
|
175
|
+
_CHAT_WORDS = (
|
|
176
|
+
"小e", "小 e", "怎么", "为什么", "为啥", "什么", "啥意思", "是不是", "能不能",
|
|
177
|
+
"可以吗", "帮我", "看看", "问一下", "问下", "解释", "翻译", "查一下", "查查",
|
|
178
|
+
"在吗", "在不在", "你好", "谢谢", "收到", "辛苦了", "吗", "呢", "吧", "啊",
|
|
179
|
+
"呀", "嘛", "哦", "啦", "?", "?",
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _looks_like_chat(text: str) -> bool:
|
|
184
|
+
"""这句是不是「跟机器人搭话」而不是「在发歌词」。
|
|
185
|
+
|
|
186
|
+
@机器人 是最强的「有意整活」信号(``explicit`` 会加版式分),但它同时
|
|
187
|
+
也是「在跟机器人说话」的信号:2026-11-06 群友 @bot 问「这是怎么触发的呢」,
|
|
188
|
+
被当成歌词接了下一句。这里用口语/指令词做一道粗筛,只挡最明显的对话。
|
|
189
|
+
"""
|
|
190
|
+
low = (text or "").lower()
|
|
191
|
+
return any(word in low for word in _CHAT_WORDS)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _reply_is_bot(bot: Bot, event: MessageEvent) -> bool:
|
|
195
|
+
"""被引用的那条是不是 bot 自己发的(= 群友在跟 bot 说话)。"""
|
|
196
|
+
reply = getattr(event, "reply", None)
|
|
197
|
+
sender = getattr(reply, "sender", None) if reply is not None else None
|
|
198
|
+
uid = getattr(sender, "user_id", None) if sender is not None else None
|
|
199
|
+
if uid is None:
|
|
200
|
+
return False
|
|
201
|
+
return str(uid) == str(bot.self_id)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
async def _quoted_text(bot: Bot, event: MessageEvent) -> str:
|
|
205
|
+
"""被引用消息的文字。
|
|
206
|
+
|
|
207
|
+
注意:引用**不等于**「在发歌词」。群友回复别人的消息说「那你点」时,
|
|
208
|
+
被引用的是别人的话,拿它来接龙就成了「别人聊天,bot 接歌词」。
|
|
209
|
+
所以这里只负责取文本,怎么用由 :func:`_handle_relay` 决定。
|
|
210
|
+
"""
|
|
211
|
+
reply = getattr(event, "reply", None)
|
|
212
|
+
if reply is None:
|
|
213
|
+
return ""
|
|
214
|
+
try:
|
|
215
|
+
message = reply.message
|
|
216
|
+
except Exception: # noqa: BLE001
|
|
217
|
+
message = None
|
|
218
|
+
if message is None:
|
|
219
|
+
return ""
|
|
220
|
+
segs = [s for s in message if s.type not in ("at", "reply", "face")]
|
|
221
|
+
if not segs or any(s.type != "text" for s in segs):
|
|
222
|
+
return ""
|
|
223
|
+
return clean_text("".join(str(s.data.get("text") or "") for s in segs))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
relay = on_message(rule=Rule(_relay_rule), priority=60, block=False)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@relay.handle()
|
|
230
|
+
async def _handle_relay(bot: Bot, event: GroupMessageEvent) -> None:
|
|
231
|
+
typed = _text_of(event)
|
|
232
|
+
if not typed:
|
|
233
|
+
return
|
|
234
|
+
# 命令(/xxx)不参与接龙
|
|
235
|
+
if typed.startswith(("/", "/")):
|
|
236
|
+
return
|
|
237
|
+
|
|
238
|
+
# 群友**自己打的字**永远是主信号;被引用的那条只可能有两种身份:
|
|
239
|
+
# a) 上下文 —— 帮候选拼出「上一句」,让「接下一句」定位得更准;
|
|
240
|
+
# b) 内容 —— 仅当自己没打实质内容、又确实在跟 bot 说话时才顶替。
|
|
241
|
+
# 2026-11-30 线上:群友回复别人的消息只打了「那你点」,旧逻辑把被引用的
|
|
242
|
+
# 「Talking to the Moon」当成内容接龙,回了「Tryna get to You」。
|
|
243
|
+
plan = plan_text(
|
|
244
|
+
typed,
|
|
245
|
+
await _quoted_text(bot, event) if event.reply is not None else "",
|
|
246
|
+
explicit=event.is_tome(), # 只有 @bot 才算「点名 bot」
|
|
247
|
+
reply_to_bot=_reply_is_bot(bot, event),
|
|
248
|
+
min_chars=int(plugin_config.lyric_relay_min_match_chars),
|
|
249
|
+
)
|
|
250
|
+
text, explicit = plan.text, plan.explicit
|
|
251
|
+
context = [(c, str(event.user_id), time.monotonic()) for c in plan.context]
|
|
252
|
+
if explicit and _looks_like_chat(text):
|
|
253
|
+
# @机器人 后的「跟机器人说话」不像歌词(「@bot 这是怎么触发的呢」):
|
|
254
|
+
# explicit 会给版式加分,正好能把这类闲聊推过门槛,这里先挡一道。
|
|
255
|
+
logger.debug(f"[lyric_relay] @机器人 的内容像在对话,不接:{text!r}")
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
lock = _lock_for(event.group_id)
|
|
259
|
+
if lock.locked():
|
|
260
|
+
return # 同群上一条还在处理,跳过这条,避免排队刷屏
|
|
261
|
+
async with lock:
|
|
262
|
+
try:
|
|
263
|
+
outcome = await asyncio.wait_for(
|
|
264
|
+
engine.handle(
|
|
265
|
+
event.group_id,
|
|
266
|
+
text,
|
|
267
|
+
event.get_user_id(),
|
|
268
|
+
ts=time.monotonic(),
|
|
269
|
+
explicit=explicit,
|
|
270
|
+
recent_fragments=(
|
|
271
|
+
(await _recent_texts(bot, event) if explicit else []) + context
|
|
272
|
+
) or None,
|
|
273
|
+
),
|
|
274
|
+
timeout=45,
|
|
275
|
+
)
|
|
276
|
+
except asyncio.TimeoutError:
|
|
277
|
+
logger.debug("[lyric_relay] 处理超时,跳过")
|
|
278
|
+
return
|
|
279
|
+
except Exception as e: # noqa: BLE001 —— 接歌词失败绝不能影响群里其他功能
|
|
280
|
+
logger.warning(f"[lyric_relay] 处理消息异常:{type(e).__name__} {e}")
|
|
281
|
+
return
|
|
282
|
+
logger.debug(
|
|
283
|
+
f"[lyric_relay] 群 {event.group_id} 结果 {outcome.status}"
|
|
284
|
+
f"({outcome.elapsed:.2f}s,{outcome.reason})"
|
|
285
|
+
)
|
|
286
|
+
if not outcome.replied or outcome.hit is None:
|
|
287
|
+
return
|
|
288
|
+
if not plugin_config.lyric_relay_auto_reply:
|
|
289
|
+
return
|
|
290
|
+
reply = render(outcome.hit, plugin_config.lyric_relay_reply_mode)
|
|
291
|
+
if reply:
|
|
292
|
+
await relay.finish(MessageSegment.reply(event.message_id) + MessageSegment.text(reply))
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
async def _recent_texts(bot: Bot, event: GroupMessageEvent) -> list[tuple[str, str, float]]:
|
|
296
|
+
"""@机器人 发言时,从群里取回最近几条消息(最多 12 条,20 分钟内)。"""
|
|
297
|
+
try:
|
|
298
|
+
history = await bot.call_api(
|
|
299
|
+
"get_group_msg_history",
|
|
300
|
+
group_id=event.group_id,
|
|
301
|
+
count=12,
|
|
302
|
+
)
|
|
303
|
+
except Exception as e: # noqa: BLE001 —— 拿不到历史就只按当前这条判
|
|
304
|
+
logger.debug(f"[lyric_relay] 读取群历史失败:{e}")
|
|
305
|
+
return []
|
|
306
|
+
out: list[tuple[str, str, float]] = []
|
|
307
|
+
for msg in (history or {}).get("messages") or []:
|
|
308
|
+
sender = (msg.get("sender") or {})
|
|
309
|
+
uid = str(msg.get("user_id") or sender.get("user_id") or "")
|
|
310
|
+
if uid == str(bot.self_id):
|
|
311
|
+
continue
|
|
312
|
+
message = msg.get("message")
|
|
313
|
+
segs = [s for s in (message or []) if isinstance(s, dict) and s.get("type") == "text"]
|
|
314
|
+
if not segs or len(segs) != len(message or []):
|
|
315
|
+
continue
|
|
316
|
+
text = clean_text("".join(str((s.get("data") or {}).get("text") or "") for s in segs))
|
|
317
|
+
if not text or is_noise(text):
|
|
318
|
+
continue
|
|
319
|
+
try:
|
|
320
|
+
ts = float(msg.get("time") or time.time())
|
|
321
|
+
except (TypeError, ValueError):
|
|
322
|
+
ts = time.time()
|
|
323
|
+
out.append((text, uid, ts))
|
|
324
|
+
return _relative_timestamps(out)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _relative_timestamps(items: list[tuple[str, str, float]]) -> list[tuple[str, str, float]]:
|
|
328
|
+
"""把「墙钟秒」「单调时钟」两种时间基准对齐成单调时钟(测试可直接传单调秒)。"""
|
|
329
|
+
now_mono = time.monotonic()
|
|
330
|
+
now_wall = time.time()
|
|
331
|
+
out = []
|
|
332
|
+
for text, uid, ts in items:
|
|
333
|
+
if ts > 3_000_000_000: # 明显是 Unix 时间戳
|
|
334
|
+
out.append((text, uid, now_mono - max(0.0, now_wall - ts)))
|
|
335
|
+
else:
|
|
336
|
+
out.append((text, uid, ts))
|
|
337
|
+
return out
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
# ---------------------------------------------------------------- /歌词 命令
|
|
341
|
+
lyric_cmd = on_command(
|
|
342
|
+
"什么歌", aliases={"歌词", "查歌词", "这是啥歌", "这首歌是什么"}, priority=8, block=True
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
@lyric_cmd.handle()
|
|
347
|
+
async def _handle_lyric(bot: Bot, event: MessageEvent, arg: Message = CommandArg()) -> None:
|
|
348
|
+
if isinstance(event, GroupMessageEvent) and not _enabled(event.group_id):
|
|
349
|
+
await lyric_cmd.finish("本群没开歌词接龙,找群管发「/开启 歌词」。")
|
|
350
|
+
raw = arg.extract_plain_text().strip()
|
|
351
|
+
if not raw:
|
|
352
|
+
await lyric_cmd.finish(
|
|
353
|
+
"用法:\n"
|
|
354
|
+
"/什么歌 <歌词片段或歌名> 查这句是哪首歌\n"
|
|
355
|
+
"/歌词 <歌词片段或歌名> 同上(别名)\n"
|
|
356
|
+
"群里直接发歌词,bot 也会自动接下一句~"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# 兼容旧习惯:带着「完整版/全文/全部」发过来时,只取后面的歌名/歌词
|
|
360
|
+
# (现在不再输出整首,统一只回答「是什么歌」)
|
|
361
|
+
raw = re.sub(r"^(?:完整版|全文|全部|整首|全部歌词)\s*", "", raw).strip()
|
|
362
|
+
if not raw:
|
|
363
|
+
await lyric_cmd.finish("要查哪句歌词?例如 /什么歌 从前从前有个人爱你很久")
|
|
364
|
+
|
|
365
|
+
try:
|
|
366
|
+
reply = await asyncio.wait_for(_query(raw), timeout=30)
|
|
367
|
+
except asyncio.TimeoutError:
|
|
368
|
+
reply = "查得有点久(可能曲库没响应),换个说法再试?"
|
|
369
|
+
except Exception as e: # noqa: BLE001
|
|
370
|
+
logger.warning(f"[lyric_relay] /歌词 失败:{type(e).__name__} {e}")
|
|
371
|
+
reply = "刚才查歌词出错了,稍后再试。"
|
|
372
|
+
await lyric_cmd.finish(reply)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _split_title_and_fragment(raw: str) -> tuple[str, str]:
|
|
376
|
+
"""``「晴天 从前从前有个人爱你很久」`` → ``("晴天", "从前从前有个人爱你很久")``。
|
|
377
|
+
|
|
378
|
+
规则:第一段是书名号里的 / 很短的词,且后面还有内容 → 当成「歌名 + 片段」。
|
|
379
|
+
"""
|
|
380
|
+
from .text import clean_text
|
|
381
|
+
|
|
382
|
+
parts = raw.split(maxsplit=1)
|
|
383
|
+
if len(parts) == 2 and len(parts[0]) <= 20 and parts[1].strip():
|
|
384
|
+
return clean_text(parts[0]), clean_text(parts[1])
|
|
385
|
+
return "", ""
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _song_line(song) -> str:
|
|
389
|
+
"""统一格式:🎵 《歌名》- 歌手。"""
|
|
390
|
+
title = clean_display_title(song.title)
|
|
391
|
+
return f"🎵 《{title}》- {song.artist}" if song.artist else f"🎵 《{title}》"
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
_DISPLAY_SUFFIX_RE = re.compile(
|
|
395
|
+
r"\s*[((\[【][^))\]】]{0,40}[))\]】]\s*\)?"
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def clean_display_title(title: str) -> str:
|
|
400
|
+
"""展示用歌名:去掉所有括号注释("(原唱 XX)"、"(Live版)"、"《电影》主题曲"…)。
|
|
401
|
+
|
|
402
|
+
只用于**展示**,检索时仍用 library.clean_title(它只削明确的版本后缀)。
|
|
403
|
+
群友看到「晴天 - 周杰伦」,而不是「晴天 (原唱 周杰伦) (女声版)) - RyaVocal」。
|
|
404
|
+
"""
|
|
405
|
+
text = _DISPLAY_SUFFIX_RE.sub(" ", title or "")
|
|
406
|
+
text = re.sub(r"\s+", " ", text).strip(" -\u3000")
|
|
407
|
+
return text or (title or "")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
async def _query(raw: str) -> str:
|
|
411
|
+
"""查「这段是哪首歌」:本地索引 → 当歌名找 → 网络搜片段。
|
|
412
|
+
|
|
413
|
+
只回歌名 + 歌手 —— 群友要的是「这是什么歌」,不是整首歌词。
|
|
414
|
+
顺带把命中的那一句回显一下,方便确认没找错。
|
|
415
|
+
"""
|
|
416
|
+
from .library import clean_title
|
|
417
|
+
from .text import Fragment, normalize
|
|
418
|
+
|
|
419
|
+
# 最快:本地索引里已经有这句歌词(之前接过这首歌)→ 0 网络
|
|
420
|
+
from .search import Hit, exact_hits
|
|
421
|
+
|
|
422
|
+
local = [h for h in exact_hits(library, raw) if h.next_line]
|
|
423
|
+
if local:
|
|
424
|
+
return _render_song(local[0])
|
|
425
|
+
|
|
426
|
+
title_hint, fragment = _split_title_and_fragment(raw)
|
|
427
|
+
|
|
428
|
+
# 0) 「歌名 + 片段」
|
|
429
|
+
if title_hint and fragment:
|
|
430
|
+
song = await library.find_by_name(title_hint)
|
|
431
|
+
if song is not None:
|
|
432
|
+
frag = Fragment(text=fragment, norm=normalize(fragment), user_id="0", ts=time.monotonic())
|
|
433
|
+
ctx = SearchContext.build([frag], explicit_title=clean_title(song.title), recent_song=song)
|
|
434
|
+
hit = await search(library, ctx, min_score=plugin_config.lyric_relay_min_score)
|
|
435
|
+
if hit is not None:
|
|
436
|
+
return _render_song(hit)
|
|
437
|
+
return _song_line(song)
|
|
438
|
+
|
|
439
|
+
# 1) 当歌名
|
|
440
|
+
song = await library.find_by_name(raw)
|
|
441
|
+
if song is not None:
|
|
442
|
+
return _song_line(song)
|
|
443
|
+
|
|
444
|
+
# 2) 当片段
|
|
445
|
+
frag = Fragment(text=raw, norm=normalize(raw), user_id="0", ts=time.monotonic())
|
|
446
|
+
ctx = SearchContext.build([frag], explicit_title=clean_title(raw) if len(raw) <= 12 else "")
|
|
447
|
+
hit = await search(library, ctx, min_score=plugin_config.lyric_relay_min_score)
|
|
448
|
+
if hit is None:
|
|
449
|
+
return f"没找到「{raw}」对应的歌,可能是我曲库里没有。"
|
|
450
|
+
return _render_song(hit)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _render_song(hit) -> str:
|
|
454
|
+
"""「是什么歌」的结果:歌名 + 歌手,附命中的那句做佐证。"""
|
|
455
|
+
lines = [f"🎵 《{clean_display_title(hit.song.title)}》- {hit.song.artist}"
|
|
456
|
+
if hit.song.artist else f"🎵 《{clean_display_title(hit.song.title)}》"]
|
|
457
|
+
matched = " ".join(line.strip() for line in hit.matched_text if line.strip())
|
|
458
|
+
if matched:
|
|
459
|
+
lines.append(f"(对应歌词:{matched[:60]})")
|
|
460
|
+
return "\n".join(lines)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
# ---------------------------------------------------------------- 生命周期
|
|
464
|
+
_driver = get_driver()
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
switch_cmd = on_command(
|
|
468
|
+
"歌词开关", aliases={"接龙开关"}, priority=61, block=True,
|
|
469
|
+
rule=Rule(lambda event: isinstance(event, GroupMessageEvent)),
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
@switch_cmd.handle()
|
|
474
|
+
async def _handle_switch(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()) -> None:
|
|
475
|
+
"""按群开关(仅在 lyric_relay_per_group_switch=true 时可用)。"""
|
|
476
|
+
if not plugin_config.lyric_relay_per_group_switch:
|
|
477
|
+
await switch_cmd.finish(
|
|
478
|
+
"按群开关没启用(lyric_relay_per_group_switch=false):本群跟随总开关,"
|
|
479
|
+
"要让每个群单独开关,请让 bot 主人在 .env 里打开它。"
|
|
480
|
+
)
|
|
481
|
+
if not _is_admin(bot, event):
|
|
482
|
+
await switch_cmd.finish("只有群主/管理员能改这个开关。")
|
|
483
|
+
word = arg.extract_plain_text().strip().lower()
|
|
484
|
+
if word in ("on", "开", "开启", "1", "true", "打开"):
|
|
485
|
+
features.set_enabled(event.group_id, True)
|
|
486
|
+
await switch_cmd.finish("本群「歌词接龙」已开启。")
|
|
487
|
+
if word in ("off", "关", "关闭", "0", "false", "关掉"):
|
|
488
|
+
features.set_enabled(event.group_id, False)
|
|
489
|
+
await switch_cmd.finish("本群「歌词接龙」已关闭。")
|
|
490
|
+
now = "开启" if features.is_enabled(event.group_id) else "关闭"
|
|
491
|
+
await switch_cmd.finish(
|
|
492
|
+
f"本群「歌词接龙」当前是{now}。用法:/歌词开关 on 或 /歌词开关 off"
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _save_index() -> None:
|
|
497
|
+
try:
|
|
498
|
+
index_store.save_from(library.index)
|
|
499
|
+
except Exception as e: # noqa: BLE001
|
|
500
|
+
logger.warning(f"[lyric_relay] 保存歌词索引失败:{e}")
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
@_driver.on_startup
|
|
504
|
+
async def _startup() -> None:
|
|
505
|
+
if not plugin_config.lyric_relay_enabled:
|
|
506
|
+
logger.info("[lyric_relay] 插件总开关已关闭(lyric_relay_enabled=false)")
|
|
507
|
+
logger.info(
|
|
508
|
+
f"[lyric_relay] 配置快照:{json.dumps(plugin_config.model_dump(mode='json'), ensure_ascii=False)}"
|
|
509
|
+
)
|
|
510
|
+
logger.info(
|
|
511
|
+
f"[lyric_relay] 就绪:lrclib={plugin_config.lyric_relay_lrclib_base} "
|
|
512
|
+
f"netease={plugin_config.lyric_relay_netease_fallback} "
|
|
513
|
+
f"llm={'on:' + judge.model if (judge.configured and plugin_config.lyric_relay_use_llm) else 'off'} "
|
|
514
|
+
f"索引歌曲={library.index.song_count}"
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
@_driver.on_shutdown
|
|
519
|
+
async def _shutdown() -> None:
|
|
520
|
+
_save_index()
|
|
521
|
+
await library.close()
|
|
522
|
+
await judge.close()
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# ---------------------------------------------------------------- 定时任务
|
|
526
|
+
try:
|
|
527
|
+
from nonebot_plugin_apscheduler import scheduler
|
|
528
|
+
|
|
529
|
+
@scheduler.scheduled_job("interval", minutes=5, id="lyric_relay_cleanup")
|
|
530
|
+
async def _cleanup() -> None:
|
|
531
|
+
engine.cleanup(time.monotonic())
|
|
532
|
+
|
|
533
|
+
@scheduler.scheduled_job("interval", minutes=10, id="lyric_relay_save")
|
|
534
|
+
async def _periodic_save() -> None:
|
|
535
|
+
if library.index.song_count:
|
|
536
|
+
_save_index()
|
|
537
|
+
except Exception as e: # noqa: BLE001 —— 没有 apscheduler 也能工作,只是不自动落盘
|
|
538
|
+
logger.debug(f"[lyric_relay] 定时任务未启用:{e}")
|