From e89d1d4688d685544553babfa782d8c40dd15f89 Mon Sep 17 00:00:00 2001 From: HibiKier <45528451+HibiKier@users.noreply.github.com> Date: Wed, 25 Sep 2024 19:04:36 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8D=E7=BE=A4?= =?UTF-8?q?=E6=AC=A2=E8=BF=8E=E6=B6=88=E6=81=AF=E8=AE=BE=E7=BD=AE=20(#1651?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../builtin_plugins/admin/welcome_message.py | 87 ++++++++++++------- 1 file changed, 55 insertions(+), 32 deletions(-) diff --git a/zhenxun/builtin_plugins/admin/welcome_message.py b/zhenxun/builtin_plugins/admin/welcome_message.py index 6cb6c8dc..e9bb9c33 100644 --- a/zhenxun/builtin_plugins/admin/welcome_message.py +++ b/zhenxun/builtin_plugins/admin/welcome_message.py @@ -1,23 +1,21 @@ -import os import shutil -from typing import Annotated, Dict +from pathlib import Path +from typing import Annotated import ujson as json from nonebot import on_command from nonebot.params import Command from nonebot.plugin import PluginMetadata -from nonebot_plugin_alconna import Image -from nonebot_plugin_alconna import Text as alcText -from nonebot_plugin_alconna import UniMsg from nonebot_plugin_session import EventSession +from nonebot_plugin_alconna import Text, Image, UniMsg -from zhenxun.configs.config import Config -from zhenxun.configs.path_config import DATA_PATH -from zhenxun.configs.utils import PluginExtraData, RegisterConfig from zhenxun.services.log import logger +from zhenxun.configs.config import Config from zhenxun.utils.enum import PluginType from zhenxun.utils.http_utils import AsyncHttpx +from zhenxun.configs.path_config import DATA_PATH from zhenxun.utils.rules import admin_check, ensure_group +from zhenxun.configs.utils import RegisterConfig, PluginExtraData base_config = Config.get("admin_bot_manage") @@ -25,7 +23,8 @@ __plugin_meta__ = PluginMetadata( name="自定义群欢迎消息", description="自定义群欢迎消息", usage=""" - 设置欢迎消息 欢迎新人! + 设置群欢迎消息,当消息中包含 -at 时会at入群用户 + 设置欢迎消息 欢迎新人![图片] 设置欢迎消息 欢迎你 -at """.strip(), extra=PluginExtraData( @@ -61,7 +60,7 @@ BASE_PATH.mkdir(parents=True, exist_ok=True) old_file = DATA_PATH / "custom_welcome_msg" / "custom_welcome_msg.json" if old_file.exists(): try: - old_data: Dict[str, str] = json.load(old_file.open(encoding="utf8")) + old_data: dict[str, str] = json.load(old_file.open(encoding="utf8")) for group_id, message in old_data.items(): file = BASE_PATH / "qq" / f"{group_id}" / "text.json" file.parent.mkdir(parents=True, exist_ok=True) @@ -74,15 +73,18 @@ if old_file.exists(): logger.debug("群欢迎消息数据迁移", group_id=group_id) shutil.rmtree(old_file.parent.absolute()) except Exception as e: - pass + logger.error("群欢迎消息数据迁移失败...", e=e) -@_matcher.handle() -async def _( - session: EventSession, - message: UniMsg, - command: Annotated[tuple[str, ...], Command()], -): +def get_path(session: EventSession) -> Path: + """根据Session获取存储路径 + + 参数: + session: EventSession: + + 返回: + Path: 存储路径 + """ path = BASE_PATH / f"{session.platform or session.bot_type}" / f"{session.id2}" if session.id3: path = ( @@ -91,32 +93,53 @@ async def _( / f"{session.id3}" / f"{session.id2}" ) - file = path / "text.json" + path.mkdir(parents=True, exist_ok=True) + for f in path.iterdir(): + f.unlink() + return path + + +async def save(path: Path, message: UniMsg) -> str: + """保存群欢迎消息 + + 参数: + path: 存储路径 + message: 消息内容 + + 返回: + str: 消息内容文本格式 + """ idx = 0 text = "" - for f in os.listdir(path): - (path / f).unlink() - message[0].text = message[0].text.replace(command[0], "").strip() + file = path / "text.json" for msg in message: - if isinstance(msg, alcText): + if isinstance(msg, Text): text += msg.text elif isinstance(msg, Image): if msg.url: text += f"[image:{idx}]" - await AsyncHttpx.download_file(msg.url, path / f"{idx}.png") - idx += 1 + if await AsyncHttpx.download_file(msg.url, path / f"{idx}.png"): + idx += 1 else: - logger.debug("图片 URL 为空...", command[0]) - if not file.exists(): - file.parent.mkdir(exist_ok=True, parents=True) - is_at = "-at" in message - text = text.replace("-at", "") + logger.warning("图片 URL 为空...", "设置欢迎消息") json.dump( - {"at": is_at, "message": text}, - file.open("w"), + {"at": "-at" in text, "message": text.replace("-at", "", 1)}, + file.open("w", encoding="utf-8"), ensure_ascii=False, indent=4, ) - uni_msg = alcText("设置欢迎消息成功: \n") + message + return text + + +@_matcher.handle() +async def _( + session: EventSession, + message: UniMsg, + command: Annotated[tuple[str, ...], Command()], +): + path = get_path(session) + message[0].text = message[0].text.replace(command[0], "").strip() + text = await save(path, message) + uni_msg = Text("设置欢迎消息成功: \n") + message await uni_msg.send() logger.info(f"设置群欢迎消息成功: {text}", command[0], session=session)