This commit is contained in:
HibiKier 2023-03-12 21:53:15 +08:00
parent c574459485
commit 33d5cd6b5c
6 changed files with 88 additions and 81 deletions

View File

@ -1 +1 @@
__version__: v0.1.6.6 __version__: v0.1.6.7

View File

@ -58,15 +58,15 @@ async def _(bot: Bot, event: MessageEvent):
try: try:
code, error = await check_update(bot) code, error = await check_update(bot)
if error: if error:
logger.error(f"更新真寻未知错误 {error}") logger.error(f"错误: {error}", "检查更新真寻")
await bot.send_private_msg( await bot.send_private_msg(
user_id=event.user_id, message=f"更新真寻未知错误 {error}" user_id=event.user_id, message=f"更新真寻未知错误 {error}"
) )
except Exception as e: except Exception as e:
logger.error(f"更新真寻未知错误 {type(e)}{e}") logger.error(f"更新真寻未知错误", "检查更新真寻", e=e)
await bot.send_private_msg( await bot.send_private_msg(
user_id=event.user_id, user_id=event.user_id,
message=f"更新真寻未知错误 {type(e)}{e}", message=f"更新真寻未知错误 {type(e)}: {e}",
) )
else: else:
if code == 200: if code == 200:
@ -108,7 +108,7 @@ async def _():
data = await get_latest_version_data() data = await get_latest_version_data()
if data: if data:
latest_version = data["name"] latest_version = data["name"]
if _version != latest_version: if _version.lower() != latest_version.lower():
bot = get_bot() bot = get_bot()
await bot.send_private_msg( await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), user_id=int(list(bot.config.superusers)[0]),

View File

@ -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 asyncio
import platform
import tarfile
import shutil
import os 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": # if str(platform.system()).lower() == "windows":
# policy = asyncio.WindowsSelectorEventLoopPolicy() # policy = asyncio.WindowsSelectorEventLoopPolicy()
@ -55,7 +57,7 @@ async def remind(bot: Bot):
is_restart_file.unlink() is_restart_file.unlink()
async def check_update(bot: Bot) -> 'int, str': async def check_update(bot: Bot) -> Tuple[int, str]:
logger.info("开始检查更新真寻酱....") logger.info("开始检查更新真寻酱....")
_version = "v0.0.0" _version = "v0.0.0"
if _version_file.exists(): if _version_file.exists():
@ -73,7 +75,7 @@ async def check_update(bot: Bot) -> 'int, str':
message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....", message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....",
) )
logger.info(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): if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz):
logger.info("下载真寻最新版文件完成....") logger.info("下载真寻最新版文件完成....")
error = await asyncio.get_event_loop().run_in_executor( error = await asyncio.get_event_loop().run_in_executor(
@ -85,23 +87,25 @@ async def check_update(bot: Bot) -> 'int, str':
logger.info("开始获取真寻更新日志.....") logger.info("开始获取真寻更新日志.....")
update_info = data["body"] update_info = data["body"]
width = 0 width = 0
height = len(update_info.split('\n')) * 24 height = len(update_info.split("\n")) * 24
A = BuildImage(width, height, font_size=20) 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) w, h = A.getsize(m)
if w > width: if w > width:
width = w width = w
A = BuildImage(width + 50, height, font_size=20) A = BuildImage(width + 50, height, font_size=20)
A.text((10, 10), update_info) 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( await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), user_id=int(list(bot.config.superusers)[0]),
message=Message(f"真寻更新完成,版本:{_version} -> {latest_version}\n" message=Message(
f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"更新日期:{data['created_at']}\n" f"更新日期:{data['created_at']}\n"
f"更新日志:\n" f"更新日志:\n"
f"{image('update_info.png')}"), f"{image('update_info.png')}"
),
) )
return 200, '' return 200, ""
else: else:
logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}") logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}")
await bot.send_private_msg( await bot.send_private_msg(
@ -119,7 +123,7 @@ async def check_update(bot: Bot) -> 'int, str':
await bot.send_private_msg( await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=f"自动获取真寻版本失败...." user_id=int(list(bot.config.superusers)[0]), message=f"自动获取真寻版本失败...."
) )
return 999, '' return 999, ""
def _file_handle(latest_version: str) -> str: def _file_handle(latest_version: str) -> str:
@ -128,7 +132,7 @@ def _file_handle(latest_version: str) -> str:
if backup_dir.exists(): if backup_dir.exists():
shutil.rmtree(backup_dir) shutil.rmtree(backup_dir)
tf = None tf = None
error = '' error = ""
# try: # try:
backup_dir.mkdir(exist_ok=True, parents=True) backup_dir.mkdir(exist_ok=True, parents=True)
logger.info("开始解压真寻文件压缩包....") logger.info("开始解压真寻文件压缩包....")
@ -143,16 +147,16 @@ def _file_handle(latest_version: str) -> str:
delete_file = update_info["delete_file"] delete_file = update_info["delete_file"]
config_file = Path() / "configs" / "config.py" config_file = Path() / "configs" / "config.py"
config_path_file = Path() / "configs" / "path_config.py" config_path_file = Path() / "configs" / "path_config.py"
for file in [config_file.name]: # for file in [config_file.name]:
tmp = "" # tmp = ""
new_file = Path(zhenxun_latest_file) / "configs" / file # new_file = Path(zhenxun_latest_file) / "configs" / file
old_file = Path() / "configs" / file # old_file = Path() / "configs" / file
new_lines = open(new_file, "r", encoding="utf8").readlines() # new_lines = open(new_file, "r", encoding="utf8").readlines()
old_lines = open(old_file, "r", encoding="utf8").readlines() # old_lines = open(old_file, "r", encoding="utf8").readlines()
for nl in new_lines: # for nl in new_lines:
tmp += check_old_lines(old_lines, nl) # tmp += check_old_lines(old_lines, nl)
with open(old_file, "w", encoding="utf8") as f: # with open(old_file, "w", encoding="utf8") as f:
f.write(tmp) # f.write(tmp)
for file in delete_file + update_file: for file in delete_file + update_file:
if file != "configs": if file != "configs":
file = Path() / file file = Path() / file
@ -189,9 +193,7 @@ def _file_handle(latest_version: str) -> str:
local_update_info_file.unlink() local_update_info_file.unlink()
with open(_version_file, "w", encoding="utf8") as f: with open(_version_file, "w", encoding="utf8") as f:
f.write(f"__version__: {latest_version}") f.write(f"__version__: {latest_version}")
os.system( os.system(f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}")
f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}"
)
return error return error

View File

@ -1,5 +1,5 @@
from datetime import datetime, timedelta 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 loguru import logger as logger_
from nonebot.log import default_filter, default_format from nonebot.log import default_filter, default_format
@ -49,8 +49,8 @@ class logger:
cls, cls,
info: str, info: str,
command: Optional[str] = None, command: Optional[str] = None,
user_id: Optional[int] = None, user_id: Optional[Union[int, str]] = None,
group_id: Optional[int] = None, group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None, target: Optional[Any] = None,
): ):
template = cls.__parser_template(info, command, user_id, group_id, target) template = cls.__parser_template(info, command, user_id, group_id, target)
@ -76,8 +76,8 @@ class logger:
cls, cls,
info: str, info: str,
command: Optional[str] = None, command: Optional[str] = None,
user_id: Optional[int] = None, user_id: Optional[Union[int, str]] = None,
group_id: Optional[int] = None, group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None, target: Optional[Any] = None,
e: Optional[Exception] = None, e: Optional[Exception] = None,
): ):
@ -91,8 +91,8 @@ class logger:
cls, cls,
info: str, info: str,
command: Optional[str] = None, command: Optional[str] = None,
user_id: Optional[int] = None, user_id: Optional[Union[int, str]] = None,
group_id: Optional[int] = None, group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None, target: Optional[Any] = None,
e: Optional[Exception] = None, e: Optional[Exception] = None,
): ):
@ -106,8 +106,8 @@ class logger:
cls, cls,
info: str, info: str,
command: Optional[str] = None, command: Optional[str] = None,
user_id: Optional[int] = None, user_id: Optional[Union[int, str]] = None,
group_id: Optional[int] = None, group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None, target: Optional[Any] = None,
e: Optional[Exception] = None, e: Optional[Exception] = None,
): ):
@ -121,8 +121,8 @@ class logger:
cls, cls,
info: str, info: str,
command: Optional[str] = None, command: Optional[str] = None,
user_id: Optional[int] = None, user_id: Optional[Union[int, str]] = None,
group_id: Optional[int] = None, group_id: Optional[Union[int, str]] = None,
target: Optional[Any] = None, target: Optional[Any] = None,
) -> str: ) -> str:
arg_list = [] arg_list = []

View File

@ -10,7 +10,6 @@
"poetry.lock", "poetry.lock",
"pyproject.toml" "pyproject.toml"
], ],
"add_file": ["resources/image/other/btn_false.png", "add_file": ["resources/image/csgo_cases"],
"resources/image/other/btn_true.png"],
"delete_file": [] "delete_file": []
} }

View File

@ -30,7 +30,7 @@ ModeType = Literal[
def compare_image_with_hash( 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: ) -> bool:
""" """
说明: 说明:
@ -65,7 +65,9 @@ def get_img_hash(image_file: Union[str, Path]) -> ImageHash:
def compressed_image( 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._current_h = 0
self.uid = uuid.uuid1() self.uid = uuid.uuid1()
self.font_name = font self.font_name = font
self.font_size = font_size
self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size)) self.font = ImageFont.truetype(str(FONT_PATH / font), int(font_size))
if not plain_text and not color: if not plain_text and not color:
color = (255, 255, 255) color = (255, 255, 255)
@ -224,7 +227,7 @@ class BuildImage:
) )
if is_alpha: if is_alpha:
try: try:
array = self.markImg.load() if array := self.markImg.load():
for i in range(w): for i in range(w):
for j in range(h): for j in range(h):
pos = array[i, j] pos = array[i, j]
@ -246,7 +249,7 @@ class BuildImage:
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
@classmethod @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: 字体名称
:param font_size: 字体大小 :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( async def apaste(
self, self,
img: "BuildImage" or Image, img: "BuildImage" or Image,
pos: Tuple[int, int] = None, pos: Optional[Tuple[int, int]] = None,
alpha: bool = False, alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None, center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
): ):
@ -276,8 +279,8 @@ class BuildImage:
def paste( def paste(
self, self,
img: "BuildImage" or Image, img: "BuildImage",
pos: Tuple[int, int] = None, pos: Optional[Tuple[int, int]] = None,
alpha: bool = False, alpha: bool = False,
center_type: Optional[Literal["center", "by_height", "by_width"]] = None, center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
): ):
@ -308,6 +311,11 @@ class BuildImage:
width = pos[0] width = pos[0]
height = int((self.h - img.h) / 2) height = int((self.h - img.h) / 2)
pos = (width, height) 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): if isinstance(img, BuildImage):
img = img.markImg img = img.markImg
if self._current_w >= self.w: if self._current_w >= self.w:
@ -335,8 +343,8 @@ class BuildImage:
:param font: 字体 :param font: 字体
:param font_size: 字体大小 :param font_size: 字体大小
""" """
font = cls.load_font(font, font_size) font_ = cls.load_font(font, font_size)
return font.getsize(msg) return font_.getsize(msg)
def getsize(self, msg: str) -> Tuple[int, int]: def getsize(self, msg: str) -> Tuple[int, int]:
""" """
@ -411,7 +419,7 @@ class BuildImage:
text: str, text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None, 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, font_size: Optional[int] = None,
**kwargs, **kwargs,
): ):
@ -436,7 +444,7 @@ class BuildImage:
text: str, text: str,
fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), fill: Union[str, Tuple[int, int, int]] = (0, 0, 0),
center_type: Optional[Literal["center", "by_height", "by_width"]] = None, 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, font_size: Optional[int] = None,
**kwargs, **kwargs,
): ):
@ -491,9 +499,7 @@ class BuildImage:
参数: 参数:
:param path: 图片路径 :param path: 图片路径
""" """
if not path: self.markImg.save(path or self.background) # type: ignore
path = self.background
self.markImg.save(path)
def show(self): def show(self):
""" """
@ -612,7 +618,7 @@ class BuildImage:
self, self,
xy: Tuple[int, int, int, int], xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None, fill: Optional[Tuple[int, int, int]] = None,
outline: str = None, outline: Optional[str] = None,
width: int = 1, width: int = 1,
): ):
""" """
@ -630,7 +636,7 @@ class BuildImage:
self, self,
xy: Tuple[int, int, int, int], xy: Tuple[int, int, int, int],
fill: Optional[Tuple[int, int, int]] = None, fill: Optional[Tuple[int, int, int]] = None,
outline: str = None, outline: Optional[str] = None,
width: int = 1, width: int = 1,
): ):
""" """
@ -830,7 +836,7 @@ class BuildImage:
""" """
self.markImg.transpose(angle) 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) 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):
""" """
说明: 说明:
图片变化 图片变化