diff --git a/zhenxun/builtin_plugins/admin/admin_help.py b/zhenxun/builtin_plugins/admin/admin_help.py index bdf48929..a0cb4166 100644 --- a/zhenxun/builtin_plugins/admin/admin_help.py +++ b/zhenxun/builtin_plugins/admin/admin_help.py @@ -2,7 +2,6 @@ import nonebot from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Arparma, on_alconna from nonebot_plugin_alconna.matcher import AlconnaMatcher -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH @@ -18,6 +17,7 @@ from zhenxun.utils.image_utils import ( group_image, text2image, ) +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import admin_check, ensure_group __plugin_meta__ = PluginMetadata( @@ -149,13 +149,12 @@ async def build_help() -> BuildImage: @_matcher.handle() async def _( session: EventSession, - matcher: AlconnaMatcher, arparma: Arparma, ): if not ADMIN_HELP_IMAGE.exists(): try: await build_help() except EmptyError: - await Text("管理员帮助为空").finish(reply=True) - await Image(ADMIN_HELP_IMAGE).send() + await MessageUtils.build_message("管理员帮助为空").finish(reply=True) + await MessageUtils.build_message(ADMIN_HELP_IMAGE).send() logger.info("查看管理员帮助", arparma.header_result, session=session) diff --git a/zhenxun/builtin_plugins/admin/ban/__init__.py b/zhenxun/builtin_plugins/admin/ban/__init__.py index d21641c6..19e8f455 100644 --- a/zhenxun/builtin_plugins/admin/ban/__init__.py +++ b/zhenxun/builtin_plugins/admin/ban/__init__.py @@ -11,13 +11,13 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import Image, Mention, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import admin_check from ._data_source import BanManage @@ -146,9 +146,9 @@ async def _( _user_id = user_id.result if user_id.available else None _group_id = group_id.result if group_id.available else None if image := await BanManage.build_ban_image(filter_type, _user_id, _group_id): - await Image(image.pic2bytes()).finish(reply=True) + await MessageUtils.build_message(image).finish(reply_to=True) else: - await Text("数据为空捏...").finish(reply=True) + await MessageUtils.build_message("数据为空捏...").finish(reply_to=True) @_ban_matcher.handle() @@ -166,7 +166,7 @@ async def _( user_id = user.result.target else: if session.id1 not in bot.config.superusers: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) user_id = user.result _duration = duration.result * 60 if duration.available else -1 if (gid := session.id3 or session.id2) and not group_id.available: @@ -181,13 +181,13 @@ async def _( session=session, target=f"{gid}:{user_id}", ) - await MessageFactory( + await MessageUtils.build_message( [ - Text("对 "), - Mention(user_id) if isinstance(user.result, At) else Text(user_id), # type: ignore - Text(f" 狠狠惩戒了一番,一脚踢进了小黑屋!"), + "对 ", + At(flag="user", target=user_id) if isinstance(user.result, At) else user_id, # type: ignore + f" 狠狠惩戒了一番,一脚踢进了小黑屋!", ] - ).finish(reply=True) + ).finish(reply_to=True) elif session.id1 in bot.config.superusers: _group_id = group_id.result if group_id.available else None await BanManage.ban(user_id, _group_id, _duration, session, True) @@ -198,7 +198,9 @@ async def _( target=f"{_group_id}:{user_id}", ) at_msg = user_id if user_id else f"群组:{_group_id}" - await Text(f"对 {at_msg} 狠狠惩戒了一番,一脚踢进了小黑屋!").finish(reply=True) + await MessageUtils.build_message( + f"对 {at_msg} 狠狠惩戒了一番,一脚踢进了小黑屋!" + ).finish(reply_to=True) @_unban_matcher.handle() @@ -215,7 +217,7 @@ async def _( user_id = user.result.target else: if session.id1 not in bot.config.superusers: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) user_id = user.result if gid := session.id3 or session.id2: if group_id.available: @@ -229,15 +231,17 @@ async def _( session=session, target=f"{gid}:{user_id}", ) - await MessageFactory( + await MessageUtils.build_message( [ - Text("将 "), - Mention(user_id) if isinstance(user.result, At) else Text(user_id), # type: ignore - Text(f" 从黑屋中拉了出来并急救了一下!"), + "将 ", + At(flag="user", target=user_id) if isinstance(user.result, At) else user_id, # type: ignore + f" 从黑屋中拉了出来并急救了一下!", ] ).finish(reply=True) else: - await Text(f"该用户不在黑名单中捏...").finish(reply=True) + await MessageUtils.build_message(f"该用户不在黑名单中捏...").finish( + reply_to=True + ) elif session.id1 in bot.config.superusers: _group_id = group_id.result if group_id.available else None if await BanManage.unban(user_id, _group_id, session, True): @@ -248,6 +252,10 @@ async def _( target=f"{_group_id}:{user_id}", ) at_msg = user_id if user_id else f"群组:{_group_id}" - await Text(f"对 {at_msg} 从黑屋中拉了出来并急救了一下!").finish(reply=True) + await MessageUtils.build_message( + f"对 {at_msg} 从黑屋中拉了出来并急救了一下!" + ).finish(reply_to=True) else: - await Text(f"该用户不在黑名单中捏...").finish(reply=True) + await MessageUtils.build_message(f"该用户不在黑名单中捏...").finish( + reply_to=True + ) diff --git a/zhenxun/builtin_plugins/admin/ban/_data_source.py b/zhenxun/builtin_plugins/admin/ban/_data_source.py index cc35b9c3..3d8f704d 100644 --- a/zhenxun/builtin_plugins/admin/ban/_data_source.py +++ b/zhenxun/builtin_plugins/admin/ban/_data_source.py @@ -102,7 +102,7 @@ class BanManage: user_level = 9999 if not is_superuser and user_id and session.id1: user_level = await LevelUser.get_user_level(session.id1, group_id) - if not await BanConsole.check_ban_level(user_id, group_id, user_level): + if await BanConsole.check_ban_level(user_id, group_id, user_level): await BanConsole.unban(user_id, group_id) return True return False diff --git a/zhenxun/builtin_plugins/admin/group_member_update/__init__.py b/zhenxun/builtin_plugins/admin/group_member_update/__init__.py index 9286e750..c7036cc8 100644 --- a/zhenxun/builtin_plugins/admin/group_member_update/__init__.py +++ b/zhenxun/builtin_plugins/admin/group_member_update/__init__.py @@ -3,13 +3,13 @@ from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import GroupIncreaseNoticeEvent from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Arparma, on_alconna -from nonebot_plugin_saa import Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import admin_check, ensure_group from ._data_source import MemberUpdateManage @@ -44,8 +44,10 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma): if gid := session.id3 or session.id2: logger.info("更新群组成员信息", arparma.header_result, session=session) await MemberUpdateManage.update(bot, gid) - await Text("已经成功更新了群组成员信息!").finish(reply=True) - await Text("群组id为空...").send() + await MessageUtils.build_message("已经成功更新了群组成员信息!").finish( + reply_to=True + ) + await MessageUtils.build_message("群组id为空...").send() _notice = on_notice(priority=1, block=False) diff --git a/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py b/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py index 63c7484f..76b10259 100644 --- a/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py +++ b/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py @@ -1,13 +1,13 @@ from nonebot.adapters import Bot from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import AlconnaQuery, Arparma, Match, Query -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.enum import BlockType, PluginType +from zhenxun.utils.message import MessageUtils from ._data_source import PluginManage, build_plugin, build_task from .command import _group_status_matcher, _status_matcher @@ -98,9 +98,9 @@ async def _( arparma.header_result, session=session, ) - await Image(image.pic2bytes()).finish(reply=True) + await MessageUtils.build_message(image).finish(reply_to=True) else: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) @_status_matcher.assign("open") @@ -115,7 +115,7 @@ async def _( all: Query[bool] = AlconnaQuery("all.value", False), ): if not all.result and not plugin_name.available: - await Text("请输入功能名称").finish(reply=True) + await MessageUtils.build_message("请输入功能名称").finish(reply_to=True) name = plugin_name.result gid = session.id3 or session.id2 if gid: @@ -154,7 +154,7 @@ async def _( logger.info( f"开启功能 {name}", arparma.header_result, session=session ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) elif session.id1 in bot.config.superusers: """私聊""" group_id = group.result if group.available else None @@ -174,7 +174,7 @@ async def _( arparma.header_result, session=session, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) if default_status.result: result = await PluginManage.set_default_status(name, True) logger.info( @@ -183,7 +183,7 @@ async def _( session=session, target=group_id, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) if task.result: split_list = name.split() if len(split_list) > 1: @@ -204,7 +204,7 @@ async def _( arparma.header_result, session=session, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) else: result = await PluginManage.superuser_block(name, None, group_id) logger.info( @@ -213,7 +213,7 @@ async def _( session=session, target=group_id, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) @_status_matcher.assign("close") @@ -229,7 +229,7 @@ async def _( all: Query[bool] = AlconnaQuery("all.value", False), ): if not all.result and not plugin_name.available: - await Text("请输入功能名称").finish(reply=True) + await MessageUtils.build_message("请输入功能名称").finish(reply_to=True) name = plugin_name.result gid = session.id3 or session.id2 if gid: @@ -268,7 +268,7 @@ async def _( logger.info( f"关闭功能 {name}", arparma.header_result, session=session ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) elif session.id1 in bot.config.superusers: group_id = group.result if group.available else None if all.result: @@ -287,7 +287,7 @@ async def _( arparma.header_result, session=session, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) if default_status.result: result = await PluginManage.set_default_status(name, False) logger.info( @@ -296,7 +296,7 @@ async def _( session=session, target=group_id, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) if task.result: split_list = name.split() if len(split_list) > 1: @@ -317,7 +317,7 @@ async def _( arparma.header_result, session=session, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) else: _type = BlockType.ALL if block_type.available: @@ -332,7 +332,7 @@ async def _( session=session, target=group_id, ) - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) @_group_status_matcher.handle() @@ -345,14 +345,14 @@ async def _( if status == "sleep": await PluginManage.sleep(gid) logger.info("进行休眠", arparma.header_result, session=session) - await Text("那我先睡觉了...").finish() + await MessageUtils.build_message("那我先睡觉了...").finish() else: if await PluginManage.is_wake(gid): - await Text("我还醒着呢!").finish() + await MessageUtils.build_message("我还醒着呢!").finish() await PluginManage.wake(gid) logger.info("醒来", arparma.header_result, session=session) - await Text("呜..醒来了...").finish() - return Text("群组id为空...").send() + await MessageUtils.build_message("呜..醒来了...").finish() + return MessageUtils.build_message("群组id为空...").send() @_status_matcher.assign("task") @@ -367,6 +367,6 @@ async def _( arparma.header_result, session=session, ) - await Image(image.pic2bytes()).finish(reply=True) + await MessageUtils.build_message(image).finish(reply_to=True) else: - await Text("获取群被动任务失败...").finish(reply=True) + await MessageUtils.build_message("获取群被动任务失败...").finish(reply_to=True) diff --git a/zhenxun/builtin_plugins/chat_history/chat_message_handle.py b/zhenxun/builtin_plugins/chat_history/chat_message_handle.py index c23d7ca9..1287e1b0 100644 --- a/zhenxun/builtin_plugins/chat_history/chat_message_handle.py +++ b/zhenxun/builtin_plugins/chat_history/chat_message_handle.py @@ -12,7 +12,6 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData @@ -21,6 +20,7 @@ from zhenxun.models.group_member_info import GroupInfoUser from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import ImageTemplate +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="消息统计", @@ -120,8 +120,8 @@ async def _( logger.info( f"查看消息排行 数量={count.result}", arparma.header_result, session=session ) - await Image(A.pic2bytes()).finish(reply=True) - await Text("群组消息记录为空...").finish() + await MessageUtils.build_message(A).finish(reply_to=True) + await MessageUtils.build_message("群组消息记录为空...").finish() # # @test.handle() diff --git a/zhenxun/builtin_plugins/help/__init__.py b/zhenxun/builtin_plugins/help/__init__.py index 12021a46..f274c484 100644 --- a/zhenxun/builtin_plugins/help/__init__.py +++ b/zhenxun/builtin_plugins/help/__init__.py @@ -11,7 +11,6 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH @@ -19,6 +18,7 @@ from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from ._data_source import create_help_img, get_plugin_help from ._utils import GROUP_HELP_PATH @@ -75,11 +75,13 @@ async def _( _is_superuser = False if result := await get_plugin_help(name.result, _is_superuser): if isinstance(result, BuildImage): - await Image(result.pic2bytes()).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) else: - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) else: - await Text("没有此功能的帮助信息...").send(reply=True) + await MessageUtils.build_message("没有此功能的帮助信息...").send( + reply_to=True + ) logger.info( f"查看帮助详情: {name.result}", "帮助", @@ -90,10 +92,10 @@ async def _( _image_path = GROUP_HELP_PATH / f"{gid}.png" if not _image_path.exists(): await create_help_img(gid) - await Image(_image_path).finish() + await MessageUtils.build_message(_image_path).finish() else: if not SIMPLE_HELP_IMAGE.exists(): if SIMPLE_HELP_IMAGE.exists(): SIMPLE_HELP_IMAGE.unlink() await create_help_img(None) - await Image(SIMPLE_HELP_IMAGE).finish() + await MessageUtils.build_message(SIMPLE_HELP_IMAGE).finish() diff --git a/zhenxun/builtin_plugins/help_help.py b/zhenxun/builtin_plugins/help_help.py index 56556e70..b2682aa4 100644 --- a/zhenxun/builtin_plugins/help_help.py +++ b/zhenxun/builtin_plugins/help_help.py @@ -5,7 +5,7 @@ from nonebot import on_message from nonebot.matcher import Matcher from nonebot.plugin import PluginMetadata from nonebot.rule import to_me -from nonebot_plugin_alconna import Image, UniMessage, UniMsg +from nonebot_plugin_alconna import UniMsg from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH @@ -14,7 +14,9 @@ from zhenxun.models.ban_console import BanConsole from zhenxun.models.group_console import GroupConsole from zhenxun.models.plugin_info import PluginInfo from zhenxun.services.log import logger +from zhenxun.utils._build_image import BuildImage from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="功能名称当命令检测", @@ -27,7 +29,6 @@ __plugin_meta__ = PluginMetadata( ).dict(), ) - _matcher = on_message(rule=to_me(), priority=996, block=False) @@ -52,7 +53,7 @@ async def _(matcher: Matcher, message: UniMsg, session: EventSession): image = None if _path.exists(): if files := os.listdir(_path): - image = Image(path=_path / random.choice(files)) + image = _path / random.choice(files) message_list = [] if image: message_list.append(image) @@ -62,5 +63,5 @@ async def _(matcher: Matcher, message: UniMsg, session: EventSession): logger.info( f"检测到功能名称当命令使用,已发送帮助信息", "功能帮助", session=session ) - await UniMessage(message_list).send(reply_to=True) + await MessageUtils.build_message(message_list).send(reply_to=True) matcher.stop_propagation() diff --git a/zhenxun/builtin_plugins/nickname.py b/zhenxun/builtin_plugins/nickname.py index 4eda8187..f5cce1fb 100644 --- a/zhenxun/builtin_plugins/nickname.py +++ b/zhenxun/builtin_plugins/nickname.py @@ -7,7 +7,6 @@ from nonebot.params import Depends, RegexGroup from nonebot.plugin import PluginMetadata from nonebot.rule import to_me from nonebot_plugin_alconna import Alconna, Option, on_alconna, store_true -from nonebot_plugin_saa import Text from nonebot_plugin_session import EventSession from nonebot_plugin_userinfo import EventUserInfo, UserInfo @@ -19,6 +18,7 @@ from zhenxun.models.group_member_info import GroupInfoUser from zhenxun.services.log import logger from zhenxun.utils.depends import UserName from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="昵称系统", @@ -124,27 +124,37 @@ def CheckNickname(): (name,) = reg_group logger.debug(f"昵称检查: {name}", "昵称设置", session=session) if not name: - await Text("叫你空白?叫你虚空?叫你无名??").finish(at_sender=True) + await MessageUtils.build_message("叫你空白?叫你虚空?叫你无名??").finish( + at_sender=True + ) if session.id1 in bot.config.superusers: logger.debug( f"超级用户设置昵称, 跳过合法检测: {name}", "昵称设置", session=session ) return if len(name) > 20: - await Text("昵称可不能超过20个字!").finish(at_sender=True) + await MessageUtils.build_message("昵称可不能超过20个字!").finish( + at_sender=True + ) if name in bot.config.nickname: - await Text("笨蛋!休想占用我的名字! #").finish(at_sender=True) + await MessageUtils.build_message("笨蛋!休想占用我的名字! #").finish( + at_sender=True + ) if black_word: for x in name: if x in black_word: logger.debug("昵称设置禁止字符: [{x}]", "昵称设置", session=session) - await Text(f"字符 [{x}] 为禁止字符!").finish(at_sender=True) + await MessageUtils.build_message(f"字符 [{x}] 为禁止字符!").finish( + at_sender=True + ) for word in black_word: if word in name: logger.debug( "昵称设置禁止字符: [{word}]", "昵称设置", session=session ) - await Text(f"字符 [{x}] 为禁止字符!").finish(at_sender=True) + await MessageUtils.build_message(f"字符 [{x}] 为禁止字符!").finish( + at_sender=True + ) return Depends(dependency) @@ -171,7 +181,9 @@ async def _( session.platform, ) logger.info(f"设置群昵称成功: {name}", "昵称设置", session=session) - await Text(random.choice(CALL_NAME).format(name)).finish(reply=True) + await MessageUtils.build_message( + random.choice(CALL_NAME).format(name) + ).finish(reply_to=True) else: await FriendUser.set_user_nickname( session.id1, @@ -182,8 +194,10 @@ async def _( session.platform, ) logger.info(f"设置私聊昵称成功: {name}", "昵称设置", session=session) - await Text(random.choice(CALL_NAME).format(name)).finish(reply=True) - await Text("用户id为空...").send() + await MessageUtils.build_message( + random.choice(CALL_NAME).format(name) + ).finish(reply_to=True) + await MessageUtils.build_message("用户id为空...").send() @_global_nickname_matcher.handle(parameterless=[CheckNickname()]) @@ -202,8 +216,10 @@ async def _( ) await GroupInfoUser.filter(user_id=session.id1).update(nickname=name) logger.info(f"设置全局昵称成功: {name}", "设置全局昵称", session=session) - await Text(random.choice(CALL_NAME).format(name)).finish(reply=True) - await Text("用户id为空...").send() + await MessageUtils.build_message(random.choice(CALL_NAME).format(name)).finish( + reply_to=True + ) + await MessageUtils.build_message("用户id为空...").send() @_matcher.assign("name") @@ -216,9 +232,11 @@ async def _(session: EventSession, user_info: UserInfo = EventUserInfo()): nickname = await FriendUser.get_user_nickname(session.id1) card = user_info.user_name if nickname: - await Text(random.choice(REMIND).format(nickname)).finish(reply=True) + await MessageUtils.build_message( + random.choice(REMIND).format(nickname) + ).finish(reply_to=True) else: - await Text( + await MessageUtils.build_message( random.choice( [ "没..没有昵称嘛,{}", @@ -227,8 +245,8 @@ async def _(session: EventSession, user_info: UserInfo = EventUserInfo()): "你是{}?", ] ).format(card) - ).finish(reply=True) - await Text("用户id为空...").send() + ).finish(reply_to=True) + await MessageUtils.build_message("用户id为空...").send() @_matcher.assign("cancel") @@ -240,7 +258,9 @@ async def _(bot: Bot, session: EventSession, user_info: UserInfo = EventUserInfo else: nickname = await FriendUser.get_user_nickname(session.id1) if nickname: - await Text(random.choice(CANCEL).format(nickname)).send(reply=True) + await MessageUtils.build_message( + random.choice(CANCEL).format(nickname) + ).send(reply_to=True) if gid: await GroupInfoUser.set_user_nickname(session.id1, gid, "") else: @@ -248,5 +268,7 @@ async def _(bot: Bot, session: EventSession, user_info: UserInfo = EventUserInfo await BanConsole.ban(session.id1, gid, 9, 60, bot.self_id) return else: - await Text("你在做梦吗?你没有昵称啊").finish(reply=True) - await Text("用户id为空...").send() + await MessageUtils.build_message("你在做梦吗?你没有昵称啊").finish( + reply_to=True + ) + await MessageUtils.build_message("用户id为空...").send() diff --git a/zhenxun/builtin_plugins/platform/qq/group_handle.py b/zhenxun/builtin_plugins/platform/qq/group_handle.py index bb6aee49..e04f8e5a 100644 --- a/zhenxun/builtin_plugins/platform/qq/group_handle.py +++ b/zhenxun/builtin_plugins/platform/qq/group_handle.py @@ -16,7 +16,7 @@ from nonebot.adapters.onebot.v12 import ( GroupMemberIncreaseEvent, ) from nonebot.plugin import PluginMetadata -from nonebot_plugin_saa import Image, Mention, MessageFactory, Text +from nonebot_plugin_alconna import At from zhenxun.configs.config import NICKNAME, Config from zhenxun.configs.path_config import DATA_PATH, IMAGE_PATH @@ -29,6 +29,7 @@ from zhenxun.models.plugin_info import PluginInfo from zhenxun.models.task_info import TaskInfo from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType, RequestHandleType +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import FreqLimiter __plugin_meta__ = PluginMetadata( @@ -235,26 +236,26 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent | GroupMemberIncreaseEvent msg_split = re.split(r"\[image:\d+\]", message) msg_list = [] if data["at"]: - msg_list.append(Mention(user_id)) + msg_list.append(At(flag="user", target=user_id)) for i, text in enumerate(msg_split): - msg_list.append(Text(text)) + msg_list.append(text) img_file = path / f"{i}.png" if img_file.exists(): - msg_list.append(Image(img_file)) + msg_list.append(img_file) if not TaskInfo.is_block("group_welcome", group_id): logger.info(f"发送群欢迎消息...", "入群检测", group_id=group_id) if msg_list: - await MessageFactory(msg_list).send() + await MessageUtils.build_message(msg_list).send() else: image = ( IMAGE_PATH / "qxz" / random.choice(os.listdir(IMAGE_PATH / "qxz")) ) - await MessageFactory( + await MessageUtils.build_message( [ - Text("新人快跑啊!!本群现状↓(快使用自定义!)"), - Image(image), + "新人快跑啊!!本群现状↓(快使用自定义!)", + image, ] ).send() diff --git a/zhenxun/builtin_plugins/scheduler/morning.py b/zhenxun/builtin_plugins/scheduler/morning.py index c254d5e8..edbc959f 100644 --- a/zhenxun/builtin_plugins/scheduler/morning.py +++ b/zhenxun/builtin_plugins/scheduler/morning.py @@ -1,7 +1,6 @@ import nonebot from nonebot.plugin import PluginMetadata from nonebot_plugin_apscheduler import scheduler -from nonebot_plugin_saa import Image from zhenxun.configs.config import NICKNAME from zhenxun.configs.path_config import IMAGE_PATH @@ -9,6 +8,7 @@ from zhenxun.configs.utils import PluginExtraData, Task from zhenxun.models.task_info import TaskInfo from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import broadcast_group __plugin_meta__ = PluginMetadata( @@ -50,21 +50,23 @@ async def check(group_id: str) -> bool: minute=1, ) async def _(): - img = Image(IMAGE_PATH / "zhenxun" / "zao.jpg") - await broadcast_group("早上好" + img, log_cmd="被动早晚安", check_func=check) + message = MessageUtils.build_message(["早上好", IMAGE_PATH / "zhenxun" / "zao.jpg"]) + await broadcast_group(message, log_cmd="被动早晚安", check_func=check) logger.info("每日早安发送...") # # 睡觉了 @scheduler.scheduled_job( "cron", - hour=23, - minute=59, + hour=1, + minute=16, ) async def _(): - img = Image(IMAGE_PATH / "zhenxun" / "sleep.jpg") + message = MessageUtils.build_message( + [f"{NICKNAME}要睡觉了,你们也要早点睡呀", IMAGE_PATH / "zhenxun" / "sleep.jpg"] + ) await broadcast_group( - f"{NICKNAME}要睡觉了,你们也要早点睡呀" + img, + message, log_cmd="被动早晚安", check_func=check, ) diff --git a/zhenxun/builtin_plugins/shop/__init__.py b/zhenxun/builtin_plugins/shop/__init__.py index 041ca6e8..9ce4c51c 100644 --- a/zhenxun/builtin_plugins/shop/__init__.py +++ b/zhenxun/builtin_plugins/shop/__init__.py @@ -5,16 +5,17 @@ from nonebot_plugin_alconna import ( Args, Arparma, Subcommand, + UniMessage, UniMsg, on_alconna, ) -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from nonebot_plugin_userinfo import EventUserInfo, UserInfo from zhenxun.configs.utils import BaseBlock, PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.enum import BlockType, PluginType +from zhenxun.utils.message import MessageUtils from ._data_source import ShopManage @@ -84,7 +85,7 @@ _matcher.shortcut( async def _(session: EventSession, arparma: Arparma): image = await ShopManage.build_shop_image() logger.info("查看商店", arparma.header_result, session=session) - await Image(image.pic2bytes()).send() + await MessageUtils.build_message(image).send() @_matcher.assign("my-cost") @@ -92,9 +93,9 @@ async def _(session: EventSession, arparma: Arparma): if session.id1: logger.info("查看金币", arparma.header_result, session=session) gold = await ShopManage.my_cost(session.id1, session.platform) - await Text(f"你的当前余额: {gold}").send(reply=True) + await MessageUtils.build_message(f"你的当前余额: {gold}").send(reply_to=True) else: - await Text(f"用户id为空...").send(reply=True) + await MessageUtils.build_message(f"用户id为空...").send(reply_to=True) @_matcher.assign("my-props") @@ -108,10 +109,12 @@ async def _( user_info.user_displayname or user_info.user_name, session.platform, ): - await Image(image.pic2bytes()).finish(reply=True) - return await Text(f"你的道具为空捏...").send(reply=True) + await MessageUtils.build_message(image.pic2bytes()).finish(reply_to=True) + return await MessageUtils.build_message(f"你的道具为空捏...").send( + reply_to=True + ) else: - await Text(f"用户id为空...").send(reply=True) + await MessageUtils.build_message(f"用户id为空...").send(reply_to=True) @_matcher.assign("buy") @@ -123,9 +126,9 @@ async def _(session: EventSession, arparma: Arparma, name: str, num: int): session=session, ) result = await ShopManage.buy_prop(session.id1, name, num, session.platform) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) else: - await Text(f"用户id为空...").send(reply=True) + await MessageUtils.build_message(f"用户id为空...").send(reply_to=True) @_matcher.assign("use") @@ -141,6 +144,6 @@ async def _( result = await ShopManage.use(bot, event, session, message, name, num, "") logger.info(f"使用道具 {name}, 数量: {num}", arparma.header_result, session=session) if isinstance(result, str): - await Text(result).send(reply=True) - elif isinstance(result, MessageFactory): - await result.finish(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) + elif isinstance(result, UniMessage): + await result.finish(reply_to=True) diff --git a/zhenxun/builtin_plugins/shop/_data_source.py b/zhenxun/builtin_plugins/shop/_data_source.py index 94f92433..8f509631 100644 --- a/zhenxun/builtin_plugins/shop/_data_source.py +++ b/zhenxun/builtin_plugins/shop/_data_source.py @@ -5,7 +5,7 @@ from types import MappingProxyType from typing import Any, Callable, Literal from nonebot.adapters import Bot, Event -from nonebot_plugin_alconna import UniMsg +from nonebot_plugin_alconna import UniMessage, UniMsg from nonebot_plugin_saa import MessageFactory from nonebot_plugin_session import EventSession from pydantic import BaseModel, create_model @@ -190,7 +190,7 @@ class ShopManage: session: EventSession, message: UniMsg, **kwargs, - ) -> str | MessageFactory | None: + ) -> str | UniMessage | None: """运行道具函数 参数: @@ -229,7 +229,7 @@ class ShopManage: goods_name: str, num: int, text: str, - ) -> str | MessageFactory | None: + ) -> str | UniMessage | None: """使用道具 参数: diff --git a/zhenxun/builtin_plugins/sign_in/__init__.py b/zhenxun/builtin_plugins/sign_in/__init__.py index 3eabb3f4..ac09256a 100644 --- a/zhenxun/builtin_plugins/sign_in/__init__.py +++ b/zhenxun/builtin_plugins/sign_in/__init__.py @@ -8,12 +8,12 @@ from nonebot_plugin_alconna import ( store_true, ) from nonebot_plugin_apscheduler import scheduler -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginCdBlock, PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.depends import UserName +from zhenxun.utils.message import MessageUtils from ._data_source import SignManage from .goods_register import driver @@ -121,8 +121,8 @@ async def _(session: EventSession, arparma: Arparma, nickname: str = UserName()) if session.id1: if path := await SignManage.sign(session, nickname): logger.info("签到成功", arparma.header_result, session=session) - await Image(path).finish() - return Text("用户id为空...").send() + await MessageUtils.build_message(path).finish() + return MessageUtils.build_message("用户id为空...").send() @_sign_matcher.assign("my") @@ -130,22 +130,24 @@ async def _(session: EventSession, arparma: Arparma, nickname: str = UserName()) if session.id1: if image := await SignManage.sign(session, nickname, True): logger.info("查看我的签到", arparma.header_result, session=session) - await Image(image).finish() - return Text("用户id为空...").send() + await MessageUtils.build_message(image).finish() + return MessageUtils.build_message("用户id为空...").send() @_sign_matcher.assign("list") async def _(session: EventSession, arparma: Arparma, num: int): gid = session.id3 or session.id2 if not arparma.find("global") and not gid: - await Text("私聊中无法查看 '好感度排行',请发送 '好感度总排行'").finish() + await MessageUtils.build_message( + "私聊中无法查看 '好感度排行',请发送 '好感度总排行'" + ).finish() if session.id1: if arparma.find("global"): gid = None if image := await SignManage.rank(session.id1, num, gid): logger.info("查看签到排行", arparma.header_result, session=session) - await Image(image.pic2bytes()).finish() - return Text("用户id为空...").send() + await MessageUtils.build_message(image).finish() + return MessageUtils.build_message("用户id为空...").send() @scheduler.scheduled_job( diff --git a/zhenxun/builtin_plugins/superuser/exec_sql.py b/zhenxun/builtin_plugins/superuser/exec_sql.py index 2badb14c..e99cd8f6 100644 --- a/zhenxun/builtin_plugins/superuser/exec_sql.py +++ b/zhenxun/builtin_plugins/superuser/exec_sql.py @@ -3,7 +3,6 @@ from nonebot.permission import SUPERUSER from nonebot.plugin import PluginMetadata from nonebot.rule import to_me from nonebot_plugin_alconna import UniMsg -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from tortoise import Tortoise @@ -12,6 +11,7 @@ from zhenxun.services.db_context import TestSQL from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import ImageTemplate +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="数据库操作", @@ -56,7 +56,7 @@ async def _(session: EventSession, message: UniMsg): if sql_text.startswith("exec"): sql_text = sql_text[4:].strip() if not sql_text: - await Text("需要执行的的SQL语句!").finish() + await MessageUtils.build_message("需要执行的的SQL语句!").finish() logger.info(f"执行SQL语句: {sql_text}", "exec", session=session) try: if not sql_text.lower().startswith("select"): @@ -77,11 +77,11 @@ async def _(session: EventSession, message: UniMsg): table = await ImageTemplate.table_page( "EXEC", f"总共有 {len(data_list)} 条数据捏", list(_column), data_list ) - await Image(table.pic2bytes()).send() + await MessageUtils.build_message(table).send() except Exception as e: logger.error("执行 SQL 语句失败...", session=session, e=e) - await Text(f"执行 SQL 语句失败... {type(e)}").finish() - await Text("执行 SQL 语句成功!").finish() + await MessageUtils.build_message(f"执行 SQL 语句失败... {type(e)}").finish() + await MessageUtils.build_message("执行 SQL 语句成功!").finish() @_table_matcher.handle() @@ -97,7 +97,7 @@ async def _(session: EventSession): table = await ImageTemplate.table_page( "数据库表", f"总共有 {len(data_list)} 张表捏", column_name, data_list ) - await Image(table.pic2bytes()).send() + await MessageUtils.build_message(table).send() except Exception as e: logger.error("获取表数据失败...", session=session, e=e) - await Text(f"获取表数据失败... {type(e)}").send() + await MessageUtils.build_message(f"获取表数据失败... {type(e)}").send() diff --git a/zhenxun/builtin_plugins/superuser/power/__ini__.py b/zhenxun/builtin_plugins/superuser/power/__ini__.py new file mode 100644 index 00000000..e69de29b diff --git a/zhenxun/builtin_plugins/superuser/request_manage.py b/zhenxun/builtin_plugins/superuser/request_manage.py index aa4a1e34..7f7c4497 100644 --- a/zhenxun/builtin_plugins/superuser/request_manage.py +++ b/zhenxun/builtin_plugins/superuser/request_manage.py @@ -14,7 +14,6 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH @@ -24,6 +23,7 @@ from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType, RequestHandleType, RequestType from zhenxun.utils.exception import NotFoundError from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import get_user_avatar usage = """ @@ -143,11 +143,13 @@ async def _( if handle_type == RequestHandleType.IGNORE: await FgRequest.ignore(id) except NotFoundError: - await Text("未发现此id的请求...").finish(reply=True) + await MessageUtils.build_message("未发现此id的请求...").finish(reply_to=True) except Exception: - await Text("其他错误, 可能flag已失效...").finish(reply=True) + await MessageUtils.build_message("其他错误, 可能flag已失效...").finish( + reply_to=True + ) logger.info("处理请求", arparma.header_result, session=session) - await Text("成功处理请求!").finish(reply=True) + await MessageUtils.build_message("成功处理请求!").finish(reply_to=True) @_read_matcher.handle() @@ -232,9 +234,9 @@ async def _( await result_image.text((15, 13), _type_text, fill=(140, 140, 143)) req_image_list.append(result_image) if not req_image_list: - await Text("没有任何请求喔...").finish(reply=True) + await MessageUtils.build_message("没有任何请求喔...").finish(reply_to=True) if len(req_image_list) == 1: - await Image(req_image_list[0].pic2bytes()).finish() + await MessageUtils.build_message(req_image_list[0]).finish() width = sum([img.width for img in req_image_list]) height = max([img.height for img in req_image_list]) background = BuildImage(width, height) @@ -242,8 +244,8 @@ async def _( await req_image_list[1].line((0, 10, 1, req_image_list[1].height - 10), width=1) await background.paste(req_image_list[1], (req_image_list[1].width, 0)) logger.info("查看请求", arparma.header_result, session=session) - await Image(background.pic2bytes()).finish() - await Text("没有任何请求喔...").finish(reply=True) + await MessageUtils.build_message(background).finish() + await MessageUtils.build_message("没有任何请求喔...").finish(reply_to=True) @_clear_matcher.handle() @@ -270,4 +272,4 @@ async def _( handle_type=RequestHandleType.IGNORE ) logger.info(f"清空{_type}请求", arparma.header_result, session=session) - await Text(f"已清空{_type}请求!").finish() + await MessageUtils.build_message(f"已清空{_type}请求!").finish() diff --git a/zhenxun/builtin_plugins/superuser/super_help.py b/zhenxun/builtin_plugins/superuser/super_help.py index 5136bb5c..5fa1e09e 100644 --- a/zhenxun/builtin_plugins/superuser/super_help.py +++ b/zhenxun/builtin_plugins/superuser/super_help.py @@ -1,15 +1,12 @@ import nonebot -from arclet.alconna import Args, Option from nonebot.permission import SUPERUSER from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Arparma, on_alconna from nonebot_plugin_alconna.matcher import AlconnaMatcher -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession -from zhenxun.configs.config import Config -from zhenxun.configs.path_config import DATA_PATH, IMAGE_PATH -from zhenxun.configs.utils import PluginExtraData, RegisterConfig +from zhenxun.configs.path_config import IMAGE_PATH +from zhenxun.configs.utils import PluginExtraData from zhenxun.models.plugin_info import PluginInfo from zhenxun.models.task_info import TaskInfo from zhenxun.services.log import logger @@ -21,6 +18,7 @@ from zhenxun.utils.image_utils import ( group_image, text2image, ) +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import admin_check, ensure_group __plugin_meta__ = PluginMetadata( @@ -156,6 +154,6 @@ async def _( try: await build_help() except EmptyError: - await Text("超级用户帮助为空").finish(reply=True) - await Image(SUPERUSER_HELP_IMAGE).send() + await MessageUtils.build_message("超级用户帮助为空").finish(reply_to=True) + await MessageUtils.build_message(SUPERUSER_HELP_IMAGE).send() logger.info("查看超级用户帮助", arparma.header_result, session=session) diff --git a/zhenxun/models/ban_console.py b/zhenxun/models/ban_console.py index b93d2fcb..0ab0fc69 100644 --- a/zhenxun/models/ban_console.py +++ b/zhenxun/models/ban_console.py @@ -68,7 +68,7 @@ class BanConsole(Model): level: 权限等级 返回: - bool: 权限判断 + bool: 权限判断,能否unban """ user = await cls._get_data(user_id, group_id) if user: @@ -76,7 +76,7 @@ class BanConsole(Model): f"检测用户被ban等级,user_level: {user.ban_level},level: {level}", target=f"{group_id}:{user_id}", ) - return user.ban_level >= level + return user.ban_level <= level return False @classmethod diff --git a/zhenxun/plugins/ai/__init__.py b/zhenxun/plugins/ai/__init__.py index 52862676..28e15354 100644 --- a/zhenxun/plugins/ai/__init__.py +++ b/zhenxun/plugins/ai/__init__.py @@ -4,7 +4,6 @@ from nonebot import on_message from nonebot.plugin import PluginMetadata from nonebot.rule import to_me from nonebot_plugin_alconna import UniMsg -from nonebot_plugin_saa import Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME, Config @@ -13,6 +12,7 @@ from zhenxun.models.friend_user import FriendUser from zhenxun.models.group_member_info import GroupInfoUser from zhenxun.services.log import logger from zhenxun.utils.depends import UserName +from zhenxun.utils.message import MessageUtils from .data_source import get_chat_result, hello, no_result @@ -82,6 +82,6 @@ async def _(message: UniMsg, session: EventSession, uname: str = UserName()): result = str(result) for t in Config.get_config("ai", "TEXT_FILTER"): result = result.replace(t, "*") - await Text(result).finish() + await MessageUtils.build_message(result).finish() else: await no_result().finish() diff --git a/zhenxun/plugins/ai/data_source.py b/zhenxun/plugins/ai/data_source.py index dbef7731..555f3885 100644 --- a/zhenxun/plugins/ai/data_source.py +++ b/zhenxun/plugins/ai/data_source.py @@ -3,13 +3,13 @@ import random import re import ujson as json -from nonebot_plugin_alconna import UniMsg -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import UniMessage, UniMsg from zhenxun.configs.config import NICKNAME, Config from zhenxun.configs.path_config import DATA_PATH, IMAGE_PATH from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.utils.message import MessageUtils from .utils import ai_message_manager @@ -24,7 +24,7 @@ anime_data = json.load(open(DATA_PATH / "anime.json", "r", encoding="utf8")) async def get_chat_result( message: UniMsg, user_id: str, nickname: str -) -> Text | MessageFactory | None: +) -> UniMessage | None: """获取 AI 返回值,顺序: 特殊回复 -> 图灵 -> 青云客 参数: @@ -42,7 +42,7 @@ async def get_chat_result( special_rst = await ai_message_manager.get_result(user_id, nickname) if special_rst: ai_message_manager.add_result(user_id, special_rst) - return Text(special_rst) + return MessageUtils.build_message(special_rst) if index == 5: index = 0 if len(text) < 6 and random.random() < 0.6: @@ -66,7 +66,7 @@ async def get_chat_result( ai_message_manager.add_result(user_id, rst) for t in Config.get_config("ai", "TEXT_FILTER"): rst = rst.replace(t, "*") - return Text(rst) + return MessageUtils.build_message(rst) # 图灵接口 @@ -182,7 +182,7 @@ async def xie_ai(text: str) -> str: return "" -def hello() -> MessageFactory: +def hello() -> UniMessage: """一些打招呼的内容""" result = random.choice( ( @@ -194,31 +194,27 @@ def hello() -> MessageFactory: ) ) img = random.choice(os.listdir(IMAGE_PATH / "zai")) - return MessageFactory([Image(IMAGE_PATH / "zai" / img), Text(result)]) + return MessageUtils.build_message([IMAGE_PATH / "zai" / img, result]) -def no_result() -> MessageFactory: +def no_result() -> UniMessage: """ 没有回答时的回复 """ - return MessageFactory( + return MessageUtils.build_message( [ - Text( - random.choice( - [ - "你在说啥子?", - f"纯洁的{NICKNAME}没听懂", - "下次再告诉你(下次一定)", - "你觉得我听懂了吗?嗯?", - "我!不!知!道!", - ] - ) - ), - Image( - IMAGE_PATH - / "noresult" - / random.choice(os.listdir(IMAGE_PATH / "noresult")) + random.choice( + [ + "你在说啥子?", + f"纯洁的{NICKNAME}没听懂", + "下次再告诉你(下次一定)", + "你觉得我听懂了吗?嗯?", + "我!不!知!道!", + ] ), + IMAGE_PATH + / "noresult" + / random.choice(os.listdir(IMAGE_PATH / "noresult")), ] ) diff --git a/zhenxun/plugins/alapi/cover.py b/zhenxun/plugins/alapi/cover.py index f6f5fd99..e26bf79c 100644 --- a/zhenxun/plugins/alapi/cover.py +++ b/zhenxun/plugins/alapi/cover.py @@ -1,10 +1,10 @@ from nonebot.plugin import PluginMetadata -from nonebot_plugin_alconna import Alconna, Args, Arparma, on_alconna -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import Alconna, Args, Arparma, Image, on_alconna from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from ._data_source import get_data @@ -34,11 +34,13 @@ async def _(session: EventSession, arparma: Arparma, url: str): params = {"c": url} data, code = await get_data(cover_url, params) if code != 200 and isinstance(data, str): - await Text(data).finish(reply=True) + await MessageUtils.build_message(data).finish(reply_to=True) data = data["data"] # type: ignore title = data["title"] # type: ignore img = data["cover"] # type: ignore - await MessageFactory([Text(f"title:{title}\n"), Image(img)]).send(reply=True) + await MessageUtils.build_message([f"title:{title}\n", Image(url=img)]).send( + reply_to=True + ) logger.info( f" 获取b站封面: {title} url:{img}", arparma.header_result, session=session ) diff --git a/zhenxun/plugins/black_word/black_word.py b/zhenxun/plugins/black_word/black_word.py index 1cad209f..8b819c6a 100644 --- a/zhenxun/plugins/black_word/black_word.py +++ b/zhenxun/plugins/black_word/black_word.py @@ -5,7 +5,6 @@ from nonebot.adapters import Bot from nonebot.permission import SUPERUSER from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, Option, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME @@ -13,6 +12,7 @@ from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from .data_source import set_user_punish, show_black_text_image @@ -163,14 +163,14 @@ async def _( try: date_ = datetime.strptime(date_str, "%Y-%m-%d") except ValueError: - await Text("日期格式错误,需要:年-月-日").finish() + await MessageUtils.build_message("日期格式错误,需要:年-月-日").finish() result = await show_black_text_image( user_id, group_id, date_, date_type_, ) - await Image(result.pic2bytes()).send() + await MessageUtils.build_message(result).send() @_show_punish_matcher.handle() @@ -212,7 +212,7 @@ async def _(): max_width, max_height, font="CJGaoDeGuo.otf", font_size=24, color="#E3DBD1" ) await A.text((10, 10), text) - await Image(A.pic2bytes()).send() + await MessageUtils.build_message(A).send() @_punish_matcher.handle() @@ -227,7 +227,7 @@ async def _( result = await set_user_punish( bot, uid, session.id2 or session.id3, id, punish_level ) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) logger.info( f"设置惩罚 uid:{uid} id_:{id} punish_level:{punish_level} --> {result}", arparma.header_result, diff --git a/zhenxun/plugins/check/__init__.py b/zhenxun/plugins/check/__init__.py index 8e8b91d7..198f9f60 100644 --- a/zhenxun/plugins/check/__init__.py +++ b/zhenxun/plugins/check/__init__.py @@ -8,6 +8,7 @@ from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils from .data_source import Check @@ -36,5 +37,5 @@ _matcher = on_alconna( @_matcher.handle() async def _(session: EventSession, arparma: Arparma): image = await check.show() - await Image(image.pic2bytes()).send() + await MessageUtils.build_message(image).send() logger.info("自检", arparma.header_result, session=session) diff --git a/zhenxun/plugins/coser.py b/zhenxun/plugins/coser.py index a3194c11..90062d51 100644 --- a/zhenxun/plugins/coser.py +++ b/zhenxun/plugins/coser.py @@ -2,10 +2,8 @@ import time from typing import Tuple from nonebot.adapters import Bot -from nonebot.params import RegexGroup from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config @@ -13,6 +11,7 @@ from zhenxun.configs.path_config import TEMP_PATH from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.utils.message import MessageUtils from zhenxun.utils.withdraw_manage import WithdrawManager __plugin_meta__ = PluginMetadata( @@ -72,8 +71,8 @@ async def _( path = TEMP_PATH / f"cos_cc{int(time.time())}.jpeg" try: await AsyncHttpx.download_file(url, path) - receipt = await Image(path).send() - message_id = receipt.extract_message_id().dict().get("message_id") + receipt = await MessageUtils.build_message(path).send() + message_id = receipt.msg_ids[0]["message_id"] if message_id and WithdrawManager.check(session, withdraw_time): WithdrawManager.append( bot, @@ -82,7 +81,7 @@ async def _( ) logger.info(f"发送cos", arparma.header_result, session=session) except Exception as e: - await Text("你cos给我看!").send() + await MessageUtils.build_message("你cos给我看!").send() logger.error( f"cos错误", arparma.header_result, diff --git a/zhenxun/plugins/draw_card/handles/base_handle.py b/zhenxun/plugins/draw_card/handles/base_handle.py index 1e48482a..28c39807 100644 --- a/zhenxun/plugins/draw_card/handles/base_handle.py +++ b/zhenxun/plugins/draw_card/handles/base_handle.py @@ -7,7 +7,6 @@ from typing import Generic, TypeVar import aiohttp import anyio import ujson as json -from nonebot_plugin_saa import Image from nonebot_plugin_saa import Image as SaaImage from nonebot_plugin_saa import MessageFactory, Text from PIL import Image diff --git a/zhenxun/plugins/epic/data_source.py b/zhenxun/plugins/epic/data_source.py index e0666a2b..87bc5a63 100644 --- a/zhenxun/plugins/epic/data_source.py +++ b/zhenxun/plugins/epic/data_source.py @@ -3,11 +3,13 @@ from datetime import datetime from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Bot as v11Bot from nonebot.adapters.onebot.v12 import Bot as v12Bot -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import Image, UniMessage from zhenxun.configs.config import NICKNAME from zhenxun.services.log import logger +from zhenxun.utils._build_image import BuildImage from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.utils.message import MessageUtils # 获取所有 Epic Game Store 促销游戏 @@ -56,7 +58,7 @@ async def get_epic_game_desp(name) -> dict | None: # https://github.com/SD4RK/epicstore_api/blob/master/examples/free_games_example.py async def get_epic_free( bot: Bot, type_event: str -) -> tuple[MessageFactory | list | str, int]: +) -> tuple[UniMessage | list | str, int]: games = await get_epic_game() if not games: return "Epic 可能又抽风啦,请稍后再试(", 404 @@ -86,18 +88,8 @@ async def get_epic_free( "%b.%d %H:%M" ) if type_event == "Group": - _message = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format( - game_corp, game_name, game_price, start_date, end_date - ) - data = { - "type": "node", - "data": { - "name": f"这里是{NICKNAME}酱", - "uin": f"{bot.self_id}", - "content": _message, - }, - } - msg_list.append(data) + _message = f"\n由 {game_corp} 公司发行的游戏 {game_name} ({game_price}) 在 UTC 时间 {start_date} 即将推出免费游玩,预计截至 {end_date}。" + msg_list.append(_message) else: msg = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format( game_corp, game_name, game_price, start_date, end_date @@ -171,36 +163,20 @@ async def get_epic_free( f"/p/{slugs[0]}" if len(slugs) else "" ) if isinstance(bot, (v11Bot, v12Bot)) and type_event == "Group": - _message = "[CQ:image,file={}]\n\nFREE now :: {} ({})\n{}\n此游戏由 {} 开发、{} 发行,将在 UTC 时间 {} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{}\n".format( - game_thumbnail, - game_name, - game_price, - game_desp, - game_dev, - game_pub, - end_date, - game_url, - ) - data = { - "type": "node", - "data": { - "name": f"这里是{NICKNAME}酱", - "uin": f"{bot.self_id}", - "content": _message, - }, - } - msg_list.append(data) + _message = [ + Image(url=game_thumbnail), + f"\nFREE now :: {game_name} ({game_price})\n{game_desp}\n此游戏由 {game_dev} 开发、{game_pub} 发行,将在 UTC 时间 {end_date} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{game_url}\n", + ] + msg_list.append(_message) else: _message = [] if game_thumbnail: - _message.append(Image(game_thumbnail)) + _message.append(Image(url=game_thumbnail)) _message.append( - Text( - f"\n\nFREE now :: {game_name} ({game_price})\n{game_desp}\n此游戏由 {game_dev} 开发、{game_pub} 发行,将在 UTC 时间 {end_date} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{game_url}\n" - ) + f"\n\nFREE now :: {game_name} ({game_price})\n{game_desp}\n此游戏由 {game_dev} 开发、{game_pub} 发行,将在 UTC 时间 {end_date} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{game_url}\n" ) - return MessageFactory(_message), 200 + return MessageUtils.build_message(_message), 200 except TypeError as e: # logger.info(str(e)) pass - return msg_list, 200 + return MessageUtils.template2forward(msg_list, bot.self_id), 200 diff --git a/zhenxun/plugins/fudu.py b/zhenxun/plugins/fudu.py index ffb1057d..338b0c3a 100644 --- a/zhenxun/plugins/fudu.py +++ b/zhenxun/plugins/fudu.py @@ -5,7 +5,6 @@ from nonebot.adapters import Event from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Image as alcImg from nonebot_plugin_alconna import UniMsg -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME, Config @@ -14,6 +13,7 @@ from zhenxun.configs.utils import PluginExtraData, RegisterConfig, Task from zhenxun.models.task_info import TaskInfo from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import get_download_image_hash +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import ensure_group __plugin_meta__ = PluginMetadata( @@ -113,7 +113,7 @@ async def _(message: UniMsg, event: Event, session: EventSession): if not plain_text and not image_list: return if plain_text and plain_text.startswith(f"@可爱的{NICKNAME}"): - await Text("复制粘贴的虚空艾特?").send(reply=True) + await MessageUtils.build_message("复制粘贴的虚空艾特?").send(reply=True) if image_list: img_hash = await get_download_image_hash(image_list[0], group_id) else: @@ -132,18 +132,20 @@ async def _(message: UniMsg, event: Event, session: EventSession): ) and not _manage.is_repeater(group_id): if random.random() < 0.2: if plain_text.startswith("打断施法"): - await Text("打断" + plain_text).finish() + await MessageUtils.build_message("打断" + plain_text).finish() else: - await Text("打断施法!").finish() + await MessageUtils.build_message("打断施法!").finish() _manage.set_repeater(group_id) rst = None if image_list and plain_text: - rst = MessageFactory( - [Text(plain_text), Image(TEMP_PATH / f"compare_{group_id}_img.jpg")] + rst = MessageUtils.build_message( + [plain_text, TEMP_PATH / f"compare_download_{group_id}_img.jpg"] ) elif image_list: - rst = Image(TEMP_PATH / f"compare_{group_id}_img.jpg") + rst = MessageUtils.build_message( + TEMP_PATH / f"compare_download_{group_id}_img.jpg" + ) elif plain_text: - rst = Text(plain_text) + rst = MessageUtils.build_message(plain_text) if rst: await rst.finish() diff --git a/zhenxun/plugins/gold_redbag/__init__.py b/zhenxun/plugins/gold_redbag/__init__.py index 1b047665..e3c851af 100644 --- a/zhenxun/plugins/gold_redbag/__init__.py +++ b/zhenxun/plugins/gold_redbag/__init__.py @@ -8,17 +8,16 @@ from nonebot.exception import ActionFailed from nonebot.permission import SUPERUSER from nonebot.plugin import PluginMetadata from nonebot.rule import to_me -from nonebot_plugin_alconna import Alconna, Args, Arparma -from nonebot_plugin_alconna import At as alcAt -from nonebot_plugin_alconna import Match, Option, on_alconna +from nonebot_plugin_alconna import Alconna, Args, Arparma, At, Match, Option, on_alconna from nonebot_plugin_apscheduler import scheduler -from nonebot_plugin_saa import Image, Mention, MessageFactory, Text +from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME from zhenxun.configs.utils import PluginCdBlock, PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.depends import GetConfig, UserName +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import PlatformUtils from zhenxun.utils.rules import ensure_group @@ -92,7 +91,7 @@ __plugin_meta__ = PluginMetadata( _red_bag_matcher = on_alconna( - Alconna("塞红包", Args["amount", int]["num", int, 5]["user?", alcAt]), + Alconna("塞红包", Args["amount", int]["num", int, 5]["user?", At]), aliases={"金币红包"}, priority=5, block=True, @@ -130,7 +129,7 @@ async def _( arparma: Arparma, amount: int, num: int, - user: Match[alcAt], + user: Match[At], default_interval: int = GetConfig(config="DEFAULT_INTERVAL"), user_name: str = UserName(), ): @@ -142,9 +141,9 @@ async def _( """以频道id为键""" user_id = session.id1 if not user_id: - await Text("用户id为空").finish() + await MessageUtils.build_message("用户id为空").finish() if not group_id: - await Text("群组id为空").finish() + await MessageUtils.build_message("群组id为空").finish() group_red_bag = RedBagManager.get_group_data(group_id) # 剩余过期时间 time_remaining = group_red_bag.check_timeout(user_id) @@ -153,13 +152,13 @@ async def _( if user_red_bag := group_red_bag.get_user_red_bag(user_id): now = time.time() if now < user_red_bag.start_time + default_interval: - await Text( + await MessageUtils.build_message( f"你的红包还没消化完捏...还剩下 {user_red_bag.num - len(user_red_bag.open_user)} 个! 请等待红包领取完毕..." f"(或等待{time_remaining}秒红包cd)" ).finish() result = await RedBagManager.check_gold(user_id, amount, session.platform) if result: - await Text(result).finish(at_sender=True) + await MessageUtils.build_message(result).finish(at_sender=True) await group_red_bag.add_red_bag( f"{user_name}的红包", int(amount), @@ -172,15 +171,13 @@ async def _( image = await RedBagManager.random_red_bag_background( user_id, platform=session.platform ) - message_list: list = [ - Text(f"{user_name}发起了金币红包\n金额: {amount}\n数量: {num}\n") - ] + message_list: list = [f"{user_name}发起了金币红包\n金额: {amount}\n数量: {num}\n"] if at_user: - message_list.append(Text("指定人: ")) - message_list.append(Mention(at_user)) - message_list.append(Text("\n")) - message_list.append(Image(image.pic2bytes())) - await MessageFactory(message_list).send() + message_list.append("指定人: ") + message_list.append(At(flag="user", target=at_user)) + message_list.append("\n") + message_list.append(image) + await MessageUtils.build_message(message_list).send() logger.info( f"塞入 {num} 个红包,共 {amount} 金币", arparma.header_result, session=session @@ -197,9 +194,9 @@ async def _( """以频道id为键""" user_id = session.id1 if not user_id: - await Text("用户id为空").finish() + await MessageUtils.build_message("用户id为空").finish() if not group_id: - await Text("群组id为空").finish() + await MessageUtils.build_message("群组id为空").finish() if group_red_bag := RedBagManager.get_group_data(group_id): open_data, settlement_list = await group_red_bag.open(user_id, session.platform) # send_msg = Text("没有红包给你开!") @@ -209,18 +206,18 @@ async def _( result_image = await RedBagManager.build_open_result_image( red_bag, user_id, amount, session.platform ) - send_msg.append( - Text(f"开启了 {red_bag.promoter} 的红包, 获取 {amount} 个金币\n") - ) - send_msg.append(Image(result_image.pic2bytes())) - send_msg.append(Text("\n")) + send_msg.append(f"开启了 {red_bag.promoter} 的红包, 获取 {amount} 个金币\n") + send_msg.append(result_image) + send_msg.append("\n") logger.info( f"抢到了 {red_bag.promoter}({red_bag.promoter_id}) 的红包,获取了{amount}个金币", "开红包", session=session, ) send_msg = ( - MessageFactory(send_msg[:-1]) if send_msg else Text("没有红包给你开!") + MessageUtils.build_message(send_msg[:-1]) + if send_msg + else MessageUtils.build_message("没有红包给你开!") ) await send_msg.send(reply=True) if settlement_list: @@ -228,8 +225,8 @@ async def _( result_image = await red_bag.build_amount_rank( rank_num, session.platform ) - await MessageFactory( - [Text(f"{red_bag.name}已结算\n"), Image(result_image.pic2bytes())] + await MessageUtils.build_message( + [f"{red_bag.name}已结算\n", result_image] ).send() @@ -242,17 +239,17 @@ async def _( group_id = session.id3 or session.id2 user_id = session.id1 if not user_id: - await Text("用户id为空").finish() + await MessageUtils.build_message("用户id为空").finish() if not group_id: - await Text("群组id为空").finish() + await MessageUtils.build_message("群组id为空").finish() if group_red_bag := RedBagManager.get_group_data(group_id): if user_red_bag := group_red_bag.get_user_red_bag(user_id): now = time.time() if now - user_red_bag.start_time < default_interval: - await Text( + await MessageUtils.build_message( f"你的红包还没有过时, 在 {int(default_interval - now + user_red_bag.start_time)} " f"秒后可以退回..." - ).finish(reply=True) + ).finish(reply_to=True) user_red_bag = group_red_bag.get_user_red_bag(user_id) if user_red_bag and ( data := await group_red_bag.settlement(user_id, session.platform) @@ -261,13 +258,13 @@ async def _( rank_num, session.platform ) logger.info(f"退回了红包 {data[0]} 金币", "红包退回", session=session) - await MessageFactory( + await MessageUtils.build_message( [ - Text(f"已成功退还了 " f"{data[0]} 金币\n"), - Image(image_result.pic2bytes()), + f"已成功退还了 " f"{data[0]} 金币\n", + image_result, ] ).finish(reply=True) - await Text("目前没有红包可以退回...").finish(reply=True) + await MessageUtils.build_message("目前没有红包可以退回...").finish(reply_to=True) @_festive_matcher.handle() @@ -352,4 +349,6 @@ async def _( except ActionFailed: logger.warning(f"节日红包图片信息发送失败...", "节日红包", group_id=g) if gl: - await Text(f"节日红包发送成功,累计成功发送 {_suc_cnt} 个群组!").send() + await MessageUtils.build_message( + f"节日红包发送成功,累计成功发送 {_suc_cnt} 个群组!" + ).send() diff --git a/zhenxun/plugins/group_welcome_msg.py b/zhenxun/plugins/group_welcome_msg.py index 064987e6..7148e8e9 100644 --- a/zhenxun/plugins/group_welcome_msg.py +++ b/zhenxun/plugins/group_welcome_msg.py @@ -3,12 +3,12 @@ import re import ujson as json from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Arparma, on_alconna -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import DATA_PATH from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.rules import ensure_group __plugin_meta__ = PluginMetadata( @@ -46,17 +46,17 @@ async def _( ) file = path / "text.json" if not file.exists(): - await Text("未设置群欢迎消息...").finish(reply=True) + await MessageUtils.build_message("未设置群欢迎消息...").finish(reply_to=True) message = json.load(open(file, encoding="utf8"))["message"] message_split = re.split(r"\[image:\d+\]", message) if len(message_split) == 1: - await Text(message_split[0]).finish(reply=True) + await MessageUtils.build_message(message_split[0]).finish(reply_to=True) idx = 0 data_list = [] for msg in message_split[:-1]: - data_list.append(Text(msg)) - data_list.append(Image(path / f"{idx}.png")) + data_list.append(msg) + data_list.append(path / f"{idx}.png") idx += 1 data_list.append(message_split[-1]) - await MessageFactory(data_list).send(reply=True) + await MessageUtils.build_message(data_list).send(reply_to=True) logger.info("查看群欢迎消息", arparma.header_result, session=session) diff --git a/zhenxun/plugins/luxun.py b/zhenxun/plugins/luxun.py index e407cb3a..1c1ab09c 100644 --- a/zhenxun/plugins/luxun.py +++ b/zhenxun/plugins/luxun.py @@ -1,12 +1,12 @@ from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH from zhenxun.configs.utils import BaseBlock, PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="鲁迅说", @@ -54,14 +54,14 @@ async def _(content: str, session: EventSession, arparma: Arparma): ) text = "" if len(content) > 40: - await Text("太长了,鲁迅说不完...").finish() + await MessageUtils.build_message("太长了,鲁迅说不完...").finish() while A.getsize(content)[0] > A.width - 50: n = int(len(content) / 2) text += content[:n] + "\n" content = content[n:] text += content if len(text.split("\n")) > 2: - await Text("太长了,鲁迅说不完...").finish() + await MessageUtils.build_message("太长了,鲁迅说不完...").finish() await A.text( (int((480 - A.getsize(text.split("\n")[0])[0]) / 2), 300), text, (255, 255, 255) ) @@ -70,5 +70,5 @@ async def _(content: str, session: EventSession, arparma: Arparma): "--鲁迅", "msyh.ttf", 30, (255, 255, 255) ) await A.paste(_sign, (320, 400)) - await Image(A.pic2bytes()).send() + await MessageUtils.build_message(A).send() logger.info(f"鲁迅说: {content}", arparma.header_result, session=session) diff --git a/zhenxun/plugins/one_friend/__init__.py b/zhenxun/plugins/one_friend/__init__.py index 67c5082e..0191084f 100644 --- a/zhenxun/plugins/one_friend/__init__.py +++ b/zhenxun/plugins/one_friend/__init__.py @@ -6,13 +6,13 @@ from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args from nonebot_plugin_alconna import At as alcAt from nonebot_plugin_alconna import Match, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import PlatformUtils __plugin_meta__ = PluginMetadata( @@ -44,9 +44,9 @@ _matcher.shortcut( async def _(bot: Bot, text: str, at: Match[alcAt], session: EventSession): gid = session.id3 or session.id2 if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() at_user = None if at.available: at_user = at.result.target @@ -75,5 +75,5 @@ async def _(bot: Bot, text: str, at: Match[alcAt], session: EventSession): await A.paste(content, (150, 38)) await A.text((150, 85), text, (125, 125, 125)) logger.info(f"发送有一个朋友: {text}", "我有一个朋友", session=session) - await Image(A.pic2bytes()).finish() - await Text("获取用户信息失败...").send() + await MessageUtils.build_message(A).finish() + await MessageUtils.build_message("获取用户信息失败...").send() diff --git a/zhenxun/plugins/open_cases/__init__.py b/zhenxun/plugins/open_cases/__init__.py index bac0bcc2..2798942e 100644 --- a/zhenxun/plugins/open_cases/__init__.py +++ b/zhenxun/plugins/open_cases/__init__.py @@ -6,12 +6,12 @@ from typing import List from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Arparma, Match from nonebot_plugin_apscheduler import scheduler -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginCdBlock, PluginExtraData, RegisterConfig, Task from zhenxun.services.log import logger from zhenxun.utils.image_utils import text2image +from zhenxun.utils.message import MessageUtils from .command import ( _group_open_matcher, @@ -126,11 +126,11 @@ async def _( if day.available: _day = day.result if _day > 180: - await Text("天数必须大于0且小于180").finish() + await MessageUtils.build_message("天数必须大于0且小于180").finish() result = await init_skin_trends(name, skin, abrasion, _day) if not result: - await Text("未查询到数据...").finish(reply=True) - await Image(result.pic2bytes()).send() + await MessageUtils.build_message("未查询到数据...").finish(reply_to=True) + await MessageUtils.build_message(result).send() logger.info( f"查看 [{name}:{skin}({abrasion})] 价格趋势", arparma.header_result, @@ -148,26 +148,26 @@ async def _(session: EventSession, arparma: Arparma): async def _(session: EventSession, arparma: Arparma, name: Match[str]): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() case_name = None if name.available: case_name = name.result.replace("武器箱", "").strip() result = await open_case(session.id1, gid, case_name, session) - await result.finish(reply=True) + await result.finish(reply_to=True) @_my_open_matcher.handle() async def _(session: EventSession, arparma: Arparma): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() - await Text( + await MessageUtils.build_message("群组id为空...").finish() + await MessageUtils.build_message( await total_open_statistics(session.id1, gid), - ).send(reply=True) + ).send(reply_to=True) logger.info("查询我的开箱", arparma.header_result, session=session) @@ -175,9 +175,9 @@ async def _(session: EventSession, arparma: Arparma): async def _(session: EventSession, arparma: Arparma): gid = session.id3 or session.id2 if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result = await group_statistics(gid) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) logger.info("查询群开箱统计", arparma.header_result, session=session) @@ -185,11 +185,11 @@ async def _(session: EventSession, arparma: Arparma): async def _(session: EventSession, arparma: Arparma): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result = await get_my_knifes(session.id1, gid) - await result.send(reply=True) + await result.send(reply_to=True) logger.info("查询我的金色", arparma.header_result, session=session) @@ -197,18 +197,18 @@ async def _(session: EventSession, arparma: Arparma): async def _(session: EventSession, arparma: Arparma, num: int, name: Match[str]): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() if num > 30: - await Text("开箱次数不要超过30啊笨蛋!").finish() + await MessageUtils.build_message("开箱次数不要超过30啊笨蛋!").finish() if num < 0: - await Text("再负开箱就扣你明天开箱数了!").finish() + await MessageUtils.build_message("再负开箱就扣你明天开箱数了!").finish() case_name = None if name.available: case_name = name.result.replace("武器箱", "").strip() result = await open_multiple_case(session.id1, gid, case_name, num, session) - await result.send(reply=True) + await result.send(reply_to=True) logger.info(f"{num}连开箱", arparma.header_result, session=session) @@ -229,8 +229,8 @@ async def _(session: EventSession, arparma: Arparma, name: Match[str]): skin_list.append(f"{skin_name}") text = "武器箱:\n" + "\n".join(case_list) + "\n皮肤:\n" + ", ".join(skin_list) img = await text2image(text, padding=20, color="#f9f6f2") - await MessageFactory( - [Text("未指定武器箱, 当前已包含武器箱/皮肤\n"), Image(img.pic2bytes())] + await MessageUtils.build_message( + ["未指定武器箱, 当前已包含武器箱/皮肤\n", img] ).finish() if case_name in ["ALL", "ALL1"]: if case_name == "ALL": @@ -239,34 +239,40 @@ async def _(session: EventSession, arparma: Arparma, name: Match[str]): else: case_list = list(KNIFE2ID.keys()) type_ = "罕见皮肤" - await Text(f"即将更新所有{type_}, 请稍等").send() + await MessageUtils.build_message(f"即将更新所有{type_}, 请稍等").send() for i, case_name in enumerate(case_list): try: info = await update_skin_data(case_name, arparma.find("s")) if "请先登录" in info: - await Text(f"未登录, 已停止更新, 请配置BUFF token...").send() + await MessageUtils.build_message( + f"未登录, 已停止更新, 请配置BUFF token..." + ).send() return rand = random.randint(300, 500) result = f"更新全部{type_}完成" if i < len(case_list) - 1: next_case = case_list[i + 1] result = f"将在 {rand} 秒后更新下一{type_}: {next_case}" - await Text(f"{info}, {result}").send() + await MessageUtils.build_message(f"{info}, {result}").send() logger.info(f"info, {result}", "更新武器箱", session=session) await asyncio.sleep(rand) except Exception as e: logger.error(f"更新{type_}: {case_name}", session=session, e=e) - await Text(f"更新{type_}: {case_name} 发生错误: {type(e)}: {e}").send() - await Text(f"更新全部{type_}完成").send() + await MessageUtils.build_message( + f"更新{type_}: {case_name} 发生错误: {type(e)}: {e}" + ).send() + await MessageUtils.build_message(f"更新全部{type_}完成").send() else: - await Text(f"开始{arparma.header_result}: {case_name}, 请稍等").send() + await MessageUtils.build_message( + f"开始{arparma.header_result}: {case_name}, 请稍等" + ).send() try: - await Text(await update_skin_data(case_name, arparma.find("s"))).send( - at_sender=True - ) + await MessageUtils.build_message( + await update_skin_data(case_name, arparma.find("s")) + ).send(at_sender=True) except Exception as e: logger.error(f"{arparma.header_result}: {case_name}", session=session, e=e) - await Text( + await MessageUtils.build_message( f"成功{arparma.header_result}: {case_name} 发生错误: {type(e)}: {e}" ).send() @@ -278,9 +284,9 @@ async def _(session: EventSession, arparma: Arparma, name: Match[str]): case_name = name.result.strip() result = await build_case_image(case_name) if isinstance(result, str): - await Text(result).send() + await MessageUtils.build_message(result).send() else: - await Image(result.pic2bytes()).send() + await MessageUtils.build_message(result).send() logger.info("查看武器箱", arparma.header_result, session=session) @@ -289,9 +295,9 @@ async def _(session: EventSession, arparma: Arparma, name: Match[str]): case_name = None if name.available: case_name = name.result.strip() - await Text("开始更新图片...").send(reply=True) + await MessageUtils.build_message("开始更新图片...").send(reply_to=True) await download_image(case_name) - await Text("更新图片完成...").send(at_sender=True) + await MessageUtils.build_message("更新图片完成...").send(at_sender=True) logger.info("更新武器箱图片", arparma.header_result, session=session) diff --git a/zhenxun/plugins/open_cases/open_cases_c.py b/zhenxun/plugins/open_cases/open_cases_c.py index 74f642aa..f56aa9fe 100644 --- a/zhenxun/plugins/open_cases/open_cases_c.py +++ b/zhenxun/plugins/open_cases/open_cases_c.py @@ -3,7 +3,7 @@ import random import re from datetime import datetime -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import UniMessage from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config @@ -11,6 +11,7 @@ from zhenxun.configs.path_config import IMAGE_PATH from zhenxun.models.sign_user import SignUser from zhenxun.services.log import logger from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import cn2py from .build_image import draw_card @@ -96,7 +97,7 @@ async def get_user_max_count(user_id: str) -> int: async def open_case( user_id: str, group_id: str, case_name: str | None, session: EventSession -) -> MessageFactory: +) -> UniMessage: """开箱 参数: @@ -111,7 +112,7 @@ async def open_case( user_id = str(user_id) group_id = str(group_id) if not CaseManager.CURRENT_CASES: - return MessageFactory([Text("未收录任何武器箱")]) + return MessageUtils.build_message("未收录任何武器箱") if not case_name: case_name = random.choice(CaseManager.CURRENT_CASES) # type: ignore if case_name not in CaseManager.CURRENT_CASES: @@ -128,16 +129,12 @@ async def open_case( max_count = await get_user_max_count(user_id) # 一天次数上限 if user.today_open_total >= max_count: - return MessageFactory( - [ - Text( - f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)" - ) - ] + return MessageUtils.build_message( + f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)" ) skin_list = await random_skin(1, case_name) # type: ignore if not skin_list: - return MessageFactory(Text("未抽取到任何皮肤")) + return MessageUtils.build_message("未抽取到任何皮肤") skin, rand = skin_list[0] rand = str(rand)[:11] case_price = 0 @@ -176,13 +173,11 @@ async def open_case( logger.debug(f"添加 1 条开箱日志", "开箱", session=session) over_count = max_count - user.today_open_total img = await draw_card(skin, rand) - return MessageFactory( + return MessageUtils.build_message( [ - Text(f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n"), - Image(img.pic2bytes()), - Text( - f"\n箱子单价:{case_price}\n花费:{17 + case_price:.2f}\n:{ridicule_result}" - ), + f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n", + img, + f"\n箱子单价:{case_price}\n花费:{17 + case_price:.2f}\n:{ridicule_result}", ] ) @@ -193,7 +188,7 @@ async def open_multiple_case( case_name: str | None, num: int = 10, session: EventSession | None = None, -) -> MessageFactory: +) -> UniMessage: """多连开箱 参数: @@ -209,17 +204,12 @@ async def open_multiple_case( user_id = str(user_id) group_id = str(group_id) if not CaseManager.CURRENT_CASES: - return MessageFactory([Text("未收录任何武器箱")]) + return MessageUtils.build_message("未收录任何武器箱") if not case_name: case_name = random.choice(CaseManager.CURRENT_CASES) # type: ignore if case_name not in CaseManager.CURRENT_CASES: - return MessageFactory( - [ - Text( - "武器箱未收录, 当前可用武器箱:\n" - + ", ".join(CaseManager.CURRENT_CASES) - ) - ] + return MessageUtils.build_message( + "武器箱未收录, 当前可用武器箱:\n" + ", ".join(CaseManager.CURRENT_CASES) ) user, _ = await OpenCasesUser.get_or_create( user_id=user_id, @@ -228,21 +218,13 @@ async def open_multiple_case( ) max_count = await get_user_max_count(user_id) if user.today_open_total >= max_count: - return MessageFactory( - [ - Text( - f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)" - ) - ] + return MessageUtils.build_message( + f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)" ) if max_count - user.today_open_total < num: - return MessageFactory( - [ - Text( - f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)" - f"\n剩余开箱次数:{max_count - user.today_open_total}" - ) - ] + return MessageUtils.build_message( + f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)" + f"\n剩余开箱次数:{max_count - user.today_open_total}" ) logger.debug(f"尝试开启武器箱: {case_name}", "开箱", session=session) case = cn2py(case_name) # type: ignore @@ -250,7 +232,7 @@ async def open_multiple_case( img_list = [] skin_list = await random_skin(num, case_name) # type: ignore if not skin_list: - return MessageFactory([Text("未抽取到任何皮肤...")]) + return MessageUtils.build_message("未抽取到任何皮肤...") total_price = 0 log_list = [] now = datetime.now() @@ -314,13 +296,11 @@ async def open_multiple_case( result = "" for color_name in skin_count: result += f"[{color_name}:{skin_count[color_name]}] " - return MessageFactory( + return MessageUtils.build_message( [ - Text(f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n"), - Image(mark_image.pic2bytes()), - Text( - f"\n{result[:-1]}\n箱子单价:{case_price}\n总获取金额:{total_price:.2f}\n总花费:{(17 + case_price) * num:.2f}" - ), + f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n", + mark_image, + f"\n{result[:-1]}\n箱子单价:{case_price}\n总获取金额:{total_price:.2f}\n总花费:{(17 + case_price) * num:.2f}", ] ) @@ -382,7 +362,7 @@ async def group_statistics(group_id: str): ) -async def get_my_knifes(user_id: str, group_id: str) -> MessageFactory: +async def get_my_knifes(user_id: str, group_id: str) -> UniMessage: """获取我的金色 参数: @@ -397,7 +377,7 @@ async def get_my_knifes(user_id: str, group_id: str) -> MessageFactory: user_id=user_id, group_id=group_id, color="KNIFE" ).all() if not data_list: - return MessageFactory([Text("您木有开出金色级别的皮肤喔...")]) + return MessageUtils.build_message("您木有开出金色级别的皮肤喔...") length = len(data_list) if length < 5: h = 600 @@ -427,7 +407,7 @@ async def get_my_knifes(user_id: str, group_id: str) -> MessageFactory: await knife_img.text((5, 560), f"\t价格:{skin.price}") image_list.append(knife_img) A = await A.auto_paste(image_list, 5) - return MessageFactory([Image(A.pic2bytes())]) + return MessageUtils.build_message(A) async def get_old_knife(user_id: str, group_id: str) -> list[OpenCasesLog]: diff --git a/zhenxun/plugins/parse_bilibili/__init__.py b/zhenxun/plugins/parse_bilibili/__init__.py index f42f78ae..1d319093 100644 --- a/zhenxun/plugins/parse_bilibili/__init__.py +++ b/zhenxun/plugins/parse_bilibili/__init__.py @@ -4,8 +4,7 @@ import time import ujson as json from nonebot import on_message from nonebot.plugin import PluginMetadata -from nonebot_plugin_alconna import Hyper, UniMsg -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import Hyper, Image, UniMsg from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import TEMP_PATH @@ -14,6 +13,7 @@ from zhenxun.models.task_info import TaskInfo from zhenxun.services.log import logger from zhenxun.utils.enum import PluginType from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.utils.message import MessageUtils from .information_container import InformationContainer from .parse_url import parse_bili_url @@ -138,12 +138,10 @@ async def _(session: EventSession, message: UniMsg): _tmp[vd_url] = time.time() _path = TEMP_PATH / f"{aid}.jpg" await AsyncHttpx.download_file(pic, _path) - await MessageFactory( + await MessageUtils.build_message( [ - Image(_path), - Text( - f"av{aid}\n标题:{title}\nUP:{author}\n上传日期:{date}\n回复:{reply},收藏:{favorite},投币:{coin}\n点赞:{like},弹幕:{danmuku}\n{vd_url}" - ), + _path, + f"av{aid}\n标题:{title}\nUP:{author}\n上传日期:{date}\n回复:{reply},收藏:{favorite},投币:{coin}\n点赞:{like},弹幕:{danmuku}\n{vd_url}", ] ).send() @@ -161,14 +159,12 @@ async def _(session: EventSession, message: UniMsg): parent_area_name = live_info.get("parent_area_name", "") # 父分区 logger.info(f"解析bilibili转发 {live_url}", "b站解析", session=session) _tmp[live_url] = time.time() - await MessageFactory( + await MessageUtils.build_message( [ - Image(user_cover), - Text( - f"开播用户:https://space.bilibili.com/{uid}\n开播时间:{live_time}\n直播分区:{parent_area_name}——>{area_name}\n标题:{title}\n简介:{description}\n直播截图:\n" - ), - Image(keyframe), - Text(f"{live_url}"), + Image(url=user_cover), + f"开播用户:https://space.bilibili.com/{uid}\n开播时间:{live_time}\n直播分区:{parent_area_name}——>{area_name}\n标题:{title}\n简介:{description}\n直播截图:\n", + Image(url=keyframe), + f"{live_url}", ] ).send() elif image_info: diff --git a/zhenxun/plugins/parse_bilibili/get_image.py b/zhenxun/plugins/parse_bilibili/get_image.py index e2f4ddcb..bbc005c5 100644 --- a/zhenxun/plugins/parse_bilibili/get_image.py +++ b/zhenxun/plugins/parse_bilibili/get_image.py @@ -1,12 +1,13 @@ import os import re -from nonebot_plugin_saa import Image +from nonebot_plugin_alconna import UniMessage from zhenxun.configs.path_config import TEMP_PATH from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncPlaywright from zhenxun.utils.image_utils import BuildImage +from zhenxun.utils.message import MessageUtils from zhenxun.utils.user_agent import get_user_agent_str @@ -21,7 +22,7 @@ async def resize(path: str): await A.save(path) -async def get_image(url) -> Image | None: +async def get_image(url) -> UniMessage | None: """获取Bilibili链接的截图,并返回base64格式的图片 参数: @@ -101,7 +102,7 @@ async def get_image(url) -> Image | None: except Exception as e: logger.warning(f"尝试解析bilibili转发失败", e=e) return None - return Image(screenshot_path) + return MessageUtils.build_message(screenshot_path) except Exception as e: logger.error(f"尝试解析bilibili转发失败", e=e) return None diff --git a/zhenxun/plugins/pid_search.py b/zhenxun/plugins/pid_search.py index 2d1b7c05..97fc4d40 100644 --- a/zhenxun/plugins/pid_search.py +++ b/zhenxun/plugins/pid_search.py @@ -3,7 +3,6 @@ from asyncio.exceptions import TimeoutError from nonebot.adapters import Bot from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, on_alconna -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config @@ -11,6 +10,7 @@ from zhenxun.configs.path_config import TEMP_PATH from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import change_pixiv_image_links from zhenxun.utils.withdraw_manage import WithdrawManager @@ -69,13 +69,17 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, pid: str): session=session, e=e, ) - await Text(f"发生了一些错误..{type(e)}:{e}").finish() + await MessageUtils.build_message(f"发生了一些错误..{type(e)}:{e}").finish() else: if data.get("error"): - await Text(data["error"]["user_message"]).finish(reply=True) + await MessageUtils.build_message(data["error"]["user_message"]).finish( + reply_to=True + ) data = data["illust"] if not data["width"] and not data["height"]: - await Text(f"没有搜索到 PID:{pid} 的图片").finish(reply=True) + await MessageUtils.build_message( + f"没有搜索到 PID:{pid} 的图片" + ).finish(reply_to=True) pid = data["id"] title = data["title"] author = data["user"]["name"] @@ -93,20 +97,20 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, pid: str): TEMP_PATH / f"pid_search_{session.id1}_{i}.png", headers=headers, ): - await Text("图片下载失败了...").finish(reply=True) + await MessageUtils.build_message("图片下载失败了...").finish( + reply_to=True + ) tmp = "" if session.id3 or session.id2: tmp = "\n【注】将在30后撤回......" - receipt = await MessageFactory( + receipt = await MessageUtils.build_message( [ - Text( - f"title:{title}\n" - f"pid:{pid}\n" - f"author:{author}\n" - f"author_id:{author_id}\n" - ), - Image(TEMP_PATH / f"pid_search_{session.id1}_{i}.png"), - Text(f"{tmp}"), + f"title:{title}\n" + f"pid:{pid}\n" + f"author:{author}\n" + f"author_id:{author_id}\n", + TEMP_PATH / f"pid_search_{session.id1}_{i}.png", + f"{tmp}", ] ).send() logger.info( @@ -114,8 +118,8 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, pid: str): ) if session.id3 or session.id2: await WithdrawManager.withdraw_message( - bot, receipt.extract_message_id().message_id, 30 # type: ignore + bot, receipt.msg_ids[0]["message_id"], 30 # type: ignore ) break else: - await Text("图片下载失败了...").send(reply=True) + await Text("图片下载失败了...").send(reply_to=True) diff --git a/zhenxun/plugins/pix_gallery/_data_source.py b/zhenxun/plugins/pix_gallery/_data_source.py index a15eec28..7e9db221 100644 --- a/zhenxun/plugins/pix_gallery/_data_source.py +++ b/zhenxun/plugins/pix_gallery/_data_source.py @@ -192,7 +192,7 @@ async def search_image( return pid_count, pic_count -async def get_image(img_url: str, user_id: str) -> str | Path | None: +async def get_image(img_url: str, user_id: str) -> Path | None: """下载图片 参数: @@ -200,7 +200,7 @@ async def get_image(img_url: str, user_id: str) -> str | Path | None: user_id: 用户id 返回: - str | Path | None: 图片名称 + Path | None: 图片名称 """ if "https://www.pixiv.net/artworks" in img_url: pid = img_url.rsplit("/", maxsplit=1)[-1] diff --git a/zhenxun/plugins/pix_gallery/pix.py b/zhenxun/plugins/pix_gallery/pix.py index d67e5ada..2f8d25c3 100644 --- a/zhenxun/plugins/pix_gallery/pix.py +++ b/zhenxun/plugins/pix_gallery/pix.py @@ -11,12 +11,12 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config from zhenxun.configs.utils import BaseBlock, PluginExtraData, RegisterConfig from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import PlatformUtils from zhenxun.utils.withdraw_manage import WithdrawManager @@ -96,7 +96,7 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) global PIX_RATIO, OMEGA_RATIO gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if PIX_RATIO is None: pix_omega_pixiv_ratio = Config.get_config("pix", "PIX_OMEGA_PIXIV_RATIO") PIX_RATIO = pix_omega_pixiv_ratio[0] / ( @@ -117,7 +117,9 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) if (nsfw_tag == 1 and not Config.get_config("pix", "ALLOW_GROUP_SETU")) or ( nsfw_tag == 2 and not Config.get_config("pix", "ALLOW_GROUP_R18") ): - await Text("你不能看这些噢,这些都是是留给管理员看的...").finish() + await MessageUtils.build_message( + "你不能看这些噢,这些都是是留给管理员看的..." + ).finish() if (n := len(spt)) == 1: if str(spt[0]).isdigit() and int(spt[0]) < 100: num = int(spt[0]) @@ -132,7 +134,9 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) session.id1 in bot.config.superusers and num > 30 ): num = random.randint(1, 10) - await Text(f"太贪心了,就给你发 {num}张 好了").send() + await MessageUtils.build_message( + f"太贪心了,就给你发 {num}张 好了" + ).send() spt = spt[:-1] keyword = " ".join(spt) pix_num = int(num * PIX_RATIO) + 15 if PIX_RATIO != 0 else 0 @@ -149,7 +153,7 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) elif keyword.lower().startswith("pid"): pid = keyword.replace("pid", "").replace(":", "").replace(":", "") if not str(pid).isdigit(): - await Text("PID必须是数字...").finish(reply=True) + await MessageUtils.build_message("PID必须是数字...").finish(reply_to=True) all_image = await Pixiv.query_images( pid=int(pid), r18=1 if nsfw_tag == 2 else 0 ) @@ -169,15 +173,15 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) all_image.append(x) tmp_.append(x.pid) if not all_image: - await Text(f"未在图库中找到与 {keyword} 相关Tag/UID/PID的图片...").finish( - reply=True - ) + await MessageUtils.build_message( + f"未在图库中找到与 {keyword} 相关Tag/UID/PID的图片..." + ).finish(reply_to=True) msg_list = [] for _ in range(num): img_url = None author = None if not all_image: - await Text("坏了...发完了,没图了...").finish() + await MessageUtils.build_message("坏了...发完了,没图了...").finish() img = random.choice(all_image) all_image.remove(img) # type: ignore if isinstance(img, OmegaPixivIllusts): @@ -194,24 +198,22 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) if _img: if Config.get_config("pix", "SHOW_INFO"): msg_list.append( - MessageFactory( + MessageUtils.build_message( [ - Text( - f"title:{title}\n" - f"author:{author}\n" - f"PID:{pid}\nUID:{uid}\n" - ), - Image(_img), + f"title:{title}\n" + f"author:{author}\n" + f"PID:{pid}\nUID:{uid}\n", + _img, ] ) ) else: - msg_list.append(Image(_img)) + msg_list.append(_img) logger.info( f" 查看PIX图库PID: {pid}", arparma.header_result, session=session ) else: - msg_list.append(Text("这张图似乎下载失败了")) + msg_list.append(MessageUtils.build_message("这张图似乎下载失败了")) logger.info( f" 查看PIX图库PID: {pid},下载图片出错", arparma.header_result, @@ -225,7 +227,7 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) for msg in msg_list: receipt = await msg.send() if receipt: - message_id = receipt.extract_message_id().message_id + message_id = receipt.msg_ids[0]["message_id"] await WithdrawManager.withdraw_message( bot, str(message_id), @@ -236,7 +238,7 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, tags: Match[str]) for msg in msg_list: receipt = await msg.send() if receipt: - message_id = receipt.extract_message_id().message_id + message_id = receipt.msg_ids[0]["message_id"] await WithdrawManager.withdraw_message( bot, message_id, diff --git a/zhenxun/plugins/pix_gallery/pix_show_info.py b/zhenxun/plugins/pix_gallery/pix_show_info.py index 9dcf1af9..cb1cbf2a 100644 --- a/zhenxun/plugins/pix_gallery/pix_show_info.py +++ b/zhenxun/plugins/pix_gallery/pix_show_info.py @@ -1,11 +1,11 @@ from nonebot.adapters import Bot from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from ._data_source import gen_keyword_pic, get_keyword_num from ._model.pixiv_keyword_user import PixivKeywordUser @@ -40,8 +40,10 @@ async def _(arparma: Arparma, session: EventSession): "keyword", flat=True ) if not data: - await Text("您目前没有提供任何Pixiv搜图关键字...").finish(reply=True) - await Text(f"您目前提供的如下关键字:\n\t" + ",".join(data)).send() # type: ignore + await MessageUtils.build_message("您目前没有提供任何Pixiv搜图关键字...").finish( + reply_to=True + ) + await MessageUtils.build_message(f"您目前提供的如下关键字:\n\t" + ",".join(data)).send() # type: ignore logger.info("查看我的pix关键词", arparma.header_result, session=session) @@ -52,12 +54,14 @@ async def _(bot: Bot, arparma: Arparma, session: EventSession): image = await gen_keyword_pic( _pass_keyword, not_pass_keyword, session.id1 in bot.config.superusers ) - await Image(image.pic2bytes()).send() # type: ignore + await MessageUtils.build_message(image).send() # type: ignore else: if session.id1 in bot.config.superusers: - await Text(f"目前没有已收录或待收录的搜索关键词...").send() + await MessageUtils.build_message( + f"目前没有已收录或待收录的搜索关键词..." + ).send() else: - await Text(f"目前没有已收录的搜索关键词...").send() + await MessageUtils.build_message(f"目前没有已收录的搜索关键词...").send() @_pix_matcher.handle() @@ -66,7 +70,7 @@ async def _(bot: Bot, arparma: Arparma, session: EventSession, keyword: Match[st if keyword.available: _keyword = keyword.result count, r18_count, count_, setu_count, r18_count_ = await get_keyword_num(_keyword) - await Text( + await MessageUtils.build_message( f"PIX图库:{_keyword}\n" f"总数:{count + r18_count}\n" f"美图:{count}\n" diff --git a/zhenxun/plugins/pixiv_rank_search/__init__.py b/zhenxun/plugins/pixiv_rank_search/__init__.py index a82a269e..01945cd8 100644 --- a/zhenxun/plugins/pixiv_rank_search/__init__.py +++ b/zhenxun/plugins/pixiv_rank_search/__init__.py @@ -13,12 +13,12 @@ from nonebot_plugin_alconna import ( on_alconna, store_true, ) -from nonebot_plugin_saa import MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config from zhenxun.configs.utils import BaseBlock, PluginExtraData, RegisterConfig from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import is_valid_date from .data_source import download_pixiv_imgs, get_pixiv_urls, search_pixiv_urls @@ -148,34 +148,40 @@ async def _( ): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() code = 0 info_list = [] _datetime = None if datetime.available: _datetime = datetime.result if not is_valid_date(_datetime): - await Text("日期不合法,示例: 2018-4-25").finish(reply=True) + await MessageUtils.build_message("日期不合法,示例: 2018-4-25").finish( + reply_to=True + ) if rank_type in [6, 7, 8, 9]: if gid: - await Text("羞羞脸!私聊里自己看!").finish(at_sender=True) + await MessageUtils.build_message("羞羞脸!私聊里自己看!").finish( + at_sender=True + ) info_list, code = await get_pixiv_urls( rank_dict[str(rank_type)], num, date=_datetime ) if code != 200 and info_list: if isinstance(info_list[0], str): - await Text(info_list[0]).finish() + await MessageUtils.build_message(info_list[0]).finish() if not info_list: - await Text("没有找到啊,等等再试试吧~V").send(at_sender=True) + await MessageUtils.build_message("没有找到啊,等等再试试吧~V").send( + at_sender=True + ) for title, author, urls in info_list: try: images = await download_pixiv_imgs(urls, session.id1) # type: ignore - await MessageFactory( - [Text(f"title: {title}\n"), Text(f"author: {author}\n")] + images + await MessageUtils.build_message( + [f"title: {title}\nauthor: {author}\n"] + images # type: ignore ).send() except (NetworkError, TimeoutError): - await Text("这张图网络直接炸掉了!").send() + await MessageUtils.build_message("这张图网络直接炸掉了!").send() logger.info( f" 查看了P站排行榜 rank_type{rank_type}", arparma.header_result, session=session ) @@ -187,29 +193,33 @@ async def _( ): gid = session.id3 or session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if gid: if arparma.find("r") and not Config.get_config( "pixiv_rank_search", "ALLOW_GROUP_R18" ): - await Text("(脸红#) 你不会害羞的 八嘎!").finish(at_sender=True) + await MessageUtils.build_message("(脸红#) 你不会害羞的 八嘎!").finish( + at_sender=True + ) r18 = 0 if arparma.find("r") else 1 info_list = None keyword = keyword.replace("#", " ") info_list, code = await search_pixiv_urls(keyword, num, page, r18) if code != 200 and isinstance(info_list[0], str): - await Text(info_list[0]).finish() + await MessageUtils.build_message(info_list[0]).finish() if not info_list: - await Text("没有找到啊,等等再试试吧~V").finish(at_sender=True) + await MessageUtils.build_message("没有找到啊,等等再试试吧~V").finish( + at_sender=True + ) for title, author, urls in info_list: try: images = await download_pixiv_imgs(urls, session.id1) # type: ignore - await MessageFactory( - [Text(f"title: {title}\n"), Text(f"author: {author}\n")] + images + await MessageUtils.build_message( + [f"title: {title}\nauthor: {author}\n"] + images # type: ignore ).send() except (NetworkError, TimeoutError): - await Text("这张图网络直接炸掉了!").send() + await MessageUtils.build_message("这张图网络直接炸掉了!").send() logger.info( f" 查看了搜索 {keyword} R18:{r18}", arparma.header_result, session=session ) diff --git a/zhenxun/plugins/pixiv_rank_search/data_source.py b/zhenxun/plugins/pixiv_rank_search/data_source.py index 28b31b53..d3f54dfe 100644 --- a/zhenxun/plugins/pixiv_rank_search/data_source.py +++ b/zhenxun/plugins/pixiv_rank_search/data_source.py @@ -121,7 +121,7 @@ async def parser_data( async def download_pixiv_imgs( urls: list[str], user_id: str, forward_msg_index: int | None = None -) -> list[Image]: +) -> list[Path]: """下载图片 参数: @@ -156,12 +156,12 @@ async def download_pixiv_imgs( change_img_md5(file) image = None if forward_msg_index is not None: - image = Image( + image = ( TEMP_PATH / f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg" ) else: - image = Image(TEMP_PATH / f"{user_id}_{index}_pixiv.jpg") + image = TEMP_PATH / f"{user_id}_{index}_pixiv.jpg" if image: result_list.append(image) index += 1 diff --git a/zhenxun/plugins/poke/__init__.py b/zhenxun/plugins/poke/__init__.py index 555ebf15..7f46be96 100644 --- a/zhenxun/plugins/poke/__init__.py +++ b/zhenxun/plugins/poke/__init__.py @@ -5,12 +5,12 @@ from nonebot import on_notice from nonebot.adapters.onebot.v11 import PokeNotifyEvent from nonebot.adapters.onebot.v11.message import MessageSegment from nonebot.plugin import PluginMetadata -from nonebot_plugin_saa import Image, MessageFactory, Text from zhenxun.configs.path_config import IMAGE_PATH, RECORD_PATH from zhenxun.configs.utils import PluginExtraData from zhenxun.models.ban_console import BanConsole from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import CountLimiter __plugin_meta__ = PluginMetadata( @@ -66,10 +66,10 @@ async def _(event: PokeNotifyEvent): index = random.randint( 0, len(os.listdir(IMAGE_PATH / "image_management" / path)) - 1 ) - await MessageFactory( + await MessageUtils.build_message( [ - Text(f"id: {index}"), - Image(IMAGE_PATH / "image_management" / path / f"{index}.jpg"), + f"id: {index}", + IMAGE_PATH / "image_management" / path / f"{index}.jpg", ] ).send() logger.info(f"USER {event.user_id} 戳了戳我") @@ -79,7 +79,8 @@ async def _(event: PokeNotifyEvent): await poke_.send(result) await poke_.send(voice.split("_")[1]) logger.info( - f'USER {event.user_id} 戳了戳我 回复: {result} \n {voice.split("_")[1]}' + f'USER {event.user_id} 戳了戳我 回复: {result} \n {voice.split("_")[1]}', + "戳一戳", ) else: await poke_.send(MessageSegment("poke", {"qq": event.user_id})) diff --git a/zhenxun/plugins/russian/__init__.py b/zhenxun/plugins/russian/__init__.py index db797e64..ee25fdfd 100644 --- a/zhenxun/plugins/russian/__init__.py +++ b/zhenxun/plugins/russian/__init__.py @@ -3,12 +3,12 @@ from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Arparma from nonebot_plugin_alconna import At as alcAt from nonebot_plugin_alconna import Match, UniMsg -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.depends import UserName +from zhenxun.utils.message import MessageUtils from .command import ( _accept_matcher, @@ -79,20 +79,22 @@ async def _( ): gid = session.id2 if message.extract_plain_text() == "取消": - await Text("已取消装弹...").finish() + await MessageUtils.build_message("已取消装弹...").finish() if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() if money <= 0: - await Text("赌注金额必须大于0!").finish(reply=True) + await MessageUtils.build_message("赌注金额必须大于0!").finish(reply_to=True) if num in ["取消", "算了"]: - await Text("已取消装弹...").finish() + await MessageUtils.build_message("已取消装弹...").finish() if not num.isdigit(): - await Text("输入的子弹数必须是数字!").finish(reply=True) + await MessageUtils.build_message("输入的子弹数必须是数字!").finish( + reply_to=True + ) b_num = int(num) if b_num < 0 or b_num > 6: - await Text("子弹数量必须在1-6之间!").finish(reply=True) + await MessageUtils.build_message("子弹数量必须在1-6之间!").finish(reply_to=True) _at_user = at_user.result.target if at_user.available else None rus = Russian( at_user=_at_user, player1=(session.id1, uname), money=money, bullet_num=b_num @@ -110,9 +112,9 @@ async def _( async def _(bot: Bot, session: EventSession, arparma: Arparma, uname: str = UserName()): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result = await russian_manage.accept(bot, gid, session.id1, uname) await result.send() logger.info(f"俄罗斯轮盘接受对决", arparma.header_result, session=session) @@ -122,9 +124,9 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, uname: str = User async def _(session: EventSession, arparma: Arparma, uname: str = UserName()): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result = russian_manage.refuse(gid, session.id1, uname) await result.send() logger.info(f"俄罗斯轮盘拒绝对决", arparma.header_result, session=session) @@ -134,9 +136,9 @@ async def _(session: EventSession, arparma: Arparma, uname: str = UserName()): async def _(session: EventSession, arparma: Arparma): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result = await russian_manage.settlement(gid, session.id1, session.platform) await result.send() logger.info(f"俄罗斯轮盘结算", arparma.header_result, session=session) @@ -146,9 +148,9 @@ async def _(session: EventSession, arparma: Arparma): async def _(bot: Bot, session: EventSession, arparma: Arparma, uname: str = UserName()): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() result, settle = await russian_manage.shoot( bot, gid, session.id1, uname, session.platform ) @@ -162,11 +164,11 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, uname: str = User async def _(session: EventSession, arparma: Arparma): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() user, _ = await RussianUser.get_or_create(user_id=session.id1, group_id=gid) - await Text( + await MessageUtils.build_message( f"俄罗斯轮盘\n" f"总胜利场次:{user.win_count}\n" f"当前连胜:{user.winning_streak}\n" @@ -176,7 +178,7 @@ async def _(session: EventSession, arparma: Arparma): f"最高连败:{user.max_losing_streak}\n" f"赚取金币:{user.make_money}\n" f"输掉金币:{user.lose_money}", - ).send(reply=True) + ).send(reply_to=True) logger.info(f"俄罗斯轮盘查看战绩", arparma.header_result, session=session) @@ -184,16 +186,16 @@ async def _(session: EventSession, arparma: Arparma): async def _(session: EventSession, arparma: Arparma, rank_type: str, num: int): gid = session.id2 if not session.id1: - await Text("用户id为空...").finish() + await MessageUtils.build_message("用户id为空...").finish() if not gid: - await Text("群组id为空...").finish() + await MessageUtils.build_message("群组id为空...").finish() if 51 < num or num < 10: num = 10 result = await russian_manage.rank(session.id1, gid, rank_type, num) if isinstance(result, str): - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) result.show() - await Image(result.pic2bytes()).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) logger.info( f"查看轮盘排行: {rank_type} 数量: {num}", arparma.header_result, session=session ) diff --git a/zhenxun/plugins/search_image/__init__.py b/zhenxun/plugins/search_image/__init__.py index d98e9ca1..38e86de0 100644 --- a/zhenxun/plugins/search_image/__init__.py +++ b/zhenxun/plugins/search_image/__init__.py @@ -1,15 +1,16 @@ +from pathlib import Path + from nonebot.adapters import Bot from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma from nonebot_plugin_alconna import Image as alcImg from nonebot_plugin_alconna import Match, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import PlatformUtils -from zhenxun.utils.utils import template2forward from .saucenao import get_saucenao_image @@ -48,7 +49,7 @@ _matcher = on_alconna( ) -async def get_image_info(mod: str, url: str) -> str | list[Image | Text] | None: +async def get_image_info(mod: str, url: str) -> str | list[str | Path] | None: if mod == "saucenao": return await get_saucenao_image(url) @@ -73,21 +74,21 @@ async def _( ): gid = session.id3 or session.id2 if not image.url: - await Text("图片url为空...").finish() - await Text("开始处理图片...").send() + await MessageUtils.build_message("图片url为空...").finish() + await MessageUtils.build_message("开始处理图片...").send() info_list = await get_image_info(mode, image.url) if isinstance(info_list, str): - await Text(info_list).finish(at_sender=True) + await MessageUtils.build_message(info_list).finish(at_sender=True) if not info_list: - await Text("未查询到...").finish() + await MessageUtils.build_message("未查询到...").finish() platform = PlatformUtils.get_platform(bot) if "qq" == platform and gid: - forward = template2forward(info_list, bot.self_id) # type: ignore + forward = MessageUtils.template2forward(info_list[1:], bot.self_id) # type: ignore await bot.send_group_forward_msg( group_id=int(gid), messages=forward, # type: ignore ) else: for info in info_list[1:]: - await info.send() + await MessageUtils.build_message(info).send() logger.info(f" 识图: {image.url}", arparma.header_result, session=session) diff --git a/zhenxun/plugins/search_image/saucenao.py b/zhenxun/plugins/search_image/saucenao.py index c76c96b2..eab44fab 100644 --- a/zhenxun/plugins/search_image/saucenao.py +++ b/zhenxun/plugins/search_image/saucenao.py @@ -1,6 +1,5 @@ import random - -from nonebot_plugin_saa import Image, Text +from pathlib import Path from zhenxun.configs.config import Config from zhenxun.configs.path_config import TEMP_PATH @@ -12,7 +11,7 @@ API_URL_ASCII2D = "https://ascii2d.net/search/url/" API_URL_IQDB = "https://iqdb.org/" -async def get_saucenao_image(url: str) -> str | list[Image | Text]: +async def get_saucenao_image(url: str) -> str | list[str | Path]: """获取图片源 参数: @@ -44,7 +43,7 @@ async def get_saucenao_image(url: str) -> str | list[Image | Text]: msg_list = [] index = random.randint(0, 10000) if await AsyncHttpx.download_file(url, TEMP_PATH / f"saucenao_search_{index}.jpg"): - msg_list.append(Image(TEMP_PATH / f"saucenao_search_{index}.jpg")) + msg_list.append(TEMP_PATH / f"saucenao_search_{index}.jpg") for info in data: try: similarity = info["header"]["similarity"] @@ -57,7 +56,7 @@ async def get_saucenao_image(url: str) -> str | list[Image | Text]: tmp += f'source:{info["data"]["ext_urls"][0]}\n' except KeyError: tmp += f'source:{info["header"]["thumbnail"]}\n' - msg_list.append(Text(tmp[:-1])) + msg_list.append(tmp[:-1]) except Exception as e: logger.warning(f"识图获取图片信息发生错误", e=e) return msg_list diff --git a/zhenxun/plugins/send_setu_/send_setu/__init__.py b/zhenxun/plugins/send_setu_/send_setu/__init__.py index fd341730..8f9bd2ff 100644 --- a/zhenxun/plugins/send_setu_/send_setu/__init__.py +++ b/zhenxun/plugins/send_setu_/send_setu/__init__.py @@ -2,7 +2,6 @@ import random from typing import Tuple from nonebot.adapters import Bot -from nonebot.adapters.onebot.v11 import MessageSegment from nonebot.matcher import Matcher from nonebot.message import run_postprocessor from nonebot.plugin import PluginMetadata @@ -23,11 +22,11 @@ from zhenxun.configs.utils import PluginCdBlock, PluginExtraData, RegisterConfig from zhenxun.models.sign_user import SignUser from zhenxun.models.user_console import UserConsole from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.platform import PlatformUtils -from zhenxun.utils.utils import template2forward from zhenxun.utils.withdraw_manage import WithdrawManager -from ._data_source import Image, SetuManage, base_config +from ._data_source import SetuManage, base_config __plugin_meta__ = PluginMetadata( name="色图", @@ -196,7 +195,7 @@ async def _( if is_r18 and gid: """群聊中禁止查看r18""" if not base_config.get("ALLOW_GROUP_R18"): - await Text( + await MessageUtils.build_message( random.choice( [ "这种不好意思的东西怎么可能给这么多人看啦", @@ -209,11 +208,11 @@ async def _( """指定id""" result = await SetuManage.get_setu(local_id=local_id.result) if isinstance(result, str): - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply=True) await result[0].finish() result_list = await SetuManage.get_setu(tags=_tags, num=_num, is_r18=is_r18) if isinstance(result_list, str): - await Text(result_list).finish(reply=True) + await MessageUtils.build_message(result_list).finish(reply=True) max_once_num2forward = base_config.get("MAX_ONCE_NUM2FORWARD") platform = PlatformUtils.get_platform(bot) if ( @@ -223,7 +222,7 @@ async def _( and len(result_list) >= max_once_num2forward ): logger.debug("使用合并转发转发色图数据", arparma.header_result, session=session) - forward = template2forward(result_list, bot.self_id) # type: ignore + forward = MessageUtils.template2forward(result_list, bot.self_id) # type: ignore await bot.send_group_forward_msg( group_id=int(gid), messages=forward, # type: ignore @@ -233,7 +232,7 @@ async def _( logger.info(f"发送色图 {result}", arparma.header_result, session=session) receipt = await result.send() if receipt: - message_id = receipt.extract_message_id().message_id # type: ignore + message_id = receipt.msg_ids[0]["message_id"] await WithdrawManager.withdraw_message( bot, message_id, diff --git a/zhenxun/plugins/send_setu_/send_setu/_data_source.py b/zhenxun/plugins/send_setu_/send_setu/_data_source.py index e54099d0..6bac3d22 100644 --- a/zhenxun/plugins/send_setu_/send_setu/_data_source.py +++ b/zhenxun/plugins/send_setu_/send_setu/_data_source.py @@ -3,13 +3,14 @@ import random from pathlib import Path from asyncpg import UniqueViolationError -from nonebot_plugin_saa import Image, MessageFactory, Text +from nonebot_plugin_alconna import UniMessage from zhenxun.configs.config import NICKNAME, Config from zhenxun.configs.path_config import IMAGE_PATH, TEMP_PATH from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx from zhenxun.utils.image_utils import compressed_image +from zhenxun.utils.message import MessageUtils from zhenxun.utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu @@ -36,7 +37,7 @@ class SetuManage: num: int = 10, tags: list[str] | None = None, is_r18: bool = False, - ) -> list[MessageFactory] | str: + ) -> list[UniMessage] | str: """获取色图 参数: @@ -82,7 +83,7 @@ class SetuManage: result_list.append(cls.init_image_message(file_path, setu)) if flag: result_list.append( - MessageFactory([Text("坏了,已经没图了,被榨干了!")]) + MessageUtils.build_message("坏了,已经没图了,被榨干了!") ) return result_list data_list = await cls.search_lolicon(tags, num, is_r18) @@ -101,17 +102,19 @@ class SetuManage: for setu in data_list: file = await cls.get_image(setu) if isinstance(file, str): - result_list.append(MessageFactory([Text(file)])) + result_list.append(MessageUtils.build_message(file)) continue result_list.append(cls.init_image_message(file, setu)) if not result_list: return "没找到符合条件的色图..." if flag: - result_list.append(MessageFactory([Text("坏了,已经没图了,被榨干了!")])) + result_list.append( + MessageUtils.build_message("坏了,已经没图了,被榨干了!") + ) return result_list @classmethod - def init_image_message(cls, file: Path, setu: Setu) -> MessageFactory: + def init_image_message(cls, file: Path, setu: Setu) -> UniMessage: """初始化图片发送消息 参数: @@ -119,20 +122,18 @@ class SetuManage: setu: Setu 返回: - MessageFactory: 发送消息内容 + UniMessage: 发送消息内容 """ data_list = [] if base_config.get("SHOW_INFO"): data_list.append( - Text( - f"id:{setu.local_id or ''}\n" - f"title:{setu.title}\n" - f"author:{setu.author}\n" - f"PID:{setu.pid}\n" - ) + f"id:{setu.local_id or ''}\n" + f"title:{setu.title}\n" + f"author:{setu.author}\n" + f"PID:{setu.pid}\n" ) - data_list.append(Image(file)) - return MessageFactory(data_list) + data_list.append(file) + return MessageUtils.build_message(data_list) @classmethod async def get_setu_list( @@ -167,7 +168,7 @@ class SetuManage: return image_list @classmethod - def get_luo(cls, impression: float) -> MessageFactory | None: + def get_luo(cls, impression: float) -> UniMessage | None: """罗翔 参数: @@ -179,15 +180,13 @@ class SetuManage: if initial_setu_probability := base_config.get("INITIAL_SETU_PROBABILITY"): probability = float(impression) + initial_setu_probability * 100 if probability < random.randint(1, 101): - return MessageFactory( + return MessageUtils.build_message( [ - Text("我为什么要给你发这个?"), - Image( - IMAGE_PATH - / "luoxiang" - / random.choice(os.listdir(IMAGE_PATH / "luoxiang")) - ), - Text(f"\n(快向{NICKNAME}签到提升好感度吧!)"), + "我为什么要给你发这个?", + IMAGE_PATH + / "luoxiang" + / random.choice(os.listdir(IMAGE_PATH / "luoxiang")), + f"\n(快向{NICKNAME}签到提升好感度吧!)", ] ) return None diff --git a/zhenxun/plugins/send_voice/dinggong.py b/zhenxun/plugins/send_voice/dinggong.py index 270e7dac..a01129ca 100644 --- a/zhenxun/plugins/send_voice/dinggong.py +++ b/zhenxun/plugins/send_voice/dinggong.py @@ -4,12 +4,12 @@ import random from nonebot.plugin import PluginMetadata from nonebot.rule import to_me from nonebot_plugin_alconna import Alconna, Arparma, UniMessage, Voice, on_alconna -from nonebot_plugin_saa import Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import RECORD_PATH from zhenxun.configs.utils import PluginCdBlock, PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils __plugin_meta__ = PluginMetadata( name="钉宫骂我", @@ -41,11 +41,11 @@ path = RECORD_PATH / "dinggong" @_matcher.handle() async def _(session: EventSession, arparma: Arparma): if not path.exists(): - await Text("钉宫语音文件夹不存在...").finish() + await MessageUtils.build_message("钉宫语音文件夹不存在...").finish() files = os.listdir(path) if not files: - await Text("钉宫语音文件夹为空...").finish() + await MessageUtils.build_message("钉宫语音文件夹为空...").finish() voice = random.choice(files) await UniMessage([Voice(path=path / voice)]).send() - await Text(voice.split("_")[1]).send() + await MessageUtils.build_message(voice.split("_")[1]).send() logger.info(f"发送钉宫骂人: {voice}", arparma.header_result, session=session) diff --git a/zhenxun/plugins/statistics/_data_source.py b/zhenxun/plugins/statistics/_data_source.py index 526d4713..e83707b1 100644 --- a/zhenxun/plugins/statistics/_data_source.py +++ b/zhenxun/plugins/statistics/_data_source.py @@ -6,7 +6,6 @@ from zhenxun.models.group_console import GroupConsole from zhenxun.models.group_member_info import GroupInfoUser from zhenxun.models.plugin_info import PluginInfo from zhenxun.models.statistics import Statistics -from zhenxun.models.user_console import UserConsole from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import BuildImage, BuildMat, MatType diff --git a/zhenxun/plugins/statistics/statistics_handle.py b/zhenxun/plugins/statistics/statistics_handle.py index f756ad2a..bea1b2d8 100644 --- a/zhenxun/plugins/statistics/statistics_handle.py +++ b/zhenxun/plugins/statistics/statistics_handle.py @@ -13,6 +13,7 @@ from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData from zhenxun.utils.enum import PluginType +from zhenxun.utils.message import MessageUtils from ._data_source import StatisticsManage @@ -155,8 +156,8 @@ async def _( plugin_name, arparma.find("global"), st, uid, gid ): if isinstance(result, str): - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply_to=True) else: - await Image(result.pic2bytes()).send() + await MessageUtils.build_message(result).send() else: await Text("获取数据失败...").send() diff --git a/zhenxun/plugins/statistics/statistics_hook.py b/zhenxun/plugins/statistics/statistics_hook.py index 27062a4a..bf8f959c 100644 --- a/zhenxun/plugins/statistics/statistics_hook.py +++ b/zhenxun/plugins/statistics/statistics_hook.py @@ -27,11 +27,10 @@ async def _( ): plugin = await PluginInfo.get_or_none(module=matcher.plugin_name) plugin_type = plugin.plugin_type if plugin else None - if ( - plugin_type == PluginType.NORMAL - and matcher.priority not in [1, 999] - and matcher.plugin_name not in ["update_info", "statistics_handle"] - ): + if plugin_type == PluginType.NORMAL and matcher.plugin_name not in [ + "update_info", + "statistics_handle", + ]: await Statistics.create( user_id=session.id1, group_id=session.id3 or session.id2, diff --git a/zhenxun/plugins/translate/__init__.py b/zhenxun/plugins/translate/__init__.py index 62dc15c9..146705f0 100644 --- a/zhenxun/plugins/translate/__init__.py +++ b/zhenxun/plugins/translate/__init__.py @@ -1,12 +1,12 @@ from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, Option, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger from zhenxun.utils.depends import CheckConfig from zhenxun.utils.image_utils import ImageTemplate +from zhenxun.utils.message import MessageUtils from .data_source import language, translate_message @@ -19,7 +19,7 @@ __plugin_meta__ = PluginMetadata( 示例: 翻译 你好: 将中文翻译为英文 翻译 Hello: 将英文翻译为中文 - + 翻译 你好 -to 希腊语: 将"你好"翻译为希腊语 翻译 你好: 允许form和to使用中文 翻译 你好 -form:中文 to:日语 你好: 指定原语种并将"你好"翻译为日文 @@ -57,7 +57,7 @@ async def _(session: EventSession, arparma: Arparma): for key, value in language.items(): data_list.append([key, value]) image = await ImageTemplate.table_page("翻译语种", "", column_list, data_list) - await Image(image.pic2bytes()).send() + await MessageUtils.build_message(image).send() logger.info(f"查看翻译语种", arparma.header_result, session=session) @@ -79,11 +79,11 @@ async def _( values = language.values() keys = language.keys() if source not in values and source not in keys: - await Text("源语种不支持...").finish() + await MessageUtils.build_message("源语种不支持...").finish() if to not in values and to not in keys: - await Text("目标语种不支持...").finish() + await MessageUtils.build_message("目标语种不支持...").finish() result = await translate_message(text, source, to) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply=True) logger.info( f"source: {source}, to: {to}, 翻译: {text}", arparma.header_result, diff --git a/zhenxun/plugins/wbtop/__init__.py b/zhenxun/plugins/wbtop/__init__.py index 60ab1e37..9b760c9a 100644 --- a/zhenxun/plugins/wbtop/__init__.py +++ b/zhenxun/plugins/wbtop/__init__.py @@ -1,12 +1,12 @@ from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, on_alconna -from nonebot_plugin_saa import Image, Text from nonebot_plugin_session import EventSession from zhenxun.configs.path_config import IMAGE_PATH from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncPlaywright +from zhenxun.utils.message import MessageUtils from .data_source import get_hot_image @@ -33,7 +33,7 @@ _matcher = on_alconna(Alconna("微博热搜", Args["idx?", int]), priority=5, bl async def _(session: EventSession, arparma: Arparma, idx: Match[int]): result, data_list = await get_hot_image() if isinstance(result, str): - await Text(result).finish(reply=True) + await MessageUtils.build_message(result).finish(reply=True) if idx.available: _idx = idx.result url = data_list[_idx - 1]["url"] @@ -45,12 +45,12 @@ async def _(session: EventSession, arparma: Arparma, idx: Match[int]): wait_time=12, ) if img: - await Image(file).send() + await MessageUtils.build_message(file).send() logger.info( f"查询微博热搜 Id: {_idx}", arparma.header_result, session=session ) else: - await Text("获取图片失败...").send() + await MessageUtils.build_message("获取图片失败...").send() else: - await Image(result.pic2bytes()).send() + await MessageUtils.build_message(result).send() logger.info(f"查询微博热搜", arparma.header_result, session=session) diff --git a/zhenxun/plugins/wbtop/data_source.py b/zhenxun/plugins/wbtop/data_source.py index c734b1ec..e9c20627 100644 --- a/zhenxun/plugins/wbtop/data_source.py +++ b/zhenxun/plugins/wbtop/data_source.py @@ -50,11 +50,11 @@ async def get_hot_image() -> tuple[BuildImage | str, list]: await bk.paste(wbtop_bk) text_bk = BuildImage(700, 32 * 50, color="#797979") image_list = [] - for i, data in enumerate(data): - title = f"{i + 1}. {data['hot_word']}" - hot = str(data["hot_word_num"]) + for i, _data in enumerate(data): + title = f"{i + 1}. {_data['hot_word']}" + hot = str(_data["hot_word_num"]) img = BuildImage(700, 30, font_size=20) - w, h = img.getsize(title) + _, h = img.getsize(title) await img.text((10, int((30 - h) / 2)), title) await img.text((580, int((30 - h) / 2)), hot) image_list.append(img) diff --git a/zhenxun/plugins/word_bank/_data_source.py b/zhenxun/plugins/word_bank/_data_source.py index 467490f3..c9a53a1b 100644 --- a/zhenxun/plugins/word_bank/_data_source.py +++ b/zhenxun/plugins/word_bank/_data_source.py @@ -1,10 +1,12 @@ +from nonebot_plugin_alconna import At from nonebot_plugin_alconna import At as alcAt +from nonebot_plugin_alconna import Image from nonebot_plugin_alconna import Image as alcImage from nonebot_plugin_alconna import Text as alcText from nonebot_plugin_alconna import UniMessage, UniMsg -from nonebot_plugin_saa import Image, Mention, MessageFactory, Text from zhenxun.utils.image_utils import ImageTemplate +from zhenxun.utils.message import MessageUtils from ._model import WordBank @@ -210,7 +212,7 @@ class WordBankManage: index: int | None = None, group_id: str | None = None, word_scope: int | None = 1, - ) -> Text | MessageFactory | Image: + ) -> UniMessage: """获取群词条 参数: @@ -228,25 +230,25 @@ class WordBankManage: word_scope, ) if not _problem_list: - return Text(problem) + return MessageUtils.build_message(problem) for msg in _problem_list: _text = str(msg) - if isinstance(msg, Mention): - _text = f"[at:{msg.data}]" + if isinstance(msg, At): + _text = f"[at:{msg.target}]" elif isinstance(msg, Image): - _text = msg.data + _text = msg.url or msg.path elif isinstance(msg, list): _text = [] for m in msg: __text = str(m) - if isinstance(m, Mention): - __text = f"[at:{m.data['user_id']}]" + if isinstance(m, At): + __text = f"[at:{m.target}]" elif isinstance(m, Image): # TODO: 显示词条回答图片 # __text = (m.data["image"], 30, 30) __text = "[图片]" _text.append(__text) - msg_list.append("".join(_text)) + msg_list.append("".join(str(_text))) column_name = ["序号", "回答内容"] data_list = [] for index, msg in enumerate(msg_list): @@ -254,7 +256,7 @@ class WordBankManage: template_image = await ImageTemplate.table_page( f"词条 {problem} 的回答", None, column_name, data_list ) - return Image(template_image.pic2bytes()) + return MessageUtils.build_message(template_image) else: result = [] if group_id: @@ -265,7 +267,7 @@ class WordBankManage: raise Exception("群组id和词条范围不能都为空") global_problem_list = await WordBank.get_problem_by_scope(0) if not _problem_list and not global_problem_list: - return Text("未收录任何词条...") + return MessageUtils.build_message("未收录任何词条...") column_name = ["序号", "关键词", "匹配类型", "收录用户"] data_list = [list(s) for s in _problem_list] for i in range(len(data_list)): @@ -273,7 +275,7 @@ class WordBankManage: group_image = await ImageTemplate.table_page( "群组内词条" if group_id else "私聊词条", None, column_name, data_list ) - result.append(Image(group_image.pic2bytes())) + result.append(group_image) if global_problem_list: data_list = [list(s) for s in global_problem_list] for i in range(len(data_list)): @@ -281,5 +283,5 @@ class WordBankManage: global_image = await ImageTemplate.table_page( "全局词条", None, column_name, data_list ) - result.append(Image(global_image.pic2bytes())) - return MessageFactory(result) + result.append(global_image) + return MessageUtils.build_message(result) diff --git a/zhenxun/plugins/word_bank/_model.py b/zhenxun/plugins/word_bank/_model.py index eef86941..abf03779 100644 --- a/zhenxun/plugins/word_bank/_model.py +++ b/zhenxun/plugins/word_bank/_model.py @@ -8,7 +8,7 @@ from typing import Any from nonebot_plugin_alconna import At as alcAt from nonebot_plugin_alconna import Image as alcImage from nonebot_plugin_alconna import Text as alcText -from nonebot_plugin_saa import Image, Mention, MessageFactory, Text +from nonebot_plugin_alconna import UniMessage from tortoise import Tortoise, fields from tortoise.expressions import Q from typing_extensions import Self @@ -17,6 +17,7 @@ from zhenxun.configs.path_config import DATA_PATH from zhenxun.services.db_context import Model from zhenxun.utils.http_utils import AsyncHttpx from zhenxun.utils.image_utils import get_img_hash +from zhenxun.utils.message import MessageUtils from ._config import int2type @@ -208,7 +209,7 @@ class WordBank(Model): user_id: int, group_id: int, query: Self | None = None, - ) -> MessageFactory | Text: + ) -> UniMessage: """将占位符转换为实际内容 参数: @@ -232,16 +233,16 @@ class WordBank(Model): answer_split = re.split(rf"\[.*:placeholder_.*?]", answer) placeholder_split = query.placeholder.split(",") for index, ans in enumerate(answer_split): - result_list.append(Text(ans)) + result_list.append(ans) if index < len(type_list): t = type_list[index] p = placeholder_split[index] if t == "image": - result_list.append(Image(path / p)) + result_list.append(path / p) elif t == "at": - result_list.append(Mention(p)) - return MessageFactory(result_list) - return Text(answer) + result_list.append(alcAt(flag="user", target=p)) + return MessageUtils.build_message(result_list) + return MessageUtils.build_message(answer) @classmethod async def check_problem( @@ -296,7 +297,7 @@ class WordBank(Model): problem: str, word_scope: int | None = None, word_type: int | None = None, - ) -> Text | MessageFactory | None: + ) -> UniMessage | None: """根据问题内容获取随机回答 参数: @@ -324,7 +325,7 @@ class WordBank(Model): random_answer, ) if random_answer.placeholder - else Text(random_answer.answer) + else MessageUtils.build_message(random_answer.answer) ) @classmethod @@ -334,7 +335,7 @@ class WordBank(Model): index: int | None = None, group_id: str | None = None, word_scope: int | None = 0, - ) -> tuple[str, list[Text | MessageFactory]]: + ) -> tuple[str, list[UniMessage]]: """获取指定问题所有回答 参数: @@ -344,7 +345,7 @@ class WordBank(Model): word_scope: 词条范围 返回: - tuple[str, list[Text | MessageFactory]]: 问题和所有回答 + tuple[str, list[UniMessage]]: 问题和所有回答 """ if index is not None: # TODO: group_by和order_by不能同时使用 diff --git a/zhenxun/plugins/word_bank/word_handle.py b/zhenxun/plugins/word_bank/word_handle.py index 820ae244..0f70a44a 100644 --- a/zhenxun/plugins/word_bank/word_handle.py +++ b/zhenxun/plugins/word_bank/word_handle.py @@ -9,14 +9,15 @@ from nonebot.params import RegexGroup from nonebot.plugin import PluginMetadata from nonebot.typing import T_State from nonebot_plugin_alconna import AlconnaQuery, Arparma +from nonebot_plugin_alconna import Image from nonebot_plugin_alconna import Image as alcImage from nonebot_plugin_alconna import Match, Query, UniMsg -from nonebot_plugin_saa import Image, MessageFactory, Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import Config from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from ._config import scope2int, type2int from ._data_source import WordBankManage, get_answer, get_img_and_at_list, get_problem @@ -96,7 +97,7 @@ async def _( user_id = session.id1 group_id = session.id3 or session.id2 if not group_id and user_id not in bot.config.superusers: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) word_scope, word_type, problem, answer = reg_group if not word_scope and not group_id: word_scope = "私聊" @@ -105,11 +106,13 @@ async def _( and word_scope in ["全局", "私聊"] and user_id not in bot.config.superusers ): - await Text("权限不足,无法添加该范围词条...").finish(reply=True) + await MessageUtils.build_message("权限不足,无法添加该范围词条...").finish( + reply_to=True + ) if (not problem or not problem.strip()) and word_type != "图片": - await Text("词条问题不能为空!").finish(reply=True) + await MessageUtils.build_message("词条问题不能为空!").finish(reply_to=True) if (not answer or not answer.strip()) and not len(img_list) and not len(at_list): - await Text("词条回答不能为空!").finish(reply=True) + await MessageUtils.build_message("词条回答不能为空!").finish(reply_to=True) if word_type != "图片": state["problem_image"] = "YES" temp_problem = message.copy() @@ -118,7 +121,7 @@ async def _( # if at_list: answer = get_answer(message.copy()) # text = str(message.pop(0)).split("答", maxsplit=1)[-1].strip() - # temp_problem.insert(0, alcText(text)) + # temp_problem.insert(0, alcMessageUtils.build_message(text)) state["word_scope"] = word_scope state["word_type"] = word_type state["problem"] = get_problem(temp_problem) @@ -141,7 +144,7 @@ async def _( answer: Any = Arg("answer"), ): if not session.id1: - await Text("用户id不存在...").finish() + await MessageUtils.build_message("用户id不存在...").finish() user_id = session.id1 group_id = session.id3 or session.id2 try: @@ -152,16 +155,16 @@ async def _( try: re.compile(problem) except re.error: - await Text(f"添加词条失败,正则表达式 {problem} 非法!").finish( - reply=True - ) + await MessageUtils.build_message( + f"添加词条失败,正则表达式 {problem} 非法!" + ).finish(reply_to=True) # if str(event.user_id) in bot.config.superusers and isinstance(event, PrivateMessageEvent): # word_scope = "私聊" nickname = None if problem and bot.config.nickname: nickname = [nk for nk in bot.config.nickname if problem.startswith(nk)] if not problem: - await Text("获取问题失败...").finish(reply=True) + await MessageUtils.build_message("获取问题失败...").finish(reply_to=True) await WordBank.add_problem_answer( user_id, ( @@ -186,13 +189,15 @@ async def _( session=session, e=e, ) - await Text( + await MessageUtils.build_message( f"添加词条 {problem if word_type != '图片' else '图片'} 发生错误!" - ).finish(reply=True) + ).finish(reply_to=True) if word_type == "图片": - result = MessageFactory([Text("添加词条 "), Image(problem), Text(" 成功!")]) + result = MessageUtils.build_message( + ["添加词条 ", Image(url=problem), " 成功!"] + ) else: - result = Text(f"添加词条 {problem} 成功!") + result = MessageUtils.build_message(f"添加词条 {problem} 成功!") await result.send() logger.info( f"添加词条 {problem} 成功!", @@ -212,9 +217,9 @@ async def _( all: Query[bool] = AlconnaQuery("all.value", False), ): if not problem.available and not index.available: - await Text("此命令之后需要跟随指定词条或id,通过“显示词条“查看").finish( - reply=True - ) + await MessageUtils.build_message( + "此命令之后需要跟随指定词条或id,通过“显示词条“查看" + ).finish(reply_to=True) word_scope = 1 if session.id3 or session.id2 else 2 if all.result: word_scope = 0 @@ -228,7 +233,7 @@ async def _( ) else: if session.id1 not in bot.config.superusers: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) result, _ = await WordBankManage.delete_word( problem.result, index.result if index.available else None, @@ -236,7 +241,7 @@ async def _( None, word_scope, ) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) logger.info(f"删除词条: {problem.result}", arparma.header_result, session=session) @@ -251,9 +256,9 @@ async def _( all: Query[bool] = AlconnaQuery("all.value", False), ): if not problem.available and not index.available: - await Text("此命令之后需要跟随指定词条或id,通过“显示词条“查看").finish( - reply=True - ) + await MessageUtils.build_message( + "此命令之后需要跟随指定词条或id,通过“显示词条“查看" + ).finish(reply_to=True) word_scope = 1 if session.id3 or session.id2 else 2 if all.result: word_scope = 0 @@ -267,7 +272,7 @@ async def _( ) else: if session.id1 not in bot.config.superusers: - await Text("权限不足捏...").finish(reply=True) + await MessageUtils.build_message("权限不足捏...").finish(reply_to=True) result, old_problem = await WordBankManage.update_word( replace, problem.result if problem.available else "", @@ -275,7 +280,7 @@ async def _( session.id3 or session.id2, word_scope, ) - await Text(result).send(reply=True) + await MessageUtils.build_message(result).send(reply_to=True) logger.info( f"更新词条词条: {old_problem} -> {replace}", arparma.header_result, @@ -303,7 +308,9 @@ async def _( if index.result < 0 or index.result > len( await WordBank.get_problem_by_scope(2) ): - await Text("id必须在范围内...").finish(reply=True) + await MessageUtils.build_message("id必须在范围内...").finish( + reply_to=True + ) result = await WordBankManage.show_word( problem.result, index.result if index.available else None, diff --git a/zhenxun/utils/http_utils.py b/zhenxun/utils/http_utils.py index 142d2ceb..b751f9cd 100644 --- a/zhenxun/utils/http_utils.py +++ b/zhenxun/utils/http_utils.py @@ -9,19 +9,17 @@ import httpx import rich from httpx import ConnectTimeout, Response from nonebot import require +from nonebot_plugin_alconna import UniMessage from playwright.async_api import Page from retrying import retry from zhenxun.configs.config import SYSTEM_PROXY from zhenxun.services.log import logger +from zhenxun.utils.message import MessageUtils from zhenxun.utils.user_agent import get_user_agent from .browser import get_browser -require("nonebot_plugin_saa") - -from nonebot_plugin_saa import Image - class AsyncHttpx: @@ -332,7 +330,7 @@ class AsyncPlaywright: type_: Literal["jpeg", "png"] | None = None, user_agent: str | None = None, **kwargs, - ) -> Image | None: + ) -> UniMessage | None: """截图,该方法仅用于简单快捷截图,复杂截图请操作 page 参数: @@ -367,7 +365,7 @@ class AsyncPlaywright: card = await card.wait_for_selector(e, timeout=wait_time) if card: await card.screenshot(path=path, timeout=timeout, type=type_) - return Image(path) + return MessageUtils.build_message(path) return None diff --git a/zhenxun/utils/message.py b/zhenxun/utils/message.py new file mode 100644 index 00000000..22e6b744 --- /dev/null +++ b/zhenxun/utils/message.py @@ -0,0 +1,124 @@ +from io import BytesIO +from pathlib import Path + +from nonebot.adapters.onebot.v11 import Message, MessageSegment +from nonebot_plugin_alconna import At, Image, Text, UniMessage + +from zhenxun.configs.config import NICKNAME +from zhenxun.services.log import logger +from zhenxun.utils._build_image import BuildImage + +MESSAGE_TYPE = ( + str | int | float | Path | bytes | BytesIO | BuildImage | At | Image | Text +) + + +class MessageUtils: + + @classmethod + def __build_message(cls, msg_list: list[MESSAGE_TYPE]) -> list[Text | Image]: + """构造消息 + + 参数: + msg_list: 消息列表 + + 返回: + list[Text | Text]: 构造完成的消息列表 + """ + message_list = [] + for msg in msg_list: + if isinstance(msg, (Image, Text, At)): + message_list.append(msg) + elif isinstance(msg, (str, int, float)): + message_list.append(Text(str(msg))) + elif isinstance(msg, Path): + if msg.exists(): + message_list.append(Image(path=msg)) + else: + logger.warning(f"图片路径不存在: {msg}") + elif isinstance(msg, bytes): + message_list.append(Image(raw=msg)) + elif isinstance(msg, BytesIO): + message_list.append(Image(raw=msg)) + elif isinstance(msg, BuildImage): + message_list.append(Image(raw=msg.pic2bytes())) + return message_list + + @classmethod + def build_message( + cls, msg_list: MESSAGE_TYPE | list[MESSAGE_TYPE | list[MESSAGE_TYPE]] + ) -> UniMessage: + """构造消息 + + 参数: + msg_list: 消息列表 + + 返回: + UniMessage: 构造完成的消息列表 + """ + message_list = [] + if not isinstance(msg_list, list): + msg_list = [msg_list] + for m in msg_list: + _data = m if isinstance(m, list) else [m] + message_list += cls.__build_message(_data) # type: ignore + return UniMessage(message_list) + + @classmethod + def custom_forward_msg( + cls, + msg_list: list[str | Message], + uin: str, + name: str = f"这里是{NICKNAME}", + ) -> list[dict]: + """生成自定义合并消息 + + 参数: + msg_list: 消息列表 + uin: 发送者 QQ + name: 自定义名称 + + 返回: + list[dict]: 转发消息 + """ + mes_list = [] + for _message in msg_list: + data = { + "type": "node", + "data": { + "name": name, + "uin": f"{uin}", + "content": _message, + }, + } + mes_list.append(data) + return mes_list + + @classmethod + def template2forward(cls, msg_list: list[UniMessage], uni: str) -> list[dict]: + """模板转转发消息 + + 参数: + msg_list: 消息列表 + uni: 发送者qq + + 返回: + list[dict]: 转发消息 + """ + forward_data = [] + for r_list in msg_list: + s = "" + if isinstance(r_list, (UniMessage, list)): + for r in r_list: + if isinstance(r, Text): + s += str(r) + elif isinstance(r, Image): + if v := r.url or r.path: + s += MessageSegment.image(v) + elif isinstance(r_list, Image): + if v := r_list.url or r_list.path: + s = MessageSegment.image(v) + else: + s = str(r_list) + forward_data.append(s) + return cls.custom_forward_msg(forward_data, uni) diff --git a/zhenxun/utils/utils.py b/zhenxun/utils/utils.py index 50bc2b69..9e3caca2 100644 --- a/zhenxun/utils/utils.py +++ b/zhenxun/utils/utils.py @@ -233,61 +233,3 @@ def is_valid_date(date_text: str, separator: str = "-") -> bool: return True except ValueError: return False - - -def custom_forward_msg( - msg_list: list[str | Message], - uin: str, - name: str = f"这里是{NICKNAME}", -) -> list[dict]: - """生成自定义合并消息 - - 参数: - msg_list: 消息列表 - uin: 发送者 QQ - name: 自定义名称 - - 返回: - list[dict]: 转发消息 - """ - mes_list = [] - for _message in msg_list: - data = { - "type": "node", - "data": { - "name": name, - "uin": f"{uin}", - "content": _message, - }, - } - mes_list.append(data) - return mes_list - - -def template2forward( - msg_list: list[MessageFactory | Text | Image], uni: str -) -> list[dict]: - """模板转转发消息 - - 参数: - msg_list: 消息列表 - uni: 发送者qq - - 返回: - list[dict]: 转发消息 - """ - forward_data = [] - for r_list in msg_list: - s = "" - if isinstance(r_list, MessageFactory): - for r in r_list: - if isinstance(r, Text): - s += str(r) - elif isinstance(r, Image): - s += MessageSegment.image(r.data["image"]) - elif isinstance(r_list, Image): - s = MessageSegment.image(r_list.data["image"]) - else: - s = str(r_list) - forward_data.append(s) - return custom_forward_msg(forward_data, uni)