From 33d5cd6b5c1ff73fdb07250a779cbde1891780bb Mon Sep 17 00:00:00 2001 From: HibiKier <775757368@qq.com> Date: Sun, 12 Mar 2023 21:53:15 +0800 Subject: [PATCH] fix bug --- __version__ | 2 +- plugins/check_zhenxun_update/__init__.py | 8 +-- plugins/check_zhenxun_update/data_source.py | 78 +++++++++++---------- services/log.py | 22 +++--- update_info.json | 3 +- utils/image_utils.py | 56 ++++++++------- 6 files changed, 88 insertions(+), 81 deletions(-) diff --git a/__version__ b/__version__ index fd493918..7221760d 100644 --- a/__version__ +++ b/__version__ @@ -1 +1 @@ -__version__: v0.1.6.6 +__version__: v0.1.6.7 diff --git a/plugins/check_zhenxun_update/__init__.py b/plugins/check_zhenxun_update/__init__.py index 6344bd36..506ae25d 100755 --- a/plugins/check_zhenxun_update/__init__.py +++ b/plugins/check_zhenxun_update/__init__.py @@ -58,15 +58,15 @@ async def _(bot: Bot, event: MessageEvent): try: code, error = await check_update(bot) if error: - logger.error(f"更新真寻未知错误 {error}") + logger.error(f"错误: {error}", "检查更新真寻") await bot.send_private_msg( user_id=event.user_id, message=f"更新真寻未知错误 {error}" ) except Exception as e: - logger.error(f"更新真寻未知错误 {type(e)}:{e}") + logger.error(f"更新真寻未知错误", "检查更新真寻", e=e) await bot.send_private_msg( user_id=event.user_id, - message=f"更新真寻未知错误 {type(e)}:{e}", + message=f"更新真寻未知错误 {type(e)}: {e}", ) else: if code == 200: @@ -108,7 +108,7 @@ async def _(): data = await get_latest_version_data() if data: latest_version = data["name"] - if _version != latest_version: + if _version.lower() != latest_version.lower(): bot = get_bot() await bot.send_private_msg( user_id=int(list(bot.config.superusers)[0]), diff --git a/plugins/check_zhenxun_update/data_source.py b/plugins/check_zhenxun_update/data_source.py index 8529d64c..fbb67555 100755 --- a/plugins/check_zhenxun_update/data_source.py +++ b/plugins/check_zhenxun_update/data_source.py @@ -1,18 +1,20 @@ -from nonebot.adapters.onebot.v11 import Bot, Message -from utils.image_utils import BuildImage -from configs.path_config import IMAGE_PATH -from utils.message_builder import image -from utils.http_utils import AsyncHttpx -from typing import List -from services.log import logger -from pathlib import Path -import ujson as json -import nonebot import asyncio -import platform -import tarfile -import shutil import os +import platform +import shutil +import tarfile +from pathlib import Path +from typing import List, Tuple + +import nonebot +import ujson as json +from nonebot.adapters.onebot.v11 import Bot, Message + +from configs.path_config import IMAGE_PATH +from services.log import logger +from utils.http_utils import AsyncHttpx +from utils.image_utils import BuildImage +from utils.message_builder import image # if str(platform.system()).lower() == "windows": # policy = asyncio.WindowsSelectorEventLoopPolicy() @@ -55,7 +57,7 @@ async def remind(bot: Bot): is_restart_file.unlink() -async def check_update(bot: Bot) -> 'int, str': +async def check_update(bot: Bot) -> Tuple[int, str]: logger.info("开始检查更新真寻酱....") _version = "v0.0.0" if _version_file.exists(): @@ -73,7 +75,7 @@ async def check_update(bot: Bot) -> 'int, str': message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....", ) logger.info(f"开始下载真寻最新版文件....") - tar_gz_url = (await AsyncHttpx.get(tar_gz_url)).headers.get('Location') + tar_gz_url = (await AsyncHttpx.get(tar_gz_url)).headers.get("Location") if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz): logger.info("下载真寻最新版文件完成....") error = await asyncio.get_event_loop().run_in_executor( @@ -85,23 +87,25 @@ async def check_update(bot: Bot) -> 'int, str': logger.info("开始获取真寻更新日志.....") update_info = data["body"] width = 0 - height = len(update_info.split('\n')) * 24 + height = len(update_info.split("\n")) * 24 A = BuildImage(width, height, font_size=20) - for m in update_info.split('\n'): + for m in update_info.split("\n"): w, h = A.getsize(m) if w > width: width = w A = BuildImage(width + 50, height, font_size=20) A.text((10, 10), update_info) - A.save(f'{IMAGE_PATH}/update_info.png') + A.save(f"{IMAGE_PATH}/update_info.png") await bot.send_private_msg( user_id=int(list(bot.config.superusers)[0]), - message=Message(f"真寻更新完成,版本:{_version} -> {latest_version}\n" - f"更新日期:{data['created_at']}\n" - f"更新日志:\n" - f"{image('update_info.png')}"), + message=Message( + f"真寻更新完成,版本:{_version} -> {latest_version}\n" + f"更新日期:{data['created_at']}\n" + f"更新日志:\n" + f"{image('update_info.png')}" + ), ) - return 200, '' + return 200, "" else: logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}") await bot.send_private_msg( @@ -119,7 +123,7 @@ async def check_update(bot: Bot) -> 'int, str': await bot.send_private_msg( user_id=int(list(bot.config.superusers)[0]), message=f"自动获取真寻版本失败...." ) - return 999, '' + return 999, "" def _file_handle(latest_version: str) -> str: @@ -128,7 +132,7 @@ def _file_handle(latest_version: str) -> str: if backup_dir.exists(): shutil.rmtree(backup_dir) tf = None - error = '' + error = "" # try: backup_dir.mkdir(exist_ok=True, parents=True) logger.info("开始解压真寻文件压缩包....") @@ -143,16 +147,16 @@ def _file_handle(latest_version: str) -> str: delete_file = update_info["delete_file"] config_file = Path() / "configs" / "config.py" config_path_file = Path() / "configs" / "path_config.py" - for file in [config_file.name]: - tmp = "" - new_file = Path(zhenxun_latest_file) / "configs" / file - old_file = Path() / "configs" / file - new_lines = open(new_file, "r", encoding="utf8").readlines() - old_lines = open(old_file, "r", encoding="utf8").readlines() - for nl in new_lines: - tmp += check_old_lines(old_lines, nl) - with open(old_file, "w", encoding="utf8") as f: - f.write(tmp) + # for file in [config_file.name]: + # tmp = "" + # new_file = Path(zhenxun_latest_file) / "configs" / file + # old_file = Path() / "configs" / file + # new_lines = open(new_file, "r", encoding="utf8").readlines() + # old_lines = open(old_file, "r", encoding="utf8").readlines() + # for nl in new_lines: + # tmp += check_old_lines(old_lines, nl) + # with open(old_file, "w", encoding="utf8") as f: + # f.write(tmp) for file in delete_file + update_file: if file != "configs": file = Path() / file @@ -189,9 +193,7 @@ def _file_handle(latest_version: str) -> str: local_update_info_file.unlink() with open(_version_file, "w", encoding="utf8") as f: f.write(f"__version__: {latest_version}") - os.system( - f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}" - ) + os.system(f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}") return error diff --git a/services/log.py b/services/log.py index 34cd4528..c656100d 100755 --- a/services/log.py +++ b/services/log.py @@ -1,5 +1,5 @@ from datetime import datetime, timedelta -from typing import Any, Dict, Optional +from typing import Any, Dict, Optional, Union from loguru import logger as logger_ from nonebot.log import default_filter, default_format @@ -49,8 +49,8 @@ class logger: cls, info: str, command: Optional[str] = None, - user_id: Optional[int] = None, - group_id: Optional[int] = None, + user_id: Optional[Union[int, str]] = None, + group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) @@ -76,8 +76,8 @@ class logger: cls, info: str, command: Optional[str] = None, - user_id: Optional[int] = None, - group_id: Optional[int] = None, + user_id: Optional[Union[int, str]] = None, + group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): @@ -91,8 +91,8 @@ class logger: cls, info: str, command: Optional[str] = None, - user_id: Optional[int] = None, - group_id: Optional[int] = None, + user_id: Optional[Union[int, str]] = None, + group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): @@ -106,8 +106,8 @@ class logger: cls, info: str, command: Optional[str] = None, - user_id: Optional[int] = None, - group_id: Optional[int] = None, + user_id: Optional[Union[int, str]] = None, + group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): @@ -121,8 +121,8 @@ class logger: cls, info: str, command: Optional[str] = None, - user_id: Optional[int] = None, - group_id: Optional[int] = None, + user_id: Optional[Union[int, str]] = None, + group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] diff --git a/update_info.json b/update_info.json index 073339a2..140e2ea4 100644 --- a/update_info.json +++ b/update_info.json @@ -10,7 +10,6 @@ "poetry.lock", "pyproject.toml" ], - "add_file": ["resources/image/other/btn_false.png", - "resources/image/other/btn_true.png"], + "add_file": ["resources/image/csgo_cases"], "delete_file": [] } \ No newline at end of file diff --git a/utils/image_utils.py b/utils/image_utils.py index f835aa2b..77fc4711 100755 --- a/utils/image_utils.py +++ b/utils/image_utils.py @@ -30,7 +30,7 @@ ModeType = Literal[ def compare_image_with_hash( - image_file1: str, image_file2: str, max_dif: int = 1.5 + image_file1: str, image_file2: str, max_dif: float = 1.5 ) -> bool: """ 说明: @@ -65,7 +65,9 @@ def get_img_hash(image_file: Union[str, Path]) -> ImageHash: def compressed_image( - in_file: Union[str, Path], out_file: Union[str, Path] = None, ratio: float = 0.9 + in_file: Union[str, Path], + out_file: Optional[Union[str, Path]] = None, + ratio: float = 0.9, ): """ 说明: @@ -192,6 +194,7 @@ class BuildImage: self._current_h = 0 self.uid = uuid.uuid1() self.font_name = font + self.font_size = font_size self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size)) if not plain_text and not color: color = (255, 255, 255) @@ -224,13 +227,13 @@ class BuildImage: ) if is_alpha: try: - array = self.markImg.load() - for i in range(w): - for j in range(h): - pos = array[i, j] - is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3 - if is_edit: - array[i, j] = (255, 255, 255, 0) + if array := self.markImg.load(): + for i in range(w): + for j in range(h): + pos = array[i, j] + is_edit = sum([1 for x in pos[0:3] if x > 240]) == 3 + if is_edit: + array[i, j] = (255, 255, 255, 0) except Exception as e: logger.warning(f"背景透明化发生错误..{type(e)}:{e}") self.draw = ImageDraw.Draw(self.markImg) @@ -246,7 +249,7 @@ class BuildImage: self.loop = asyncio.get_event_loop() @classmethod - def load_font(cls, font: str, font_size: int) -> FreeTypeFont: + def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 @@ -254,12 +257,12 @@ class BuildImage: :param font: 字体名称 :param font_size: 字体大小 """ - return ImageFont.truetype(str(FONT_PATH / font), font_size) + return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, - pos: Tuple[int, int] = None, + pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, ): @@ -276,8 +279,8 @@ class BuildImage: def paste( self, - img: "BuildImage" or Image, - pos: Tuple[int, int] = None, + img: "BuildImage", + pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, ): @@ -308,6 +311,11 @@ class BuildImage: width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) + if pos: + if pos[0] < 0: + pos = (self.w + pos[0], pos[1]) + if pos[1] < 0: + pos = (pos[0], self.h + pos[1]) if isinstance(img, BuildImage): img = img.markImg if self._current_w >= self.w: @@ -335,8 +343,8 @@ class BuildImage: :param font: 字体 :param font_size: 字体大小 """ - font = cls.load_font(font, font_size) - return font.getsize(msg) + font_ = cls.load_font(font, font_size) + return font_.getsize(msg) def getsize(self, msg: str) -> Tuple[int, int]: """ @@ -411,7 +419,7 @@ class BuildImage: text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, - font: Union[FreeTypeFont, str] = None, + font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): @@ -436,7 +444,7 @@ class BuildImage: text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, - font: Union[FreeTypeFont, str] = None, + font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): @@ -491,9 +499,7 @@ class BuildImage: 参数: :param path: 图片路径 """ - if not path: - path = self.background - self.markImg.save(path) + self.markImg.save(path or self.background) # type: ignore def show(self): """ @@ -612,7 +618,7 @@ class BuildImage: self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, - outline: str = None, + outline: Optional[str] = None, width: int = 1, ): """ @@ -630,7 +636,7 @@ class BuildImage: self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, - outline: str = None, + outline: Optional[str] = None, width: int = 1, ): """ @@ -830,7 +836,7 @@ class BuildImage: """ self.markImg.transpose(angle) - async def afilter(self, filter_: str, aud: int = None): + async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 @@ -840,7 +846,7 @@ class BuildImage: """ await self.loop.run_in_executor(None, self.filter, filter_, aud) - def filter(self, filter_: str, aud: int = None): + def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化