mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-03 02:30:01 +08:00
update 0.0.7.0
This commit is contained in:
+1
-1
@@ -22,7 +22,7 @@ async def init(**kwargs) -> Optional[Browser]:
|
||||
_browser = await browser.chromium.launch(**kwargs)
|
||||
return _browser
|
||||
except NotImplementedError:
|
||||
logger.warning("win环境下 初始化playwright失败....请替换环境至linux")
|
||||
logger.warning("win环境下 初始化playwright失败,相关功能将被限制....")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from utils.image_utils import CreateMat
|
||||
from utils.image_utils import BuildMat
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from typing import List, Union
|
||||
import asyncio
|
||||
@@ -8,7 +8,7 @@ import os
|
||||
|
||||
async def init_rank(
|
||||
title: str, all_user_id: List[int], all_user_data: List[int], group_id: int, total_count: int = 10
|
||||
) -> CreateMat:
|
||||
) -> BuildMat:
|
||||
"""
|
||||
说明:
|
||||
初始化通用的数据排行榜
|
||||
@@ -43,14 +43,14 @@ async def init_rank(
|
||||
|
||||
def _init_rank_graph(
|
||||
title: str, _uname_lst: List[str], _num_lst: List[Union[int, float]]
|
||||
) -> CreateMat:
|
||||
) -> BuildMat:
|
||||
"""
|
||||
生成排行榜统计图
|
||||
:param title: 排行榜标题
|
||||
:param _uname_lst: 用户名列表
|
||||
:param _num_lst: 数值列表
|
||||
"""
|
||||
image = CreateMat(
|
||||
image = BuildMat(
|
||||
y=_num_lst,
|
||||
y_name="* 可以在命令后添加数字来指定排行人数 至多 50 *",
|
||||
mat_type="barh",
|
||||
|
||||
+89
-66
@@ -33,17 +33,20 @@ class AsyncHttpx:
|
||||
proxy: Dict[str, str] = None,
|
||||
allow_redirects: bool = True,
|
||||
timeout: Optional[int] = 30,
|
||||
**kwargs,
|
||||
) -> Response:
|
||||
"""
|
||||
Get
|
||||
:param url: url
|
||||
:param params: params
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param use_proxy: 使用默认代理
|
||||
:param proxy: 指定代理
|
||||
:param allow_redirects: allow_redirects
|
||||
:param timeout: 超时时间
|
||||
说明:
|
||||
Get
|
||||
参数:
|
||||
:param url: url
|
||||
:param params: params
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param use_proxy: 使用默认代理
|
||||
:param proxy: 指定代理
|
||||
:param allow_redirects: allow_redirects
|
||||
:param timeout: 超时时间
|
||||
"""
|
||||
if not headers:
|
||||
headers = get_user_agent()
|
||||
@@ -56,6 +59,7 @@ class AsyncHttpx:
|
||||
cookies=cookies,
|
||||
allow_redirects=allow_redirects,
|
||||
timeout=timeout,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -74,21 +78,24 @@ class AsyncHttpx:
|
||||
cookies: Optional[Dict[str, str]] = None,
|
||||
allow_redirects: bool = True,
|
||||
timeout: Optional[int] = 30,
|
||||
**kwargs,
|
||||
) -> Response:
|
||||
"""
|
||||
Post
|
||||
:param url: url
|
||||
:param data: data
|
||||
:param content: content
|
||||
:param files: files
|
||||
:param use_proxy: 是否默认代理
|
||||
:param proxy: 指定代理
|
||||
:param json: json
|
||||
:param params: params
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param allow_redirects: allow_redirects
|
||||
:param timeout: 超时时间
|
||||
说明:
|
||||
Post
|
||||
参数:
|
||||
:param url: url
|
||||
:param data: data
|
||||
:param content: content
|
||||
:param files: files
|
||||
:param use_proxy: 是否默认代理
|
||||
:param proxy: 指定代理
|
||||
:param json: json
|
||||
:param params: params
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param allow_redirects: allow_redirects
|
||||
:param timeout: 超时时间
|
||||
"""
|
||||
if not headers:
|
||||
headers = get_user_agent()
|
||||
@@ -105,6 +112,7 @@ class AsyncHttpx:
|
||||
cookies=cookies,
|
||||
allow_redirects=allow_redirects,
|
||||
timeout=timeout,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -119,17 +127,20 @@ class AsyncHttpx:
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
cookies: Optional[Dict[str, str]] = None,
|
||||
timeout: Optional[int] = 30,
|
||||
**kwargs,
|
||||
) -> bool:
|
||||
"""
|
||||
下载文件
|
||||
:param url: url
|
||||
:param path: 存储路径
|
||||
:param params: params
|
||||
:param use_proxy: 使用代理
|
||||
:param proxy: 指定代理
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param timeout: 超时时间
|
||||
说明:
|
||||
下载文件
|
||||
参数:
|
||||
:param url: url
|
||||
:param path: 存储路径
|
||||
:param params: params
|
||||
:param use_proxy: 使用代理
|
||||
:param proxy: 指定代理
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param timeout: 超时时间
|
||||
"""
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
@@ -146,18 +157,19 @@ class AsyncHttpx:
|
||||
use_proxy=use_proxy,
|
||||
proxy=proxy,
|
||||
timeout=timeout,
|
||||
**kwargs,
|
||||
)
|
||||
).content
|
||||
async with aiofiles.open(path, "wb") as wf:
|
||||
await wf.write(content)
|
||||
logger.info(f"下载图片 {url} 成功.. Path:{path.absolute()}")
|
||||
logger.info(f"下载 {url} 成功.. Path:{path.absolute()}")
|
||||
return True
|
||||
except (TimeoutError, ConnectTimeout):
|
||||
pass
|
||||
else:
|
||||
logger.error(f"下载图片 {url} 下载超时.. Path:{path.absolute()}")
|
||||
logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}")
|
||||
except Exception as e:
|
||||
logger.error(f"下载图片 {url} 未知错误 {type(e)}:{e}.. Path:{path.absolute()}")
|
||||
logger.error(f"下载 {url} 未知错误 {type(e)}:{e}.. Path:{path.absolute()}")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@@ -173,19 +185,21 @@ class AsyncHttpx:
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
cookies: Optional[Dict[str, str]] = None,
|
||||
timeout: Optional[int] = 30,
|
||||
**kwargs,
|
||||
) -> List[bool]:
|
||||
"""
|
||||
分组同时下载文件
|
||||
:param url_list: url列表
|
||||
:param path_list: 存储路径列表
|
||||
:param limit_async_number: 限制同时请求数量
|
||||
:param params: params
|
||||
:param use_proxy: 使用代理
|
||||
:param proxy: 指定代理
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param timeout: 超时时间
|
||||
:return:
|
||||
说明:
|
||||
分组同时下载文件
|
||||
参数:
|
||||
:param url_list: url列表
|
||||
:param path_list: 存储路径列表
|
||||
:param limit_async_number: 限制同时请求数量
|
||||
:param params: params
|
||||
:param use_proxy: 使用代理
|
||||
:param proxy: 指定代理
|
||||
:param headers: 请求头
|
||||
:param cookies: cookies
|
||||
:param timeout: 超时时间
|
||||
"""
|
||||
if n := len(url_list) != len(path_list):
|
||||
raise UrlPathNumberNotEqual(
|
||||
@@ -222,7 +236,8 @@ class AsyncHttpx:
|
||||
cookies=cookies,
|
||||
use_proxy=use_proxy,
|
||||
timeout=timeout,
|
||||
proxy=proxy
|
||||
proxy=proxy,
|
||||
** kwargs,
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -235,14 +250,16 @@ class AsyncHttpx:
|
||||
class AsyncPlaywright:
|
||||
|
||||
@classmethod
|
||||
async def _new_page(cls, user_agent: Optional[str] = None) -> Page:
|
||||
async def _new_page(cls, user_agent: Optional[str] = None, **kwargs) -> Page:
|
||||
"""
|
||||
获取一个新页面
|
||||
:param user_agent: 请求头
|
||||
说明:
|
||||
获取一个新页面
|
||||
参数:
|
||||
:param user_agent: 请求头
|
||||
"""
|
||||
browser = await get_browser()
|
||||
if browser:
|
||||
return await browser.new_page(user_agent=user_agent)
|
||||
return await browser.new_page(user_agent=user_agent, **kwargs)
|
||||
raise BrowserIsNone("获取Browser失败...")
|
||||
|
||||
@classmethod
|
||||
@@ -255,17 +272,20 @@ class AsyncPlaywright:
|
||||
Literal["domcontentloaded", "load", "networkidle"]
|
||||
] = "networkidle",
|
||||
referer: str = None,
|
||||
**kwargs
|
||||
) -> Optional[Page]:
|
||||
"""
|
||||
goto
|
||||
:param url: 网址
|
||||
:param timeout: 超时限制
|
||||
:param wait_until: 等待类型
|
||||
:param referer:
|
||||
说明:
|
||||
goto
|
||||
参数:
|
||||
:param url: 网址
|
||||
:param timeout: 超时限制
|
||||
:param wait_until: 等待类型
|
||||
:param referer:
|
||||
"""
|
||||
page = None
|
||||
try:
|
||||
page = await cls._new_page()
|
||||
page = await cls._new_page(**kwargs)
|
||||
await page.goto(url, timeout=timeout, wait_until=wait_until, referer=referer)
|
||||
return page
|
||||
except Exception as e:
|
||||
@@ -288,17 +308,20 @@ class AsyncPlaywright:
|
||||
] = "networkidle",
|
||||
timeout: float = None,
|
||||
type_: Literal["jpeg", "png"] = None,
|
||||
**kwargs
|
||||
) -> Optional[MessageSegment]:
|
||||
"""
|
||||
截图,该方法仅用于简单快捷截图,复杂截图请操作 page
|
||||
:param url: 网址
|
||||
:param path: 存储路径
|
||||
:param element: 元素选择
|
||||
:param sleep: 延迟截取
|
||||
:param viewport_size: 窗口大小
|
||||
:param wait_until: 等待类型
|
||||
:param timeout: 超时限制
|
||||
:param type_: 保存类型
|
||||
说明:
|
||||
截图,该方法仅用于简单快捷截图,复杂截图请操作 page
|
||||
参数:
|
||||
:param url: 网址
|
||||
:param path: 存储路径
|
||||
:param element: 元素选择
|
||||
:param sleep: 延迟截取
|
||||
:param viewport_size: 窗口大小
|
||||
:param wait_until: 等待类型
|
||||
:param timeout: 超时限制
|
||||
:param type_: 保存类型
|
||||
"""
|
||||
page = None
|
||||
if viewport_size is None:
|
||||
@@ -306,7 +329,7 @@ class AsyncPlaywright:
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
try:
|
||||
page = await cls.goto(url, wait_until=wait_until)
|
||||
page = await cls.goto(url, wait_until=wait_until, **kwargs)
|
||||
await page.set_viewport_size(viewport_size)
|
||||
if sleep:
|
||||
await asyncio.sleep(sleep)
|
||||
|
||||
+251
-26
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from configs.path_config import IMAGE_PATH, FONT_PATH
|
||||
from PIL import Image, ImageFile, ImageDraw, ImageFont, ImageFilter
|
||||
from imagehash import ImageHash
|
||||
@@ -135,7 +136,7 @@ def is_valid(file: str) -> bool:
|
||||
return valid
|
||||
|
||||
|
||||
class CreateImg:
|
||||
class BuildImage:
|
||||
"""
|
||||
快捷生成图片与操作图片的工具类
|
||||
"""
|
||||
@@ -219,10 +220,34 @@ class CreateImg:
|
||||
if plain_text:
|
||||
fill = font_color if font_color else (0, 0, 0)
|
||||
self.text((0, 0), plain_text, fill)
|
||||
try:
|
||||
self.loop = asyncio.get_event_loop()
|
||||
except RuntimeError:
|
||||
new_loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(new_loop)
|
||||
self.loop = asyncio.get_event_loop()
|
||||
|
||||
async def apaste(
|
||||
self,
|
||||
img: "BuildImage" or Image,
|
||||
pos: Tuple[int, int] = None,
|
||||
alpha: bool = False,
|
||||
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 贴图
|
||||
参数:
|
||||
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
|
||||
:param pos: 贴图位置(左上角)
|
||||
:param alpha: 图片背景是否为透明
|
||||
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.paste, img, pos, alpha, center_type)
|
||||
|
||||
def paste(
|
||||
self,
|
||||
img: "CreateImg" or Image,
|
||||
img: "BuildImage" or Image,
|
||||
pos: Tuple[int, int] = None,
|
||||
alpha: bool = False,
|
||||
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
|
||||
@@ -231,7 +256,7 @@ class CreateImg:
|
||||
说明:
|
||||
贴图
|
||||
参数:
|
||||
:param img: 已打开的图片文件,可以为 CreateImg 或 Image
|
||||
:param img: 已打开的图片文件,可以为 BuildImage 或 Image
|
||||
:param pos: 贴图位置(左上角)
|
||||
:param alpha: 图片背景是否为透明
|
||||
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
|
||||
@@ -254,7 +279,7 @@ class CreateImg:
|
||||
width = pos[0]
|
||||
height = int((self.h - img.h) / 2)
|
||||
pos = (width, height)
|
||||
if isinstance(img, CreateImg):
|
||||
if isinstance(img, BuildImage):
|
||||
img = img.markImg
|
||||
if self.current_w == self.w:
|
||||
self.current_w = 0
|
||||
@@ -280,6 +305,18 @@ class CreateImg:
|
||||
"""
|
||||
return self.font.getsize(msg)
|
||||
|
||||
async def apoint(
|
||||
self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 绘制多个或单独的像素
|
||||
参数:
|
||||
:param pos: 坐标
|
||||
:param fill: 填错颜色
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.point, pos, fill)
|
||||
|
||||
def point(self, pos: Tuple[int, int], fill: Optional[Tuple[int, int, int]] = None):
|
||||
"""
|
||||
说明:
|
||||
@@ -290,6 +327,24 @@ class CreateImg:
|
||||
"""
|
||||
self.draw.point(pos, fill=fill)
|
||||
|
||||
async def aellipse(
|
||||
self,
|
||||
pos: Tuple[int, int, int, int],
|
||||
fill: Optional[Tuple[int, int, int]] = None,
|
||||
outline: Optional[Tuple[int, int, int]] = None,
|
||||
width: int = 1,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 绘制圆
|
||||
参数:
|
||||
:param pos: 坐标范围
|
||||
:param fill: 填充颜色
|
||||
:param outline: 描线颜色
|
||||
:param width: 描线宽度
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.ellipse, pos, fill, outline, width)
|
||||
|
||||
def ellipse(
|
||||
self,
|
||||
pos: Tuple[int, int, int, int],
|
||||
@@ -308,6 +363,24 @@ class CreateImg:
|
||||
"""
|
||||
self.draw.ellipse(pos, fill, outline, width)
|
||||
|
||||
async def atext(
|
||||
self,
|
||||
pos: Tuple[int, int],
|
||||
text: str,
|
||||
fill: Tuple[int, int, int] = (0, 0, 0),
|
||||
center_type: Optional[Literal["center", "by_height", "by_width"]] = None,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 在图片上添加文字
|
||||
参数:
|
||||
:param pos: 文字位置
|
||||
:param text: 文字内容
|
||||
:param fill: 文字颜色
|
||||
:param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.text, pos, text, fill, center_type)
|
||||
|
||||
def text(
|
||||
self,
|
||||
pos: Tuple[int, int],
|
||||
@@ -343,6 +416,15 @@ class CreateImg:
|
||||
pos = (w, h)
|
||||
self.draw.text(pos, text, fill=fill, font=self.font)
|
||||
|
||||
async def asave(self, path: Union[str, Path]):
|
||||
"""
|
||||
说明:
|
||||
异步 保存图片
|
||||
参数:
|
||||
:param path: 图片路径
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.save, path)
|
||||
|
||||
def save(self, path: Union[str, Path]):
|
||||
"""
|
||||
说明:
|
||||
@@ -361,6 +443,17 @@ class CreateImg:
|
||||
"""
|
||||
self.markImg.show(self.markImg)
|
||||
|
||||
async def aresize(self, ratio: float = 0, w: int = 0, h: int = 0):
|
||||
"""
|
||||
说明:
|
||||
异步 压缩图片
|
||||
参数:
|
||||
:param ratio: 压缩倍率
|
||||
:param w: 压缩图片宽度至 w
|
||||
:param h: 压缩图片高度至 h
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.resize, ratio, w, h)
|
||||
|
||||
def resize(self, ratio: float = 0, w: int = 0, h: int = 0):
|
||||
"""
|
||||
说明:
|
||||
@@ -380,6 +473,15 @@ class CreateImg:
|
||||
self.size = self.w, self.h
|
||||
self.draw = ImageDraw.Draw(self.markImg)
|
||||
|
||||
async def acrop(self, box: Tuple[int, int, int, int]):
|
||||
"""
|
||||
说明:
|
||||
异步 裁剪图片
|
||||
参数:
|
||||
:param box: 左上角坐标,右下角坐标 (left, upper, right, lower)
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.crop, box)
|
||||
|
||||
def crop(self, box: Tuple[int, int, int, int]):
|
||||
"""
|
||||
说明:
|
||||
@@ -401,6 +503,16 @@ class CreateImg:
|
||||
"""
|
||||
return self.font.getsize(word)[0] > self.w
|
||||
|
||||
async def atransparent(self, alpha_ratio: float = 1, n: int = 0):
|
||||
"""
|
||||
说明:
|
||||
异步 图片透明化
|
||||
参数:
|
||||
:param alpha_ratio: 透明化程度
|
||||
:param n: 透明化大小内边距
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.transparent, alpha_ratio, n)
|
||||
|
||||
def transparent(self, alpha_ratio: float = 1, n: int = 0):
|
||||
"""
|
||||
说明:
|
||||
@@ -421,7 +533,7 @@ class CreateImg:
|
||||
def pic2bs4(self) -> str:
|
||||
"""
|
||||
说明:
|
||||
CreateImg 转 base64
|
||||
BuildImage 转 base64
|
||||
"""
|
||||
buf = BytesIO()
|
||||
self.markImg.save(buf, format="PNG")
|
||||
@@ -437,6 +549,24 @@ class CreateImg:
|
||||
"""
|
||||
self.markImg = self.markImg.convert(type_)
|
||||
|
||||
async def arectangle(
|
||||
self,
|
||||
xy: Tuple[int, int, int, int],
|
||||
fill: Optional[Tuple[int, int, int]] = None,
|
||||
outline: str = None,
|
||||
width: int = 1,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 画框
|
||||
参数:
|
||||
:param xy: 坐标
|
||||
:param fill: 填充颜色
|
||||
:param outline: 轮廓颜色
|
||||
:param width: 线宽
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.rectangle, xy, fill, outline, width)
|
||||
|
||||
def rectangle(
|
||||
self,
|
||||
xy: Tuple[int, int, int, int],
|
||||
@@ -455,6 +585,54 @@ class CreateImg:
|
||||
"""
|
||||
self.draw.rectangle(xy, fill, outline, width)
|
||||
|
||||
async def apolygon(
|
||||
self,
|
||||
xy: List[Tuple[int, int]],
|
||||
fill: Tuple[int, int, int] = (0, 0, 0),
|
||||
outline: int = 1,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 画多边形
|
||||
参数:
|
||||
:param xy: 坐标
|
||||
:param fill: 颜色
|
||||
:param outline: 线宽
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.polygon, xy, fill, outline)
|
||||
|
||||
def polygon(
|
||||
self,
|
||||
xy: List[Tuple[int, int]],
|
||||
fill: Tuple[int, int, int] = (0, 0, 0),
|
||||
outline: int = 1,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
画多边形
|
||||
参数:
|
||||
:param xy: 坐标
|
||||
:param fill: 颜色
|
||||
:param outline: 线宽
|
||||
"""
|
||||
self.draw.polygon(xy, fill, outline)
|
||||
|
||||
async def aline(
|
||||
self,
|
||||
xy: Tuple[int, int, int, int],
|
||||
fill: Optional[Tuple[int, int, int]] = None,
|
||||
width: int = 1,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
异步 画线
|
||||
参数:
|
||||
:param xy: 坐标
|
||||
:param fill: 填充
|
||||
:param width: 线宽
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.line, xy, fill, width)
|
||||
|
||||
def line(
|
||||
self,
|
||||
xy: Tuple[int, int, int, int],
|
||||
@@ -471,10 +649,17 @@ class CreateImg:
|
||||
"""
|
||||
self.draw.line(xy, fill, width)
|
||||
|
||||
async def acircle(self):
|
||||
"""
|
||||
说明:
|
||||
异步 将 BuildImage 图片变为圆形
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.circle)
|
||||
|
||||
def circle(self):
|
||||
"""
|
||||
说明:
|
||||
将 CreateImg 图片变为圆形
|
||||
将 BuildImage 图片变为圆形
|
||||
"""
|
||||
self.convert("RGBA")
|
||||
r2 = min(self.w, self.h)
|
||||
@@ -494,6 +679,15 @@ class CreateImg:
|
||||
pim_b[i - (r - r3), j - (r - r3)] = pim_a[i, j]
|
||||
self.markImg = imb
|
||||
|
||||
async def acircle_corner(self, radii: int = 30):
|
||||
"""
|
||||
说明:
|
||||
异步 矩形四角变圆
|
||||
参数:
|
||||
:param radii: 半径
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.circle_corner, radii)
|
||||
|
||||
def circle_corner(self, radii: int = 30):
|
||||
"""
|
||||
说明:
|
||||
@@ -516,6 +710,16 @@ class CreateImg:
|
||||
alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii))
|
||||
self.markImg.putalpha(alpha)
|
||||
|
||||
async def arotate(self, angle: int, expand: bool = False):
|
||||
"""
|
||||
说明:
|
||||
异步 旋转图片
|
||||
参数:
|
||||
:param angle: 角度
|
||||
:param expand: 放大图片适应角度
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.rotate, angle, expand)
|
||||
|
||||
def rotate(self, angle: int, expand: bool = False):
|
||||
"""
|
||||
说明:
|
||||
@@ -526,6 +730,15 @@ class CreateImg:
|
||||
"""
|
||||
self.markImg = self.markImg.rotate(angle, expand=expand)
|
||||
|
||||
async def atranspose(self, angle: int):
|
||||
"""
|
||||
说明:
|
||||
异步 旋转图片(包括边框)
|
||||
参数:
|
||||
:param angle: 角度
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.transpose, angle)
|
||||
|
||||
def transpose(self, angle: int):
|
||||
"""
|
||||
说明:
|
||||
@@ -535,11 +748,23 @@ class CreateImg:
|
||||
"""
|
||||
self.markImg.transpose(angle)
|
||||
|
||||
async def afilter(self, filter_: str, aud: int = None):
|
||||
"""
|
||||
说明:
|
||||
异步 图片变化
|
||||
参数:
|
||||
:param filter_: 变化效果
|
||||
:param aud: 利率
|
||||
"""
|
||||
await self.loop.run_in_executor(None, self.filter, filter_, aud)
|
||||
|
||||
def filter(self, filter_: str, aud: int = None):
|
||||
"""
|
||||
图片变化
|
||||
:param filter_: 变化效果
|
||||
:param aud: 利率
|
||||
说明:
|
||||
图片变化
|
||||
参数:
|
||||
:param filter_: 变化效果
|
||||
:param aud: 利率
|
||||
"""
|
||||
_x = None
|
||||
if filter_ == "GaussianBlur": # 高斯模糊
|
||||
@@ -564,9 +789,9 @@ class CreateImg:
|
||||
self.markImg = self.markImg.getchannel(type_)
|
||||
|
||||
|
||||
class CreateMat:
|
||||
class BuildMat:
|
||||
"""
|
||||
针对 折线图/柱状图,基于 CreateImg 编写的 非常难用的 自定义画图工具
|
||||
针对 折线图/柱状图,基于 BuildImage 编写的 非常难用的 自定义画图工具
|
||||
目前仅支持 正整数
|
||||
"""
|
||||
|
||||
@@ -592,7 +817,7 @@ class CreateMat:
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
初始化 CreateMat
|
||||
初始化 BuildMat
|
||||
参数:
|
||||
:param y: 坐标值
|
||||
:param mat_type: 图像类型 可能的值:[line]: 折线图,[bar]: 柱状图,[barh]: 横向柱状图
|
||||
@@ -802,7 +1027,7 @@ class CreateMat:
|
||||
:param y: 坐标点
|
||||
:param display_num: 显示该点的值
|
||||
"""
|
||||
_black_point = CreateImg(7, 7, color=random.choice(self.bar_color))
|
||||
_black_point = BuildImage(7, 7, color=random.choice(self.bar_color))
|
||||
_black_point.circle()
|
||||
x_interval = self._x_interval
|
||||
current_w = self.padding_w + x_interval
|
||||
@@ -887,7 +1112,7 @@ class CreateMat:
|
||||
if i != len(y):
|
||||
bar_color = random.choice(self.bar_color)
|
||||
if is_barh:
|
||||
A = CreateImg(
|
||||
A = BuildImage(
|
||||
int(y[i] * self._p * self._deviation),
|
||||
self._bar_width,
|
||||
color=bar_color,
|
||||
@@ -900,7 +1125,7 @@ class CreateMat:
|
||||
),
|
||||
)
|
||||
else:
|
||||
A = CreateImg(
|
||||
A = BuildImage(
|
||||
self._bar_width,
|
||||
int(y[i] * self._p * self._deviation),
|
||||
color=bar_color,
|
||||
@@ -925,7 +1150,7 @@ class CreateMat:
|
||||
y_index: List[Union[str, int, float]] = None,
|
||||
font_size: Optional[int] = None,
|
||||
is_grid: bool = False,
|
||||
) -> CreateImg:
|
||||
) -> BuildImage:
|
||||
"""
|
||||
说明:
|
||||
初始化图像,生成xy轴
|
||||
@@ -940,15 +1165,15 @@ class CreateMat:
|
||||
padding_h = self.padding_h
|
||||
line_length = self.line_length
|
||||
background = random.choice(self.background) if self.background else None
|
||||
A = CreateImg(
|
||||
A = BuildImage(
|
||||
self.w, self.h, font_size=font_size, font=self.font, background=background
|
||||
)
|
||||
if background:
|
||||
_tmp = CreateImg(self.w, self.h)
|
||||
_tmp = BuildImage(self.w, self.h)
|
||||
_tmp.transparent(2)
|
||||
A.paste(_tmp, alpha=True)
|
||||
if self.title:
|
||||
title = CreateImg(
|
||||
title = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=self.title,
|
||||
@@ -985,14 +1210,14 @@ class CreateMat:
|
||||
y_index = tmp
|
||||
_interval = self._y_interval
|
||||
current_w = padding_w + _interval
|
||||
_text_font = CreateImg(0, 0, font_size=self.font_size, font=self.font)
|
||||
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
|
||||
_grid = self.line_length if is_grid else 10
|
||||
x_rotate_height = 0
|
||||
for _x in x_index:
|
||||
_p = CreateImg(1, _grid, color="#a9a9a9")
|
||||
_p = BuildImage(1, _grid, color="#a9a9a9")
|
||||
A.paste(_p, (current_w, padding_h + line_length - _grid))
|
||||
w = int(_text_font.getsize(f"{_x}")[0] / 2)
|
||||
text = CreateImg(
|
||||
text = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=f"{_x}",
|
||||
@@ -1006,13 +1231,13 @@ class CreateMat:
|
||||
x_rotate_height = text.h
|
||||
_interval = self._x_interval if self.mat_type == "barh" else self._y_interval
|
||||
current_h = padding_h + line_length - _interval
|
||||
_text_font = CreateImg(0, 0, font_size=self.font_size, font=self.font)
|
||||
_text_font = BuildImage(0, 0, font_size=self.font_size, font=self.font)
|
||||
for _y in y_index:
|
||||
_p = CreateImg(_grid, 1, color="#a9a9a9")
|
||||
_p = BuildImage(_grid, 1, color="#a9a9a9")
|
||||
A.paste(_p, (padding_w + 2, current_h))
|
||||
w, h = _text_font.getsize(f"{_y}")
|
||||
h = int(h / 2)
|
||||
text = CreateImg(
|
||||
text = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=f"{_y}",
|
||||
@@ -1022,7 +1247,7 @@ class CreateMat:
|
||||
)
|
||||
idx = 0
|
||||
while text.size[0] > self.padding_w - 10 and idx < 3:
|
||||
text = CreateImg(
|
||||
text = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=f"{_y}",
|
||||
|
||||
@@ -19,7 +19,11 @@ class StaticData:
|
||||
if file.exists():
|
||||
with open(file, "r", encoding="utf8") as f:
|
||||
if file.name.endswith("json"):
|
||||
self._data: dict = json.load(f)
|
||||
try:
|
||||
self._data: dict = json.load(f)
|
||||
except ValueError:
|
||||
if f.read().strip():
|
||||
raise ValueError(f"{file} 文件加载错误,请检查文件内容格式.")
|
||||
elif file.name.endswith("yaml"):
|
||||
self._data = yaml.load(f)
|
||||
|
||||
|
||||
@@ -10,10 +10,14 @@ Config.add_plugin_config(
|
||||
"group_manager", "DEFAULT_GROUP_LEVEL", 5, help_="默认群权限", default_value=5
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"group_manager", "DEFAULT_GROUP_BOT_STATUS", True, help_="默认进群总开关状态", default_value=True
|
||||
)
|
||||
|
||||
|
||||
class GroupManager(StaticData):
|
||||
"""
|
||||
群权限 | 功能 | 聊天时间 管理器
|
||||
群权限 | 功能 | 总开关 | 聊天时间 管理器
|
||||
"""
|
||||
|
||||
def __init__(self, file: Path):
|
||||
@@ -45,6 +49,41 @@ class GroupManager(StaticData):
|
||||
"""
|
||||
self._set_plugin_status(module, "unblock", group_id)
|
||||
|
||||
def turn_on_group_bot_status(self, group_id: int):
|
||||
"""
|
||||
说明:
|
||||
开启群bot开关
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
self._set_group_bot_status(group_id, True)
|
||||
|
||||
def shutdown_group_bot_status(self, group_id: int):
|
||||
"""
|
||||
说明:
|
||||
关闭群bot开关
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
self._set_group_bot_status(group_id, False)
|
||||
|
||||
def check_group_bot_status(self, group_id: int) -> bool:
|
||||
"""
|
||||
说明:
|
||||
检查群聊bot总开关状态
|
||||
参数:
|
||||
:param group_id: 说明
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
if self._data["group_manager"][group_id].get("status") is None:
|
||||
default_group_bot_status = Config.get_config("group_manager", "DEFAULT_GROUP_BOT_STATUS")
|
||||
if default_group_bot_status:
|
||||
default_group_bot_status = True
|
||||
self._data["group_manager"][group_id]["status"] = default_group_bot_status
|
||||
return self._data["group_manager"][group_id]["status"]
|
||||
|
||||
def set_group_level(self, group_id: int, level: int):
|
||||
"""
|
||||
说明:
|
||||
@@ -125,8 +164,10 @@ class GroupManager(StaticData):
|
||||
|
||||
def delete_group(self, group_id: int):
|
||||
"""
|
||||
删除群配置
|
||||
:param group_id: 群号
|
||||
说明:
|
||||
删除群配置
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
if group_id in self._data["group_manager"]:
|
||||
del self._data["group_manager"][str(group_id)]
|
||||
@@ -136,25 +177,31 @@ class GroupManager(StaticData):
|
||||
|
||||
async def open_group_task(self, group_id: int, task: str):
|
||||
"""
|
||||
开启群被动技能
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
说明:
|
||||
开启群被动技能
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
await self._set_group_task_status(group_id, task, True)
|
||||
|
||||
async def close_group_task(self, group_id: int, task: str):
|
||||
"""
|
||||
关闭群被动技能
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
说明:
|
||||
关闭群被动技能
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
await self._set_group_task_status(group_id, task, False)
|
||||
|
||||
async def check_group_task_status(self, group_id: int, task: str) -> bool:
|
||||
"""
|
||||
查看群被动技能状态
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
说明:
|
||||
查看群被动技能状态
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if (
|
||||
@@ -167,14 +214,17 @@ class GroupManager(StaticData):
|
||||
|
||||
def get_task_data(self) -> Dict[str, str]:
|
||||
"""
|
||||
获取所有被动任务
|
||||
说明:
|
||||
获取所有被动任务
|
||||
"""
|
||||
return self._task
|
||||
|
||||
async def group_task_status(self, group_id: int) -> str:
|
||||
"""
|
||||
查看群被全部动技能状态
|
||||
:param group_id: 群号
|
||||
说明:
|
||||
查看群被全部动技能状态
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
x = "[群被动技能]:\n"
|
||||
group_id = str(group_id)
|
||||
@@ -186,10 +236,12 @@ class GroupManager(StaticData):
|
||||
|
||||
async def _set_group_task_status(self, group_id: int, task: str, status: bool):
|
||||
"""
|
||||
管理群被动技能状态
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能
|
||||
:param status: 状态
|
||||
说明:
|
||||
管理群被动技能状态
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能
|
||||
:param status: 状态
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
@@ -205,7 +257,8 @@ class GroupManager(StaticData):
|
||||
|
||||
async def init_group_task(self, group_id: Optional[Union[int, str]] = None):
|
||||
"""
|
||||
初始化群聊 被动技能 状态
|
||||
说明:
|
||||
初始化群聊 被动技能 状态
|
||||
"""
|
||||
if not self._task:
|
||||
for matcher in get_matchers():
|
||||
@@ -238,7 +291,8 @@ class GroupManager(StaticData):
|
||||
):
|
||||
self._data["group_manager"][group_id]["group_task_status"][
|
||||
task
|
||||
] = True
|
||||
] = Config.get_config('_task', f'DEFAULT_{task}', default=True)
|
||||
print(task, Config.get_config('_task', f'DEFAULT_{task}'))
|
||||
for task in list(
|
||||
self._data["group_manager"][group_id]["group_task_status"]
|
||||
):
|
||||
@@ -271,7 +325,7 @@ class GroupManager(StaticData):
|
||||
else:
|
||||
if module in self._data["group_manager"][group_id]["close_plugins"]:
|
||||
self._data["group_manager"][group_id]["close_plugins"].remove(module)
|
||||
self.save()
|
||||
self.save()
|
||||
|
||||
def _init_group(self, group_id: str):
|
||||
"""
|
||||
@@ -281,18 +335,37 @@ class GroupManager(StaticData):
|
||||
:param group_id: 群号
|
||||
"""
|
||||
default_group_level = Config.get_config("group_manager", "DEFAULT_GROUP_LEVEL")
|
||||
if not default_group_level:
|
||||
if default_group_level is None:
|
||||
default_group_level = 5
|
||||
default_group_bot_status = Config.get_config("group_manager", "DEFAULT_GROUP_BOT_STATUS")
|
||||
if default_group_bot_status:
|
||||
default_group_bot_status = True
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._data["group_manager"][group_id] = {
|
||||
"level": default_group_level,
|
||||
"status": default_group_bot_status,
|
||||
"close_plugins": [],
|
||||
"group_task_status": {},
|
||||
}
|
||||
|
||||
def _set_group_bot_status(self, group_id: Union[int, str], status: bool):
|
||||
"""
|
||||
说明:
|
||||
设置群聊bot总开关
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param status: 开关状态
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
self._data["group_manager"][group_id]["status"] = status
|
||||
self.save()
|
||||
|
||||
def get_super_old_data(self) -> Optional[dict]:
|
||||
"""
|
||||
获取旧数据,平时使用请不要调用
|
||||
说明:
|
||||
获取旧数据,平时使用请不要调用
|
||||
"""
|
||||
if self._data["super"].get("close_plugins"):
|
||||
_x = self._data["super"].get("close_plugins")
|
||||
|
||||
@@ -3,7 +3,7 @@ from nonebot.adapters.cqhttp import Bot
|
||||
from nonebot.adapters.cqhttp.exception import ActionFailed
|
||||
from services.log import logger
|
||||
from typing import Optional
|
||||
from utils.image_utils import CreateImg
|
||||
from utils.image_utils import BuildImage
|
||||
from utils.utils import get_user_avatar
|
||||
from pathlib import Path
|
||||
from io import BytesIO
|
||||
@@ -128,27 +128,27 @@ class RequestManager(StaticData):
|
||||
comment = data[id_]["comment"] if type_ == "private" else ""
|
||||
from_ = data[id_]["from"]
|
||||
sex = data[id_]["sex"]
|
||||
ava = CreateImg(
|
||||
ava = BuildImage(
|
||||
80, 80, background=BytesIO(await get_user_avatar(data[id_]["id"]))
|
||||
)
|
||||
ava.circle()
|
||||
age_bk = CreateImg(
|
||||
age_bk = BuildImage(
|
||||
len(str(age)) * 10 - 5,
|
||||
15,
|
||||
color="#04CAF7" if sex == "male" else "#F983C1",
|
||||
)
|
||||
age_bk.text((3, 1), f"{age}", fill=(255, 255, 255))
|
||||
x = CreateImg(
|
||||
x = BuildImage(
|
||||
90, 32, font_size=15, color="#EEEFF4", font="HYWenHei-85W.ttf"
|
||||
)
|
||||
x.text((0, 0), "同意/拒绝", center_type="center")
|
||||
x.circle_corner(10)
|
||||
A = CreateImg(500, 100, font_size=24, font="msyh.ttf")
|
||||
A = BuildImage(500, 100, font_size=24, font="msyh.ttf")
|
||||
A.paste(ava, (15, 0), alpha=True, center_type="by_height")
|
||||
A.text((120, 15), nickname)
|
||||
A.paste(age_bk, (120, 50), True)
|
||||
A.paste(
|
||||
CreateImg(
|
||||
BuildImage(
|
||||
200,
|
||||
0,
|
||||
font_size=12,
|
||||
@@ -160,7 +160,7 @@ class RequestManager(StaticData):
|
||||
)
|
||||
if type_ == "private":
|
||||
A.paste(
|
||||
CreateImg(
|
||||
BuildImage(
|
||||
200,
|
||||
0,
|
||||
font_size=12,
|
||||
@@ -172,7 +172,7 @@ class RequestManager(StaticData):
|
||||
)
|
||||
else:
|
||||
A.paste(
|
||||
CreateImg(
|
||||
BuildImage(
|
||||
200,
|
||||
0,
|
||||
font_size=12,
|
||||
@@ -184,7 +184,7 @@ class RequestManager(StaticData):
|
||||
)
|
||||
A.paste(x, (380, 35), True)
|
||||
A.paste(
|
||||
CreateImg(
|
||||
BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=f"id:{id_}",
|
||||
@@ -195,10 +195,10 @@ class RequestManager(StaticData):
|
||||
True,
|
||||
)
|
||||
img_list.append(A)
|
||||
A = CreateImg(500, len(img_list) * 100, 500, 100)
|
||||
A = BuildImage(500, len(img_list) * 100, 500, 100)
|
||||
for img in img_list:
|
||||
A.paste(img)
|
||||
bk = CreateImg(A.w, A.h + 50, color="#F8F9FB", font_size=20)
|
||||
bk = BuildImage(A.w, A.h + 50, color="#F8F9FB", font_size=20)
|
||||
bk.paste(A, (0, 50))
|
||||
bk.text(
|
||||
(15, 13), "好友请求" if type_ == "private" else "群聊请求", fill=(140, 140, 143)
|
||||
|
||||
@@ -69,11 +69,11 @@ class ResourcesManager(StaticData):
|
||||
for module in self._data.keys():
|
||||
for source_path in self._data[module].keys():
|
||||
move_path = Path(self._data[module][source_path])
|
||||
source_path = Path(source_path)
|
||||
file_name = source_path.name
|
||||
move_path = move_path / file_name
|
||||
move_path.mkdir(exist_ok=True, parents=True)
|
||||
try:
|
||||
source_path = Path(source_path)
|
||||
file_name = source_path.name
|
||||
move_path = move_path / file_name
|
||||
move_path.mkdir(exist_ok=True, parents=True)
|
||||
if source_path.exists():
|
||||
if move_path.exists():
|
||||
shutil.rmtree(str(move_path.absolute()), ignore_errors=True)
|
||||
|
||||
Reference in New Issue
Block a user