From a5866f382babffcce4165700048762047ae2f6b4 Mon Sep 17 00:00:00 2001 From: student_2333 Date: Wed, 1 May 2024 15:51:10 +0800 Subject: [PATCH] up --- nonebot_plugin_multincm/__init__.py | 2 +- nonebot_plugin_multincm/__main__.py | 21 +++-- nonebot_plugin_multincm/card_helper.py | 89 ------------------- nonebot_plugin_multincm/providers/base.py | 58 ++++++------ .../res/card_template.json | 36 -------- nonebot_plugin_multincm/utils.py | 12 +++ 6 files changed, 54 insertions(+), 164 deletions(-) delete mode 100644 nonebot_plugin_multincm/card_helper.py delete mode 100644 nonebot_plugin_multincm/res/card_template.json diff --git a/nonebot_plugin_multincm/__init__.py b/nonebot_plugin_multincm/__init__.py index 1c1efe2..b3af39b 100644 --- a/nonebot_plugin_multincm/__init__.py +++ b/nonebot_plugin_multincm/__init__.py @@ -7,7 +7,7 @@ auto_resolve_tip = "▶ Bot 会自动解析你发送的网易云链接\n" -__version__ = "0.5.0.dev9" +__version__ = "0.5.0.dev10" __plugin_meta__ = PluginMetadata( name="MultiNCM", description="网易云多选点歌", diff --git a/nonebot_plugin_multincm/__main__.py b/nonebot_plugin_multincm/__main__.py index 8ab0387..cedd254 100644 --- a/nonebot_plugin_multincm/__main__.py +++ b/nonebot_plugin_multincm/__main__.py @@ -3,6 +3,7 @@ import re from pathlib import Path from typing import Dict, List, NoReturn, Optional, Type, Union, cast +from nonebot_plugin_multincm.utils import logged_suppress from typing_extensions import Annotated from httpx import AsyncClient @@ -115,24 +116,30 @@ async def cache_song(song: BaseSong, session: Optional[str] = None): chat_last_song_cache.set(session, SongCache(type(song), song.song_id)) -async def send_song(song: BaseSong): +async def send_song(song: BaseSong, use_text: bool = False): await cache_song(song) - bot = cast(Bot, current_bot.get()) matcher = current_matcher.get() + msg_type = "text" if use_text else "card" try: - msg = await song.to_card_message(int(bot.self_id)) + msg = await song.to_text_message() if use_text else await song.to_card_message() except Exception: - logger.exception(f"Generate {song.calling} card failed") - await matcher.finish(f"生成{song.calling}卡片失败,请检查后台输出") + logger.exception(f"Generate {song.calling} {msg_type} message failed") + if use_text: + await matcher.finish(f"获取{song.calling}信息失败,请检查后台输出") + else: + await send_song(song, use_text=True) + return try: await matcher.send(msg) except ActionFailed: - logger.warning(f"Send {song.calling} card failed") + logger.warning(f"Send {song.calling} failed") logger.opt(exception=True).debug("Stacktrace") - await matcher.send(f"发送卡片失败\n{await song.get_url()}") + if not use_text: + await send_song(song, use_text=True) + return async def get_class_from_link_type(type_name: str) -> Type[SongOrPlaylist]: diff --git a/nonebot_plugin_multincm/card_helper.py b/nonebot_plugin_multincm/card_helper.py deleted file mode 100644 index e362fbd..0000000 --- a/nonebot_plugin_multincm/card_helper.py +++ /dev/null @@ -1,89 +0,0 @@ -import json -from typing import TypedDict - -from .const import RES_DIR - -MUSIC_CARD_TEMPLATE_PATH = RES_DIR / "card_template.json" - - -class CardConfigDict(TypedDict): - ctime: int - forward: int - token: str - type: str - - -class CardExtraDict(TypedDict): - app_type: int - appid: int - # msg_seq: int - uin: int - - -class CardMetaMusicDict(TypedDict): - action: str - android_pkg_name: str - app_type: int - appid: int - ctime: int - desc: str - jumpUrl: str - musicUrl: str - preview: str - sourceMsgId: str - source_icon: str - source_url: str - tag: str - title: str - uin: int - - -class CardMetaDict(TypedDict): - music: CardMetaMusicDict - - -class CardDict(TypedDict): - app: str - config: CardConfigDict - extra: CardExtraDict - meta: CardMetaDict - prompt: str - ver: str - view: str - - -MUSIC_CARD_TEMPLATE: CardDict = json.loads(MUSIC_CARD_TEMPLATE_PATH.read_text("u8")) - - -async def sign_card(card_json: str) -> str: - # placeholder - return card_json - - -async def construct_music_card( - *, - uin: int, - desc: str, - jump_url: str, - music_url: str, - preview: str, - title: str, - sign: bool = True, -) -> str: - data = MUSIC_CARD_TEMPLATE.copy() - # ctime = int(time.time()) - # config = data["config"] - extra = data["extra"] - meta = data["meta"]["music"] - # config["ctime"] = ctime - extra["uin"] = uin - # meta["ctime"] = ctime - meta["desc"] = desc - meta["jumpUrl"] = jump_url - meta["musicUrl"] = music_url - meta["preview"] = preview - meta["title"] = title - meta["uin"] = uin - data["prompt"] = f"[分享]{title}" - card_json = json.dumps(data) - return await sign_card(card_json) if sign else card_json diff --git a/nonebot_plugin_multincm/providers/base.py b/nonebot_plugin_multincm/providers/base.py index c4ea423..b484de3 100644 --- a/nonebot_plugin_multincm/providers/base.py +++ b/nonebot_plugin_multincm/providers/base.py @@ -1,5 +1,4 @@ import asyncio -import json from abc import ABC, abstractmethod from contextlib import suppress from typing import ( @@ -18,7 +17,6 @@ from nonebot.adapters.onebot.v11 import Message, MessageSegment -from ..card_helper import construct_music_card from ..config import config from ..draw import TablePage from ..types import PlaylistRespModelType, SearchRespModelType, SongInfoModelType @@ -76,7 +74,7 @@ async def get_cover_url(self) -> str: ... @abstractmethod async def get_lyric(self) -> Optional[str]: ... - async def to_card_message(self, uin: int) -> Message: + async def to_card_message(self) -> Message: url, playable_url, name, artists, cover_url = await asyncio.gather( self.get_url(), self.get_playable_url(), @@ -85,37 +83,35 @@ async def to_card_message(self, uin: int) -> Message: self.get_cover_url(), ) content = "、".join(artists) - seg = ( - MessageSegment( - "json", - { - "data": await construct_music_card( - uin=uin, - desc=content, - jump_url=url, - music_url=playable_url, - preview=cover_url, - title=name, - ), - }, - ) - if config.ncm_use_json_segment - else MessageSegment( - "music", - { - "type": "custom", - "subtype": "163", - "url": url, - "jumpUrl": url, # icqq - "voice": playable_url, - "title": name, - "content": content, - "image": cover_url, - }, - ) + seg = MessageSegment( + "music", + { + "type": "custom", + "url": url, + "audio": playable_url, + "title": name, + "content": content, + "image": cover_url, + "subtype": "163", # gocq + "voice": playable_url, # gocq + "jumpUrl": url, # icqq + }, ) return Message(seg) + async def _to_text_message(self) -> Message: + name, artists, cover_url = await asyncio.gather( + self.get_name(), + self.get_artists(), + self.get_cover_url(), + ) + content = "、".join(artists) + return MessageSegment.image(cover_url) + f"{name}\nBy: {content}" + + async def to_text_message(self) -> Message: + msg, url = await asyncio.gather(self._to_text_message(), self.get_url()) + return msg + f"\n{url}\n使用指令 `direct` 获取播放链接" + class BasePlaylist( ABC, diff --git a/nonebot_plugin_multincm/res/card_template.json b/nonebot_plugin_multincm/res/card_template.json deleted file mode 100644 index 1d6531d..0000000 --- a/nonebot_plugin_multincm/res/card_template.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "app": "com.tencent.structmsg", - "config": { - "ctime": 1712281916, - "forward": 1, - "token": "da6b069da1e2982db3e386233f68d76d", - "type": "normal" - }, - "extra": { - "app_type": 1, - "appid": 100495085, - "uin": 1145141919 - }, - "meta": { - "music": { - "action": "", - "android_pkg_name": "", - "app_type": 1, - "appid": 100495085, - "ctime": 1712281916, - "desc": "{{ desc }}", - "jumpUrl": "{{ jumpUrl }}", - "musicUrl": "{{ musicUrl }}", - "preview": "{{ preview }}", - "sourceMsgId": "0", - "source_icon": "https://i.gtimg.cn/open/app_icon/00/49/50/85/100495085_100_m.png", - "source_url": "", - "tag": "网易云音乐", - "title": "{{ title }}", - "uin": 1145141919 - } - }, - "prompt": "[分享]{{ title }}", - "ver": "0.0.0.1", - "view": "music" -} diff --git a/nonebot_plugin_multincm/utils.py b/nonebot_plugin_multincm/utils.py index 157f8d5..2e5e3c2 100644 --- a/nonebot_plugin_multincm/utils.py +++ b/nonebot_plugin_multincm/utils.py @@ -1,6 +1,9 @@ +from contextlib import contextmanager from typing import List, Optional, TypeVar, cast from typing_extensions import ParamSpec +from nonebot import logger + from . import lrc_parser from .config import config from .types import Artist, Lyric, LyricData, User @@ -70,3 +73,12 @@ def fmt_usr(usr: User) -> str: lines.append(f"翻译贡献者:{fmt_usr(usr)}") return "\n".join(lines).strip() + + +@contextmanager +def logged_suppress(msg: str): + try: + yield + except Exception: + logger.exception(msg) + return None