id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
188,231
import random from asyncio.exceptions import TimeoutError from datetime import datetime from typing import Optional, Tuple, Union from bilireq import dynamic from bilireq.exceptions import ResponseCodeError from bilireq.grpc.dynamic import grpc_get_user_dynamics from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType from bilireq.live import get_room_info_by_id from bilireq.user import get_videos from nonebot.adapters.onebot.v11 import Message, MessageSegment from configs.config import Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.browser import get_browser from utils.http_utils import AsyncHttpx, AsyncPlaywright from utils.manager import resources_manager from utils.message_builder import image from utils.utils import get_bot, get_local_proxy from .model import BilibiliSub from .utils import get_meta, get_user_card class BilibiliSub(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" sub_id = fields.CharField(255) """订阅id""" sub_type = fields.CharField(255) """订阅类型""" sub_users = fields.TextField() """订阅用户""" live_short_id = fields.CharField(255, null=True) """直播短id""" live_status = fields.IntField(null=True) """直播状态 0: 停播 1: 直播""" uid = fields.CharField(255, null=True) """主播/UP UID""" uname = fields.CharField(255, null=True) """主播/UP 名称""" latest_video_created = fields.BigIntField(null=True) """最后视频上传时间""" dynamic_upload_time = fields.BigIntField(null=True, default=0) """动态发布时间""" season_name = fields.CharField(255, null=True) """番剧名称""" season_id = fields.IntField(null=True) """番剧id""" season_current_episode = fields.CharField(255, null=True) """番剧最新集数""" season_update_time = fields.DateField(null=True) """番剧更新日期""" class Meta: table = "bilibili_sub" table_description = "B站订阅数据表" unique_together = ("sub_id", "sub_type") async def sub_handle( cls, sub_id: str, sub_type: Optional[str] = None, sub_user: str = "", *, live_short_id: Optional[str] = None, live_status: Optional[int] = None, dynamic_upload_time: int = 0, uid: Optional[str] = None, uname: Optional[str] = None, latest_video_created: Optional[int] = None, season_name: Optional[str] = None, season_id: Optional[int] = None, season_current_episode: Optional[str] = None, season_update_time: Optional[datetime] = None, ) -> bool: """ 说明: 添加订阅 参数: :param sub_id: 订阅名称,房间号,番剧号等 :param sub_type: 订阅类型 :param sub_user: 订阅此条目的用户 :param live_short_id: 直接短 id :param live_status: 主播开播状态 :param dynamic_upload_time: 主播/UP最新动态时间 :param uid: 主播/UP uid :param uname: 用户名称 :param latest_video_created: 最新视频上传时间 :param season_name: 番剧名称 :param season_id: 番剧 season_id :param season_current_episode: 番剧最新集数 :param season_update_time: 番剧更新时间 """ sub_id = str(sub_id) try: data = { "sub_type": sub_type, "sub_user": sub_user, "live_short_id": live_short_id, "live_status": live_status, "dynamic_upload_time": dynamic_upload_time, "uid": uid, "uname": uname, "latest_video_created": latest_video_created, "season_name": season_name, "season_id": season_id, "season_current_episode": season_current_episode, "season_update_time": season_update_time, } if sub_user: sub_user = sub_user if sub_user[-1] == "," else f"{sub_user}," sub = None if sub_type: sub = await cls.get_or_none(sub_id=sub_id, sub_type=sub_type) else: sub = await cls.get_or_none(sub_id=sub_id) if sub: sub_users = sub.sub_users + sub_user data["sub_type"] = sub_type or sub.sub_type data["sub_users"] = sub_users data["live_short_id"] = live_short_id or sub.live_short_id data["live_status"] = ( live_status if live_status is not None else sub.live_status ) data["dynamic_upload_time"] = ( dynamic_upload_time or sub.dynamic_upload_time ) data["uid"] = uid or sub.uid data["uname"] = uname or sub.uname data["latest_video_created"] = ( latest_video_created or sub.latest_video_created ) data["season_name"] = season_name or sub.season_name data["season_id"] = season_id or sub.season_id data["season_current_episode"] = ( season_current_episode or sub.season_current_episode ) data["season_update_time"] = ( season_update_time or sub.season_update_time ) else: await cls.create(sub_id=sub_id, sub_type=sub_type, sub_users=sub_user) await cls.update_or_create(sub_id=sub_id, defaults=data) return True except Exception as e: logger.error(f"添加订阅 Id: {sub_id} 错误", e=e) return False async def delete_bilibili_sub( cls, sub_id: str, sub_user: str, sub_type: Optional[str] = None ) -> bool: """ 说明: 删除订阅 参数: :param sub_id: 订阅名称 :param sub_user: 删除此条目的用户 """ try: group_id = None contains_str = sub_user if ":" in sub_user: group_id = sub_user.split(":")[1] contains_str = f":{group_id}" if sub_type: sub = await cls.get_or_none( sub_id=sub_id, sub_type=sub_type, sub_users__contains=contains_str ) else: sub = await cls.get_or_none( sub_id=sub_id, sub_users__contains=contains_str ) if not sub: return False if group_id: sub.sub_users = ",".join( [s for s in sub.sub_users.split(",") if f":{group_id}" not in s] ) else: sub.sub_users = sub.sub_users.replace(f"{sub_user},", "") if sub.sub_users.strip(): await sub.save(update_fields=["sub_users"]) else: await sub.delete() return True except Exception as e: logger.error(f"bilibili_sub 删除订阅错误", target=sub_id, e=e) return False async def get_all_sub_data( cls, ) -> Tuple[List["BilibiliSub"], List["BilibiliSub"], List["BilibiliSub"]]: """ 说明: 分类获取所有数据 """ live_data = [] up_data = [] season_data = [] query = await cls.all() for x in query: if x.sub_type == "live": live_data.append(x) if x.sub_type == "up": up_data.append(x) if x.sub_type == "season": season_data.append(x) return live_data, up_data, season_data def _run_script(cls): return [ "ALTER TABLE bilibili_sub ALTER COLUMN season_update_time TYPE timestamp with time zone USING season_update_time::timestamp with time zone;", "alter table bilibili_sub alter COLUMN sub_id type varchar(255);", # 将sub_id字段改为字符串 "alter table bilibili_sub alter COLUMN live_short_id type varchar(255);", # 将live_short_id字段改为字符串 "alter table bilibili_sub alter COLUMN uid type varchar(255);", # 将live_short_id字段改为字符串 ] The provided code snippet includes necessary dependencies for implementing the `delete_sub` function. Write a Python function `async def delete_sub(sub_id: str, sub_user: str) -> str` to solve the following problem: 删除订阅 :param sub_id: 订阅 id :param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group) Here is the function: async def delete_sub(sub_id: str, sub_user: str) -> str: """ 删除订阅 :param sub_id: 订阅 id :param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group) """ if await BilibiliSub.delete_bilibili_sub(sub_id, sub_user): return f"已成功取消订阅:{sub_id}" else: return f"取消订阅:{sub_id} 失败,请检查是否订阅过该Id...."
删除订阅 :param sub_id: 订阅 id :param sub_user: 订阅用户 id # 7384933:private or 7384933:2342344(group)
188,232
import random from asyncio.exceptions import TimeoutError from datetime import datetime from typing import Optional, Tuple, Union from bilireq import dynamic from bilireq.exceptions import ResponseCodeError from bilireq.grpc.dynamic import grpc_get_user_dynamics from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType from bilireq.live import get_room_info_by_id from bilireq.user import get_videos from nonebot.adapters.onebot.v11 import Message, MessageSegment from configs.config import Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.browser import get_browser from utils.http_utils import AsyncHttpx, AsyncPlaywright from utils.manager import resources_manager from utils.message_builder import image from utils.utils import get_bot, get_local_proxy from .model import BilibiliSub from .utils import get_meta, get_user_card SEARCH_URL = "https://api.bilibili.com/x/web-interface/search/all/v2" class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ The provided code snippet includes necessary dependencies for implementing the `get_media_id` function. Write a Python function `async def get_media_id(keyword: str) -> Optional[dict]` to solve the following problem: 获取番剧的 media_id :param keyword: 番剧名称 Here is the function: async def get_media_id(keyword: str) -> Optional[dict]: """ 获取番剧的 media_id :param keyword: 番剧名称 """ params = {"keyword": keyword} for _ in range(3): try: _season_data = {} response = await AsyncHttpx.get(SEARCH_URL, params=params, timeout=5) if response.status_code == 200: data = response.json() if data.get("data"): for item in data["data"]["result"]: if item["result_type"] == "media_bangumi": idx = 0 for x in item["data"]: _season_data[idx] = { "media_id": x["media_id"], "title": x["title"] .replace('<em class="keyword">', "") .replace("</em>", ""), } idx += 1 return _season_data except TimeoutError: pass return {}
获取番剧的 media_id :param keyword: 番剧名称
188,233
import random from asyncio.exceptions import TimeoutError from datetime import datetime from typing import Optional, Tuple, Union from bilireq import dynamic from bilireq.exceptions import ResponseCodeError from bilireq.grpc.dynamic import grpc_get_user_dynamics from bilireq.grpc.protos.bilibili.app.dynamic.v2.dynamic_pb2 import DynamicType from bilireq.live import get_room_info_by_id from bilireq.user import get_videos from nonebot.adapters.onebot.v11 import Message, MessageSegment from configs.config import Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.browser import get_browser from utils.http_utils import AsyncHttpx, AsyncPlaywright from utils.manager import resources_manager from utils.message_builder import image from utils.utils import get_bot, get_local_proxy from .model import BilibiliSub from .utils import get_meta, get_user_card async def _get_live_status(id_: str) -> str: """ 获取直播订阅状态 :param id_: 直播间 id """ """bilibili_api.live库的LiveRoom类中get_room_info改为bilireq.live库的get_room_info_by_id方法""" live_info = await get_room_info_by_id(id_) title = live_info["title"] room_id = live_info["room_id"] live_status = live_info["live_status"] cover = live_info["user_cover"] if sub := await BilibiliSub.get_or_none(sub_id=id_): if sub.live_status != live_status: await BilibiliSub.sub_handle(id_, live_status=live_status) if sub.live_status in [0, 2] and live_status == 1: return ( f"" f"{image(cover)}\n" f"{sub.uname} 开播啦!\n" f"标题:{title}\n" f"直链:https://live.bilibili.com/{room_id}" ) return "" async def _get_up_status( id_: str, live_id: Optional[str] = None ) -> Union[Message, str]: """获取up动态 参数: id_: up的id live_id: 直播间id,当订阅直播间时才有. 返回: Union[Message, str]: 消息 """ rst = "" if _user := await BilibiliSub.get_or_none(sub_id=live_id or id_): dynamics = None dynamic = None uname = "" try: dynamics = ( await grpc_get_user_dynamics(int(id_), proxy=get_local_proxy()) ).list except Exception as e: logger.error("获取动态失败...", target=id_, e=e) if dynamics: uname = dynamics[0].modules[0].module_author.author.name for dyn in dynamics: if int(dyn.extend.dyn_id_str) > _user.dynamic_upload_time: dynamic = dyn break if not dynamic: logger.debug(f"{_user.sub_type}:{id_} 未有任何动态, 已跳过....") return "" if _user.uname != uname: await BilibiliSub.sub_handle(live_id or id_, uname=uname) dynamic_img, link = await get_user_dynamic(dynamic.extend.dyn_id_str, _user) if not dynamic_img: logger.debug(f"{id_} 未发布新动态或截图失败, 已跳过....") return "" await BilibiliSub.sub_handle( live_id or id_, dynamic_upload_time=int(dynamic.extend.dyn_id_str) ) rst += ( f"{uname} {TYPE2MSG.get(dynamic.card_type, TYPE2MSG[0])}!\n" + dynamic_img + f"\n{link}\n" ) video_info = "" if video_list := [ module for module in dynamic.modules if str(module.module_dynamic.dyn_archive) ]: video = video_list[0].module_dynamic.dyn_archive video_info = ( image(video.cover) + f"标题: {video.title}\nBvid: {video.bvid}\n直链: https://www.bilibili.com/video/{video.bvid}" ) rst += video_info + "\n" download_dynamic_image = Config.get_config( "bilibili_sub", "DOWNLOAD_DYNAMIC_IMAGE" ) draw_info = "" if download_dynamic_image and ( draw_list := [ module.module_dynamic.dyn_draw for module in dynamic.modules if str(module.module_dynamic.dyn_draw) ] ): idx = 0 for draws in draw_list: for draw in list(draws.items): path = ( TEMP_PATH / f"{_user.uid}_{dynamic.extend.dyn_id_str}_draw_{idx}.jpg" ) if await AsyncHttpx.download_file(draw.src, path): draw_info += image(path) idx += 1 if draw_info: rst += "动态图片\n" + draw_info + "\n" return rst async def _get_season_status(id_: str) -> str: """ 获取 番剧 更新状态 :param id_: 番剧 id """ """bilibili_api.bangumi库中get_meta改为bilireq.bangumi库的get_meta方法""" season_info = await get_meta(id_) title = season_info["media"]["title"] if data := await BilibiliSub.get_or_none(sub_id=id_): _idx = data.season_current_episode new_ep = season_info["media"]["new_ep"]["index"] if new_ep != _idx: await BilibiliSub.sub_handle( id_, season_current_episode=new_ep, season_update_time=datetime.now() ) return ( f'{image(season_info["media"]["cover"])}\n' f"[{title}]更新啦\n" f"最新集数:{new_ep}" ) return "" class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) The provided code snippet includes necessary dependencies for implementing the `get_sub_status` function. Write a Python function `async def get_sub_status(id_: str, sub_id: str, sub_type: str) -> Union[Message, str]` to solve the following problem: 获取订阅状态 :param id_: 订阅 id :param sub_type: 订阅类型 Here is the function: async def get_sub_status(id_: str, sub_id: str, sub_type: str) -> Union[Message, str]: """ 获取订阅状态 :param id_: 订阅 id :param sub_type: 订阅类型 """ try: if sub_type == "live": return await _get_live_status(id_) elif sub_type == "up": return await _get_up_status(id_, sub_id) elif sub_type == "season": return await _get_season_status(id_) except ResponseCodeError as e: logger.error(f"Id:{id_} 获取信息失败...", e=e) # return f"Id:{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试..." except Exception as e: logger.error(f"获取订阅状态发生预料之外的错误 Id_:{id_}", e=e) # return "发生了预料之外的错误..请稍后再试或联系管理员....." return ""
获取订阅状态 :param id_: 订阅 id :param sub_type: 订阅类型
188,234
from nonebot import on_command from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message from nonebot.params import CommandArg from utils.http_utils import AsyncHttpx from services.log import logger import ujson as json HHSH_GUESS_URL = "https://lab.magiconch.com/api/nbnhhsh/guess" nbnhhsh = on_command("nbnhhsh", aliases={"能不能好好说话"}, priority=5, block=True) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def _(event: MessageEvent, arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() if not msg: await nbnhhsh.finish("没话说就别说话!") response = await AsyncHttpx.post( HHSH_GUESS_URL, data=json.dumps({"text": msg}), timeout=5, headers={"content-type": "application/json"}, ) try: data = response.json() tmp = "" rst = "" for x in data: trans = "" if x.get("trans"): trans = x["trans"][0] elif x.get("inputting"): trans = ",".join(x["inputting"]) tmp += f'{x["name"]} -> {trans}\n' rst += trans logger.info( f"(USER {event.user_id}, GROUP " f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 发送能不能好好说话: {msg} -> {rst}" ) await nbnhhsh.send(f"{tmp}={rst}", at_sender=True) except (IndexError, KeyError): await nbnhhsh.finish("没有找到对应的翻译....")
null
188,235
import asyncio import os import random import re from io import BytesIO from typing import List import jieba import jieba.analyse import matplotlib.pyplot as plt import numpy as np from emoji import replace_emoji from PIL import Image as IMG from wordcloud import ImageColorGenerator, WordCloud from configs.config import Config from configs.path_config import FONT_PATH, IMAGE_PATH from models.chat_history import ChatHistory from services import logger from utils.http_utils import AsyncHttpx async def pre_precess(msg: List[str], config) -> str: return await asyncio.get_event_loop().run_in_executor( None, _pre_precess, msg, config ) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ async def draw_word_cloud(messages, config): wordcloud_dir = IMAGE_PATH / "wordcloud" wordcloud_dir.mkdir(exist_ok=True, parents=True) # 默认用真寻图片 zx_logo_path = wordcloud_dir / "default.png" wordcloud_ttf = FONT_PATH / "STKAITI.TTF" if not os.listdir(wordcloud_dir): url = "https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/image/wordcloud/default.png" try: await AsyncHttpx.download_file(url, zx_logo_path) except Exception as e: logger.error(f"词云图片资源下载发生错误 {type(e)}:{e}") return False if not wordcloud_ttf.exists(): ttf_url = "https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/font/STKAITI.TTF" try: await AsyncHttpx.download_file(ttf_url, wordcloud_ttf) except Exception as e: logger.error(f"词云字体资源下载发生错误 {type(e)}:{e}") return False topK = min(int(len(messages)), 100000) read_name = jieba.analyse.extract_tags( await pre_precess(messages, config), topK=topK, withWeight=True, allowPOS=() ) name = [] value = [] for t in read_name: name.append(t[0]) value.append(t[1]) for i in range(len(name)): name[i] = str(name[i]) dic = dict(zip(name, value)) if Config.get_config("word_clouds", "WORD_CLOUDS_TEMPLATE") == 1: def random_pic(base_path: str) -> str: path_dir = os.listdir(base_path) path = random.sample(path_dir, 1)[0] return str(base_path) + "/" + str(path) mask = np.array(IMG.open(random_pic(wordcloud_dir))) wc = WordCloud( font_path=f"{wordcloud_ttf}", background_color="white", max_font_size=100, width=1920, height=1080, mask=mask, ) wc.generate_from_frequencies(dic) image_colors = ImageColorGenerator(mask, default_color=(255, 255, 255)) wc.recolor(color_func=image_colors) plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear") plt.axis("off") else: wc = WordCloud( font_path=str(wordcloud_ttf), width=1920, height=1200, background_color="black", ) wc.generate_from_frequencies(dic) bytes_io = BytesIO() img = wc.to_image() img.save(bytes_io, format="PNG") return bytes_io.getvalue()
null
188,236
import asyncio import os import random import re from io import BytesIO from typing import List import jieba import jieba.analyse import matplotlib.pyplot as plt import numpy as np from emoji import replace_emoji from PIL import Image as IMG from wordcloud import ImageColorGenerator, WordCloud from configs.config import Config from configs.path_config import FONT_PATH, IMAGE_PATH from models.chat_history import ChatHistory from services import logger from utils.http_utils import AsyncHttpx class ChatHistory(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" text = fields.TextField(null=True) """文本内容""" plain_text = fields.TextField(null=True) """纯文本""" create_time = fields.DatetimeField(auto_now_add=True) """创建时间""" bot_id = fields.CharField(255, null=True) """bot记录id""" class Meta: table = "chat_history" table_description = "聊天记录数据表" async def get_group_msg_rank( cls, gid: Union[int, str], limit: int = 10, order: str = "DESC", date_scope: Optional[Tuple[datetime, datetime]] = None, ) -> List["ChatHistory"]: """ 说明: 获取排行数据 参数: :param gid: 群号 :param limit: 获取数量 :param order: 排序类型,desc,des :param date_scope: 日期范围 """ o = "-" if order == "DESC" else "" query = cls.filter(group_id=str(gid)) if date_scope: query = query.filter(create_time__range=date_scope) return list( await query.annotate(count=Count("user_id")) .order_by(o + "count") .group_by("user_id") .limit(limit) .values_list("user_id", "count") ) # type: ignore async def get_group_first_msg_datetime( cls, group_id: Union[int, str] ) -> Optional[datetime]: """ 说明: 获取群第一条记录消息时间 参数: :param group_id: 群组id """ if ( message := await cls.filter(group_id=str(group_id)) .order_by("create_time") .first() ): return message.create_time async def get_message( cls, uid: Union[int, str], gid: Union[int, str], type_: Literal["user", "group"], msg_type: Optional[Literal["private", "group"]] = None, days: Optional[Union[int, Tuple[datetime, datetime]]] = None, ) -> List["ChatHistory"]: """ 说明: 获取消息查询query 参数: :param uid: 用户id :param gid: 群聊id :param type_: 类型,私聊或群聊 :param msg_type: 消息类型,用户或群聊 :param days: 限制日期 """ if type_ == "user": query = cls.filter(user_id=str(uid)) if msg_type == "private": query = query.filter(group_id__isnull=True) elif msg_type == "group": query = query.filter(group_id__not_isnull=True) else: query = cls.filter(group_id=str(gid)) if uid: query = query.filter(user_id=str(uid)) if days: if isinstance(days, int): query = query.filter( create_time__gte=datetime.now() - timedelta(days=days) ) elif isinstance(days, tuple): query = query.filter(create_time__range=days) return await query.all() # type: ignore async def _run_script(cls): return [ "alter table chat_history alter group_id drop not null;", # 允许 group_id 为空 "alter table chat_history alter text drop not null;", # 允许 text 为空 "alter table chat_history alter plain_text drop not null;", # 允许 plain_text 为空 "ALTER TABLE chat_history RENAME COLUMN user_qq TO user_id;", # 将user_id改为user_id "ALTER TABLE chat_history ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE chat_history ALTER COLUMN group_id TYPE character varying(255);", "ALTER TABLE chat_history ADD bot_id VARCHAR(255);", # 添加bot_id字段 "ALTER TABLE chat_history ALTER COLUMN bot_id TYPE character varying(255);", ] async def get_list_msg(user_id, group_id, days): messages_list = await ChatHistory().get_message( uid=user_id, gid=group_id, type_="group", days=days ) if messages_list: messages = [i.plain_text for i in messages_list] return messages else: return False
null
188,237
from nonebot import on_regex from services.log import logger from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent from nonebot.typing import T_State from utils.http_utils import AsyncHttpx quotations = on_regex("^(语录|二次元)$", priority=5, block=True) url = "https://international.v1.hitokoto.cn/?c=a" class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ async def _(bot: Bot, event: MessageEvent, state: T_State): data = (await AsyncHttpx.get(url, timeout=5)).json() result = f'{data["hitokoto"]}\t——{data["from"]}' await quotations.send(result) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 发送语录:" + result )
null
188,238
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.message_builder import at from utils.utils import is_number from ._data_source import remove_image from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser del_keyword = on_command( "删除pix关键词", aliases={"删除pix关键字"}, permission=SUPERUSER, priority=1, block=True ) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(event: MessageEvent, arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() if not msg: await del_keyword.finish("好好输入要删除什么关键字啊笨蛋!") if is_number(msg): msg = f"uid:{msg}" if msg.lower().startswith("pid"): msg = "pid:" + msg.replace("pid", "").replace(":", "") if data := await PixivKeywordUser.get_or_none(keyword=msg): await data.delete() await del_keyword.send(f"删除搜图关键词/UID:{msg} 成功...") logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 删除了pixiv搜图关键词:" + msg ) else: await del_keyword.send(f"未查询到搜索关键词/UID/PID:{msg},删除失败!")
null
188,239
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.message_builder import at from utils.utils import is_number from ._data_source import remove_image from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser del_pic = on_command("删除pix图片", permission=SUPERUSER, priority=1, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False async def remove_image(pid: int, img_p: Optional[str]): """ 删除置顶图片 :param pid: pid :param img_p: 图片 p 如 p0,p1 等 """ if img_p: if "p" not in img_p: img_p = f"p{img_p}" if img_p: await Pixiv.filter(pid=pid, img_p=img_p).delete() else: await Pixiv.filter(pid=pid).delete() class Pixiv(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" pid = fields.BigIntField() """pid""" uid = fields.BigIntField() """uid""" author = fields.CharField(255) """作者""" title = fields.CharField(255) """标题""" width = fields.IntField() """宽度""" height = fields.IntField() """高度""" view = fields.IntField() """pixiv查看数""" bookmarks = fields.IntField() """收藏数""" tags = fields.TextField() """tags""" img_url = fields.CharField(255) """pixiv url链接""" img_p = fields.CharField(255) """图片pN""" is_r18 = fields.BooleanField() class Meta: table = "pixiv" table_description = "pix图库数据表" unique_together = ("pid", "img_url", "img_p") # 0:非r18 1:r18 2:混合 async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, r18: Optional[int] = 0, num: int = 100, ) -> List[Optional["Pixiv"]]: """ 说明: 查找符合条件的图片 参数: :param keywords: 关键词 :param uid: 画师uid :param pid: 图片pid :param r18: 是否r18,0:非r18 1:r18 2:混合 :param num: 查找图片的数量 """ if not num: return [] query = cls if r18 == 0: query = query.filter(is_r18=False) elif r18 == 1: query = query.filter(is_r18=True) if keywords: for keyword in keywords: query = query.filter(tags__contains=keyword) elif uid: query = query.filter(uid=uid) elif pid: query = query.filter(pid=pid) query = query.annotate(rand=Random()).limit(num) return await query.all() # type: ignore async def get_keyword_num(cls, tags: Optional[List[str]] = None) -> Tuple[int, int]: """ 说明: 获取相关关键词(keyword, tag)在图库中的数量 参数: :param tags: 关键词/Tag """ query = cls if tags: for tag in tags: query = query.filter(tags__contains=tag) else: query = query.all() count = await query.filter(is_r18=False).count() r18_count = await query.filter(is_r18=True).count() return count, r18_count class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()): pid_arr = arg.extract_plain_text().strip() if pid_arr: msg = "" black_pid = "" flag = False pid_arr = pid_arr.split() if pid_arr[-1] in ["-black", "-b"]: flag = True pid_arr = pid_arr[:-1] for pid in pid_arr: img_p = None if "p" in pid or "ugoira" in pid: if "p" in pid: img_p = pid.split("p")[-1] pid = pid.replace("_", "") pid = pid[: pid.find("p")] elif "ugoira" in pid: img_p = pid.split("ugoira")[-1] pid = pid.replace("_", "") pid = pid[: pid.find("ugoira")] if is_number(pid): if await Pixiv.query_images(pid=int(pid), r18=2): if await remove_image(int(pid), img_p): msg += f'{pid}{f"_p{img_p}" if img_p else ""},' if flag: # if await PixivKeywordUser.add_keyword( # 114514, # 114514, # f"black:{pid}{f'_p{img_p}' if img_p else ''}", # bot.config.superusers, # ): if await PixivKeywordUser.exists( keyword=f"black:{pid}{f'_p{img_p}' if img_p else ''}" ): await PixivKeywordUser.create( user_id="114514", group_id="114514", keyword=f"black:{pid}{f'_p{img_p}' if img_p else ''}", is_pass=False, ) black_pid += f'{pid}{f"_p{img_p}" if img_p else ""},' logger.info( f"(USER {event.user_id}, GROUP " f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 删除了PIX图片 PID:{pid}{f'_p{img_p}' if img_p else ''}" ) # else: # await del_pic.send( # f"PIX:删除pid:{pid}{f'_p{img_p}' if img_p else ''} 失败.." # ) else: await del_pic.send( f"PIX:图片pix:{pid}{f'_p{img_p}' if img_p else ''} 不存在...无法删除.." ) else: await del_pic.send(f"PID必须为数字!pid:{pid}", at_sender=True) await del_pic.send(f"PIX:成功删除图片:{msg[:-1]}") if flag: await del_pic.send(f"成功图片PID加入黑名单:{black_pid[:-1]}") else: await del_pic.send("虚空删除?")
null
188,240
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.message_builder import at from utils.utils import is_number from ._data_source import remove_image from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser pass_keyword = on_command( "通过pix关键词", aliases={"通过pix关键字", "取消pix关键词", "取消pix关键字"}, permission=SUPERUSER, priority=1, block=True, ) class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: def at(qq: Union[int, str]) -> MessageSegment: { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: class PixivKeywordUser(Model): async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: async def get_black_pid(cls) -> List[str]: async def _run_script(cls): async def _( bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg(), ): tmp = {"group": {}, "private": {}} msg = arg.extract_plain_text().strip() if not msg: await pass_keyword.finish("通过虚空的关键词/UID?离谱...") msg = msg.split() flag = cmd[0][:2] == "通过" for x in msg: if x.lower().startswith("uid"): x = x.replace("uid", "").replace(":", "") x = f"uid:{x}" elif x.lower().startswith("pid"): x = x.replace("pid", "").replace(":", "") x = f"pid:{x}" if x.lower().find("pid") != -1 or x.lower().find("uid") != -1: if not is_number(x[4:]): await pass_keyword.send(f"UID/PID:{x} 非全数字,跳过该关键词...") continue data = await PixivKeywordUser.get_or_none(keyword=x) user_id = 0 group_id = 0 if data: data.is_pass = flag await data.save(update_fields=["is_pass"]) user_id, group_id = data.user_id, data.group_id if not user_id: await pass_keyword.send(f"未找到关键词/UID:{x},请检查关键词/UID是否存在...") continue if flag: if group_id == -1: if not tmp["private"].get(user_id): tmp["private"][user_id] = {"keyword": [x]} else: tmp["private"][user_id]["keyword"].append(x) else: if not tmp["group"].get(group_id): tmp["group"][group_id] = {} if not tmp["group"][group_id].get(user_id): tmp["group"][group_id][user_id] = {"keyword": [x]} else: tmp["group"][group_id][user_id]["keyword"].append(x) msg = " ".join(msg) await pass_keyword.send(f"已成功{cmd[0][:2]}搜图关键词:{msg}....") for user in tmp["private"]: x = ",".join(tmp["private"][user]["keyword"]) await bot.send_private_msg( user_id=user, message=f"你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..." ) for group in tmp["group"]: for user in tmp["group"][group]: x = ",".join(tmp["group"][group][user]["keyword"]) await bot.send_group_msg( group_id=group, message=Message(f"{at(user)}你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..."), ) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 通过了pixiv搜图关键词/UID:" + msg )
null
188,241
import asyncio from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, Message, MessageEvent from nonebot.params import CommandArg from utils.message_builder import image from ._data_source import gen_keyword_pic, get_keyword_num from ._model.pixiv_keyword_user import PixivKeywordUser my_keyword = on_command("我的pix关键词", aliases={"我的pix关键字"}, priority=1, block=True) class PixivKeywordUser(Model): async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: async def get_black_pid(cls) -> List[str]: async def _run_script(cls): async def _(event: MessageEvent): data = await PixivKeywordUser.filter(user_id=str(event.user_id)).values_list( "keyword", flat=True ) if not data: await my_keyword.finish("您目前没有提供任何Pixiv搜图关键字...", at_sender=True) await my_keyword.send(f"您目前提供的如下关键字:\n\t" + ",".join(data))
null
188,242
import asyncio from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, Message, MessageEvent from nonebot.params import CommandArg from utils.message_builder import image from ._data_source import gen_keyword_pic, get_keyword_num from ._model.pixiv_keyword_user import PixivKeywordUser command("显示pix关键词", aliases={"显示pix关键字"}, priority=1, block=True) def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") def gen_keyword_pic( _pass_keyword: List[str], not_pass_keyword: List[str], is_superuser: bool ): """ 已通过或未通过的所有关键词/uid/pid :param _pass_keyword: 通过列表 :param not_pass_keyword: 未通过列表 :param is_superuser: 是否超级用户 """ _keyword = [ x for x in _pass_keyword if not x.startswith("uid:") and not x.startswith("pid:") and not x.startswith("black:") ] _uid = [x for x in _pass_keyword if x.startswith("uid:")] _pid = [x for x in _pass_keyword if x.startswith("pid:")] _n_keyword = [ x for x in not_pass_keyword if not x.startswith("uid:") and not x.startswith("pid:") and not x.startswith("black:") ] _n_uid = [ x for x in not_pass_keyword if x.startswith("uid:") and not x.startswith("black:") ] _n_pid = [ x for x in not_pass_keyword if x.startswith("pid:") and not x.startswith("black:") ] img_width = 0 img_data = { "_keyword": {"width": 0, "data": _keyword}, "_uid": {"width": 0, "data": _uid}, "_pid": {"width": 0, "data": _pid}, "_n_keyword": {"width": 0, "data": _n_keyword}, "_n_uid": {"width": 0, "data": _n_uid}, "_n_pid": {"width": 0, "data": _n_pid}, } for x in list(img_data.keys()): img_data[x]["width"] = math.ceil(len(img_data[x]["data"]) / 40) img_width += img_data[x]["width"] * 200 if not is_superuser: img_width = ( img_width - ( img_data["_n_keyword"]["width"] + img_data["_n_uid"]["width"] + img_data["_n_pid"]["width"] ) * 200 ) del img_data["_n_keyword"] del img_data["_n_pid"] del img_data["_n_uid"] current_width = 0 A = BuildImage(img_width, 1100) for x in list(img_data.keys()): if img_data[x]["data"]: img = BuildImage(img_data[x]["width"] * 200, 1100, 200, 1100, font_size=40) start_index = 0 end_index = 40 total_index = img_data[x]["width"] * 40 for _ in range(img_data[x]["width"]): tmp = BuildImage(198, 1100, font_size=20) text_img = BuildImage(198, 100, font_size=50) key_str = "\n".join( [key for key in img_data[x]["data"][start_index:end_index]] ) tmp.text((10, 100), key_str) if x.find("_n") == -1: text_img.text((24, 24), "已收录") else: text_img.text((24, 24), "待收录") tmp.paste(text_img, (0, 0)) start_index += 40 end_index = ( end_index + 40 if end_index + 40 <= total_index else total_index ) background_img = BuildImage(200, 1100, color="#FFE4C4") background_img.paste(tmp, (1, 1)) img.paste(background_img) A.paste(img, (current_width, 0)) current_width += img_data[x]["width"] * 200 return A.pic2bs4() class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(bot: Bot, event: MessageEvent): _pass_keyword, not_pass_keyword = await PixivKeywordUser.get_current_keyword() if _pass_keyword or not_pass_keyword: await show_keyword.send( image( b64=await asyncio.get_event_loop().run_in_executor( None, gen_keyword_pic, _pass_keyword, not_pass_keyword, str(event.user_id) in bot.config.superusers, ) ) ) else: if str(event.user_id) in bot.config.superusers: await show_keyword.finish(f"目前没有已收录或待收录的搜索关键词...") else: await show_keyword.finish(f"目前没有已收录的搜索关键词...")
null
188,243
import asyncio from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, Message, MessageEvent from nonebot.params import CommandArg from utils.message_builder import image from ._data_source import gen_keyword_pic, get_keyword_num from ._model.pixiv_keyword_user import PixivKeywordUser and("查看pix图库", priority=1, block=True) async def get_keyword_num(keyword: str) -> Tuple[int, int, int, int, int]: """ 查看图片相关 tag 数量 :param keyword: 关键词tag """ count, r18_count = await Pixiv.get_keyword_num(keyword.split()) count_, setu_count, r18_count_ = await OmegaPixivIllusts.get_keyword_num( keyword.split() ) return count, r18_count, count_, setu_count, r18_count_ async def _(arg: Message = CommandArg()): keyword = arg.extract_plain_text().strip() count, r18_count, count_, setu_count, r18_count_ = await get_keyword_num(keyword) await show_pix.send( f"PIX图库:{keyword}\n" f"总数:{count + r18_count}\n" f"美图:{count}\n" f"R18:{r18_count}\n" f"---------------\n" f"Omega图库:{keyword}\n" f"总数:{count_ + setu_count + r18_count_}\n" f"美图:{count_}\n" f"色图:{setu_count}\n" f"R18:{r18_count_}" )
null
188,244
import asyncio import os import re import time from pathlib import Path from typing import List from nonebot import on_command from nonebot.adapters.onebot.v11 import Message from nonebot.params import CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import start_update_image_url from ._model.omega_pixiv_illusts import OmegaPixivIllusts from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser start_update = on_command( "更新pix关键词", aliases={"更新pix关键字"}, permission=SUPERUSER, priority=1, block=True ) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False async def start_update_image_url( current_keyword: List[str], black_pid: List[str] ) -> "int, int": """ 开始更新图片url :param current_keyword: 关键词 :param black_pid: 黑名单pid :return: pid数量和图片数量 """ global HIBIAPI pid_count = 0 pic_count = 0 tasks = [] semaphore = asyncio.Semaphore(10) for keyword in current_keyword: for page in range(1, 110): if keyword.startswith("uid:"): url = f"{HIBIAPI}/api/pixiv/member_illust" params = {"id": keyword[4:], "page": page} if page == 30: break elif keyword.startswith("pid:"): url = f"{HIBIAPI}/api/pixiv/illust" params = {"id": keyword[4:]} else: url = f"{HIBIAPI}/api/pixiv/search" params = {"word": keyword, "page": page} tasks.append( asyncio.ensure_future( search_image(url, keyword, params, semaphore, page, black_pid) ) ) if keyword.startswith("pid:"): break result = await asyncio.gather(*tasks) for x in result: pid_count += x[0] pic_count += x[1] return pid_count, pic_count class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(arg: Message = CommandArg()): msg_sp = arg.extract_plain_text().strip().split() _pass_keyword, _ = await PixivKeywordUser.get_current_keyword() _pass_keyword.reverse() black_pid = await PixivKeywordUser.get_black_pid() _keyword = [ x for x in _pass_keyword if not x.startswith("uid:") and not x.startswith("pid:") and not x.startswith("black:") ] _uid = [x for x in _pass_keyword if x.startswith("uid:")] _pid = [x for x in _pass_keyword if x.startswith("pid:")] num = 9999 msg = msg_sp[0] if len(msg_sp) else "" if len(msg_sp) == 2: if is_number(msg_sp[1]): num = int(msg_sp[1]) else: await start_update.finish("参数错误...第二参数必须为数字") if num < 10000: keyword_str = ",".join( _keyword[: num if num < len(_keyword) else len(_keyword)] ) uid_str = ",".join(_uid[: num if num < len(_uid) else len(_uid)]) pid_str = ",".join(_pid[: num if num < len(_pid) else len(_pid)]) if msg.lower() == "pid": update_lst = _pid info = f"开始更新Pixiv搜图PID:\n{pid_str}" elif msg.lower() == "uid": update_lst = _uid info = f"开始更新Pixiv搜图UID:\n{uid_str}" elif msg.lower() == "keyword": update_lst = _keyword info = f"开始更新Pixiv搜图关键词:\n{keyword_str}" else: update_lst = _pass_keyword info = f"开始更新Pixiv搜图关键词:\n{keyword_str}\n更新UID:{uid_str}\n更新PID:{pid_str}" num = num if num < len(update_lst) else len(update_lst) else: if msg.lower() == "pid": update_lst = [f"pid:{num}"] info = f"开始更新Pixiv搜图UID:\npid:{num}" else: update_lst = [f"uid:{num}"] info = f"开始更新Pixiv搜图UID:\nuid:{num}" await start_update.send(info) start_time = time.time() pid_count, pic_count = await start_update_image_url(update_lst[:num], black_pid) await start_update.send( f"Pixiv搜图关键词搜图更新完成...\n" f"累计更新PID {pid_count} 个\n" f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time)) )
null
188,245
import asyncio import os import re import time from pathlib import Path from typing import List from nonebot import on_command from nonebot.adapters.onebot.v11 import Message from nonebot.params import CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import start_update_image_url from ._model.omega_pixiv_illusts import OmegaPixivIllusts from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser check_not_update_uid_pid = on_command( "pix检测更新", aliases={"pix检查更新"}, permission=SUPERUSER, priority=1, block=True, ) async def start_update_image_url( current_keyword: List[str], black_pid: List[str] ) -> "int, int": """ 开始更新图片url :param current_keyword: 关键词 :param black_pid: 黑名单pid :return: pid数量和图片数量 """ global HIBIAPI pid_count = 0 pic_count = 0 tasks = [] semaphore = asyncio.Semaphore(10) for keyword in current_keyword: for page in range(1, 110): if keyword.startswith("uid:"): url = f"{HIBIAPI}/api/pixiv/member_illust" params = {"id": keyword[4:], "page": page} if page == 30: break elif keyword.startswith("pid:"): url = f"{HIBIAPI}/api/pixiv/illust" params = {"id": keyword[4:]} else: url = f"{HIBIAPI}/api/pixiv/search" params = {"word": keyword, "page": page} tasks.append( asyncio.ensure_future( search_image(url, keyword, params, semaphore, page, black_pid) ) ) if keyword.startswith("pid:"): break result = await asyncio.gather(*tasks) for x in result: pid_count += x[0] pic_count += x[1] return pid_count, pic_count class Pixiv(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" pid = fields.BigIntField() """pid""" uid = fields.BigIntField() """uid""" author = fields.CharField(255) """作者""" title = fields.CharField(255) """标题""" width = fields.IntField() """宽度""" height = fields.IntField() """高度""" view = fields.IntField() """pixiv查看数""" bookmarks = fields.IntField() """收藏数""" tags = fields.TextField() """tags""" img_url = fields.CharField(255) """pixiv url链接""" img_p = fields.CharField(255) """图片pN""" is_r18 = fields.BooleanField() class Meta: table = "pixiv" table_description = "pix图库数据表" unique_together = ("pid", "img_url", "img_p") # 0:非r18 1:r18 2:混合 async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, r18: Optional[int] = 0, num: int = 100, ) -> List[Optional["Pixiv"]]: """ 说明: 查找符合条件的图片 参数: :param keywords: 关键词 :param uid: 画师uid :param pid: 图片pid :param r18: 是否r18,0:非r18 1:r18 2:混合 :param num: 查找图片的数量 """ if not num: return [] query = cls if r18 == 0: query = query.filter(is_r18=False) elif r18 == 1: query = query.filter(is_r18=True) if keywords: for keyword in keywords: query = query.filter(tags__contains=keyword) elif uid: query = query.filter(uid=uid) elif pid: query = query.filter(pid=pid) query = query.annotate(rand=Random()).limit(num) return await query.all() # type: ignore async def get_keyword_num(cls, tags: Optional[List[str]] = None) -> Tuple[int, int]: """ 说明: 获取相关关键词(keyword, tag)在图库中的数量 参数: :param tags: 关键词/Tag """ query = cls if tags: for tag in tags: query = query.filter(tags__contains=tag) else: query = query.all() count = await query.filter(is_r18=False).count() r18_count = await query.filter(is_r18=True).count() return count, r18_count class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() flag = False if msg == "update": flag = True _pass_keyword, _ = await PixivKeywordUser.get_current_keyword() x_uid = [] x_pid = [] _uid = [int(x[4:]) for x in _pass_keyword if x.startswith("uid:")] _pid = [int(x[4:]) for x in _pass_keyword if x.startswith("pid:")] all_images = await Pixiv.query_images(r18=2) for img in all_images: if img.pid not in x_pid: x_pid.append(img.pid) if img.uid not in x_uid: x_uid.append(img.uid) await check_not_update_uid_pid.send( "从未更新过的UID:" + ",".join([f"uid:{x}" for x in _uid if x not in x_uid]) + "\n" + "从未更新过的PID:" + ",".join([f"pid:{x}" for x in _pid if x not in x_pid]) ) if flag: await check_not_update_uid_pid.send("开始自动自动更新PID....") update_lst = [f"pid:{x}" for x in _uid if x not in x_uid] black_pid = await PixivKeywordUser.get_black_pid() start_time = time.time() pid_count, pic_count = await start_update_image_url(update_lst, black_pid) await check_not_update_uid_pid.send( f"Pixiv搜图关键词搜图更新完成...\n" f"累计更新PID {pid_count} 个\n" f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time)) )
null
188,246
import asyncio import os import re import time from pathlib import Path from typing import List from nonebot import on_command from nonebot.adapters.onebot.v11 import Message from nonebot.params import CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import start_update_image_url from ._model.omega_pixiv_illusts import OmegaPixivIllusts from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class OmegaPixivIllusts(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" pid = fields.BigIntField() """pid""" uid = fields.BigIntField() """uid""" title = fields.CharField(255) """标题""" uname = fields.CharField(255) """画师名称""" classified = fields.IntField() """标记标签, 0=未标记, 1=已人工标记或从可信已标记来源获取""" nsfw_tag = fields.IntField() """nsfw标签,-1=未标记, 0=safe, 1=setu. 2=r18""" width = fields.IntField() """宽度""" height = fields.IntField() """高度""" tags = fields.TextField() """tags""" url = fields.CharField(255) """pixiv url链接""" class Meta: table = "omega_pixiv_illusts" table_description = "omega图库数据表" unique_together = ("pid", "url") async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, nsfw_tag: Optional[int] = 0, num: int = 100, ) -> List["OmegaPixivIllusts"]: """ 说明: 查找符合条件的图片 参数: :param keywords: 关键词 :param uid: 画师uid :param pid: 图片pid :param nsfw_tag: nsfw标签, 0=safe, 1=setu. 2=r18 :param num: 获取图片数量 """ if not num: return [] query = cls if nsfw_tag is not None: query = cls.filter(nsfw_tag=nsfw_tag) if keywords: for keyword in keywords: query = query.filter(tags__contains=keyword) elif uid: query = query.filter(uid=uid) elif pid: query = query.filter(pid=pid) query = query.annotate(rand=Random()).limit(num) return await query.all() # type: ignore async def get_keyword_num( cls, tags: Optional[List[str]] = None ) -> Tuple[int, int, int]: """ 说明: 获取相关关键词(keyword, tag)在图库中的数量 参数: :param tags: 关键词/Tag """ query = cls if tags: for tag in tags: query = query.filter(tags__contains=tag) else: query = query.all() count = await query.filter(nsfw_tag=0).count() setu_count = await query.filter(nsfw_tag=1).count() r18_count = await query.filter(nsfw_tag=2).count() return count, setu_count, r18_count async def _(): async def _tasks(line: str, all_pid: List[int], length: int, index: int): data = line.split("VALUES", maxsplit=1)[-1].strip()[1:-2] num_list = re.findall(r"(\d+)", data) pid = int(num_list[1]) uid = int(num_list[2]) id_ = 3 while num_list[id_] not in ["0", "1"]: id_ += 1 classified = int(num_list[id_]) nsfw_tag = int(num_list[id_ + 1]) width = int(num_list[id_ + 2]) height = int(num_list[id_ + 3]) str_list = re.findall(r"'(.*?)',", data) title = str_list[0] uname = str_list[1] tags = str_list[2] url = str_list[3] if pid in all_pid: logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}") return _, is_create = await OmegaPixivIllusts.get_or_create( pid=pid, title=title, width=width, height=height, url=url, uid=uid, nsfw_tag=nsfw_tag, tags=tags, uname=uname, classified=classified, ) if is_create: logger.info( f"成功添加OmegaPixivIllusts图库数据 pid:{pid} 本次预计存储 {length} 张,已更新第 {index} 张" ) else: logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}") omega_pixiv_illusts = None for file in os.listdir("."): if "omega_pixiv_artwork" in file and ".sql" in file: omega_pixiv_illusts = Path() / file if omega_pixiv_illusts: with open(omega_pixiv_illusts, "r", encoding="utf8") as f: lines = f.readlines() tasks = [] length = len([x for x in lines if "INSERT INTO" in x.upper()]) all_pid = await OmegaPixivIllusts.all().values_list("pid", flat=True) index = 0 logger.info("检测到OmegaPixivIllusts数据库,准备开始更新....") for line in lines: if "INSERT INTO" in line.upper(): index += 1 logger.info(f"line: {line} 加入更新计划") tasks.append( asyncio.ensure_future(_tasks(line, all_pid, length, index)) ) await asyncio.gather(*tasks) omega_pixiv_illusts.unlink()
null
188,247
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import uid_pid_exists from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser add_keyword = on_command("添加pix关键词", aliases={"添加pix关键字"}, priority=1, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() group_id = -1 if isinstance(event, GroupMessageEvent): group_id = event.group_id if msg: # if await PixivKeywordUser.add_keyword( # event.user_id, group_id, msg, bot.config.superusers # ): if not await PixivKeywordUser.exists(keyword=msg): await PixivKeywordUser.create( user_id=str(event.user_id), group_id=str(group_id), keyword=msg, is_pass=str(event.user_id) in bot.config.superusers, ) await add_keyword.send( f"已成功添加pixiv搜图关键词:{msg},请等待管理员通过该关键词!", at_sender=True ) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 添加了pixiv搜图关键词:" + msg ) else: await add_keyword.finish(f"该关键词 {msg} 已存在...") else: await add_keyword.finish(f"虚空关键词?.?.?.?")
null
188,248
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import uid_pid_exists from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False async def uid_pid_exists(id_: str) -> bool: """ 检测 pid/uid 是否有效 :param id_: pid/uid """ if id_.startswith("uid:"): url = f"{HIBIAPI}/api/pixiv/member" elif id_.startswith("pid:"): url = f"{HIBIAPI}/api/pixiv/illust" else: return False params = {"id": int(id_[4:])} data = (await AsyncHttpx.get(url, params=params)).json() if data.get("error"): return False return True class Pixiv(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" pid = fields.BigIntField() """pid""" uid = fields.BigIntField() """uid""" author = fields.CharField(255) """作者""" title = fields.CharField(255) """标题""" width = fields.IntField() """宽度""" height = fields.IntField() """高度""" view = fields.IntField() """pixiv查看数""" bookmarks = fields.IntField() """收藏数""" tags = fields.TextField() """tags""" img_url = fields.CharField(255) """pixiv url链接""" img_p = fields.CharField(255) """图片pN""" is_r18 = fields.BooleanField() class Meta: table = "pixiv" table_description = "pix图库数据表" unique_together = ("pid", "img_url", "img_p") # 0:非r18 1:r18 2:混合 async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, r18: Optional[int] = 0, num: int = 100, ) -> List[Optional["Pixiv"]]: """ 说明: 查找符合条件的图片 参数: :param keywords: 关键词 :param uid: 画师uid :param pid: 图片pid :param r18: 是否r18,0:非r18 1:r18 2:混合 :param num: 查找图片的数量 """ if not num: return [] query = cls if r18 == 0: query = query.filter(is_r18=False) elif r18 == 1: query = query.filter(is_r18=True) if keywords: for keyword in keywords: query = query.filter(tags__contains=keyword) elif uid: query = query.filter(uid=uid) elif pid: query = query.filter(pid=pid) query = query.annotate(rand=Random()).limit(num) return await query.all() # type: ignore async def get_keyword_num(cls, tags: Optional[List[str]] = None) -> Tuple[int, int]: """ 说明: 获取相关关键词(keyword, tag)在图库中的数量 参数: :param tags: 关键词/Tag """ query = cls if tags: for tag in tags: query = query.filter(tags__contains=tag) else: query = query.all() count = await query.filter(is_r18=False).count() r18_count = await query.filter(is_r18=True).count() return count, r18_count class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _( bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg(), ): msg = arg.extract_plain_text().strip() exists_flag = True if msg.find("-f") != -1 and str(event.user_id) in bot.config.superusers: exists_flag = False msg = msg.replace("-f", "").strip() if msg: for msg in msg.split(): if not is_number(msg): await add_uid_pid.finish("UID只能是数字的说...", at_sender=True) if cmd[0].lower().endswith("uid"): msg = f"uid:{msg}" else: msg = f"pid:{msg}" if await Pixiv.get_or_none(pid=int(msg[4:]), img_p="p0"): await add_uid_pid.finish(f"该PID:{msg[4:]}已存在...", at_sender=True) if not await uid_pid_exists(msg) and exists_flag: await add_uid_pid.finish("画师或作品不存在或搜索正在CD,请稍等...", at_sender=True) group_id = -1 if isinstance(event, GroupMessageEvent): group_id = event.group_id # if await PixivKeywordUser.add_keyword( # event.user_id, group_id, msg, bot.config.superusers # ): if not await PixivKeywordUser.exists(keyword=msg): await PixivKeywordUser.create( user_id=str(event.user_id), group_id=str(group_id), keyword=msg, is_pass=str(event.user_id) in bot.config.superusers, ) await add_uid_pid.send( f"已成功添加pixiv搜图UID/PID:{msg[4:]},请等待管理员通过!", at_sender=True ) else: await add_uid_pid.finish(f"该UID/PID:{msg[4:]} 已存在...") else: await add_uid_pid.finish("湮灭吧!虚空的UID!")
null
188,249
from typing import Tuple from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import Command, CommandArg from nonebot.permission import SUPERUSER from services.log import logger from utils.utils import is_number from ._data_source import uid_pid_exists from ._model.pixiv import Pixiv from ._model.pixiv_keyword_user import PixivKeywordUser _command("添加pix黑名单", permission=SUPERUSER, priority=1, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False class PixivKeywordUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" keyword = fields.CharField(255, unique=True) """关键词""" is_pass = fields.BooleanField() """是否通过""" class Meta: table = "pixiv_keyword_users" table_description = "pixiv关键词数据表" async def get_current_keyword(cls) -> Tuple[List[str], List[str]]: """ 说明: 获取当前通过与未通过的关键词 """ pass_keyword = [] not_pass_keyword = [] for data in await cls.all().values_list("keyword", "is_pass"): if data[1]: pass_keyword.append(data[0]) else: not_pass_keyword.append(data[0]) return pass_keyword, not_pass_keyword async def get_black_pid(cls) -> List[str]: """ 说明: 获取黑名单PID """ black_pid = [] keyword_list = await cls.filter(user_id="114514").values_list( "keyword", flat=True ) for image in keyword_list: black_pid.append(image[6:]) return black_pid async def _run_script(cls): return [ "ALTER TABLE pixiv_keyword_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE pixiv_keyword_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE pixiv_keyword_users ALTER COLUMN group_id TYPE character varying(255);", ] async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()): pid = arg.extract_plain_text().strip() img_p = "" if "p" in pid: img_p = pid.split("p")[-1] pid = pid.replace("_", "") pid = pid[: pid.find("p")] if not is_number(pid): await add_black_pid.finish("PID必须全部是数字!", at_sender=True) # if await PixivKeywordUser.add_keyword( # 114514, # 114514, # f"black:{pid}{f'_p{img_p}' if img_p else ''}", # bot.config.superusers, # ): if not await PixivKeywordUser.exists( keyword=f"black:{pid}{f'_p{img_p}' if img_p else ''}" ): await PixivKeywordUser.create( user_id=114514, group_id=114514, keyword=f"black:{pid}{f'_p{img_p}' if img_p else ''}", is_pass=str(event.user_id) in bot.config.superusers, ) await add_black_pid.send(f"已添加PID:{pid} 至黑名单中...") logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 添加了pixiv搜图黑名单 PID:{pid}" ) else: await add_black_pid.send(f"PID:{pid} 已添加黑名单中,添加失败...")
null
188,250
import random from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import CommandArg from configs.config import Config from services.log import logger from utils.manager import withdraw_message_manager from utils.message_builder import custom_forward_msg, image from utils.utils import is_number from ._data_source import get_image from ._model.omega_pixiv_illusts import OmegaPixivIllusts from ._model.pixiv import Pixiv pix = on_command("pix", aliases={"PIX", "Pix"}, priority=5, block=True) PIX_RATIO = None OMEGA_RATIO = None class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: def custom_forward_msg( msg_list: List[Union[str, Message]], uin: Union[int, str], name: str = f"这里是{NICKNAME}", ) -> List[dict]: { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: async def get_image(img_url: str, user_id: int) -> Optional[str]: class OmegaPixivIllusts(Model): async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, nsfw_tag: Optional[int] = 0, num: int = 100, ) -> List["OmegaPixivIllusts"]: async def get_keyword_num( cls, tags: Optional[List[str]] = None ) -> Tuple[int, int, int]: class Pixiv(Model): async def query_images( cls, keywords: Optional[List[str]] = None, uid: Optional[int] = None, pid: Optional[int] = None, r18: Optional[int] = 0, num: int = 100, ) -> List[Optional["Pixiv"]]: async def get_keyword_num(cls, tags: Optional[List[str]] = None) -> Tuple[int, int]: async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()): global PIX_RATIO, OMEGA_RATIO if PIX_RATIO is None: pix_omega_pixiv_ratio = Config.get_config("pix", "PIX_OMEGA_PIXIV_RATIO") PIX_RATIO = pix_omega_pixiv_ratio[0] / ( pix_omega_pixiv_ratio[0] + pix_omega_pixiv_ratio[1] ) OMEGA_RATIO = 1 - PIX_RATIO num = 1 keyword = arg.extract_plain_text().strip() x = keyword.split() if "-s" in x: x.remove("-s") nsfw_tag = 1 elif "-r" in x: x.remove("-r") nsfw_tag = 2 else: nsfw_tag = 0 if str(event.user_id) not in bot.config.superusers: 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 pix.finish("你不能看这些噢,这些都是是留给管理员看的...") if (n := len(x)) == 1: if is_number(x[0]) and int(x[0]) < 100: num = int(x[0]) keyword = "" elif x[0].startswith("#"): keyword = x[0][1:] elif n > 1: if is_number(x[-1]): num = int(x[-1]) if num > 10: if str(event.user_id) not in bot.config.superusers or ( str(event.user_id) in bot.config.superusers and num > 30 ): num = random.randint(1, 10) await pix.send(f"太贪心了,就给你发 {num}张 好了") x = x[:-1] keyword = " ".join(x) pix_num = int(num * PIX_RATIO) + 15 if PIX_RATIO != 0 else 0 omega_num = num - pix_num + 15 if is_number(keyword): if num == 1: pix_num = 15 omega_num = 15 all_image = await Pixiv.query_images( uid=int(keyword), num=pix_num, r18=1 if nsfw_tag == 2 else 0 ) + await OmegaPixivIllusts.query_images( uid=int(keyword), num=omega_num, nsfw_tag=nsfw_tag ) elif keyword.lower().startswith("pid"): pid = keyword.replace("pid", "").replace(":", "").replace(":", "") if not is_number(pid): await pix.finish("PID必须是数字...", at_sender=True) all_image = await Pixiv.query_images( pid=int(pid), r18=1 if nsfw_tag == 2 else 0 ) if not all_image: all_image = await OmegaPixivIllusts.query_images( pid=int(pid), nsfw_tag=nsfw_tag ) num = len(all_image) else: tmp = await Pixiv.query_images( x, r18=1 if nsfw_tag == 2 else 0, num=pix_num ) + await OmegaPixivIllusts.query_images(x, nsfw_tag=nsfw_tag, num=omega_num) tmp_ = [] all_image = [] for x in tmp: if x.pid not in tmp_: all_image.append(x) tmp_.append(x.pid) if not all_image: await pix.finish(f"未在图库中找到与 {keyword} 相关Tag/UID/PID的图片...", at_sender=True) msg_list = [] for _ in range(num): img_url = None author = None if not all_image: await pix.finish("坏了...发完了,没图了...") img = random.choice(all_image) all_image.remove(img) if isinstance(img, OmegaPixivIllusts): img_url = img.url author = img.uname elif isinstance(img, Pixiv): img_url = img.img_url author = img.author pid = img.pid title = img.title uid = img.uid _img = await get_image(img_url, event.user_id) if _img: if Config.get_config("pix", "SHOW_INFO"): msg_list.append( Message( f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\nUID:{uid}\n" f"{image(_img)}" ) ) else: msg_list.append(image(_img)) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 查看PIX图库PID: {pid}" ) else: msg_list.append("这张图似乎下载失败了") logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 查看PIX图库PID: {pid},下载图片出错" ) if ( Config.get_config("pix", "MAX_ONCE_NUM2FORWARD") and num >= Config.get_config("pix", "MAX_ONCE_NUM2FORWARD") and isinstance(event, GroupMessageEvent) ): msg_id = await bot.send_group_forward_msg( group_id=event.group_id, messages=custom_forward_msg(msg_list, bot.self_id) ) withdraw_message_manager.withdraw_message( event, msg_id, Config.get_config("pix", "WITHDRAW_PIX_MESSAGE") ) else: for msg in msg_list: msg_id = await pix.send(msg) withdraw_message_manager.withdraw_message( event, msg_id, Config.get_config("pix", "WITHDRAW_PIX_MESSAGE") )
null
188,251
from nonebot import on_regex from nonebot.rule import to_me from pathlib import Path about = on_regex("^关于$", priority=5, block=True, rule=to_me()) async def _(): ver_file = Path() / '__version__' version = None if ver_file.exists(): with open(ver_file, 'r', encoding='utf8') as f: version = f.read().split(':')[-1].strip() msg = f""" 『绪山真寻Bot』 版本:{version} 简介:基于Nonebot2与go-cqhttp开发,是一个非常可爱的Bot呀,希望与大家要好好相处 项目地址:https://github.com/HibiKier/zhenxun_bot 文档地址:https://hibikier.github.io/zhenxun_bot/ """.strip() await about.send(msg)
null
188,252
from asyncio.exceptions import TimeoutError from configs.config import Config from utils.http_utils import AsyncHttpx from services.log import logger url = "https://buff.163.com/api/market/goods" class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) The provided code snippet includes necessary dependencies for implementing the `get_price` function. Write a Python function `async def get_price(d_name: str) -> "str, int"` to solve the following problem: 查看皮肤价格 :param d_name: 武器皮肤,如:awp 二西莫夫 Here is the function: async def get_price(d_name: str) -> "str, int": """ 查看皮肤价格 :param d_name: 武器皮肤,如:awp 二西莫夫 """ cookie = {"session": Config.get_config("search_buff_skin_price", "COOKIE")} name_list = [] price_list = [] parameter = {"game": "csgo", "page_num": "1", "search": d_name} try: response = await AsyncHttpx.get( url, proxy=Config.get_config("search_buff_skin_price", "BUFF_PROXY"), params=parameter, cookies=cookie, ) if response.status_code == 200: try: if response.text.find("Login Required") != -1: return "BUFF登录被重置,请联系管理员重新登入", 996 data = response.json()["data"] total_page = data["total_page"] data = data["items"] for _ in range(total_page): for i in range(len(data)): name = data[i]["name"] price = data[i]["sell_reference_price"] name_list.append(name) price_list.append(price) except Exception as e: logger.error(f"BUFF查询皮肤发生错误 {type(e)}:{e}") return "没有查询到...", 998 else: return "访问失败!", response.status_code except TimeoutError: return "访问超时! 请重试或稍后再试!", 997 result = f"皮肤: {d_name}({len(name_list)})\n" for i in range(len(name_list)): result += name_list[i] + ": " + price_list[i] + "\n" return result[:-1], 999
查看皮肤价格 :param d_name: 武器皮肤,如:awp 二西莫夫
188,253
from asyncio.exceptions import TimeoutError from configs.config import Config from utils.http_utils import AsyncHttpx from services.log import logger def update_buff_cookie(cookie: str) -> str: Config.set_config("search_buff_skin_price", "COOKIE", cookie) return "更新cookie成功"
null
188,254
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message from nonebot.params import CommandArg from nonebot import on_command from utils.utils import get_message_img from utils.message_builder import share from services.log import logger fake_msg = on_command("假消息", priority=5, block=True) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def get_message_img(data: Union[str, Message]) -> List[str]: """ 说明: 获取消息中所有的 图片 的链接 参数: :param data: event.json() """ img_list = [] if isinstance(data, str): event = json.loads(data) if data and (message := event.get("message")): for msg in message: if msg["type"] == "image": img_list.append(msg["data"]["url"]) else: for seg in data["image"]: img_list.append(seg.data["url"]) return img_list def share( url: str, title: str, content: Optional[str] = None, image_url: Optional[str] = None ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.share 消息 参数: :param url: 自定义分享的链接 :param title: 自定义分享的包体 :param content: 自定义分享的内容 :param image_url: 自定义分享的展示图片 """ return MessageSegment.share(url, title, content, image_url) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def _(event: MessageEvent, arg: Message = CommandArg()): msg = arg.extract_plain_text().strip().split() img = get_message_img(event.json()) if len(msg) > 1: if len(msg) == 2: url = msg[0] title = msg[1] content = "" else: url = msg[0] title = msg[1] content = msg[2] if img: img = img[0] else: img = "" if "http" not in url: url = "http://" + url await fake_msg.send(share(url, title, content, img)) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 构造假消息 url {url}, title {title}, content {content}" ) else: await fake_msg.finish("消息格式错误:\n网址 标题 内容(可省略) 图片(可省略)")
null
188,255
import os import random from io import BytesIO from typing import Tuple, Union from nonebot.adapters.onebot.v11 import Bot from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH from models.bag_user import BagUser from utils.image_utils import BuildImage from utils.message_builder import image from utils.utils import get_user_avatar, is_number from .config import FESTIVE_KEY, GroupRedBag, RedBag def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") """所属群聊""" """红包名称""" """总金币""" """红包数量""" """发起人昵称""" """发起人id""" """是否为节日红包""" """过期时间""" """指定人id""" """红包发起时间""" """开启用户""" class GroupRedBag: """ 群组红包管理 """ def __init__(self, group_id: Union[int, str]): self.group_id = str(group_id) self._data: Dict[str, RedBag] = {} """红包列表""" def get_user_red_bag(self, user_id: Union[str, int]) -> Optional[RedBag]: """获取用户塞红包数据 参数: user_id: 用户id 返回: Optional[RedBag]: RedBag """ return self._data.get(str(user_id)) def check_open(self, user_id: Union[str, int]) -> bool: """检查是否有可开启的红包 参数: user_id: 用户id 返回: bool: 是否有可开启的红包 """ user_id = str(user_id) for _, red_bag in self._data.items(): if red_bag.assigner: if red_bag.assigner == user_id: return True else: if user_id not in red_bag.open_user: return True return False def check_timeout(self, user_id: Union[int, str]) -> int: """判断用户红包是否过期 参数: user_id: 用户id 返回: int: 距离过期时间 """ user_id = str(user_id) if user_id in self._data: reg_bag = self._data[user_id] now = time.time() if now < reg_bag.timeout + reg_bag.start_time: return int(reg_bag.timeout + reg_bag.start_time - now) return -1 async def open( self, user_id: Union[int, str] ) -> Tuple[Dict[str, Tuple[int, RedBag]], List[RedBag]]: """开启红包 参数: user_id: 用户id 返回: Dict[str, Tuple[int, RedBag]]: 键为发起者id, 值为开启金额以及对应RedBag List[RedBag]: 开完的红包 """ user_id = str(user_id) open_data = {} settlement_list: List[RedBag] = [] for _, red_bag in self._data.items(): if red_bag.num > len(red_bag.open_user): is_open = False if red_bag.assigner: is_open = red_bag.assigner == user_id else: is_open = user_id not in red_bag.open_user if is_open: random_amount = red_bag.red_bag_list.pop() await RedbagUser.add_redbag_data( user_id, self.group_id, "get", random_amount ) await BagUser.add_gold(user_id, self.group_id, random_amount) red_bag.open_user[user_id] = random_amount open_data[red_bag.promoter_id] = (random_amount, red_bag) if red_bag.num == len(red_bag.open_user): # 红包开完,结算 settlement_list.append(red_bag) if settlement_list: for uid in [red_bag.promoter_id for red_bag in settlement_list]: if uid in self._data: del self._data[uid] return open_data, settlement_list def festive_red_bag_expire(self) -> Optional[RedBag]: """节日红包过期 返回: Optional[RedBag]: 过期的节日红包 """ if FESTIVE_KEY in self._data: red_bag = self._data[FESTIVE_KEY] del self._data[FESTIVE_KEY] return red_bag return None async def settlement( self, user_id: Optional[Union[int, str]] = None ) -> Optional[int]: """红包退回 参数: user_id: 用户id, 指定id时结算指定用户红包. 返回: int: 退回金币 """ user_id = str(user_id) if user_id: if red_bag := self._data.get(user_id): del self._data[user_id] if red_bag.red_bag_list: # 退还剩余金币 if amount := sum(red_bag.red_bag_list): await BagUser.add_gold(user_id, self.group_id, amount) return amount return None async def add_red_bag( self, name: str, amount: int, num: int, promoter: str, promoter_id: str, is_festival: bool = False, timeout: int = 60, assigner: Optional[str] = None, ): """添加红包 参数: name: 红包名称 amount: 金币数量 num: 红包数量 promoter: 发起人昵称 promoter_id: 发起人id is_festival: 是否为节日红包. timeout: 超时时间. assigner: 指定人. """ user_gold = await BagUser.get_gold(promoter_id, self.group_id) if not is_festival and (amount < 1 or user_gold < amount): raise ValueError("红包金币不足或用户金币不足") red_bag_list = self._random_red_bag(amount, num) if not is_festival: await BagUser.spend_gold(promoter_id, self.group_id, amount) await RedbagUser.add_redbag_data(promoter_id, self.group_id, "send", amount) self._data[promoter_id] = RedBag( group_id=self.group_id, name=name, amount=amount, num=num, promoter=promoter, promoter_id=promoter_id, is_festival=is_festival, timeout=timeout, start_time=time.time(), assigner=assigner, red_bag_list=red_bag_list, ) def _random_red_bag(self, amount: int, num: int) -> List[int]: """初始化红包金币 参数: amount: 金币数量 num: 红包数量 返回: List[int]: 红包列表 """ red_bag_list = [] for _ in range(num - 1): tmp = int(amount / random.choice(range(3, num + 3))) red_bag_list.append(tmp) amount -= tmp red_bag_list.append(amount) return red_bag_list The provided code snippet includes necessary dependencies for implementing the `end_festive_red_bag` function. Write a Python function `async def end_festive_red_bag(bot: Bot, group_red_bag: GroupRedBag)` to solve the following problem: 结算节日红包 参数: bot: Bot group_red_bag: GroupRedBag Here is the function: async def end_festive_red_bag(bot: Bot, group_red_bag: GroupRedBag): """结算节日红包 参数: bot: Bot group_red_bag: GroupRedBag """ if festive_red_bag := group_red_bag.festive_red_bag_expire(): rank_num = Config.get_config("gold_redbag", "RANK_NUM") or 10 rank_image = await festive_red_bag.build_amount_rank(rank_num) message = ( f"{NICKNAME}的节日红包过时了,一共开启了 " f"{len(festive_red_bag.open_user)}" f" 个红包,共 {sum(festive_red_bag.open_user.values())} 金币\n" + image(rank_image) ) await bot.send_group_msg(group_id=int(group_red_bag.group_id), message=message)
结算节日红包 参数: bot: Bot group_red_bag: GroupRedBag
188,256
import os import random from io import BytesIO from typing import Tuple, Union from nonebot.adapters.onebot.v11 import Bot from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH from models.bag_user import BagUser from utils.image_utils import BuildImage from utils.message_builder import image from utils.utils import get_user_avatar, is_number from .config import FESTIVE_KEY, GroupRedBag, RedBag class BagUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" gold = fields.IntField(default=100) """金币数量""" spend_total_gold = fields.IntField(default=0) """花费金币总数""" get_total_gold = fields.IntField(default=0) """获取金币总数""" get_today_gold = fields.IntField(default=0) """今日获取金币""" spend_today_gold = fields.IntField(default=0) """今日获取金币""" property: Dict[str, int] = fields.JSONField(default={}) """道具""" class Meta: table = "bag_users" table_description = "用户道具数据表" unique_together = ("user_id", "group_id") async def get_user_total_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> str: """ 说明: 获取金币概况 参数: :param user_id: 用户id :param group_id: 所在群组id """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) return ( f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}" f"\n今日收益:{user.get_today_gold - user.spend_today_gold}" f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}" ) async def get_gold(cls, user_id: Union[int, str], group_id: Union[int, str]) -> int: """ 说明: 获取当前金币 参数: :param user_id: 用户id :param group_id: 所在群组id """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) return user.gold async def get_property( cls, user_id: Union[int, str], group_id: Union[int, str], only_active: bool = False ) -> Dict[str, int]: """ 说明: 获取当前道具 参数: :param user_id: 用户id :param group_id: 所在群组id :param only_active: 仅仅获取主动使用的道具 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) if only_active and user.property: data = {} name_list = [ x.goods_name for x in await GoodsInfo.get_all_goods() if not x.is_passive ] for key in [x for x in user.property if x in name_list]: data[key] = user.property[key] return data return user.property async def add_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int): """ 说明: 增加金币 参数: :param user_id: 用户id :param group_id: 所在群组id :param num: 金币数量 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) user.gold = user.gold + num user.get_total_gold = user.get_total_gold + num user.get_today_gold = user.get_today_gold + num await user.save(update_fields=["gold", "get_today_gold", "get_total_gold"]) async def spend_gold(cls, user_id: Union[int, str], group_id: Union[int, str], num: int): """ 说明: 花费金币 参数: :param user_id: 用户id :param group_id: 所在群组id :param num: 金币数量 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) user.gold = user.gold - num user.spend_total_gold = user.spend_total_gold + num user.spend_today_gold = user.spend_today_gold + num await user.save(update_fields=["gold", "spend_total_gold", "spend_today_gold"]) async def add_property(cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1): """ 说明: 增加道具 参数: :param user_id: 用户id :param group_id: 所在群组id :param name: 道具名称 :param num: 道具数量 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) property_ = user.property if property_.get(name) is None: property_[name] = 0 property_[name] += num user.property = property_ await user.save(update_fields=["property"]) async def delete_property( cls, user_id: Union[int, str], group_id: Union[int, str], name: str, num: int = 1 ) -> bool: """ 说明: 使用/删除 道具 参数: :param user_id: 用户id :param group_id: 所在群组id :param name: 道具名称 :param num: 使用个数 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=str(group_id)) property_ = user.property if name in property_: if (n := property_.get(name, 0)) < num: return False if n == num: del property_[name] else: property_[name] -= num await user.save(update_fields=["property"]) return True return False async def _run_script(cls): return ["ALTER TABLE bag_users DROP props;", # 删除 props 字段 "ALTER TABLE bag_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE bag_users ALTER COLUMN user_id TYPE character varying(255);", # 将user_id字段类型改为character varying(255) "ALTER TABLE bag_users ALTER COLUMN group_id TYPE character varying(255);" ] { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False The provided code snippet includes necessary dependencies for implementing the `check_gold` function. Write a Python function `async def check_gold( user_id: str, group_id: str, amount: Union[str, int] ) -> Tuple[bool, str]` to solve the following problem: 检查金币数量是否合法 参数: user_id: 用户id group_id: 群聊id amount: 金币数量 返回: Tuple[bool, str]: 是否合法以及提示语 Here is the function: async def check_gold( user_id: str, group_id: str, amount: Union[str, int] ) -> Tuple[bool, str]: """检查金币数量是否合法 参数: user_id: 用户id group_id: 群聊id amount: 金币数量 返回: Tuple[bool, str]: 是否合法以及提示语 """ if is_number(amount): amount = int(amount) user_gold = await BagUser.get_gold(user_id, group_id) if amount < 1: return False, "小气鬼,要别人倒贴金币给你嘛!" if user_gold < amount: return False, "没有金币的话请不要发红包..." return True, "" else: return False, "给我好好的输入红包里金币的数量啊喂!"
检查金币数量是否合法 参数: user_id: 用户id group_id: 群聊id amount: 金币数量 返回: Tuple[bool, str]: 是否合法以及提示语
188,257
import os import random from io import BytesIO from typing import Tuple, Union from nonebot.adapters.onebot.v11 import Bot from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH from models.bag_user import BagUser from utils.image_utils import BuildImage from utils.message_builder import image from utils.utils import get_user_avatar, is_number from .config import FESTIVE_KEY, GroupRedBag, RedBag class BuildImage: """ 快捷生成图片与操作图片的工具类 """ def __init__( self, w: int, h: int, paste_image_width: int = 0, paste_image_height: int = 0, paste_space: int = 0, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None, image_mode: ModeType = "RGBA", font_size: int = 10, background: Union[Optional[str], BytesIO, Path] = None, font: str = "yz.ttf", ratio: float = 1, is_alpha: bool = False, plain_text: Optional[str] = None, font_color: Optional[Union[str, Tuple[int, int, int]]] = None, **kwargs, ): """ 参数: :param w: 自定义图片的宽度,w=0时为图片原本宽度 :param h: 自定义图片的高度,h=0时为图片原本高度 :param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行 :param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行 :param paste_space: 自动贴图间隔 :param color: 生成图片的颜色 :param image_mode: 图片的类型 :param font_size: 文字大小 :param background: 打开图片的路径 :param font: 字体,默认在 resource/ttf/ 路径下 :param ratio: 倍率压缩 :param is_alpha: 是否背景透明 :param plain_text: 纯文字文本 """ self.w = int(w) self.h = int(h) self.paste_image_width = int(paste_image_width) self.paste_image_height = int(paste_image_height) self.paste_space = int(paste_space) self._current_w = 0 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) self.background = background if not background: if plain_text: if not color: color = (255, 255, 255, 0) ttf_w, ttf_h = self.getsize(str(plain_text)) self.w = self.w if self.w > ttf_w else ttf_w self.h = self.h if self.h > ttf_h else ttf_h self.markImg = Image.new(image_mode, (self.w, self.h), color) self.markImg.convert(image_mode) else: if not w and not h: self.markImg = Image.open(background) w, h = self.markImg.size if ratio and ratio > 0 and ratio != 1: self.w = int(ratio * w) self.h = int(ratio * h) self.markImg = self.markImg.resize( (self.w, self.h), Image.ANTIALIAS ) else: self.w = w self.h = h else: self.markImg = Image.open(background).resize( (self.w, self.h), Image.ANTIALIAS ) if is_alpha: try: 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) self.size = self.w, self.h if plain_text: fill = font_color if font_color else (0, 0, 0) self.text((0, 0), str(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() def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 参数: :param font: 字体名称 :param font_size: 字体大小 """ return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 异步 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ await self.loop.run_in_executor( None, self.paste, img, pos, alpha, center_type, allow_negative ) def paste( self, img: "BuildImage", pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) width, height = 0, 0 if not pos: pos = (0, 0) if center_type == "center": width = int((self.w - img.w) / 2) height = int((self.h - img.h) / 2) elif center_type == "by_width": width = int((self.w - img.w) / 2) height = pos[1] elif center_type == "by_height": width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) if pos and allow_negative: 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: self._current_w = 0 self._current_h += self.paste_image_height + self.paste_space if not pos: pos = (self._current_w, self._current_h) if alpha: try: self.markImg.paste(img, pos, img) except ValueError: img = img.convert("RGBA") self.markImg.paste(img, pos, img) else: self.markImg.paste(img, pos) self._current_w += self.paste_image_width + self.paste_space def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 :param font: 字体 :param font_size: 字体大小 """ font_ = cls.load_font(font, font_size) return font_.getsize(msg) # type: ignore def getsize(self, msg: Any) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 """ return self.font.getsize(str(msg)) # type: ignore 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): """ 说明: 绘制多个或单独的像素 参数: :param pos: 坐标 :param fill: 填错颜色 """ 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], 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: 描线宽度 """ self.draw.ellipse(pos, fill, outline, width) async def atext( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 异步 在图片上添加文字 参数: :param pos: 文字位置 :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ await self.loop.run_in_executor( None, self.text, pos, text, fill, center_type, font, font_size, **kwargs ) def text( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 在图片上添加文字 参数: :param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效) :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) w, h = self.w, self.h longgest_text = "" sentence = text.split("\n") for x in sentence: longgest_text = x if len(x) > len(longgest_text) else longgest_text ttf_w, ttf_h = self.getsize(longgest_text) ttf_h = ttf_h * len(sentence) if center_type == "center": w = int((w - ttf_w) / 2) h = int((h - ttf_h) / 2) elif center_type == "by_width": w = int((w - ttf_w) / 2) h = pos[1] elif center_type == "by_height": h = int((h - ttf_h) / 2) w = pos[0] pos = (w, h) if font: if isinstance(font, str): font = self.load_font(font, font_size) elif font_size: font = self.load_font(self.font_name, font_size) self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs) async def asave(self, path: Optional[Union[str, Path]] = None): """ 说明: 异步 保存图片 参数: :param path: 图片路径 """ await self.loop.run_in_executor(None, self.save, path) def save(self, path: Optional[Union[str, Path]] = None): """ 说明: 保存图片 参数: :param path: 图片路径 """ self.markImg.save(path or self.background) # type: ignore def show(self): """ 说明: 显示图片 """ self.markImg.show() 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): """ 说明: 压缩图片 参数: :param ratio: 压缩倍率 :param w: 压缩图片宽度至 w :param h: 压缩图片高度至 h """ if not w and not h and not ratio: raise Exception("缺少参数...") if not w and not h and ratio: w = int(self.w * ratio) h = int(self.h * ratio) self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS) self.w, self.h = self.markImg.size 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]): """ 说明: 裁剪图片 参数: :param box: 左上角坐标,右下角坐标 (left, upper, right, lower) """ self.markImg = self.markImg.crop(box) self.w, self.h = self.markImg.size self.size = self.w, self.h self.draw = ImageDraw.Draw(self.markImg) def check_font_size(self, word: str) -> bool: """ 说明: 检查文本所需宽度是否大于图片宽度 参数: :param word: 文本内容 """ 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): """ 说明: 图片透明化 参数: :param alpha_ratio: 透明化程度 :param n: 透明化大小内边距 """ self.markImg = self.markImg.convert("RGBA") x, y = self.markImg.size for i in range(n, x - n): for k in range(n, y - n): color = self.markImg.getpixel((i, k)) color = color[:-1] + (int(100 * alpha_ratio),) self.markImg.putpixel((i, k), color) self.draw = ImageDraw.Draw(self.markImg) def pic2bs4(self) -> str: """ 说明: BuildImage 转 base64 """ buf = BytesIO() self.markImg.save(buf, format="PNG") base64_str = base64.b64encode(buf.getvalue()).decode() return "base64://" + base64_str def convert(self, type_: ModeType): """ 说明: 修改图片类型 参数: :param type_: 类型 """ self.markImg = self.markImg.convert(type_) async def arectangle( self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[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], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[str] = None, width: int = 1, ): """ 说明: 画框 参数: :param xy: 坐标 :param fill: 填充颜色 :param outline: 轮廓颜色 :param width: 线宽 """ 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[Union[str, 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], fill: Optional[Union[Tuple[int, int, int], str]] = None, width: int = 1, ): """ 说明: 画线 参数: :param xy: 坐标 :param fill: 填充 :param width: 线宽 """ self.draw.line(xy, fill, width) async def acircle(self): """ 说明: 异步 将 BuildImage 图片变为圆形 """ await self.loop.run_in_executor(None, self.circle) def circle(self): """ 说明: 使图像变圆 """ self.markImg.convert("RGBA") size = self.markImg.size r2 = min(size[0], size[1]) if size[0] != size[1]: self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS) width = 1 antialias = 4 ellipse_box = [0, 0, r2 - 2, r2 - 2] mask = Image.new( size=[int(dim * antialias) for dim in self.markImg.size], mode="L", color="black", ) draw = ImageDraw.Draw(mask) for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"): left, top = [(value + offset) * antialias for value in ellipse_box[:2]] right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]] draw.ellipse([left, top, right, bottom], fill=fill) mask = mask.resize(self.markImg.size, Image.LANCZOS) try: self.markImg.putalpha(mask) except ValueError: pass async def acircle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 异步 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ await self.loop.run_in_executor(None, self.circle_corner, radii, point_list) def circle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ # 画圆(用于分离4个角) img = self.markImg.convert("RGBA") alpha = img.split()[-1] circle = Image.new("L", (radii * 2, radii * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形 w, h = img.size if "lt" in point_list: alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0)) if "rt" in point_list: alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0)) if "lb" in point_list: alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii)) if "rb" in point_list: alpha.paste( circle.crop((radii, radii, radii * 2, radii * 2)), (w - radii, h - radii), ) img.putalpha(alpha) self.markImg = img self.draw = ImageDraw.Draw(self.markImg) 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): """ 说明: 旋转图片 参数: :param angle: 角度 :param expand: 放大图片适应角度 """ self.markImg = self.markImg.rotate(angle, expand=expand) async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 异步 旋转图片(包括边框) 参数: :param angle: 角度 """ await self.loop.run_in_executor(None, self.transpose, angle) def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 旋转图片(包括边框) 参数: :param angle: 角度 """ self.markImg.transpose(angle) async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ await self.loop.run_in_executor(None, self.filter, filter_, aud) def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ _x = None if filter_ == "GaussianBlur": # 高斯模糊 _x = ImageFilter.GaussianBlur elif filter_ == "EDGE_ENHANCE": # 锐化效果 _x = ImageFilter.EDGE_ENHANCE elif filter_ == "BLUR": # 模糊效果 _x = ImageFilter.BLUR elif filter_ == "CONTOUR": # 铅笔滤镜 _x = ImageFilter.CONTOUR elif filter_ == "FIND_EDGES": # 边缘检测 _x = ImageFilter.FIND_EDGES if _x: if aud: self.markImg = self.markImg.filter(_x(aud)) else: self.markImg = self.markImg.filter(_x) self.draw = ImageDraw.Draw(self.markImg) async def areplace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 异步 颜色替换 参数: :param src_color: 目标颜色,或者使用列表,设置阈值 :param replace_color: 替换颜色 """ self.loop.run_in_executor( None, self.replace_color_tran, src_color, replace_color ) def replace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 颜色替换 参数: :param src_color: 目标颜色,或者使用元祖,设置阈值 :param replace_color: 替换颜色 """ if isinstance(src_color, tuple): start_ = src_color[0] end_ = src_color[1] else: start_ = src_color end_ = None for i in range(self.w): for j in range(self.h): r, g, b = self.markImg.getpixel((i, j)) if not end_: if r == start_[0] and g == start_[1] and b == start_[2]: self.markImg.putpixel((i, j), replace_color) else: if ( start_[0] <= r <= end_[0] and start_[1] <= g <= end_[1] and start_[2] <= b <= end_[2] ): self.markImg.putpixel((i, j), replace_color) # def getchannel(self, type_): self.markImg = self.markImg.getchannel(type_) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } async def get_user_avatar(qq: Union[int, str]) -> Optional[bytes]: """ 说明: 快捷获取用户头像 参数: :param qq: qq号 """ url = f"http://q1.qlogo.cn/g?b=qq&nk={qq}&s=160" async with httpx.AsyncClient() as client: for _ in range(3): try: return (await client.get(url)).content except Exception as e: logger.error("获取用户头像错误", "Util", target=qq) return None The provided code snippet includes necessary dependencies for implementing the `random_red_bag_background` function. Write a Python function `async def random_red_bag_background( user_id: Union[str, int], msg="恭喜发财 大吉大利" ) -> BuildImage` to solve the following problem: 构造发送红包图片 参数: user_id: 用户id msg: 红包消息. 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片 Here is the function: async def random_red_bag_background( user_id: Union[str, int], msg="恭喜发财 大吉大利" ) -> BuildImage: """构造发送红包图片 参数: user_id: 用户id msg: 红包消息. 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片 """ background_list = os.listdir(f"{IMAGE_PATH}/prts/redbag_2") if not background_list: raise ValueError("prts/redbag_1 背景图列表为空...") random_redbag = random.choice(background_list) redbag = BuildImage( 0, 0, font_size=38, background=IMAGE_PATH / "prts" / "redbag_2" / random_redbag ) ava_byte = await get_user_avatar(user_id) ava = None if ava_byte: ava = BuildImage(65, 65, background=BytesIO(ava_byte)) else: ava = BuildImage(65, 65, color=(0, 0, 0), is_alpha=True) await ava.acircle() await redbag.atext( (int((redbag.size[0] - redbag.getsize(msg)[0]) / 2), 210), msg, (240, 218, 164) ) await redbag.apaste(ava, (int((redbag.size[0] - ava.size[0]) / 2), 130), True) return redbag
构造发送红包图片 参数: user_id: 用户id msg: 红包消息. 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片
188,258
import os import random from io import BytesIO from typing import Tuple, Union from nonebot.adapters.onebot.v11 import Bot from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH from models.bag_user import BagUser from utils.image_utils import BuildImage from utils.message_builder import image from utils.utils import get_user_avatar, is_number from .config import FESTIVE_KEY, GroupRedBag, RedBag class BuildImage: """ 快捷生成图片与操作图片的工具类 """ def __init__( self, w: int, h: int, paste_image_width: int = 0, paste_image_height: int = 0, paste_space: int = 0, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None, image_mode: ModeType = "RGBA", font_size: int = 10, background: Union[Optional[str], BytesIO, Path] = None, font: str = "yz.ttf", ratio: float = 1, is_alpha: bool = False, plain_text: Optional[str] = None, font_color: Optional[Union[str, Tuple[int, int, int]]] = None, **kwargs, ): """ 参数: :param w: 自定义图片的宽度,w=0时为图片原本宽度 :param h: 自定义图片的高度,h=0时为图片原本高度 :param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行 :param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行 :param paste_space: 自动贴图间隔 :param color: 生成图片的颜色 :param image_mode: 图片的类型 :param font_size: 文字大小 :param background: 打开图片的路径 :param font: 字体,默认在 resource/ttf/ 路径下 :param ratio: 倍率压缩 :param is_alpha: 是否背景透明 :param plain_text: 纯文字文本 """ self.w = int(w) self.h = int(h) self.paste_image_width = int(paste_image_width) self.paste_image_height = int(paste_image_height) self.paste_space = int(paste_space) self._current_w = 0 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) self.background = background if not background: if plain_text: if not color: color = (255, 255, 255, 0) ttf_w, ttf_h = self.getsize(str(plain_text)) self.w = self.w if self.w > ttf_w else ttf_w self.h = self.h if self.h > ttf_h else ttf_h self.markImg = Image.new(image_mode, (self.w, self.h), color) self.markImg.convert(image_mode) else: if not w and not h: self.markImg = Image.open(background) w, h = self.markImg.size if ratio and ratio > 0 and ratio != 1: self.w = int(ratio * w) self.h = int(ratio * h) self.markImg = self.markImg.resize( (self.w, self.h), Image.ANTIALIAS ) else: self.w = w self.h = h else: self.markImg = Image.open(background).resize( (self.w, self.h), Image.ANTIALIAS ) if is_alpha: try: 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) self.size = self.w, self.h if plain_text: fill = font_color if font_color else (0, 0, 0) self.text((0, 0), str(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() def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 参数: :param font: 字体名称 :param font_size: 字体大小 """ return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 异步 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ await self.loop.run_in_executor( None, self.paste, img, pos, alpha, center_type, allow_negative ) def paste( self, img: "BuildImage", pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) width, height = 0, 0 if not pos: pos = (0, 0) if center_type == "center": width = int((self.w - img.w) / 2) height = int((self.h - img.h) / 2) elif center_type == "by_width": width = int((self.w - img.w) / 2) height = pos[1] elif center_type == "by_height": width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) if pos and allow_negative: 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: self._current_w = 0 self._current_h += self.paste_image_height + self.paste_space if not pos: pos = (self._current_w, self._current_h) if alpha: try: self.markImg.paste(img, pos, img) except ValueError: img = img.convert("RGBA") self.markImg.paste(img, pos, img) else: self.markImg.paste(img, pos) self._current_w += self.paste_image_width + self.paste_space def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 :param font: 字体 :param font_size: 字体大小 """ font_ = cls.load_font(font, font_size) return font_.getsize(msg) # type: ignore def getsize(self, msg: Any) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 """ return self.font.getsize(str(msg)) # type: ignore 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): """ 说明: 绘制多个或单独的像素 参数: :param pos: 坐标 :param fill: 填错颜色 """ 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], 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: 描线宽度 """ self.draw.ellipse(pos, fill, outline, width) async def atext( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 异步 在图片上添加文字 参数: :param pos: 文字位置 :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ await self.loop.run_in_executor( None, self.text, pos, text, fill, center_type, font, font_size, **kwargs ) def text( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 在图片上添加文字 参数: :param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效) :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) w, h = self.w, self.h longgest_text = "" sentence = text.split("\n") for x in sentence: longgest_text = x if len(x) > len(longgest_text) else longgest_text ttf_w, ttf_h = self.getsize(longgest_text) ttf_h = ttf_h * len(sentence) if center_type == "center": w = int((w - ttf_w) / 2) h = int((h - ttf_h) / 2) elif center_type == "by_width": w = int((w - ttf_w) / 2) h = pos[1] elif center_type == "by_height": h = int((h - ttf_h) / 2) w = pos[0] pos = (w, h) if font: if isinstance(font, str): font = self.load_font(font, font_size) elif font_size: font = self.load_font(self.font_name, font_size) self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs) async def asave(self, path: Optional[Union[str, Path]] = None): """ 说明: 异步 保存图片 参数: :param path: 图片路径 """ await self.loop.run_in_executor(None, self.save, path) def save(self, path: Optional[Union[str, Path]] = None): """ 说明: 保存图片 参数: :param path: 图片路径 """ self.markImg.save(path or self.background) # type: ignore def show(self): """ 说明: 显示图片 """ self.markImg.show() 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): """ 说明: 压缩图片 参数: :param ratio: 压缩倍率 :param w: 压缩图片宽度至 w :param h: 压缩图片高度至 h """ if not w and not h and not ratio: raise Exception("缺少参数...") if not w and not h and ratio: w = int(self.w * ratio) h = int(self.h * ratio) self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS) self.w, self.h = self.markImg.size 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]): """ 说明: 裁剪图片 参数: :param box: 左上角坐标,右下角坐标 (left, upper, right, lower) """ self.markImg = self.markImg.crop(box) self.w, self.h = self.markImg.size self.size = self.w, self.h self.draw = ImageDraw.Draw(self.markImg) def check_font_size(self, word: str) -> bool: """ 说明: 检查文本所需宽度是否大于图片宽度 参数: :param word: 文本内容 """ 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): """ 说明: 图片透明化 参数: :param alpha_ratio: 透明化程度 :param n: 透明化大小内边距 """ self.markImg = self.markImg.convert("RGBA") x, y = self.markImg.size for i in range(n, x - n): for k in range(n, y - n): color = self.markImg.getpixel((i, k)) color = color[:-1] + (int(100 * alpha_ratio),) self.markImg.putpixel((i, k), color) self.draw = ImageDraw.Draw(self.markImg) def pic2bs4(self) -> str: """ 说明: BuildImage 转 base64 """ buf = BytesIO() self.markImg.save(buf, format="PNG") base64_str = base64.b64encode(buf.getvalue()).decode() return "base64://" + base64_str def convert(self, type_: ModeType): """ 说明: 修改图片类型 参数: :param type_: 类型 """ self.markImg = self.markImg.convert(type_) async def arectangle( self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[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], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[str] = None, width: int = 1, ): """ 说明: 画框 参数: :param xy: 坐标 :param fill: 填充颜色 :param outline: 轮廓颜色 :param width: 线宽 """ 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[Union[str, 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], fill: Optional[Union[Tuple[int, int, int], str]] = None, width: int = 1, ): """ 说明: 画线 参数: :param xy: 坐标 :param fill: 填充 :param width: 线宽 """ self.draw.line(xy, fill, width) async def acircle(self): """ 说明: 异步 将 BuildImage 图片变为圆形 """ await self.loop.run_in_executor(None, self.circle) def circle(self): """ 说明: 使图像变圆 """ self.markImg.convert("RGBA") size = self.markImg.size r2 = min(size[0], size[1]) if size[0] != size[1]: self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS) width = 1 antialias = 4 ellipse_box = [0, 0, r2 - 2, r2 - 2] mask = Image.new( size=[int(dim * antialias) for dim in self.markImg.size], mode="L", color="black", ) draw = ImageDraw.Draw(mask) for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"): left, top = [(value + offset) * antialias for value in ellipse_box[:2]] right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]] draw.ellipse([left, top, right, bottom], fill=fill) mask = mask.resize(self.markImg.size, Image.LANCZOS) try: self.markImg.putalpha(mask) except ValueError: pass async def acircle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 异步 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ await self.loop.run_in_executor(None, self.circle_corner, radii, point_list) def circle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ # 画圆(用于分离4个角) img = self.markImg.convert("RGBA") alpha = img.split()[-1] circle = Image.new("L", (radii * 2, radii * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形 w, h = img.size if "lt" in point_list: alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0)) if "rt" in point_list: alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0)) if "lb" in point_list: alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii)) if "rb" in point_list: alpha.paste( circle.crop((radii, radii, radii * 2, radii * 2)), (w - radii, h - radii), ) img.putalpha(alpha) self.markImg = img self.draw = ImageDraw.Draw(self.markImg) 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): """ 说明: 旋转图片 参数: :param angle: 角度 :param expand: 放大图片适应角度 """ self.markImg = self.markImg.rotate(angle, expand=expand) async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 异步 旋转图片(包括边框) 参数: :param angle: 角度 """ await self.loop.run_in_executor(None, self.transpose, angle) def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 旋转图片(包括边框) 参数: :param angle: 角度 """ self.markImg.transpose(angle) async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ await self.loop.run_in_executor(None, self.filter, filter_, aud) def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ _x = None if filter_ == "GaussianBlur": # 高斯模糊 _x = ImageFilter.GaussianBlur elif filter_ == "EDGE_ENHANCE": # 锐化效果 _x = ImageFilter.EDGE_ENHANCE elif filter_ == "BLUR": # 模糊效果 _x = ImageFilter.BLUR elif filter_ == "CONTOUR": # 铅笔滤镜 _x = ImageFilter.CONTOUR elif filter_ == "FIND_EDGES": # 边缘检测 _x = ImageFilter.FIND_EDGES if _x: if aud: self.markImg = self.markImg.filter(_x(aud)) else: self.markImg = self.markImg.filter(_x) self.draw = ImageDraw.Draw(self.markImg) async def areplace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 异步 颜色替换 参数: :param src_color: 目标颜色,或者使用列表,设置阈值 :param replace_color: 替换颜色 """ self.loop.run_in_executor( None, self.replace_color_tran, src_color, replace_color ) def replace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 颜色替换 参数: :param src_color: 目标颜色,或者使用元祖,设置阈值 :param replace_color: 替换颜色 """ if isinstance(src_color, tuple): start_ = src_color[0] end_ = src_color[1] else: start_ = src_color end_ = None for i in range(self.w): for j in range(self.h): r, g, b = self.markImg.getpixel((i, j)) if not end_: if r == start_[0] and g == start_[1] and b == start_[2]: self.markImg.putpixel((i, j), replace_color) else: if ( start_[0] <= r <= end_[0] and start_[1] <= g <= end_[1] and start_[2] <= b <= end_[2] ): self.markImg.putpixel((i, j), replace_color) # def getchannel(self, type_): self.markImg = self.markImg.getchannel(type_) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } async def get_user_avatar(qq: Union[int, str]) -> Optional[bytes]: """ 说明: 快捷获取用户头像 参数: :param qq: qq号 """ url = f"http://q1.qlogo.cn/g?b=qq&nk={qq}&s=160" async with httpx.AsyncClient() as client: for _ in range(3): try: return (await client.get(url)).content except Exception as e: logger.error("获取用户头像错误", "Util", target=qq) return None """所属群聊""" """红包名称""" """总金币""" """红包数量""" """发起人昵称""" """发起人id""" """是否为节日红包""" """过期时间""" """指定人id""" """红包发起时间""" """开启用户""" The provided code snippet includes necessary dependencies for implementing the `build_open_result_image` function. Write a Python function `async def build_open_result_image( red_bag: RedBag, user_id: Union[int, str], amount: int ) -> BuildImage` to solve the following problem: 构造红包开启图片 参数: red_bag: RedBag user_id: 开启红包用户id amount: 开启红包获取的金额 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片 Here is the function: async def build_open_result_image( red_bag: RedBag, user_id: Union[int, str], amount: int ) -> BuildImage: """构造红包开启图片 参数: red_bag: RedBag user_id: 开启红包用户id amount: 开启红包获取的金额 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片 """ background_list = os.listdir(f"{IMAGE_PATH}/prts/redbag_1") if not background_list: raise ValueError("prts/redbag_1 背景图列表为空...") random_redbag = random.choice(background_list) head = BuildImage( 1000, 980, font_size=30, background=IMAGE_PATH / "prts" / "redbag_1" / random_redbag, ) size = BuildImage(0, 0, font_size=50).getsize(red_bag.name) ava_bk = BuildImage(100 + size[0], 66, is_alpha=True, font_size=50) ava_byte = await get_user_avatar(user_id) ava = None if ava_byte: ava = BuildImage(66, 66, is_alpha=True, background=BytesIO(ava_byte)) else: ava = BuildImage(66, 66, color=(0, 0, 0), is_alpha=True) await ava_bk.apaste(ava) ava_bk.text((100, 7), red_bag.name) ava_bk_w, ava_bk_h = ava_bk.size await head.apaste(ava_bk, (int((1000 - ava_bk_w) / 2), 300), alpha=True) size = BuildImage(0, 0, font_size=150).getsize(amount) amount_image = BuildImage(size[0], size[1], is_alpha=True, font_size=150) await amount_image.atext((0, 0), str(amount), fill=(209, 171, 108)) # 金币中文 await head.apaste(amount_image, (int((1000 - size[0]) / 2) - 50, 460), alpha=True) await head.atext( (int((1000 - size[0]) / 2 + size[0]) - 50, 500 + size[1] - 70), "金币", fill=(209, 171, 108), ) # 剩余数量和金额 text = ( f"已领取" f"{red_bag.num - len(red_bag.open_user)}" f"/{red_bag.num}个," f"共{sum(red_bag.open_user.values())}/{red_bag.amount}金币" ) await head.atext((350, 900), text, (198, 198, 198)) return head
构造红包开启图片 参数: red_bag: RedBag user_id: 开启红包用户id amount: 开启红包获取的金额 异常: ValueError: 图片背景列表为空 返回: BuildImage: 构造后的图片
188,259
from services import logger from utils.http_utils import AsyncHttpx from configs.config import Config from configs.path_config import TEMP_PATH from utils.message_builder import image from typing import Union, List import random API_URL_SAUCENAO = "https://saucenao.com/search.php" class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") async def get_saucenao_image(url: str) -> Union[str, List[str]]: api_key = Config.get_config("search_image", "API_KEY") if not api_key: return "Saucenao 缺失API_KEY!" params = { "output_type": 2, "api_key": api_key, "testmode": 1, "numres": 6, "db": 999, "url": url, } data = (await AsyncHttpx.post(API_URL_SAUCENAO, params=params)).json() if data["header"]["status"] != 0: return f"Saucenao识图失败..status:{data['header']['status']}" data = data["results"] data = ( data if len(data) < Config.get_config("search_image", "MAX_FIND_IMAGE_COUNT") else data[: Config.get_config("search_image", "MAX_FIND_IMAGE_COUNT")] ) 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")) for info in data: try: similarity = info["header"]["similarity"] tmp = f"相似度:{similarity}%\n" for x in info["data"].keys(): if x != "ext_urls": tmp += f"{x}:{info['data'][x]}\n" try: if "source" not in info["data"].keys(): tmp += f'source:{info["data"]["ext_urls"][0]}\n' except KeyError: tmp += f'source:{info["header"]["thumbnail"]}\n' msg_list.append(tmp[:-1]) except Exception as e: logger.warning(f"识图获取图片信息发生错误 {type(e)}:{e}") return msg_list
null
188,260
import time from services.log import logger from utils.langconv import * from utils.http_utils import AsyncHttpx class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ async def get_anime(anime: str) -> str: s_time = time.time() url = "https://api.trace.moe/search?anilistInfo&url={}".format(anime) logger.debug("[info]Now starting get the {}".format(url)) try: anime_json = (await AsyncHttpx.get(url)).json() if not anime_json["error"]: if anime_json == "Error reading imagenull": return "图像源错误,注意必须是静态图片哦" repass = "" # 拿到动漫 中文名 for anime in anime_json["result"][:5]: synonyms = anime["anilist"]["synonyms"] for x in synonyms: _count_ch = 0 for word in x: if "\u4e00" <= word <= "\u9fff": _count_ch += 1 if _count_ch > 3: anime_name = x break else: anime_name = anime["anilist"]["title"]["native"] episode = anime["episode"] from_ = int(anime["from"]) m, s = divmod(from_, 60) similarity = anime["similarity"] putline = "[ {} ][{}][{}:{}] 相似度:{:.2%}".format( Converter("zh-hans").convert(anime_name), episode if episode else "?", m, s, similarity, ) repass += putline + "\n" return f"耗时 {int(time.time() - s_time)} 秒\n" + repass[:-1] else: return f'访问错误 error:{anime_json["error"]}' except Exception as e: logger.error(f"识番发生错误 {type(e)}:{e}") return "发生了奇怪的错误,那就没办法了,再试一次?"
null
188,261
import os from typing import List from configs.config import NICKNAME from configs.path_config import IMAGE_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.utils import cn2py _path = IMAGE_PATH / "image_management" class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def cn2py(word: str) -> str: """ 说明: 将字符串转化为拼音 参数: :param word: 文本 """ temp = "" for i in pypinyin.pinyin(word, style=pypinyin.NORMAL): temp += "".join(i) return temp async def upload_image_to_local( img_list: List[str], path_: str, user_id: int, group_id: int = 0 ) -> str: _path_name = path_ path = _path / cn2py(path_) if not path.exists() and (path.parent.parent / cn2py(path_)).exists(): path = path.parent.parent / cn2py(path_) path.mkdir(parents=True, exist_ok=True) img_id = len(os.listdir(path)) failed_list = [] success_id = "" for img_url in img_list: if await AsyncHttpx.download_file(img_url, path / f"{img_id}.jpg"): success_id += str(img_id) + "," img_id += 1 else: failed_list.append(img_url) failed_result = "" for img in failed_list: failed_result += str(img) + "\n" logger.info( f"上传图片至 {_path_name} 共 {len(img_list)} 张,失败 {len(failed_list)} 张,id={success_id[:-1]}", "上传图片", user_id, group_id, ) if failed_list: return ( f"这次一共为 {_path_name}库 添加了 {len(img_list) - len(failed_list)} 张图片\n" f"依次的Id为:{success_id[:-1]}\n上传失败:{failed_result[:-1]}\n{NICKNAME}感谢您对图库的扩充!WW" ) else: return ( f"这次一共为 {_path_name}库 添加了 {len(img_list)} 张图片\n依次的Id为:" f"{success_id[:-1]}\n{NICKNAME}感谢您对图库的扩充!WW" )
null
188,262
from nonebot.adapters.onebot.v11 import Bot, Event from nonebot.typing import T_State from utils.utils import get_message_text from configs.config import Config { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def get_message_text(data: Union[str, Message]) -> str: """ 说明: 获取消息中 纯文本 的信息 参数: :param data: event.json() """ result = "" if isinstance(data, str): event = json.loads(data) if data and (message := event.get("message")): if isinstance(message, str): return message.strip() for msg in message: if msg["type"] == "text": result += msg["data"]["text"].strip() + " " return result.strip() else: for seg in data["text"]: result += seg.data["text"] + " " return result.strip() The provided code snippet includes necessary dependencies for implementing the `rule` function. Write a Python function `def rule(bot: Bot, event: Event, state: T_State) -> bool` to solve the following problem: 检测文本是否是关闭功能命令 :param bot: pass :param event: pass :param state: pass Here is the function: def rule(bot: Bot, event: Event, state: T_State) -> bool: """ 检测文本是否是关闭功能命令 :param bot: pass :param event: pass :param state: pass """ msg = get_message_text(event.json()) for x in Config.get_config("image_management", "IMAGE_DIR_LIST"): if msg.startswith(x): return True return False
检测文本是否是关闭功能命令 :param bot: pass :param event: pass :param state: pass
188,263
import random import warnings from pathlib import Path import cv2 import numpy as np from PIL import Image def pix_random_change(img): # Image转cv2 img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) img[0, 0, 0] = random.randint(0, 0xFFFFFFF) # cv2转Image img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) return img
null
188,264
import random import warnings from pathlib import Path import cv2 import numpy as np from PIL import Image def pix_random_change_file(path: Path): # 注意:cv2.imread()不支持路径中文 str_path = str(path.absolute()) warnings.filterwarnings("ignore", category=Warning) img = cv2.imread(str_path) img[0, 0, 0] = random.randint(0, 0xFFFFFFF) cv2.imwrite(str_path, img) return str_path
null
188,265
from nonebot import on_command from nonebot.adapters.onebot.v11 import MessageEvent, Message, GroupMessageEvent from utils.message_builder import image from nonebot.params import CommandArg from ._data_source import get_data from services.log import logger cover = on_command("b封面", aliases={"B封面"}, priority=5, block=True) cover_url = "https://v2.alapi.cn/api/bilibili/cover" def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict, str], int]: class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: async def _(event: MessageEvent, arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() params = {"c": msg} data, code = await get_data(cover_url, params) if code != 200: await cover.finish(data, at_sender=True) data = data["data"] title = data["title"] img = data["cover"] await cover.send(Message(f"title:{title}\n{image(img)}")) logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 获取b站封面: {title} url:{img}" )
null
188,266
from nonebot import on_command from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent from services.log import logger from ._data_source import get_data poetry = on_command("念诗", aliases={"来首诗", "念首诗"}, priority=5, block=True) poetry_url = "https://v2.alapi.cn/api/shici" class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict, str], int]: """ 获取ALAPI数据 :param url: 请求链接 :param params: 参数 """ if not params: params = {} params["token"] = Config.get_config("alapi", "ALAPI_TOKEN") try: data = (await AsyncHttpx.get(url, params=params, timeout=5)).json() if data["code"] == 200: if not data["data"]: return "没有搜索到...", 997 return data, 200 else: if data["code"] == 101: return "缺失ALAPI TOKEN,请在配置文件中填写!", 999 return f'发生了错误...code:{data["code"]}', 999 except TimeoutError: return "超时了....", 998 async def _(event: MessageEvent): data, code = await get_data(poetry_url) if code != 200: await poetry.finish(data, at_sender=True) data = data["data"] content = data["content"] title = data["origin"] author = data["author"] await poetry.send(f"{content}\n\t——{author}《{title}》") logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 发送古诗: f'{content}\n\t--{author}《{title}》'" )
null
188,267
from nonebot import on_regex from services.log import logger from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent from ._data_source import get_data url = "https://v2.alapi.cn/api/soul" jitang = on_regex("^毒?鸡汤$", priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict, str], int]: """ 获取ALAPI数据 :param url: 请求链接 :param params: 参数 """ if not params: params = {} params["token"] = Config.get_config("alapi", "ALAPI_TOKEN") try: data = (await AsyncHttpx.get(url, params=params, timeout=5)).json() if data["code"] == 200: if not data["data"]: return "没有搜索到...", 997 return data, 200 else: if data["code"] == 101: return "缺失ALAPI TOKEN,请在配置文件中填写!", 999 return f'发生了错误...code:{data["code"]}', 999 except TimeoutError: return "超时了....", 998 async def _(event: MessageEvent): try: data, code = await get_data(url) if code != 200: await jitang.finish(data, at_sender=True) await jitang.send(data["data"]["content"]) logger.info( f"(USER {event.user_id}, GROUP " f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 发送鸡汤:" + data["data"]["content"] ) except Exception as e: await jitang.send("鸡汤煮坏掉了...") logger.error(f"鸡汤煮坏掉了 {type(e)}:{e}")
null
188,268
from nonebot import on_regex from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent from ._data_source import get_data from services.log import logger comments_163 = on_regex( "^(网易云热评|网易云评论|到点了|12点了)$", priority=5, block=True ) comments_163_url = "https://v2.alapi.cn/api/comment" async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict, str], int]: class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: async def _(event: MessageEvent): data, code = await get_data(comments_163_url) if code != 200: await comments_163.finish(data, at_sender=True) data = data["data"] comment = data["comment_content"] song_name = data["title"] await comments_163.send(f"{comment}\n\t——《{song_name}》") logger.info( f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f" 发送网易云热评: {comment} \n\t\t————{song_name}" )
null
188,269
from utils.http_utils import AsyncHttpx from nonebot.adapters.onebot.v11 import MessageSegment from typing import Optional from services.log import logger from utils.image_utils import text2image from utils.message_builder import image from json.decoder import JSONDecodeError import re import json "" 数字格式化 """ orig = str(value) new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig) return new if orig == new else intcomma(new) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def text2image( text: str, auto_parse: bool = True, font_size: int = 20, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white", font: str = "CJGaoDeGuo.otf", font_color: Union[str, Tuple[int, int, int]] = "black", padding: Union[int, Tuple[int, int, int, int]] = 0, _add_height: float = 0, ) -> BuildImage: """ 说明: 解析文本并转为图片 使用标签 <f> </f> 可选配置项 font: str -> 特殊文本字体 fs / font_size: int -> 特殊文本大小 fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色 示例 在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>, 你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过, <f font_size=25>抽卡抽不到金色</f>,这让我很痛苦 参数: :param text: 文本 :param auto_parse: 是否自动解析,否则原样发送 :param font_size: 普通字体大小 :param color: 背景颜色 :param font: 普通字体 :param font_color: 普通字体颜色 :param padding: 文本外边距,元组类型时为 (上,左,下,右) :param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度 """ pw = ph = top_padding = left_padding = 0 if padding: if isinstance(padding, int): pw = padding * 2 ph = padding * 2 top_padding = left_padding = padding elif isinstance(padding, tuple): pw = padding[0] + padding[2] ph = padding[1] + padding[3] top_padding = padding[0] left_padding = padding[1] if auto_parse and re.search(r"<f(.*)>(.*)</f>", text): _data = [] new_text = "" placeholder_index = 0 for s in text.split("</f>"): r = re.search(r"<f(.*)>(.*)", s) if r: start, end = r.span() if start != 0 and (t := s[:start]): new_text += t _data.append( [ (start, end), f"[placeholder_{placeholder_index}]", r.group(1).strip(), r.group(2), ] ) new_text += f"[placeholder_{placeholder_index}]" placeholder_index += 1 new_text += text.split("</f>")[-1] image_list = [] current_placeholder_index = 0 # 切分换行,每行为单张图片 for s in new_text.split("\n"): _tmp_text = s img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1] img_width = 0 _tmp_index = current_placeholder_index for _ in range(s.count("[placeholder_")): placeholder = _data[_tmp_index] if "font_size" in placeholder[2]: r = re.search(r"font_size=['\"]?(\d+)", placeholder[2]) if r: w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize( placeholder[3] ) img_height = img_height if img_height > h else h img_width += w else: img_width += BuildImage(0, 0, font_size=font_size).getsize( placeholder[3] )[0] _tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "") _tmp_index += 1 img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0] # img_width += len(_tmp_text) * font_size # 开始画图 A = BuildImage( img_width, img_height, color=color, font=font, font_size=font_size ) basic_font_h = A.getsize("正")[1] current_width = 0 # 遍历占位符 for _ in range(s.count("[placeholder_")): if not s.startswith(f"[placeholder_{current_placeholder_index}]"): slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext( (current_width, A.h - basic_font_h - 1), slice_[0], font_color ) current_width += A.getsize(slice_[0])[0] placeholder = _data[current_placeholder_index] # 解析配置 _font = font _font_size = font_size _font_color = font_color for e in placeholder[2].split(): if e.startswith("font="): _font = e.split("=")[-1] if e.startswith("font_size=") or e.startswith("fs="): _font_size = int(e.split("=")[-1]) if _font_size > 1000: _font_size = 1000 if _font_size < 1: _font_size = 1 if e.startswith("font_color") or e.startswith("fc="): _font_color = e.split("=")[-1] text_img = BuildImage( 0, 0, plain_text=placeholder[3], font_size=_font_size, font_color=_font_color, font=_font, ) _img_h = ( int(A.h / 2 - text_img.h / 2) if new_text == "[placeholder_0]" else A.h - text_img.h ) await A.apaste(text_img, (current_width, _img_h - 1), True) current_width += text_img.w s = s[ s.index(f"[placeholder_{current_placeholder_index}]") + len(f"[placeholder_{current_placeholder_index}]") : ] current_placeholder_index += 1 if s: slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext((current_width, A.h - basic_font_h), slice_[0]) current_width += A.getsize(slice_[0])[0] A.crop((0, 0, current_width, A.h)) # A.show() image_list.append(A) height = 0 width = 0 for img in image_list: height += img.h width = width if width > img.w else img.w width += pw height += ph A = BuildImage(width + left_padding, height + top_padding, color=color) current_height = top_padding for img in image_list: await A.apaste(img, (left_padding, current_height), True) current_height += img.h else: width = 0 height = 0 _tmp = BuildImage(0, 0, font=font, font_size=font_size) _, h = _tmp.getsize("正") line_height = int(font_size / 3) image_list = [] for x in text.split("\n"): w, _ = _tmp.getsize(x.strip() or "正") height += h + line_height width = width if width > w else w image_list.append( BuildImage( w, h, font=font, font_size=font_size, plain_text=x.strip(), color=color, ) ) width += pw height += ph A = BuildImage( width + left_padding, height + top_padding + 2, color=color, ) cur_h = ph for img in image_list: await A.apaste(img, (pw, cur_h), True) cur_h += img.h + line_height return A def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") The provided code snippet includes necessary dependencies for implementing the `get_other_data` function. Write a Python function `async def get_other_data(place: str, count: int = 0) -> Optional[MessageSegment]` to solve the following problem: :param place: 地名 :param count: 递归次数 :return: 格式化字符串 Here is the function: async def get_other_data(place: str, count: int = 0) -> Optional[MessageSegment]: """ :param place: 地名 :param count: 递归次数 :return: 格式化字符串 """ if count == 5: return None try: html = ( (await AsyncHttpx.get("https://news.ifeng.com/c/special/7uLj4F83Cqm")) .text.replace("\n", "") .replace(" ", "") ) find_data = re.compile(r"varallData=(.*?);</script>") sum_ = re.findall(find_data, html)[0] sum_ = json.loads(sum_) except JSONDecodeError: return await get_other_data(place, count + 1) except Exception as e: logger.error(f"疫情查询发生错误 {type(e)}:{e}") return None try: other_country = sum_["yiqing_v2"]["dataList"][29]["child"] for country in other_country: if place == country["name2"]: return image( b64=(await text2image( f" {place} 疫情数据:\n" "——————————————\n" f" 新增病例:<f font_color=red>{intcomma(country['quezhen_add'])}</f>\n" f" 现有确诊:<f font_color=red>{intcomma(country['quezhen_xianyou'])}</f>\n" f" 累计确诊:<f font_color=red>{intcomma(country['quezhen'])}</f>\n" f" 累计治愈:<f font_color=#39de4b>{intcomma(country['zhiyu'])}</f>\n" f" 死亡:{intcomma(country['siwang'])}\n" "——————————————" # f"更新时间:{country['sys_publishDateTime']}" # 时间无法精确到分钟,网页用了js我暂时找不到 , font_size=30, color="#f9f6f2", padding=15 )).pic2bs4() ) else: for city in country["child"]: if place == city["name3"]: return image( b64=(await text2image( f"\n{place} 疫情数据:\n" "——————————————\n" f"\t新增病例:<f font_color=red>{intcomma(city['quezhen_add'])}</f>\n" f"\t累计确诊:<f font_color=red>{intcomma(city['quezhen'])}</f>\n" f"\t累计治愈:<f font_color=#39de4b>{intcomma(city['zhiyu'])}</f>\n" f"\t死亡:{intcomma(city['siwang'])}\n" "——————————————\n", font_size=30, color="#f9f6f2", padding=15 )).pic2bs4() ) except Exception as e: logger.error(f"疫情查询发生错误 {type(e)}:{e}") return None
:param place: 地名 :param count: 递归次数 :return: 格式化字符串
188,270
from configs.path_config import TEXT_PATH from typing import List, Union from utils.http_utils import AsyncHttpx from utils.image_utils import text2image from utils.message_builder import image from nonebot.adapters.onebot.v11 import MessageSegment import ujson as json data = {} url = "https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=diseaseh5Shelf" class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ async def text2image( text: str, auto_parse: bool = True, font_size: int = 20, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white", font: str = "CJGaoDeGuo.otf", font_color: Union[str, Tuple[int, int, int]] = "black", padding: Union[int, Tuple[int, int, int, int]] = 0, _add_height: float = 0, ) -> BuildImage: """ 说明: 解析文本并转为图片 使用标签 <f> </f> 可选配置项 font: str -> 特殊文本字体 fs / font_size: int -> 特殊文本大小 fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色 示例 在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>, 你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过, <f font_size=25>抽卡抽不到金色</f>,这让我很痛苦 参数: :param text: 文本 :param auto_parse: 是否自动解析,否则原样发送 :param font_size: 普通字体大小 :param color: 背景颜色 :param font: 普通字体 :param font_color: 普通字体颜色 :param padding: 文本外边距,元组类型时为 (上,左,下,右) :param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度 """ pw = ph = top_padding = left_padding = 0 if padding: if isinstance(padding, int): pw = padding * 2 ph = padding * 2 top_padding = left_padding = padding elif isinstance(padding, tuple): pw = padding[0] + padding[2] ph = padding[1] + padding[3] top_padding = padding[0] left_padding = padding[1] if auto_parse and re.search(r"<f(.*)>(.*)</f>", text): _data = [] new_text = "" placeholder_index = 0 for s in text.split("</f>"): r = re.search(r"<f(.*)>(.*)", s) if r: start, end = r.span() if start != 0 and (t := s[:start]): new_text += t _data.append( [ (start, end), f"[placeholder_{placeholder_index}]", r.group(1).strip(), r.group(2), ] ) new_text += f"[placeholder_{placeholder_index}]" placeholder_index += 1 new_text += text.split("</f>")[-1] image_list = [] current_placeholder_index = 0 # 切分换行,每行为单张图片 for s in new_text.split("\n"): _tmp_text = s img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1] img_width = 0 _tmp_index = current_placeholder_index for _ in range(s.count("[placeholder_")): placeholder = _data[_tmp_index] if "font_size" in placeholder[2]: r = re.search(r"font_size=['\"]?(\d+)", placeholder[2]) if r: w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize( placeholder[3] ) img_height = img_height if img_height > h else h img_width += w else: img_width += BuildImage(0, 0, font_size=font_size).getsize( placeholder[3] )[0] _tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "") _tmp_index += 1 img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0] # img_width += len(_tmp_text) * font_size # 开始画图 A = BuildImage( img_width, img_height, color=color, font=font, font_size=font_size ) basic_font_h = A.getsize("正")[1] current_width = 0 # 遍历占位符 for _ in range(s.count("[placeholder_")): if not s.startswith(f"[placeholder_{current_placeholder_index}]"): slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext( (current_width, A.h - basic_font_h - 1), slice_[0], font_color ) current_width += A.getsize(slice_[0])[0] placeholder = _data[current_placeholder_index] # 解析配置 _font = font _font_size = font_size _font_color = font_color for e in placeholder[2].split(): if e.startswith("font="): _font = e.split("=")[-1] if e.startswith("font_size=") or e.startswith("fs="): _font_size = int(e.split("=")[-1]) if _font_size > 1000: _font_size = 1000 if _font_size < 1: _font_size = 1 if e.startswith("font_color") or e.startswith("fc="): _font_color = e.split("=")[-1] text_img = BuildImage( 0, 0, plain_text=placeholder[3], font_size=_font_size, font_color=_font_color, font=_font, ) _img_h = ( int(A.h / 2 - text_img.h / 2) if new_text == "[placeholder_0]" else A.h - text_img.h ) await A.apaste(text_img, (current_width, _img_h - 1), True) current_width += text_img.w s = s[ s.index(f"[placeholder_{current_placeholder_index}]") + len(f"[placeholder_{current_placeholder_index}]") : ] current_placeholder_index += 1 if s: slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext((current_width, A.h - basic_font_h), slice_[0]) current_width += A.getsize(slice_[0])[0] A.crop((0, 0, current_width, A.h)) # A.show() image_list.append(A) height = 0 width = 0 for img in image_list: height += img.h width = width if width > img.w else img.w width += pw height += ph A = BuildImage(width + left_padding, height + top_padding, color=color) current_height = top_padding for img in image_list: await A.apaste(img, (left_padding, current_height), True) current_height += img.h else: width = 0 height = 0 _tmp = BuildImage(0, 0, font=font, font_size=font_size) _, h = _tmp.getsize("正") line_height = int(font_size / 3) image_list = [] for x in text.split("\n"): w, _ = _tmp.getsize(x.strip() or "正") height += h + line_height width = width if width > w else w image_list.append( BuildImage( w, h, font=font, font_size=font_size, plain_text=x.strip(), color=color, ) ) width += pw height += ph A = BuildImage( width + left_padding, height + top_padding + 2, color=color, ) cur_h = ph for img in image_list: await A.apaste(img, (pw, cur_h), True) cur_h += img.h + line_height return A def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") The provided code snippet includes necessary dependencies for implementing the `get_yiqing_data` function. Write a Python function `async def get_yiqing_data(area: str) -> Union[str, MessageSegment]` to solve the following problem: 查看疫情数据 :param area: 省份/城市 Here is the function: async def get_yiqing_data(area: str) -> Union[str, MessageSegment]: """ 查看疫情数据 :param area: 省份/城市 """ global data province = None city = None province_type = "省" if area == "中国": province = area province_type = "" elif area[-1] == '省' or (area in data.keys() and area[-1] != "市"): province = area if area[-1] != "省" else area[:-1] if len(data[province]) == 1: province_type = "市" city = "" else: area = area[:-1] if area[-1] == "市" else area for p in data.keys(): if area in data[p]: province = p city = area epidemic_data = (await AsyncHttpx.get(url)).json()["data"]["diseaseh5Shelf"] last_update_time = epidemic_data["lastUpdateTime"] if area == "中国": data_ = epidemic_data["areaTree"][0] else: try: data_ = [ x for x in epidemic_data["areaTree"][0]["children"] if x["name"] == province ][0] if city: data_ = [x for x in data_["children"] if x["name"] == city][0] except IndexError: return "未查询到..." confirm = data_["total"]["confirm"] # 累计确诊 heal = data_["total"]["heal"] # 累计治愈 dead = data_["total"]["dead"] # 累计死亡 now_confirm = data_["total"]["nowConfirm"] # 目前确诊 add_confirm = data_["today"]["confirm"] # 新增确诊 add_wzz = data_["today"]["wzz_add"] #新增无症状 wzz=data_["total"]["wzz"] #目前无症状 grade = "" _grade_color = "" # if data_["total"].get("grade"): # grade = data_["total"]["grade"] # if "中风险" in grade: # _grade_color = "#fa9424" # else: # _grade_color = "red" dead_rate = f"{dead / confirm * 100:.2f}" # 死亡率 heal_rate = f"{heal / confirm * 100:.2f}" # 治愈率 x = f"{city}市" if city else f"{province}{province_type}" return image(b64=(await text2image( f""" {x} 疫情数据 {f"(<f font_color={_grade_color}>{grade}</f>)" if grade else ""}: 目前确诊: 确诊人数:<f font_color=red>{now_confirm}(+{add_confirm})</f> 新增无症状:<f font_color=red>{add_wzz}</f> ----------------- 累计数据: 无症状人数:<f font_color=red>{wzz}</f> 确诊人数:<f font_color=red>{confirm}</f> 治愈人数:<f font_color=#39de4b>{heal}</f> 死亡人数:<f font_color=#191d19>{dead}</f> 治愈率:{heal_rate}% 死亡率:{dead_rate}% 更新日期:{last_update_time} """, font_size=30, color="#f9f6f2" )).pic2bs4())
查看疫情数据 :param area: 省份/城市
188,271
from configs.path_config import TEXT_PATH from typing import List, Union from utils.http_utils import AsyncHttpx from utils.image_utils import text2image from utils.message_builder import image from nonebot.adapters.onebot.v11 import MessageSegment import ujson as json china_city = TEXT_PATH / "china_city.json" data = {} The provided code snippet includes necessary dependencies for implementing the `get_city_and_province_list` function. Write a Python function `def get_city_and_province_list() -> List[str]` to solve the following problem: 获取城市省份列表 Here is the function: def get_city_and_province_list() -> List[str]: """ 获取城市省份列表 """ global data if not data: try: with open(china_city, "r", encoding="utf8") as f: data = json.load(f) except FileNotFoundError: data = {} city_list = ["中国"] for p in data.keys(): for c in data[p]: city_list.append(c) city_list.append(p) return city_list
获取城市省份列表
188,272
from nonebot.adapters.onebot.v11 import MessageSegment from utils.image_utils import BuildImage from utils.message_builder import image from configs.path_config import IMAGE_PATH from typing import Tuple, Union from utils.http_utils import AsyncHttpx import datetime class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ The provided code snippet includes necessary dependencies for implementing the `get_wbtop` function. Write a Python function `async def get_wbtop(url: str) -> Tuple[Union[dict, str], int]` to solve the following problem: :param url: 请求链接 Here is the function: async def get_wbtop(url: str) -> Tuple[Union[dict, str], int]: """ :param url: 请求链接 """ n = 0 while True: try: data = [] get_response = (await AsyncHttpx.get(url, timeout=20)) if get_response.status_code == 200: data_json = get_response.json()['data']['realtime'] for data_item in data_json: # 如果是广告,则不添加 if 'is_ad' in data_item: continue dic = { 'hot_word': data_item['note'], 'hot_word_num': str(data_item['num']), 'url': 'https://s.weibo.com/weibo?q=%23' + data_item['word'] + '%23', } data.append(dic) if not data: return "没有搜索到...", 997 return {'data': data, 'time': datetime.datetime.now()}, 200 else: if n > 2: return f'获取失败,请十分钟后再试', 999 else: n += 1 continue except TimeoutError: return "超时了....", 998
:param url: 请求链接
188,273
from nonebot.adapters.onebot.v11 import MessageSegment from utils.image_utils import BuildImage from utils.message_builder import image from configs.path_config import IMAGE_PATH from typing import Tuple, Union from utils.http_utils import AsyncHttpx import datetime class BuildImage: """ 快捷生成图片与操作图片的工具类 """ def __init__( self, w: int, h: int, paste_image_width: int = 0, paste_image_height: int = 0, paste_space: int = 0, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None, image_mode: ModeType = "RGBA", font_size: int = 10, background: Union[Optional[str], BytesIO, Path] = None, font: str = "yz.ttf", ratio: float = 1, is_alpha: bool = False, plain_text: Optional[str] = None, font_color: Optional[Union[str, Tuple[int, int, int]]] = None, **kwargs, ): """ 参数: :param w: 自定义图片的宽度,w=0时为图片原本宽度 :param h: 自定义图片的高度,h=0时为图片原本高度 :param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行 :param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行 :param paste_space: 自动贴图间隔 :param color: 生成图片的颜色 :param image_mode: 图片的类型 :param font_size: 文字大小 :param background: 打开图片的路径 :param font: 字体,默认在 resource/ttf/ 路径下 :param ratio: 倍率压缩 :param is_alpha: 是否背景透明 :param plain_text: 纯文字文本 """ self.w = int(w) self.h = int(h) self.paste_image_width = int(paste_image_width) self.paste_image_height = int(paste_image_height) self.paste_space = int(paste_space) self._current_w = 0 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) self.background = background if not background: if plain_text: if not color: color = (255, 255, 255, 0) ttf_w, ttf_h = self.getsize(str(plain_text)) self.w = self.w if self.w > ttf_w else ttf_w self.h = self.h if self.h > ttf_h else ttf_h self.markImg = Image.new(image_mode, (self.w, self.h), color) self.markImg.convert(image_mode) else: if not w and not h: self.markImg = Image.open(background) w, h = self.markImg.size if ratio and ratio > 0 and ratio != 1: self.w = int(ratio * w) self.h = int(ratio * h) self.markImg = self.markImg.resize( (self.w, self.h), Image.ANTIALIAS ) else: self.w = w self.h = h else: self.markImg = Image.open(background).resize( (self.w, self.h), Image.ANTIALIAS ) if is_alpha: try: 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) self.size = self.w, self.h if plain_text: fill = font_color if font_color else (0, 0, 0) self.text((0, 0), str(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() def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 参数: :param font: 字体名称 :param font_size: 字体大小 """ return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 异步 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ await self.loop.run_in_executor( None, self.paste, img, pos, alpha, center_type, allow_negative ) def paste( self, img: "BuildImage", pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) width, height = 0, 0 if not pos: pos = (0, 0) if center_type == "center": width = int((self.w - img.w) / 2) height = int((self.h - img.h) / 2) elif center_type == "by_width": width = int((self.w - img.w) / 2) height = pos[1] elif center_type == "by_height": width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) if pos and allow_negative: 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: self._current_w = 0 self._current_h += self.paste_image_height + self.paste_space if not pos: pos = (self._current_w, self._current_h) if alpha: try: self.markImg.paste(img, pos, img) except ValueError: img = img.convert("RGBA") self.markImg.paste(img, pos, img) else: self.markImg.paste(img, pos) self._current_w += self.paste_image_width + self.paste_space def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 :param font: 字体 :param font_size: 字体大小 """ font_ = cls.load_font(font, font_size) return font_.getsize(msg) # type: ignore def getsize(self, msg: Any) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 """ return self.font.getsize(str(msg)) # type: ignore 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): """ 说明: 绘制多个或单独的像素 参数: :param pos: 坐标 :param fill: 填错颜色 """ 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], 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: 描线宽度 """ self.draw.ellipse(pos, fill, outline, width) async def atext( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 异步 在图片上添加文字 参数: :param pos: 文字位置 :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ await self.loop.run_in_executor( None, self.text, pos, text, fill, center_type, font, font_size, **kwargs ) def text( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 在图片上添加文字 参数: :param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效) :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) w, h = self.w, self.h longgest_text = "" sentence = text.split("\n") for x in sentence: longgest_text = x if len(x) > len(longgest_text) else longgest_text ttf_w, ttf_h = self.getsize(longgest_text) ttf_h = ttf_h * len(sentence) if center_type == "center": w = int((w - ttf_w) / 2) h = int((h - ttf_h) / 2) elif center_type == "by_width": w = int((w - ttf_w) / 2) h = pos[1] elif center_type == "by_height": h = int((h - ttf_h) / 2) w = pos[0] pos = (w, h) if font: if isinstance(font, str): font = self.load_font(font, font_size) elif font_size: font = self.load_font(self.font_name, font_size) self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs) async def asave(self, path: Optional[Union[str, Path]] = None): """ 说明: 异步 保存图片 参数: :param path: 图片路径 """ await self.loop.run_in_executor(None, self.save, path) def save(self, path: Optional[Union[str, Path]] = None): """ 说明: 保存图片 参数: :param path: 图片路径 """ self.markImg.save(path or self.background) # type: ignore def show(self): """ 说明: 显示图片 """ self.markImg.show() 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): """ 说明: 压缩图片 参数: :param ratio: 压缩倍率 :param w: 压缩图片宽度至 w :param h: 压缩图片高度至 h """ if not w and not h and not ratio: raise Exception("缺少参数...") if not w and not h and ratio: w = int(self.w * ratio) h = int(self.h * ratio) self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS) self.w, self.h = self.markImg.size 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]): """ 说明: 裁剪图片 参数: :param box: 左上角坐标,右下角坐标 (left, upper, right, lower) """ self.markImg = self.markImg.crop(box) self.w, self.h = self.markImg.size self.size = self.w, self.h self.draw = ImageDraw.Draw(self.markImg) def check_font_size(self, word: str) -> bool: """ 说明: 检查文本所需宽度是否大于图片宽度 参数: :param word: 文本内容 """ 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): """ 说明: 图片透明化 参数: :param alpha_ratio: 透明化程度 :param n: 透明化大小内边距 """ self.markImg = self.markImg.convert("RGBA") x, y = self.markImg.size for i in range(n, x - n): for k in range(n, y - n): color = self.markImg.getpixel((i, k)) color = color[:-1] + (int(100 * alpha_ratio),) self.markImg.putpixel((i, k), color) self.draw = ImageDraw.Draw(self.markImg) def pic2bs4(self) -> str: """ 说明: BuildImage 转 base64 """ buf = BytesIO() self.markImg.save(buf, format="PNG") base64_str = base64.b64encode(buf.getvalue()).decode() return "base64://" + base64_str def convert(self, type_: ModeType): """ 说明: 修改图片类型 参数: :param type_: 类型 """ self.markImg = self.markImg.convert(type_) async def arectangle( self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[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], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[str] = None, width: int = 1, ): """ 说明: 画框 参数: :param xy: 坐标 :param fill: 填充颜色 :param outline: 轮廓颜色 :param width: 线宽 """ 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[Union[str, 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], fill: Optional[Union[Tuple[int, int, int], str]] = None, width: int = 1, ): """ 说明: 画线 参数: :param xy: 坐标 :param fill: 填充 :param width: 线宽 """ self.draw.line(xy, fill, width) async def acircle(self): """ 说明: 异步 将 BuildImage 图片变为圆形 """ await self.loop.run_in_executor(None, self.circle) def circle(self): """ 说明: 使图像变圆 """ self.markImg.convert("RGBA") size = self.markImg.size r2 = min(size[0], size[1]) if size[0] != size[1]: self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS) width = 1 antialias = 4 ellipse_box = [0, 0, r2 - 2, r2 - 2] mask = Image.new( size=[int(dim * antialias) for dim in self.markImg.size], mode="L", color="black", ) draw = ImageDraw.Draw(mask) for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"): left, top = [(value + offset) * antialias for value in ellipse_box[:2]] right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]] draw.ellipse([left, top, right, bottom], fill=fill) mask = mask.resize(self.markImg.size, Image.LANCZOS) try: self.markImg.putalpha(mask) except ValueError: pass async def acircle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 异步 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ await self.loop.run_in_executor(None, self.circle_corner, radii, point_list) def circle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ # 画圆(用于分离4个角) img = self.markImg.convert("RGBA") alpha = img.split()[-1] circle = Image.new("L", (radii * 2, radii * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形 w, h = img.size if "lt" in point_list: alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0)) if "rt" in point_list: alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0)) if "lb" in point_list: alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii)) if "rb" in point_list: alpha.paste( circle.crop((radii, radii, radii * 2, radii * 2)), (w - radii, h - radii), ) img.putalpha(alpha) self.markImg = img self.draw = ImageDraw.Draw(self.markImg) 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): """ 说明: 旋转图片 参数: :param angle: 角度 :param expand: 放大图片适应角度 """ self.markImg = self.markImg.rotate(angle, expand=expand) async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 异步 旋转图片(包括边框) 参数: :param angle: 角度 """ await self.loop.run_in_executor(None, self.transpose, angle) def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 旋转图片(包括边框) 参数: :param angle: 角度 """ self.markImg.transpose(angle) async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ await self.loop.run_in_executor(None, self.filter, filter_, aud) def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ _x = None if filter_ == "GaussianBlur": # 高斯模糊 _x = ImageFilter.GaussianBlur elif filter_ == "EDGE_ENHANCE": # 锐化效果 _x = ImageFilter.EDGE_ENHANCE elif filter_ == "BLUR": # 模糊效果 _x = ImageFilter.BLUR elif filter_ == "CONTOUR": # 铅笔滤镜 _x = ImageFilter.CONTOUR elif filter_ == "FIND_EDGES": # 边缘检测 _x = ImageFilter.FIND_EDGES if _x: if aud: self.markImg = self.markImg.filter(_x(aud)) else: self.markImg = self.markImg.filter(_x) self.draw = ImageDraw.Draw(self.markImg) async def areplace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 异步 颜色替换 参数: :param src_color: 目标颜色,或者使用列表,设置阈值 :param replace_color: 替换颜色 """ self.loop.run_in_executor( None, self.replace_color_tran, src_color, replace_color ) def replace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 颜色替换 参数: :param src_color: 目标颜色,或者使用元祖,设置阈值 :param replace_color: 替换颜色 """ if isinstance(src_color, tuple): start_ = src_color[0] end_ = src_color[1] else: start_ = src_color end_ = None for i in range(self.w): for j in range(self.h): r, g, b = self.markImg.getpixel((i, j)) if not end_: if r == start_[0] and g == start_[1] and b == start_[2]: self.markImg.putpixel((i, j), replace_color) else: if ( start_[0] <= r <= end_[0] and start_[1] <= g <= end_[1] and start_[2] <= b <= end_[2] ): self.markImg.putpixel((i, j), replace_color) # def getchannel(self, type_): self.markImg = self.markImg.getchannel(type_) def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") The provided code snippet includes necessary dependencies for implementing the `gen_wbtop_pic` function. Write a Python function `def gen_wbtop_pic(data: dict) -> MessageSegment` to solve the following problem: 生成微博热搜图片 :param data: 微博热搜数据 Here is the function: def gen_wbtop_pic(data: dict) -> MessageSegment: """ 生成微博热搜图片 :param data: 微博热搜数据 """ bk = BuildImage(700, 32 * 50 + 280, 700, 32, color="#797979") wbtop_bk = BuildImage(700, 280, background=f"{IMAGE_PATH}/other/webtop.png") bk.paste(wbtop_bk) text_bk = BuildImage(700, 32 * 50, 700, 32, color="#797979") 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) img.text((10, int((30 - h) / 2)), title) img.text((580, int((30 - h) / 2)), hot) text_bk.paste(img) bk.paste(text_bk, (0, 280)) return image(b64=bk.pic2bs4())
生成微博热搜图片 :param data: 微博热搜数据
188,274
import random from datetime import datetime, timedelta import nonebot import pytz from apscheduler.jobstores.base import ConflictingIdError from nonebot import Driver from models.group_member_info import GroupInfoUser from services.log import logger from utils.message_builder import at from utils.utils import get_bot, scheduler from .._models import Genshin from ..mihoyobbs_sign import mihoyobbs_sign from .data_source import genshin_sign def add_job(user_id: int, uid: int, date: datetime): try: scheduler.add_job( _sign, "date", run_date=date.replace(microsecond=0), id=f"genshin_auto_sign_{uid}_{user_id}_0", args=[user_id, uid, 0], ) logger.debug(f"genshin_sign add_job:{date.replace(microsecond=0)} 原神自动签到") except ConflictingIdError: pass async def _sign(user_id: int, uid: int, count: int): """ 执行签到任务 :param user_id: 用户id :param uid: uid :param count: 执行次数 """ try: return_data = await mihoyobbs_sign(user_id) except Exception as e: logger.error(f"mihoyobbs_sign error:{e}") return_data = "米游社签到失败,请尝试发送'米游社签到'进行手动签到" if count < 3: try: msg = await genshin_sign(uid) next_time = await Genshin.random_sign_time(uid) msg += f"\n下一次签到时间为:{next_time.replace(microsecond=0)}" logger.info(f"USER:{user_id} UID:{uid} 原神自动签到任务发生成功...") try: scheduler.add_job( _sign, "date", run_date=next_time.replace(microsecond=0), id=f"genshin_auto_sign_{uid}_{user_id}_0", args=[user_id, uid, 0], ) except ConflictingIdError: msg += "\n定时任务设定失败..." except Exception as e: logger.error(f"USER:{user_id} UID:{uid} 原神自动签到任务发生错误 {type(e)}:{e}") msg = None if not msg: now = datetime.now(pytz.timezone("Asia/Shanghai")) if now.hour < 23: random_hours = random.randint(1, 23 - now.hour) next_time = now + timedelta(hours=random_hours) scheduler.add_job( _sign, "date", run_date=next_time.replace(microsecond=0), id=f"genshin_auto_sign_{uid}_{user_id}_{count}", args=[user_id, uid, count + 1], ) msg = ( f"{now.replace(microsecond=0)} 原神" f"签到失败,将在 {next_time.replace(microsecond=0)} 时重试!" ) else: msg = "今日原神签到失败,请手动签到..." logger.debug(f"USER:{user_id} UID:{uid} 原神今日签到失败...") else: msg = "今日原神自动签到重试次数已达到3次,请手动签到。" logger.debug(f"USER:{user_id} UID:{uid} 原神今日签到失败次数打到 3 次...") bot = get_bot() if bot: if user_id in [x["user_id"] for x in await bot.get_friend_list()]: await bot.send_private_msg(user_id=user_id, message=return_data) await bot.send_private_msg(user_id=user_id, message=msg) else: if user := await Genshin.get_or_none(uid=uid): group_id = user.bind_group if not group_id: if group_list := await GroupInfoUser.get_user_all_group(user_id): group_id = group_list[0] if group_id: await bot.send_group_msg( group_id=group_id, message=at(user_id) + msg ) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) scheduler = scheduler { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } class Genshin(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" uid = fields.BigIntField() """uid""" mys_id: int = fields.BigIntField(null=True) """米游社id""" cookie: str = fields.TextField(default="") """米游社cookie""" auto_sign = fields.BooleanField(default=False) """是否自动签到""" today_query_uid = fields.TextField(default="") """cookie今日查询uid""" auto_sign_time = fields.DatetimeField(null=True) """签到日期时间""" resin_remind = fields.BooleanField(default=False) """树脂提醒""" resin_recovery_time = fields.DatetimeField(null=True) """满树脂提醒日期""" bind_group: int = fields.BigIntField(null=True) """发送提示 绑定群聊""" login_ticket = fields.TextField(default="") """login_ticket""" stuid: str = fields.TextField(default="") """stuid""" stoken: str = fields.TextField(default="") """stoken""" class Meta: table = "genshin" table_description = "原神数据表" unique_together = ("user_id", "uid") async def random_sign_time(cls, uid: int) -> Optional[datetime]: """ 说明: 随机签到时间 说明: :param uid: uid """ user = await cls.get_or_none(uid=uid) if user and user.cookie: if user.auto_sign_time and user.auto_sign_time.astimezone( pytz.timezone("Asia/Shanghai") ) - timedelta(seconds=2) >= datetime.now(pytz.timezone("Asia/Shanghai")): return user.auto_sign_time.astimezone(pytz.timezone("Asia/Shanghai")) hours = int(str(datetime.now()).split()[1].split(":")[0]) minutes = int(str(datetime.now()).split()[1].split(":")[1]) date = ( datetime.now() + timedelta(days=1) - timedelta(hours=hours) - timedelta(minutes=minutes - 1) ) random_hours = random.randint(0, 22) random_minutes = random.randint(1, 59) date += timedelta(hours=random_hours) + timedelta(minutes=random_minutes) user.auto_sign_time = date await user.save(update_fields=["auto_sign_time"]) return date return None async def random_cookie(cls, uid: int) -> Optional[str]: """ 说明: 随机获取查询角色信息cookie 参数: :param uid: 原神uid """ # 查找用户今日是否已经查找过,防止重复 user = await cls.get_or_none(today_query_uid__contains=str(uid)) if user: return user.cookie for user in await cls.filter(cookie__not="").annotate(rand=Random()).all(): if not user.today_query_uid or len(user.today_query_uid[:-1].split()) < 30: user.today_query_uid = user.today_query_uid + f"{uid} " await user.save(update_fields=["today_query_uid"]) return user.cookie return None async def _run_script(cls): return [ "ALTER TABLE genshin ADD auto_sign_time timestamp with time zone;", "ALTER TABLE genshin ADD resin_remind boolean DEFAULT False;", "ALTER TABLE genshin ADD resin_recovery_time timestamp with time zone;", "ALTER TABLE genshin ADD login_ticket VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin ADD stuid VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin ADD stoken VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE genshin ALTER COLUMN user_id TYPE character varying(255);", ] The provided code snippet includes necessary dependencies for implementing the `_` function. Write a Python function `async def _()` to solve the following problem: 启动时分配定时任务 Here is the function: async def _(): """ 启动时分配定时任务 """ g_list = await Genshin.filter(auto_sign=True).all() for u in g_list: if u.auto_sign_time: if date := await Genshin.random_sign_time(u.uid): scheduler.add_job( _sign, "date", run_date=date.replace(microsecond=0), id=f"genshin_auto_sign_{u.uid}_{u.user_id}_0", args=[u.user_id, u.uid, 0], ) logger.info( f"genshin_sign add_job:USER:{u.user_id} UID:{u.uid} " f"{date} 原神自动签到" )
启动时分配定时任务
188,275
from typing import Dict, List, Optional, Tuple, Union from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import Config from services.log import logger from utils.http_utils import AsyncHttpx from .._models import Genshin from .._utils import element_mastery, get_ds from .draw_image import get_genshin_image, init_image async def get_image( user_id: int, uid: str, server_id: str, mys_id: Optional[str] = None, nickname: Optional[str] = None, ) -> Optional[Union[MessageSegment, str]]: """ 生成图片 :param user_id:用户qq :param uid: 用户uid :param server_id: 服务器 :param mys_id: 米游社id :param nickname: QQ昵称 :return: """ data, code = await get_info(uid, server_id) if code != 200: return data if data: char_data_list, role_data, world_data_dict, home_data_list = parsed_data(data) mys_data = await get_mys_data(uid, mys_id) if mys_data: nickname = None if char_data_list: char_detailed_data = await get_character( uid, [x["id"] for x in char_data_list], server_id ) _x = {} if char_detailed_data: for char in char_detailed_data["avatars"]: _x[char["name"]] = { "weapon": char["weapon"]["name"], "weapon_image": char["weapon"]["icon"], "level": char["weapon"]["level"], "affix_level": char["weapon"]["affix_level"], } await init_image(world_data_dict, char_data_list, _x, home_data_list) return await get_genshin_image( user_id, uid, char_data_list, role_data, world_data_dict, home_data_list, _x, mys_data, nickname, ) return "未找到用户数据..." async def query_role_data( user_id: int, uid: int, mys_id: Optional[str] = None, nickname: Optional[str] = None ) -> Optional[Union[MessageSegment, str]]: uid = str(uid) if uid[0] == "1" or uid[0] == "2": server_id = "cn_gf01" elif uid[0] == "5": server_id = "cn_qd01" else: return None return await get_image(user_id, uid, server_id, mys_id, nickname)
null
188,276
import asyncio from asyncio.exceptions import TimeoutError from io import BytesIO from typing import Optional, Tuple, Union import nonebot from nonebot import Driver from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import Config 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 from utils.utils import get_user_avatar from .._models import Genshin from .._utils import get_ds async def parse_data_and_draw( user_id: int, uid: str, server_id: str, uname: str ) -> Union[str, MessageSegment]: data, code = await get_memo(uid, server_id) if code != 200: return data user_avatar = BytesIO(await get_user_avatar(user_id)) for x in data["expeditions"]: file_name = x["avatar_side_icon"].split("_")[-1] role_avatar = memo_path / "role_avatar" / file_name if not role_avatar.exists(): await AsyncHttpx.download_file(x["avatar_side_icon"], role_avatar) return await asyncio.get_event_loop().run_in_executor( None, _parse_data_and_draw, data, user_avatar, uid, uname ) async def get_user_memo( user_id: int, uid: int, uname: str ) -> Optional[Union[str, MessageSegment]]: uid = str(uid) if uid[0] in ["1", "2"]: server_id = "cn_gf01" elif uid[0] == "5": server_id = "cn_qd01" else: return None return await parse_data_and_draw(user_id, uid, server_id, uname)
null
188,277
import uuid import time import random import string import hashlib from .setting import * md5(text: str) -> str: md5 = hashlib.md5() md5.update(text.encode()) return md5.hexdigest( i = str(timestamp()) r = random_text(6) c = md5("salt=" + n + "&t=" + i + "&r=" + r) return f"{i},{r},{c} i = str(timestamp()) r = str(random.randint(100001, 200000)) c = md5("salt=" + n + "&t=" + i + "&r=" + r + add) return f"{i},{r},{c} mihoyobbs_Salt_web = "9nQiU3AV0rJSIBWgdynfoGMGKaklfbM7 'Accept': 'application/json, text/plain, */*', 'DS': "", 'Origin': 'https://webstatic.mihoyo.com', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) ' 'x-rpc-client_type': 'Referer': '', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.8', 'X-Requested-With': 'com.mihoyo.hyperion', "Cookie": "", 'x-rpc-device_id': "" } = "https://bbs-api.mihoyo.com "https://api-takumi.mihoyo.com" 291431091" 202207181446311" 202202251749321" def get_ds(web: bool) -> str: if web: n = mihoyobbs_Salt_web else: n = mihoyobbs_Salt i = str(timestamp()) r = random_text(6) c = md5("salt=" + n + "&t=" + i + "&r=" + r) return f"{i},{r},{c}"
null
188,278
import uuid import time import random import string import hashlib from .setting import * md5(text: str) -> str: md5 = hashlib.md5() md5.update(text.encode()) return md5.hexdigest( i = str(timestamp()) r = random_text(6) c = md5("salt=" + n + "&t=" + i + "&r=" + r) return f"{i},{r},{c} i = str(timestamp()) r = str(random.randint(100001, 200000)) add = f'&b={b}&q={q}' c = md5("salt=" + n + "&t=" + i + "&r=" + r + add) return f"{i},{r},{c} mihoyobbs_Salt2 = "t0qEgfub6cvueAPgR5m9aQWWVciEer7v" 'Accept': 'application/json, text/plain, */*', 'DS': "", 'Origin': 'https://webstatic.mihoyo.com', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) ' 'x-rpc-client_type': 'Referer': '', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.8', 'X-Requested-With': 'com.mihoyo.hyperion', "Cookie": "", 'x-rpc-device_id': "" } = "https://bbs-api.mihoyo.com "https://api-takumi.mihoyo.com" 291431091" 202207181446311" 202202251749321" def get_ds2(q: str, b: str) -> str: n = mihoyobbs_Salt2 i = str(timestamp()) r = str(random.randint(100001, 200000)) add = f'&b={b}&q={q}' c = md5("salt=" + n + "&t=" + i + "&r=" + r + add) return f"{i},{r},{c}"
null
188,279
import uuid import time import random import string import hashlib from .setting import * 'Accept': 'application/json, text/plain, */*', 'DS': "", 'Origin': 'https://webstatic.mihoyo.com', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) ' 'x-rpc-client_type': 'Referer': '', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.8', 'X-Requested-With': 'com.mihoyo.hyperion', "Cookie": "", 'x-rpc-device_id': "" } = "https://bbs-api.mihoyo.com "https://api-takumi.mihoyo.com" 291431091" 202207181446311" 202202251749321" def get_device_id(cookie) -> str: return str(uuid.uuid3(uuid.NAMESPACE_URL, cookie))
null
188,280
import uuid import time import random import string import hashlib from .setting import * temp_cnt = raw_data["cnt"] return f"{temp_name}x{temp_cnt} 'Accept': 'application/json, text/plain, */*', 'DS': "", 'Origin': 'https://webstatic.mihoyo.com', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) ' 'x-rpc-client_type': 'Referer': '', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.8', 'X-Requested-With': 'com.mihoyo.hyperion', "Cookie": "", 'x-rpc-device_id': "" } = "https://bbs-api.mihoyo.com "https://api-takumi.mihoyo.com" 291431091" 202207181446311" 202202251749321" def get_item(raw_data: dict) -> str: temp_name = raw_data["name"] temp_cnt = raw_data["cnt"] return f"{temp_name}x{temp_cnt}"
null
188,281
import uuid import time import random import string import hashlib from .setting import * next_day_time = now_time - now_time % 86400 + time.timezone + 86400 return next_day_time 'Accept': 'application/json, text/plain, */*', 'DS': "", 'Origin': 'https://webstatic.mihoyo.com', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) ' 'x-rpc-client_type': 'Referer': '', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.8', 'X-Requested-With': 'com.mihoyo.hyperion', "Cookie": "", 'x-rpc-device_id': "" } = "https://bbs-api.mihoyo.com "https://api-takumi.mihoyo.com" 291431091" 202207181446311" 202202251749321" def next_day() -> int: now_time = int(time.time()) next_day_time = now_time - now_time % 86400 + time.timezone + 86400 return next_day_time
null
188,282
import random from datetime import datetime, timedelta import nonebot import pytz from apscheduler.jobstores.base import ConflictingIdError, JobLookupError from nonebot import Driver from nonebot.adapters.onebot.v11 import ActionFailed from nonebot.plugin import require from configs.config import Config from models.group_member_info import GroupInfoUser from services.log import logger from utils.message_builder import at from utils.utils import get_bot, scheduler from .._models import Genshin from ..query_memo import get_memo def add_job(user_id: str, uid: int): # 移除 try: scheduler.remove_job(f"genshin_resin_remind_{uid}_{user_id}") except JobLookupError: pass date = datetime.now(pytz.timezone("Asia/Shanghai")) + timedelta(seconds=30) try: scheduler.add_job( _remind, "date", run_date=date.replace(microsecond=0), id=f"genshin_resin_remind_{uid}_{user_id}", args=[user_id, uid], ) except ConflictingIdError: pass class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class Genshin(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" uid = fields.BigIntField() """uid""" mys_id: int = fields.BigIntField(null=True) """米游社id""" cookie: str = fields.TextField(default="") """米游社cookie""" auto_sign = fields.BooleanField(default=False) """是否自动签到""" today_query_uid = fields.TextField(default="") """cookie今日查询uid""" auto_sign_time = fields.DatetimeField(null=True) """签到日期时间""" resin_remind = fields.BooleanField(default=False) """树脂提醒""" resin_recovery_time = fields.DatetimeField(null=True) """满树脂提醒日期""" bind_group: int = fields.BigIntField(null=True) """发送提示 绑定群聊""" login_ticket = fields.TextField(default="") """login_ticket""" stuid: str = fields.TextField(default="") """stuid""" stoken: str = fields.TextField(default="") """stoken""" class Meta: table = "genshin" table_description = "原神数据表" unique_together = ("user_id", "uid") async def random_sign_time(cls, uid: int) -> Optional[datetime]: """ 说明: 随机签到时间 说明: :param uid: uid """ user = await cls.get_or_none(uid=uid) if user and user.cookie: if user.auto_sign_time and user.auto_sign_time.astimezone( pytz.timezone("Asia/Shanghai") ) - timedelta(seconds=2) >= datetime.now(pytz.timezone("Asia/Shanghai")): return user.auto_sign_time.astimezone(pytz.timezone("Asia/Shanghai")) hours = int(str(datetime.now()).split()[1].split(":")[0]) minutes = int(str(datetime.now()).split()[1].split(":")[1]) date = ( datetime.now() + timedelta(days=1) - timedelta(hours=hours) - timedelta(minutes=minutes - 1) ) random_hours = random.randint(0, 22) random_minutes = random.randint(1, 59) date += timedelta(hours=random_hours) + timedelta(minutes=random_minutes) user.auto_sign_time = date await user.save(update_fields=["auto_sign_time"]) return date return None async def random_cookie(cls, uid: int) -> Optional[str]: """ 说明: 随机获取查询角色信息cookie 参数: :param uid: 原神uid """ # 查找用户今日是否已经查找过,防止重复 user = await cls.get_or_none(today_query_uid__contains=str(uid)) if user: return user.cookie for user in await cls.filter(cookie__not="").annotate(rand=Random()).all(): if not user.today_query_uid or len(user.today_query_uid[:-1].split()) < 30: user.today_query_uid = user.today_query_uid + f"{uid} " await user.save(update_fields=["today_query_uid"]) return user.cookie return None async def _run_script(cls): return [ "ALTER TABLE genshin ADD auto_sign_time timestamp with time zone;", "ALTER TABLE genshin ADD resin_remind boolean DEFAULT False;", "ALTER TABLE genshin ADD resin_recovery_time timestamp with time zone;", "ALTER TABLE genshin ADD login_ticket VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin ADD stuid VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin ADD stoken VARCHAR(255) DEFAULT '';", "ALTER TABLE genshin RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE genshin ALTER COLUMN user_id TYPE character varying(255);", ] The provided code snippet includes necessary dependencies for implementing the `_` function. Write a Python function `async def _()` to solve the following problem: 启动时分配定时任务 Here is the function: async def _(): """ 启动时分配定时任务 """ g_list = await Genshin.filter(resin_remind=True).all() update_list = [] date = datetime.now(pytz.timezone("Asia/Shanghai")) + timedelta(seconds=30) for u in g_list: if u.resin_remind: if u.resin_recovery_time: if u.resin_recovery_time and u.resin_recovery_time > datetime.now( pytz.timezone("Asia/Shanghai") ): add_job(u.user_id, u.uid) logger.info( f"genshin_resin_remind add_job:USER:{u.user_id} UID:{u.uid}启动原神树脂提醒 " ) else: u.resin_recovery_time = None # type: ignore update_list.append(u) add_job(u.user_id, u.uid) logger.info( f"genshin_resin_remind add_job CHECK:USER:{u.user_id} UID:{u.uid}启动原神树脂提醒 " ) else: add_job(u.user_id, u.uid) logger.info( f"genshin_resin_remind add_job CHECK:USER:{u.user_id} UID:{u.uid}启动原神树脂提醒 " ) if update_list: await Genshin.bulk_update(update_list, ["resin_recovery_time"])
启动时分配定时任务
188,283
import os import random from dataclasses import dataclass from datetime import datetime from typing import List, Tuple, Union import ujson as json from configs.path_config import DATA_PATH, IMAGE_PATH from utils.image_utils import BuildImage ALC_PATH = IMAGE_PATH / "genshin" / "alc" ALC_PATH.mkdir(exist_ok=True, parents=True) BACKGROUND_PATH = ALC_PATH / "back.png" def random_fortune() -> Tuple[List[Fortune], List[Fortune]]: """ 说明: 随机运势 """ data = json.load(CONFIG_PATH.open("r", encoding="utf8")) fortune_data = {} good_fortune = [] bad_fortune = [] while len(fortune_data) < 6: r = random.choice(list(data.keys())) if r not in fortune_data: fortune_data[r] = data[r] for i, k in enumerate(fortune_data): if i < 3: good_fortune.append( Fortune(title=k, desc=random.choice(fortune_data[k]["buff"])) ) else: bad_fortune.append( Fortune(title=k, desc=random.choice(fortune_data[k]["debuff"])) ) return good_fortune, bad_fortune def int2cn(v: Union[str, int]): """ 说明: 数字转中文 参数: :param v: str """ return "".join([chinese[x] for x in str(v)]) class BuildImage: """ 快捷生成图片与操作图片的工具类 """ def __init__( self, w: int, h: int, paste_image_width: int = 0, paste_image_height: int = 0, paste_space: int = 0, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None, image_mode: ModeType = "RGBA", font_size: int = 10, background: Union[Optional[str], BytesIO, Path] = None, font: str = "yz.ttf", ratio: float = 1, is_alpha: bool = False, plain_text: Optional[str] = None, font_color: Optional[Union[str, Tuple[int, int, int]]] = None, **kwargs, ): """ 参数: :param w: 自定义图片的宽度,w=0时为图片原本宽度 :param h: 自定义图片的高度,h=0时为图片原本高度 :param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行 :param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行 :param paste_space: 自动贴图间隔 :param color: 生成图片的颜色 :param image_mode: 图片的类型 :param font_size: 文字大小 :param background: 打开图片的路径 :param font: 字体,默认在 resource/ttf/ 路径下 :param ratio: 倍率压缩 :param is_alpha: 是否背景透明 :param plain_text: 纯文字文本 """ self.w = int(w) self.h = int(h) self.paste_image_width = int(paste_image_width) self.paste_image_height = int(paste_image_height) self.paste_space = int(paste_space) self._current_w = 0 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) self.background = background if not background: if plain_text: if not color: color = (255, 255, 255, 0) ttf_w, ttf_h = self.getsize(str(plain_text)) self.w = self.w if self.w > ttf_w else ttf_w self.h = self.h if self.h > ttf_h else ttf_h self.markImg = Image.new(image_mode, (self.w, self.h), color) self.markImg.convert(image_mode) else: if not w and not h: self.markImg = Image.open(background) w, h = self.markImg.size if ratio and ratio > 0 and ratio != 1: self.w = int(ratio * w) self.h = int(ratio * h) self.markImg = self.markImg.resize( (self.w, self.h), Image.ANTIALIAS ) else: self.w = w self.h = h else: self.markImg = Image.open(background).resize( (self.w, self.h), Image.ANTIALIAS ) if is_alpha: try: 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) self.size = self.w, self.h if plain_text: fill = font_color if font_color else (0, 0, 0) self.text((0, 0), str(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() def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 参数: :param font: 字体名称 :param font_size: 字体大小 """ return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 异步 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ await self.loop.run_in_executor( None, self.paste, img, pos, alpha, center_type, allow_negative ) def paste( self, img: "BuildImage", pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) width, height = 0, 0 if not pos: pos = (0, 0) if center_type == "center": width = int((self.w - img.w) / 2) height = int((self.h - img.h) / 2) elif center_type == "by_width": width = int((self.w - img.w) / 2) height = pos[1] elif center_type == "by_height": width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) if pos and allow_negative: 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: self._current_w = 0 self._current_h += self.paste_image_height + self.paste_space if not pos: pos = (self._current_w, self._current_h) if alpha: try: self.markImg.paste(img, pos, img) except ValueError: img = img.convert("RGBA") self.markImg.paste(img, pos, img) else: self.markImg.paste(img, pos) self._current_w += self.paste_image_width + self.paste_space def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 :param font: 字体 :param font_size: 字体大小 """ font_ = cls.load_font(font, font_size) return font_.getsize(msg) # type: ignore def getsize(self, msg: Any) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 """ return self.font.getsize(str(msg)) # type: ignore 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): """ 说明: 绘制多个或单独的像素 参数: :param pos: 坐标 :param fill: 填错颜色 """ 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], 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: 描线宽度 """ self.draw.ellipse(pos, fill, outline, width) async def atext( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 异步 在图片上添加文字 参数: :param pos: 文字位置 :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ await self.loop.run_in_executor( None, self.text, pos, text, fill, center_type, font, font_size, **kwargs ) def text( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 在图片上添加文字 参数: :param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效) :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) w, h = self.w, self.h longgest_text = "" sentence = text.split("\n") for x in sentence: longgest_text = x if len(x) > len(longgest_text) else longgest_text ttf_w, ttf_h = self.getsize(longgest_text) ttf_h = ttf_h * len(sentence) if center_type == "center": w = int((w - ttf_w) / 2) h = int((h - ttf_h) / 2) elif center_type == "by_width": w = int((w - ttf_w) / 2) h = pos[1] elif center_type == "by_height": h = int((h - ttf_h) / 2) w = pos[0] pos = (w, h) if font: if isinstance(font, str): font = self.load_font(font, font_size) elif font_size: font = self.load_font(self.font_name, font_size) self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs) async def asave(self, path: Optional[Union[str, Path]] = None): """ 说明: 异步 保存图片 参数: :param path: 图片路径 """ await self.loop.run_in_executor(None, self.save, path) def save(self, path: Optional[Union[str, Path]] = None): """ 说明: 保存图片 参数: :param path: 图片路径 """ self.markImg.save(path or self.background) # type: ignore def show(self): """ 说明: 显示图片 """ self.markImg.show() 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): """ 说明: 压缩图片 参数: :param ratio: 压缩倍率 :param w: 压缩图片宽度至 w :param h: 压缩图片高度至 h """ if not w and not h and not ratio: raise Exception("缺少参数...") if not w and not h and ratio: w = int(self.w * ratio) h = int(self.h * ratio) self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS) self.w, self.h = self.markImg.size 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]): """ 说明: 裁剪图片 参数: :param box: 左上角坐标,右下角坐标 (left, upper, right, lower) """ self.markImg = self.markImg.crop(box) self.w, self.h = self.markImg.size self.size = self.w, self.h self.draw = ImageDraw.Draw(self.markImg) def check_font_size(self, word: str) -> bool: """ 说明: 检查文本所需宽度是否大于图片宽度 参数: :param word: 文本内容 """ 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): """ 说明: 图片透明化 参数: :param alpha_ratio: 透明化程度 :param n: 透明化大小内边距 """ self.markImg = self.markImg.convert("RGBA") x, y = self.markImg.size for i in range(n, x - n): for k in range(n, y - n): color = self.markImg.getpixel((i, k)) color = color[:-1] + (int(100 * alpha_ratio),) self.markImg.putpixel((i, k), color) self.draw = ImageDraw.Draw(self.markImg) def pic2bs4(self) -> str: """ 说明: BuildImage 转 base64 """ buf = BytesIO() self.markImg.save(buf, format="PNG") base64_str = base64.b64encode(buf.getvalue()).decode() return "base64://" + base64_str def convert(self, type_: ModeType): """ 说明: 修改图片类型 参数: :param type_: 类型 """ self.markImg = self.markImg.convert(type_) async def arectangle( self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[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], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[str] = None, width: int = 1, ): """ 说明: 画框 参数: :param xy: 坐标 :param fill: 填充颜色 :param outline: 轮廓颜色 :param width: 线宽 """ 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[Union[str, 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], fill: Optional[Union[Tuple[int, int, int], str]] = None, width: int = 1, ): """ 说明: 画线 参数: :param xy: 坐标 :param fill: 填充 :param width: 线宽 """ self.draw.line(xy, fill, width) async def acircle(self): """ 说明: 异步 将 BuildImage 图片变为圆形 """ await self.loop.run_in_executor(None, self.circle) def circle(self): """ 说明: 使图像变圆 """ self.markImg.convert("RGBA") size = self.markImg.size r2 = min(size[0], size[1]) if size[0] != size[1]: self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS) width = 1 antialias = 4 ellipse_box = [0, 0, r2 - 2, r2 - 2] mask = Image.new( size=[int(dim * antialias) for dim in self.markImg.size], mode="L", color="black", ) draw = ImageDraw.Draw(mask) for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"): left, top = [(value + offset) * antialias for value in ellipse_box[:2]] right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]] draw.ellipse([left, top, right, bottom], fill=fill) mask = mask.resize(self.markImg.size, Image.LANCZOS) try: self.markImg.putalpha(mask) except ValueError: pass async def acircle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 异步 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ await self.loop.run_in_executor(None, self.circle_corner, radii, point_list) def circle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ # 画圆(用于分离4个角) img = self.markImg.convert("RGBA") alpha = img.split()[-1] circle = Image.new("L", (radii * 2, radii * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形 w, h = img.size if "lt" in point_list: alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0)) if "rt" in point_list: alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0)) if "lb" in point_list: alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii)) if "rb" in point_list: alpha.paste( circle.crop((radii, radii, radii * 2, radii * 2)), (w - radii, h - radii), ) img.putalpha(alpha) self.markImg = img self.draw = ImageDraw.Draw(self.markImg) 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): """ 说明: 旋转图片 参数: :param angle: 角度 :param expand: 放大图片适应角度 """ self.markImg = self.markImg.rotate(angle, expand=expand) async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 异步 旋转图片(包括边框) 参数: :param angle: 角度 """ await self.loop.run_in_executor(None, self.transpose, angle) def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 旋转图片(包括边框) 参数: :param angle: 角度 """ self.markImg.transpose(angle) async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ await self.loop.run_in_executor(None, self.filter, filter_, aud) def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ _x = None if filter_ == "GaussianBlur": # 高斯模糊 _x = ImageFilter.GaussianBlur elif filter_ == "EDGE_ENHANCE": # 锐化效果 _x = ImageFilter.EDGE_ENHANCE elif filter_ == "BLUR": # 模糊效果 _x = ImageFilter.BLUR elif filter_ == "CONTOUR": # 铅笔滤镜 _x = ImageFilter.CONTOUR elif filter_ == "FIND_EDGES": # 边缘检测 _x = ImageFilter.FIND_EDGES if _x: if aud: self.markImg = self.markImg.filter(_x(aud)) else: self.markImg = self.markImg.filter(_x) self.draw = ImageDraw.Draw(self.markImg) async def areplace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 异步 颜色替换 参数: :param src_color: 目标颜色,或者使用列表,设置阈值 :param replace_color: 替换颜色 """ self.loop.run_in_executor( None, self.replace_color_tran, src_color, replace_color ) def replace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 颜色替换 参数: :param src_color: 目标颜色,或者使用元祖,设置阈值 :param replace_color: 替换颜色 """ if isinstance(src_color, tuple): start_ = src_color[0] end_ = src_color[1] else: start_ = src_color end_ = None for i in range(self.w): for j in range(self.h): r, g, b = self.markImg.getpixel((i, j)) if not end_: if r == start_[0] and g == start_[1] and b == start_[2]: self.markImg.putpixel((i, j), replace_color) else: if ( start_[0] <= r <= end_[0] and start_[1] <= g <= end_[1] and start_[2] <= b <= end_[2] ): self.markImg.putpixel((i, j), replace_color) # def getchannel(self, type_): self.markImg = self.markImg.getchannel(type_) The provided code snippet includes necessary dependencies for implementing the `build_alc_image` function. Write a Python function `async def build_alc_image() -> str` to solve the following problem: 说明: 构造今日运势图片 Here is the function: async def build_alc_image() -> str: """ 说明: 构造今日运势图片 """ for file in os.listdir(ALC_PATH): if file not in ["back.png", f"{datetime.now().date()}.png"]: (ALC_PATH / file).unlink() path = ALC_PATH / f"{datetime.now().date()}.png" if path.exists(): return BuildImage(0, 0, background=path).pic2bs4() good_fortune, bad_fortune = random_fortune() background = BuildImage( 0, 0, background=BACKGROUND_PATH, font="HYWenHei-85W.ttf", font_size=30 ) now = datetime.now() await background.atext((78, 145), str(now.year), fill="#8d7650ff") month = str(now.month) month_w = 358 if now.month < 10: month_w = 373 elif now.month != 10: month = "0" + month[-1] await background.atext((month_w, 145), f"{int2cn(month)}月", fill="#8d7650ff") day = str(now.day) if now.day > 10 and day[-1] != "0": day = day[0] + "0" + day[-1] day_str = f"{int2cn(day)}日" day_w = 193 if (n := len(day_str)) == 3: day_w = 207 elif n == 2: day_w = 228 await background.atext( (day_w, 145), f"{int2cn(day)}日", fill="#f7f8f2ff", font_size=35 ) fortune_h = 230 for fortune in good_fortune: await background.atext( (150, fortune_h), fortune.title, fill="#756141ff", font_size=25 ) await background.atext( (150, fortune_h + 28), fortune.desc, fill="#b5b3acff", font_size=19 ) fortune_h += 55 fortune_h += 4 for fortune in bad_fortune: await background.atext( (150, fortune_h), fortune.title, fill="#756141ff", font_size=25 ) await background.atext( (150, fortune_h + 28), fortune.desc, fill="#b5b3acff", font_size=19 ) fortune_h += 55 await background.asave(path) return background.pic2bs4()
说明: 构造今日运势图片
188,284
from pathlib import Path from typing import Tuple, Optional, List from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH from utils.message_builder import image from services.log import logger from utils.image_utils import BuildImage from asyncio.exceptions import TimeoutError from asyncio import Semaphore from utils.image_utils import is_valid from utils.http_utils import AsyncHttpx from httpx import ConnectTimeout from .map import Map import asyncio import nonebot import os resource_name_list: List[str] = [] MAP_RATIO = 0.5 global CENTER_POINT planning_route: bool = False map_ = Map( resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO ) count = map_.get_resource_count() rand = await asyncio.get_event_loop().run_in_executor( None, map_.generate_resource_icon_in_map ) return ( f"{image(TEMP_PATH / f'genshin_map_{rand}.png')}" f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki" global CENTER_POINT, MAP_RATIO def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") class Map: """ 原神资源生成类 """ def __init__( self, resource_name: str, center_point: Tuple[int, int], deviation: Tuple[int, int] = (25, 51), padding: int = 100, planning_route: bool = False, ratio: float = 1, ): """ 参数: :param resource_name: 资源名称 :param center_point: 中心点 :param deviation: 坐标误差 :param padding: 截图外边距 :param planning_route: 是否规划最佳线路 :param ratio: 压缩比率 """ self.map = BuildImage(0, 0, background=map_path) self.resource_name = resource_name self.center_x = center_point[0] self.center_y = center_point[1] self.deviation = deviation self.padding = int(padding * ratio) self.planning_route = planning_route self.ratio = ratio self.deviation = ( int(self.deviation[0] * ratio), int(self.deviation[1] * ratio), ) data = json.load(open(resource_label_file, "r", encoding="utf8")) # 资源 id self.resource_id = [ data[x]["id"] for x in data if x != "CENTER_POINT" and data[x]["name"] == resource_name ][0] # 传送锚点 id self.teleport_anchor_id = [ data[x]["id"] for x in data if x != "CENTER_POINT" and data[x]["name"] == "传送锚点" ][0] # 神像 id self.teleport_god_id = [ data[x]["id"] for x in data if x != "CENTER_POINT" and data[x]["name"] == "七天神像" ][0] # 资源坐标 data = json.load(open(resource_point_file, "r", encoding="utf8")) self.resource_point = [ Resources( int((self.center_x + data[x]["x_pos"]) * ratio), int((self.center_y + data[x]["y_pos"]) * ratio), ) for x in data if x != "CENTER_POINT" and data[x]["label_id"] == self.resource_id ] # 传送锚点坐标 self.teleport_anchor_point = [ Resources( int((self.center_x + data[x]["x_pos"]) * ratio), int((self.center_y + data[x]["y_pos"]) * ratio), ) for x in data if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_anchor_id ] # 神像坐标 self.teleport_god_point = [ Resources( int((self.center_x + data[x]["x_pos"]) * ratio), int((self.center_y + data[x]["y_pos"]) * ratio), ) for x in data if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_god_id ] # 将地图上生成资源图标 def generate_resource_icon_in_map(self) -> int: x_list = [x.x for x in self.resource_point] y_list = [x.y for x in self.resource_point] min_width = min(x_list) - self.padding max_width = max(x_list) + self.padding min_height = min(y_list) - self.padding max_height = max(y_list) + self.padding self._generate_transfer_icon((min_width, min_height, max_width, max_height)) for res in self.resource_point: icon = self._get_icon_image(self.resource_id) self.map.paste( icon, (res.x - self.deviation[0], res.y - self.deviation[1]), True ) if self.planning_route: self._generate_best_route() self.map.crop((min_width, min_height, max_width, max_height)) rand = random.randint(1, 10000) self.map.save(f"{TEMP_PATH}/genshin_map_{rand}.png") return rand # 资源数量 def get_resource_count(self) -> int: return len(self.resource_point) # 生成传送锚点和神像 def _generate_transfer_icon(self, box: Tuple[int, int, int, int]): min_width, min_height, max_width, max_height = box for resources in [self.teleport_anchor_point, self.teleport_god_point]: id_ = ( self.teleport_anchor_id if resources == self.teleport_anchor_point else self.teleport_god_id ) for res in resources: if min_width < res.x < max_width and min_height < res.y < max_height: icon = self._get_icon_image(id_) self.map.paste( icon, (res.x - self.deviation[0], res.y - self.deviation[1]), True, ) # 生成最优路线(说是最优其实就是直线最短) def _generate_best_route(self): line_points = [] teleport_list = self.teleport_anchor_point + self.teleport_god_point for teleport in teleport_list: current_res, res_min_distance = teleport.get_resource_distance(self.resource_point) current_teleport, teleport_min_distance = current_res.get_resource_distance(teleport_list) if current_teleport == teleport: self.map.line( (current_teleport.x, current_teleport.y, current_res.x, current_res.y), (255, 0, 0), width=1 ) is_used_res_points = [] for res in self.resource_point: if res in is_used_res_points: continue current_teleport, teleport_min_distance = res.get_resource_distance(teleport_list) current_res, res_min_distance = res.get_resource_distance(self.resource_point) if teleport_min_distance < res_min_distance: self.map.line( (current_teleport.x, current_teleport.y, res.x, res.y), (255, 0, 0), width=1 ) else: is_used_res_points.append(current_res) self.map.line( (current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1 ) res_cp = self.resource_point[:] res_cp.remove(current_res) # for _ in res_cp: current_teleport_, teleport_min_distance = res.get_resource_distance(teleport_list) current_res, res_min_distance = res.get_resource_distance(res_cp) if teleport_min_distance < res_min_distance: self.map.line( (current_teleport.x, current_teleport.y, res.x, res.y), (255, 0, 0), width=1 ) else: self.map.line( (current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1 ) is_used_res_points.append(current_res) is_used_res_points.append(res) # resources_route = [] # # 先连上最近的资源路径 # for res in self.resource_point: # # 拿到最近的资源 # current_res, _ = res.get_resource_distance( # self.resource_point # + self.teleport_anchor_point # + self.teleport_god_point # ) # self.map.line( # (current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1 # ) # resources_route.append((current_res, res)) # teleport_list = self.teleport_anchor_point + self.teleport_god_point # for res1, res2 in resources_route: # point_list = [x for x in resources_route if res1 in x or res2 in x] # if not list(set(point_list).intersection(set(teleport_list))): # if res1 not in teleport_list and res2 not in teleport_list: # # while True: # # tmp = [x for x in point_list] # # break # teleport1, distance1 = res1.get_resource_distance(teleport_list) # teleport2, distance2 = res2.get_resource_distance(teleport_list) # if distance1 > distance2: # self.map.line( # (teleport1.x, teleport1.y, res1.x, res1.y), # (255, 0, 0), # width=1, # ) # else: # self.map.line( # (teleport2.x, teleport2.y, res2.x, res2.y), # (255, 0, 0), # width=1, # ) # self.map.line(xy, (255, 0, 0), width=3) # 获取资源图标 def _get_icon_image(self, id_: int) -> "BuildImage": icon = icon_path / f"{id_}.png" if icon.exists(): return BuildImage( int(50 * self.ratio), int(50 * self.ratio), background=icon ) return BuildImage( int(50 * self.ratio), int(50 * self.ratio), background=f"{icon_path}/box.png", ) # def _get_shortest_path(self, res: 'Resources', res_2: 'Resources'): # 拿到资源在该列表中的最短路径 async def query_resource(resource_name: str) -> str: global CENTER_POINT planning_route: bool = False if resource_name and resource_name[-2:] in ["路径", "路线"]: resource_name = resource_name[:-2].strip() planning_route = True if not resource_name or resource_name not in resource_name_list: # return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.." return "" map_ = Map( resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO ) count = map_.get_resource_count() rand = await asyncio.get_event_loop().run_in_executor( None, map_.generate_resource_icon_in_map ) return ( f"{image(TEMP_PATH / f'genshin_map_{rand}.png')}" f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki" )
null
188,285
from pathlib import Path from typing import Tuple, Optional, List from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH from utils.message_builder import image from services.log import logger from utils.image_utils import BuildImage from asyncio.exceptions import TimeoutError from asyncio import Semaphore from utils.image_utils import is_valid from utils.http_utils import AsyncHttpx from httpx import ConnectTimeout from .map import Map import asyncio import nonebot import os resource_type_file = TEXT_PATH / "genshin" / "resource_type_file.json" temp = {} for id_ in data.keys(): temp[data[id_]["name"]] = [] for x in data[id_]["children"]: temp[data[id_]["name"]].append(x["name"]) mes = "当前资源列表如下:\n" for resource_type in temp.keys(): mes += f"{resource_type}:{','.join(temp[resource_type])}\n" return mes try: import ujson as json except ModuleNotFoundError: import json ) def get_resource_type_list(): with open(resource_type_file, "r", encoding="utf8") as f: data = json.load(f) temp = {} for id_ in data.keys(): temp[data[id_]["name"]] = [] for x in data[id_]["children"]: temp[data[id_]["name"]].append(x["name"]) mes = "当前资源列表如下:\n" for resource_type in temp.keys(): mes += f"{resource_type}:{','.join(temp[resource_type])}\n" return mes
null
188,286
from pathlib import Path from typing import Tuple, Optional, List from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH from utils.message_builder import image from services.log import logger from utils.image_utils import BuildImage from asyncio.exceptions import TimeoutError from asyncio import Semaphore from utils.image_utils import is_valid from utils.http_utils import AsyncHttpx from httpx import ConnectTimeout from .map import Map import asyncio import nonebot import os resource_name_list: List[str] = [] The provided code snippet includes necessary dependencies for implementing the `check_resource_exists` function. Write a Python function `def check_resource_exists(resource: str) -> bool` to solve the following problem: 检查资源是否存在 :param resource: 资源名称 Here is the function: def check_resource_exists(resource: str) -> bool: """ 检查资源是否存在 :param resource: 资源名称 """ resource = resource.replace("路径", "").replace("路线", "") return resource in resource_name_list
检查资源是否存在 :param resource: 资源名称
188,287
from pathlib import Path from typing import Tuple, Optional, List from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH from utils.message_builder import image from services.log import logger from utils.image_utils import BuildImage from asyncio.exceptions import TimeoutError from asyncio import Semaphore from utils.image_utils import is_valid from utils.http_utils import AsyncHttpx from httpx import ConnectTimeout from .map import Map import asyncio import nonebot import os resource_label_file = TEXT_PATH / "genshin" / "resource_label_file.json" resource_type_file = TEXT_PATH / "genshin" / "resource_type_file.json" resource_name_list: List[str] = [] global CENTER_POINT for id_ in data.keys(): temp[data[id_]["name"]] = [] for x in data[id_]["children"]: temp[data[id_]["name"]].append(x["name"]) resource_label_file.parent.mkdir(parents=True, exist_ok=True) global CENTER_POINT, MAP_RATIO class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: try: import ujson as json except ModuleNotFoundError: import json ) async def init(flag: bool = False): global CENTER_POINT, resource_name_list try: semaphore = asyncio.Semaphore(10) await download_map_init(semaphore, flag) await download_resource_data(semaphore) await download_resource_type() if not CENTER_POINT: if resource_label_file.exists(): CENTER_POINT = json.load( open(resource_label_file, "r", encoding="utf8") )["CENTER_POINT"] if resource_label_file.exists(): with open(resource_type_file, "r", encoding="utf8") as f: data = json.load(f) for id_ in data: for x in data[id_]["children"]: resource_name_list.append(x["name"]) except TimeoutError: logger.warning("原神资源查询信息初始化超时....")
null
188,288
from typing import List from nonebot.adapters.onebot.v11 import MessageEvent from ._config import SearchType class SearchType(Enum): """ 查询类型 """ DAY = "day_statistics" """天""" WEEK = "week_statistics" """周""" MONTH = "month_statistics" """月""" TOTAL = "total_statistics" """总数""" def parse_data(cmd: str, event: MessageEvent, superusers: List[str]): search_type = SearchType.TOTAL if cmd[:2] == "全局": if str(event.user_id) in superusers: if cmd[2] == '日': search_type = SearchType.DAY elif cmd[2] == '周': _type = SearchType.WEEK elif cmd[2] == '月': _type = SearchType.MONTH
null
188,289
import asyncio import os from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent from nonebot.params import CommandArg from configs.path_config import DATA_PATH, IMAGE_PATH from models.group_info import GroupInfo from utils.depends import OneCommand from utils.image_utils import BuildMat from utils.manager import plugins2settings_manager from utils.message_builder import image statistics = on_command( "功能调用统计", aliases={ "全局功能调用统计", "全局日功能调用统计", "全局周功能调用统计", "全局月功能调用统计", "日功能调用统计", "周功能调用统计", "月功能调用统计", "我的功能调用统计", "我的日功能调用统计", "我的周功能调用统计", "我的月功能调用统计", }, priority=5, block=True, ) statistics_group_file = DATA_PATH / "statistics" / "_prefix_count.json" statistics_user_file = DATA_PATH / "statistics" / "_prefix_user_count.json" async def generate_statistics_img( data: dict, arg: str, name: str, plugin: str, day_index: int ): try: plugin = plugins2settings_manager.get_plugin_data(plugin).cmd[0] except (KeyError, IndexError, AttributeError): pass bar_graph = None if arg == "day_statistics": bar_graph = await init_bar_graph(data, f"{name} 日功能调用统计") elif arg == "week_statistics": if plugin: current_week = day_index % 7 week_lst = [] if current_week == 0: week_lst = [1, 2, 3, 4, 5, 6, 7] else: for i in range(current_week + 1, 7): week_lst.append(str(i)) for i in range(current_week + 1): week_lst.append(str(i)) count = [] for i in range(7): if int(week_lst[i]) == 7: try: count.append(data[str(0)][plugin]) except KeyError: count.append(0) else: try: count.append(data[str(week_lst[i])][plugin]) except KeyError: count.append(0) week_lst = ["7" if i == "0" else i for i in week_lst] bar_graph = BuildMat( y=count, mat_type="line", title=f"{name} 周 {plugin} 功能调用统计【为7天统计】", x_index=week_lst, display_num=True, background=[ f"{IMAGE_PATH}/background/create_mat/{x}" for x in os.listdir(f"{IMAGE_PATH}/background/create_mat") ], bar_color=["*"], ) else: bar_graph = await init_bar_graph(update_data(data), f"{name} 周功能调用统计【为7天统计】") elif arg == "month_statistics": if plugin: day_index = day_index % 30 day_lst = [] for i in range(day_index + 1, 30): day_lst.append(i) for i in range(day_index + 1): day_lst.append(i) count = [data[str(day_lst[i])][plugin] for i in range(30)] day_lst = [str(x + 1) for x in day_lst] bar_graph = BuildMat( y=count, mat_type="line", title=f"{name} 月 {plugin} 功能调用统计【为30天统计】", x_index=day_lst, display_num=True, background=[ f"{IMAGE_PATH}/background/create_mat/{x}" for x in os.listdir(f"{IMAGE_PATH}/background/create_mat") ], bar_color=["*"], ) else: bar_graph = await init_bar_graph(update_data(data), f"{name} 月功能调用统计【为30天统计】") elif arg == "total_statistics": bar_graph = await init_bar_graph(data, f"{name} 功能调用统计") await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph) return bar_graph.pic2bs4() async def init_bar_graph(data: dict, title: str) -> BuildMat: return await asyncio.get_event_loop().run_in_executor(None, _init_bar_graph, data, title) class GroupInfo(Model): group_id = fields.CharField(255, pk=True) """群聊id""" group_name = fields.TextField(default="") """群聊名称""" max_member_count = fields.IntField(default=0) """最大人数""" member_count = fields.IntField(default=0) """当前人数""" group_flag: int = fields.IntField(default=0) """群认证标记""" class Meta: table = "group_info" table_description = "群聊信息表" def _run_script(cls): return ["ALTER TABLE group_info ADD group_flag Integer NOT NULL DEFAULT 0;", # group_info表添加一个group_flag "ALTER TABLE group_info ALTER COLUMN group_id TYPE character varying(255);" # 将group_id字段类型改为character varying(255) ] def OneCommand(): """ 获取单个命令Command """ async def dependency( cmd: Tuple[str, ...] = Command(), ): return cmd[0] if cmd else None return Depends(dependency) def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") try: import ujson as json except ModuleNotFoundError: import json async def _(bot: Bot, event: MessageEvent, cmd: str = OneCommand(), arg: Message = CommandArg()): msg = arg.extract_plain_text().strip() if cmd[0][:2] == "全局": if str(event.user_id) in bot.config.superusers: data: dict = json.load(open(statistics_group_file, "r", encoding="utf8")) if cmd[0][2] == '日': _type = 'day_statistics' elif cmd[0][2] == '周': _type = 'week_statistics' elif cmd[0][2] == '月': _type = 'month_statistics' else: _type = 'total_statistics' tmp_dict = {} data = data[_type] if _type in ["day_statistics", "total_statistics"]: for key in data['total']: tmp_dict[key] = data['total'][key] else: for group in data.keys(): if group != 'total': for day in data[group].keys(): for plugin_name in data[group][day].keys(): if data[group][day][plugin_name] is not None: if tmp_dict.get(plugin_name) is None: tmp_dict[plugin_name] = 1 else: tmp_dict[plugin_name] += data[group][day][plugin_name] bar_graph = await init_bar_graph(tmp_dict, cmd[0]) await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph) await statistics.finish(image(b64=bar_graph.pic2bs4())) return if cmd[0][:2] == "我的": _type = "user" key = str(event.user_id) cmd = list(cmd) cmd[0] = cmd[0][2:] if not statistics_user_file.exists(): await statistics.finish("统计文件不存在...", at_sender=True) else: if not isinstance(event, GroupMessageEvent): await statistics.finish("请在群内调用此功能...") _type = "group" key = str(event.group_id) if not statistics_group_file.exists(): await statistics.finish("统计文件不存在...", at_sender=True) plugin = "" if cmd[0][0] == "日": arg = "day_statistics" elif cmd[0][0] == "周": arg = "week_statistics" elif cmd[0][0] == "月": arg = "month_statistics" else: arg = "total_statistics" if msg: plugin = plugins2settings_manager.get_plugin_module(msg) if not plugin: if arg not in ["day_statistics", "total_statistics"]: await statistics.finish("未找到此功能的调用...", at_sender=True) if _type == "group": data: dict = json.load(open(statistics_group_file, "r", encoding="utf8")) if not data[arg].get(str(event.group_id)): await statistics.finish("该群统计数据不存在...", at_sender=True) else: data: dict = json.load(open(statistics_user_file, "r", encoding="utf8")) if not data[arg].get(str(event.user_id)): await statistics.finish("该用户统计数据不存在...", at_sender=True) day_index = data["day_index"] data = data[arg][key] if _type == "group": group = await GroupInfo.filter(group_id=str(event.group_id)).first() name = group if group else str(event.group_id) else: name = event.sender.card or event.sender.nickname img = await generate_statistics_img(data, arg, name, plugin, day_index) await statistics.send(image(b64=img))
null
188,290
from datetime import datetime from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent from nonebot.matcher import Matcher from nonebot.message import run_postprocessor from nonebot.typing import Optional, T_State from configs.path_config import DATA_PATH from models.statistics import Statistics from utils.manager import plugins2settings_manager from utils.utils import scheduler class Statistics(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" plugin_name = fields.CharField(255) """插件名称""" create_time = fields.DatetimeField(auto_now=True) """添加日期""" class Meta: table = "statistics" table_description = "用户权限数据库" async def _run_script(cls): return [ "ALTER TABLE statistics RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE statistics ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE statistics ALTER COLUMN group_id TYPE character varying(255);", ] async def _( matcher: Matcher, exception: Optional[Exception], bot: Bot, event: MessageEvent, state: T_State, ): # global _prefix_count_dict if ( matcher.type == "message" and matcher.priority not in [1, 999] and matcher.plugin_name not in ["update_info", "statistics_handle"] ): await Statistics.create( user_id=str(event.user_id), group_id=getattr(event, "group_id", None), plugin_name=matcher.plugin_name, create_time=datetime.now(), ) # module = matcher.plugin_name # day_index = _prefix_count_dict["day_index"] # try: # group_id = str(event.group_id) # except AttributeError: # group_id = "total" # user_id = str(event.user_id) # plugin_name = plugins2settings_manager.get_plugin_data(module) # if plugin_name and plugin_name.cmd: # plugin_name = plugin_name.cmd[0] # check_exists_key(group_id, user_id, plugin_name) # for data in [_prefix_count_dict, _prefix_user_count_dict]: # data["total_statistics"]["total"][plugin_name] += 1 # data["day_statistics"]["total"][plugin_name] += 1 # data["week_statistics"]["total"][plugin_name] += 1 # data["month_statistics"]["total"][plugin_name] += 1 # # print(_prefix_count_dict) # if group_id != "total": # for data in [_prefix_count_dict, _prefix_user_count_dict]: # if data == _prefix_count_dict: # key = group_id # else: # key = user_id # data["total_statistics"][key][plugin_name] += 1 # data["day_statistics"][key][plugin_name] += 1 # data["week_statistics"][key][str(day_index % 7)][plugin_name] += 1 # data["month_statistics"][key][str(day_index % 30)][plugin_name] += 1 # with open(statistics_group_file, "w", encoding="utf8") as f: # json.dump(_prefix_count_dict, f, indent=4, ensure_ascii=False) # with open(statistics_user_file, "w", encoding="utf8") as f: # json.dump(_prefix_user_count_dict, f, ensure_ascii=False, indent=4)
null
188,291
import os import shutil from datetime import datetime import nonebot import ujson as json from asyncpg.exceptions import UniqueViolationError from nonebot import Driver from PIL import UnidentifiedImageError from configs.config import Config from configs.path_config import IMAGE_PATH, TEMP_PATH, TEXT_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.utils import change_pixiv_image_links, get_bot from .._model import Setu path = TEXT_PATH setu_data_file = path / "setu_data.json" r18_data_file = path / "r18_setu_data.json" if setu_data_file.exists() or r18_data_file.exists(): index = 0 r18_index = 0 count = 0 fail_count = 0 for file in [setu_data_file, r18_data_file]: if file.exists(): data = json.load(open(file, "r", encoding="utf8")) for x in data: if file == setu_data_file: idx = index if "R-18" in data[x]["tags"]: data[x]["tags"].remove("R-18") else: idx = r18_index img_url = ( data[x]["img_url"].replace("i.pixiv.cat", "i.pximg.net") if "i.pixiv.cat" in data[x]["img_url"] else data[x]["img_url"] ) # idx = r18_index if 'R-18' in data[x]["tags"] else index try: if not await Setu.exists(pid=data[x]["pid"], url=img_url): await Setu.create( local_id=idx, title=data[x]["title"], author=data[x]["author"], pid=data[x]["pid"], img_hash=data[x]["img_hash"], img_url=img_url, is_r18="R-18" in data[x]["tags"], tags=",".join(data[x]["tags"]), ) count += 1 if "R-18" in data[x]["tags"]: r18_index += 1 else: index += 1 logger.info(f'添加旧色图数据成功 PID:{data[x]["pid"]} index:{idx}....') except UniqueViolationError: fail_count += 1 logger.info( f'添加旧色图数据失败,色图重复 PID:{data[x]["pid"]} index:{idx}....' ) file.unlink() setu_url_path = path / "setu_url.json" setu_r18_url_path = path / "setu_r18_url.json" if setu_url_path.exists(): setu_url_path.unlink() if setu_r18_url_path.exists(): setu_r18_url_path.unlink() logger.info(f"更新旧色图数据完成,成功更新数据:{count} 条,累计失败:{fail_count} 条") class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id async def update_old_setu_data(): path = TEXT_PATH setu_data_file = path / "setu_data.json" r18_data_file = path / "r18_setu_data.json" if setu_data_file.exists() or r18_data_file.exists(): index = 0 r18_index = 0 count = 0 fail_count = 0 for file in [setu_data_file, r18_data_file]: if file.exists(): data = json.load(open(file, "r", encoding="utf8")) for x in data: if file == setu_data_file: idx = index if "R-18" in data[x]["tags"]: data[x]["tags"].remove("R-18") else: idx = r18_index img_url = ( data[x]["img_url"].replace("i.pixiv.cat", "i.pximg.net") if "i.pixiv.cat" in data[x]["img_url"] else data[x]["img_url"] ) # idx = r18_index if 'R-18' in data[x]["tags"] else index try: if not await Setu.exists(pid=data[x]["pid"], url=img_url): await Setu.create( local_id=idx, title=data[x]["title"], author=data[x]["author"], pid=data[x]["pid"], img_hash=data[x]["img_hash"], img_url=img_url, is_r18="R-18" in data[x]["tags"], tags=",".join(data[x]["tags"]), ) count += 1 if "R-18" in data[x]["tags"]: r18_index += 1 else: index += 1 logger.info(f'添加旧色图数据成功 PID:{data[x]["pid"]} index:{idx}....') except UniqueViolationError: fail_count += 1 logger.info( f'添加旧色图数据失败,色图重复 PID:{data[x]["pid"]} index:{idx}....' ) file.unlink() setu_url_path = path / "setu_url.json" setu_r18_url_path = path / "setu_r18_url.json" if setu_url_path.exists(): setu_url_path.unlink() if setu_r18_url_path.exists(): setu_r18_url_path.unlink() logger.info(f"更新旧色图数据完成,成功更新数据:{count} 条,累计失败:{fail_count} 条")
null
188,292
import os import shutil from datetime import datetime import nonebot import ujson as json from asyncpg.exceptions import UniqueViolationError from nonebot import Driver from PIL import UnidentifiedImageError from configs.config import Config from configs.path_config import IMAGE_PATH, TEMP_PATH, TEXT_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.utils import change_pixiv_image_links, get_bot from .._model import Setu _path = IMAGE_PATH path = TEXT_PATH class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ def get_img_hash(image_file: Union[str, Path]) -> ImageHash: """ 说明: 获取图片的hash值 参数: :param image_file: 图片文件路径 """ with open(image_file, "rb") as fp: hash_value = imagehash.average_hash(Image.open(fp)) return hash_value def compressed_image( in_file: Union[str, Path], out_file: Optional[Union[str, Path]] = None, ratio: float = 0.9, ): """ 说明: 压缩图片 参数: :param in_file: 被压缩的文件路径 :param out_file: 压缩后输出的文件路径 :param ratio: 压缩率,宽高 * 压缩率 """ in_file = IMAGE_PATH / in_file if isinstance(in_file, str) else in_file if out_file: out_file = IMAGE_PATH / out_file if isinstance(out_file, str) else out_file else: out_file = in_file h, w, d = cv2.imread(str(in_file.absolute())).shape img = cv2.resize( cv2.imread(str(in_file.absolute())), (int(w * ratio), int(h * ratio)) ) cv2.imwrite(str(out_file.absolute()), img) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def get_bot(id_: Optional[str] = None) -> Optional[Bot]: """ 说明: 获取 bot 对象 """ try: return nonebot.get_bot(id_) except ValueError: return None def change_pixiv_image_links( url: str, size: Optional[str] = None, nginx_url: Optional[str] = None ): """ 说明: 根据配置改变图片大小和反代链接 参数: :param url: 图片原图链接 :param size: 模式 :param nginx_url: 反代 """ if size == "master": img_sp = url.rsplit(".", maxsplit=1) url = img_sp[0] img_type = img_sp[1] url = url.replace("original", "master") + f"_master1200.{img_type}" if not nginx_url: nginx_url = Config.get_config("pixiv", "PIXIV_NGINX_URL") if nginx_url: url = ( url.replace("i.pximg.net", nginx_url) .replace("i.pixiv.cat", nginx_url) .replace("_webp", "") ) return url class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id The provided code snippet includes necessary dependencies for implementing the `update_setu_img` function. Write a Python function `async def update_setu_img(flag: bool = False)` to solve the following problem: 更新色图 :param flag: 是否手动更新 Here is the function: async def update_setu_img(flag: bool = False): """ 更新色图 :param flag: 是否手动更新 """ image_list = await Setu.all().order_by("local_id") image_list.reverse() _success = 0 error_info = [] error_type = [] count = 0 for image in image_list: count += 1 path = _path / "_r18" if image.is_r18 else _path / "_setu" local_image = path / f"{image.local_id}.jpg" path.mkdir(exist_ok=True, parents=True) TEMP_PATH.mkdir(exist_ok=True, parents=True) if not local_image.exists() or not image.img_hash: temp_file = TEMP_PATH / f"{image.local_id}.jpg" if temp_file.exists(): temp_file.unlink() url_ = change_pixiv_image_links(image.img_url) try: if not await AsyncHttpx.download_file( url_, TEMP_PATH / f"{image.local_id}.jpg" ): continue _success += 1 try: if ( os.path.getsize( TEMP_PATH / f"{image.local_id}.jpg", ) > 1024 * 1024 * 1.5 ): compressed_image( TEMP_PATH / f"{image.local_id}.jpg", path / f"{image.local_id}.jpg", ) else: logger.info( f"不需要压缩,移动图片{TEMP_PATH}/{image.local_id}.jpg " f"--> /{path}/{image.local_id}.jpg" ) os.rename( TEMP_PATH / f"{image.local_id}.jpg", path / f"{image.local_id}.jpg", ) except FileNotFoundError: logger.warning(f"文件 {image.local_id}.jpg 不存在,跳过...") continue img_hash = str(get_img_hash(f"{path}/{image.local_id}.jpg")) image.img_hash = img_hash await image.save(update_fields=["img_hash"]) # await Setu.update_setu_data(image.pid, img_hash=img_hash) except UnidentifiedImageError: # 图片已删除 unlink = False with open(local_image, "r") as f: if "404 Not Found" in f.read(): unlink = True if unlink: local_image.unlink() max_num = await Setu.delete_image(image.pid, image.img_url) if (path / f"{max_num}.jpg").exists(): os.rename(path / f"{max_num}.jpg", local_image) logger.warning(f"更新色图 PID:{image.pid} 404,已删除并替换") except Exception as e: _success -= 1 logger.error(f"更新色图 {image.local_id}.jpg 错误 {type(e)}: {e}") if type(e) not in error_type: error_type.append(type(e)) error_info.append(f"更新色图 {image.local_id}.jpg 错误 {type(e)}: {e}") else: logger.info(f"更新色图 {image.local_id}.jpg 已存在") if _success or error_info or flag: if bot := get_bot(): await bot.send_private_msg( user_id=int(list(bot.config.superusers)[0]), message=f'{str(datetime.now()).split(".")[0]} 更新 色图 完成,本地存在 {count} 张,实际更新 {_success} 张,' f"以下为更新时未知错误:\n" + "\n".join(error_info), )
更新色图 :param flag: 是否手动更新
188,293
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu url = "https://api.lolicon.app/setu/v2" if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 for x in lst: if x not in tmp: tmp.append(x) if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" text_list = [] add_databases_list = [] return urls, text_list, add_databases_list class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ async def get_setu_urls( tags: List[str], num: int = 1, r18: bool = False, command: str = "" ) -> Tuple[List[str], List[str], List[tuple], int]: tags = tags[:3] if len(tags) > 3 else tags params = { "r18": 1 if r18 else 0, # 添加r18参数 0为否,1为是,2为混合 "tag": tags, # 若指定tag "num": 20, # 一次返回的结果数量 "size": ["original"], } for count in range(3): logger.debug(f"尝试获取图片URL第 {count+1} 次", "色图") try: response = await AsyncHttpx.get( url, timeout=Config.get_config("send_setu", "TIMEOUT"), params=params ) if response.status_code == 200: data = response.json() if not data["error"]: data = data["data"] ( urls, text_list, add_databases_list, ) = await asyncio.get_event_loop().run_in_executor( None, _setu_data_process, data, command ) num = num if num < len(data) else len(data) random_idx = random.sample(range(len(data)), num) x_urls = [] x_text_lst = [] for x in random_idx: x_urls.append(urls[x]) x_text_lst.append(text_list[x]) if not x_urls: return ["没找到符合条件的色图..."], [], [], 401 return x_urls, x_text_lst, add_databases_list, 200 else: return ["没找到符合条件的色图..."], [], [], 401 except TimeoutError as e: logger.error(f"获取图片URL超时", "色图", e=e) except Exception as e: logger.error(f"访问页面错误", "色图", e=e) return ["我网线被人拔了..QAQ"], [], [], 999
null
188,294
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu path = "_setu" r18_path = "_r18" async def search_online_setu( url_: str, id_: Optional[int] = None, path_: Optional[str] = None ) -> Tuple[Union[MessageSegment, str], int]: """ 下载色图 :param url_: 色图url :param id_: 本地id :param path_: 存储路径 """ url_ = change_pixiv_image_links(url_) index = random.randint(1, 100000) if id_ is None else id_ base_path = IMAGE_PATH / path_ if path_ else TEMP_PATH file_name = f"{index}_temp_setu.jpg" if path_ == TEMP_PATH else f"{index}.jpg" file = base_path / file_name base_path.mkdir(parents=True, exist_ok=True) for i in range(3): logger.debug(f"尝试在线搜索第 {i+1} 次", "色图") try: if not await AsyncHttpx.download_file( url_, file, timeout=Config.get_config("send_setu", "TIMEOUT"), ): continue if id_ is not None: if os.path.getsize(base_path / f"{index}.jpg") > 1024 * 1024 * 1.5: compressed_image( base_path / f"{index}.jpg", ) logger.info(f"下载 lolicon 图片 {url_} 成功, id:{index}") change_img_md5(file) return image(file), index except TimeoutError as e: logger.error(f"下载图片超时", "色图", e=e) except Exception as e: logger.error(f"下载图片错误", "色图", e=e) return "图片被小怪兽恰掉啦..!QAQ", -1 path_ = None id_ = None if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 return await search_online_setu(setu_image.img_url, id_, path_ local_id = setu_image.local_id if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def change_img_md5(path_file: Union[str, Path]) -> bool: """ 说明: 改变图片MD5 参数: :param path_file: 图片路径 """ try: with open(path_file, "a") as f: f.write(str(int(time.time() * 1000))) return True except Exception as e: logger.warning(f"改变图片MD5错误 Path:{path_file}", e=e) return False class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id async def check_local_exists_or_download( setu_image: Setu, ) -> Tuple[Union[MessageSegment, str], int]: path_ = None id_ = None if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 return await search_online_setu(setu_image.img_url, id_, path_)
null
188,295
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu tmp = [] for x in lst: if x not in tmp: tmp.append(x) if tmp: for x in tmp: try: idx = await Setu.filter(is_r18="R-18" in x[5]).count() if not await Setu.exists(pid=x[2], img_url=x[4]): await Setu.create( local_id=idx, title=x[0], author=x[1], pid=x[2], img_hash=x[3], img_url=x[4], tags=x[5], is_r18="R-18" in x[5], ) except UniqueViolationError: pass local_id = setu_image.local_id title = setu_image.title author = setu_image.author pid = setu_image.pid class Setu(Model): async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): async def delete_image(cls, pid: int, img_url: str) -> int: async def add_data_to_database(lst: List[tuple]): tmp = [] for x in lst: if x not in tmp: tmp.append(x) if tmp: for x in tmp: try: idx = await Setu.filter(is_r18="R-18" in x[5]).count() if not await Setu.exists(pid=x[2], img_url=x[4]): await Setu.create( local_id=idx, title=x[0], author=x[1], pid=x[2], img_hash=x[3], img_url=x[4], tags=x[5], is_r18="R-18" in x[5], ) except UniqueViolationError: pass
null
188,296
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu if not image_list: return ["没找到符合条件的色图..."], 998 return image_list, 200 class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id async def get_setu_list( index: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False ) -> Tuple[list, int]: if index: image_count = await Setu.filter(is_r18=r18).count() - 1 if index < 0 or index > image_count: return [f"超过当前上下限!({image_count})"], 999 image_list = [await Setu.query_image(index, r18=r18)] elif tags: image_list = await Setu.query_image(tags=tags, r18=r18) else: image_list = await Setu.query_image(r18=r18) if not image_list: return ["没找到符合条件的色图..."], 998 return image_list, 200 # type: ignore
null
188,297
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 local_id = setu_image.local_id title = setu_image.title author = setu_image.author pid = setu_image.pid if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id The provided code snippet includes necessary dependencies for implementing the `gen_message` function. Write a Python function `def gen_message(setu_image: Setu) -> str` to solve the following problem: 判断是否获取图片信息 Args: setu_image (Setu): Setu Returns: str: 图片信息 Here is the function: def gen_message(setu_image: Setu) -> str: """判断是否获取图片信息 Args: setu_image (Setu): Setu Returns: str: 图片信息 """ local_id = setu_image.local_id title = setu_image.title author = setu_image.author pid = setu_image.pid if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" return ""
判断是否获取图片信息 Args: setu_image (Setu): Setu Returns: str: 图片信息
188,298
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" if initial_setu_probability: probability = float(impression) + initial_setu_probability * 100 if probability < random.randint(1, 101): return ( "我为什么要给你发这个?" + image( IMAGE_PATH / "luoxiang" / random.choice(os.listdir(IMAGE_PATH / "luoxiang")) ) + f"\n(快向{NICKNAME}签到提升好感度吧!)" ) def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") def get_luoxiang(impression): initial_setu_probability = Config.get_config( "send_setu", "INITIAL_SETU_PROBABILITY" ) if initial_setu_probability: probability = float(impression) + initial_setu_probability * 100 if probability < random.randint(1, 101): return ( "我为什么要给你发这个?" + image( IMAGE_PATH / "luoxiang" / random.choice(os.listdir(IMAGE_PATH / "luoxiang")) ) + f"\n(快向{NICKNAME}签到提升好感度吧!)" ) return None
null
188,299
import asyncio import os import random import re from asyncio.exceptions import TimeoutError from typing import Any, List, Optional, Tuple, Union from asyncpg.exceptions import UniqueViolationError from nonebot.adapters.onebot.v11 import MessageSegment from configs.config import NICKNAME, Config from configs.path_config import IMAGE_PATH, TEMP_PATH from services.log import logger from utils.http_utils import AsyncHttpx from utils.image_utils import compressed_image, get_img_hash from utils.message_builder import image from utils.utils import change_img_md5, change_pixiv_image_links from .._model import Setu if Config.get_config("send_setu", "DOWNLOAD_SETU"): id_ = setu_image.local_id path_ = r18_path if setu_image.is_r18 else path file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" if file.exists(): change_img_md5(file) return image(file), 200 local_id = setu_image.local_id title = setu_image.title author = setu_image.author pid = setu_image.pid if Config.get_config("send_setu", "SHOW_INFO"): return f"id:{local_id}\n" f"title:{title}\n" f"author:{author}\n" f"PID:{pid}\n" class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ def get_img_hash(image_file: Union[str, Path]) -> ImageHash: """ 说明: 获取图片的hash值 参数: :param image_file: 图片文件路径 """ with open(image_file, "rb") as fp: hash_value = imagehash.average_hash(Image.open(fp)) return hash_value class Setu(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" local_id = fields.IntField() """本地存储下标""" title = fields.CharField(255) """标题""" author = fields.CharField(255) """作者""" pid = fields.BigIntField() """pid""" img_hash: str = fields.TextField() """图片hash""" img_url = fields.CharField(255) """pixiv url链接""" is_r18 = fields.BooleanField() """是否r18""" tags = fields.TextField() """tags""" class Meta: table = "setu" table_description = "色图数据表" unique_together = ("pid", "img_url") async def query_image( cls, local_id: Optional[int] = None, tags: Optional[List[str]] = None, r18: bool = False, limit: int = 50, ): """ 说明: 通过tag查找色图 参数: :param local_id: 本地色图 id :param tags: tags :param r18: 是否 r18,0:非r18 1:r18 2:混合 :param limit: 获取数量 """ if local_id: return await cls.filter(is_r18=r18, local_id=local_id).first() query = cls.filter(is_r18=r18) if tags: for tag in tags: query = query.filter( Q(tags__contains=tag) | Q(title__contains=tag) | Q(author__contains=tag) ) query = query.annotate(rand=Random()).limit(limit) return await query.all() async def delete_image(cls, pid: int, img_url: str) -> int: """ 说明: 删除图片并替换 参数: :param pid: 图片pid """ print(pid) return_id = -1 if query := await cls.get_or_none(pid=pid, img_url=img_url): num = await cls.filter(is_r18=query.is_r18).count() last_image = await cls.get_or_none(is_r18=query.is_r18, local_id=num - 1) if last_image: return_id = last_image.local_id last_image.local_id = query.local_id await last_image.save(update_fields=["local_id"]) await query.delete() return return_id async def find_img_index(img_url, user_id): if not await AsyncHttpx.download_file( img_url, TEMP_PATH / f"{user_id}_find_setu_index.jpg", timeout=Config.get_config("send_setu", "TIMEOUT"), ): return "检索图片下载上失败..." img_hash = str(get_img_hash(TEMP_PATH / f"{user_id}_find_setu_index.jpg")) if setu_img := await Setu.get_or_none(img_hash=img_hash): return ( f"id:{setu_img.local_id}\n" f"title:{setu_img.title}\n" f"author:{setu_img.author}\n" f"PID:{setu_img.pid}" ) return "该图不在色图库中或色图库未更新!"
null
188,300
from configs.config import Config from nonebot.internal.rule import Rule def rule() -> Rule: async def _rule() -> bool: return Config.get_config("self_message", "STATUS") return Rule(_rule)
null
188,301
from datetime import datetime from nonebot.log import logger from nonebot.adapters.onebot.v11 import Bot from configs.config import NICKNAME from utils.http_utils import AsyncHttpx async def get_epic_game(): epic_url = "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions?locale=zh-CN&country=CN&allowCountries=CN" headers = { "Referer": "https://www.epicgames.com/store/zh-CN/", "Content-Type": "application/json; charset=utf-8", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36", } try: res = await AsyncHttpx.get(epic_url, headers=headers, timeout=10) res_json = res.json() games = res_json["data"]["Catalog"]["searchStore"]["elements"] return games except Exception as e: logger.error(f"Epic 访问接口错误 {type(e)}:{e}") return None game_desp(name): async def get_epic_free(bot: Bot, type_event: str): games = await get_epic_game() if not games: return "Epic 可能又抽风啦,请稍后再试(", 404 else: msg_list = [] for game in games: game_name = game["title"] game_corp = game["seller"]["name"] game_price = game["price"]["totalPrice"]["fmtPrice"]["originalPrice"] # 赋初值以避免 local variable referenced before assignment game_thumbnail, game_dev, game_pub = None, game_corp, game_corp try: game_promotions = game["promotions"]["promotionalOffers"] upcoming_promotions = game["promotions"]["upcomingPromotionalOffers"] if not game_promotions and upcoming_promotions: # 促销暂未上线,但即将上线 promotion_data = upcoming_promotions[0]["promotionalOffers"][0] start_date_iso, end_date_iso = ( promotion_data["startDate"][:-1], promotion_data["endDate"][:-1], ) # 删除字符串中最后一个 "Z" 使 Python datetime 可处理此时间 start_date = datetime.fromisoformat(start_date_iso).strftime( "%b.%d %H:%M" ) end_date = datetime.fromisoformat(end_date_iso).strftime( "%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) else: msg = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format( game_corp, game_name, game_price, start_date, end_date ) msg_list.append(msg) else: for image in game["keyImages"]: if ( image.get("url") and not game_thumbnail and image["type"] in [ "Thumbnail", "VaultOpened", "DieselStoreFrontWide", "OfferImageWide", ] ): game_thumbnail = image["url"] break for pair in game["customAttributes"]: if pair["key"] == "developerName": game_dev = pair["value"] if pair["key"] == "publisherName": game_pub = pair["value"] if game.get("productSlug"): gamesDesp = await get_epic_game_desp(game["productSlug"]) try: #是否存在简短的介绍 if "shortDescription" in gamesDesp: game_desp = gamesDesp["shortDescription"] except KeyError: game_desp = gamesDesp["description"] else: game_desp = game["description"] try: end_date_iso = game["promotions"]["promotionalOffers"][0][ "promotionalOffers" ][0]["endDate"][:-1] end_date = datetime.fromisoformat(end_date_iso).strftime( "%b.%d %H:%M" ) except IndexError: end_date = '未知' # API 返回不包含游戏商店 URL,此处自行拼接,可能出现少数游戏 404 请反馈 if game.get("productSlug"): game_url = "https://store.epicgames.com/zh-CN/p/{}".format( game["productSlug"].replace("/home", "") ) elif game.get("url"): game_url = game["url"] else: slugs = ( [ x["pageSlug"] for x in game.get("offerMappings", []) if x.get("pageType") == "productHome" ] + [ x["pageSlug"] for x in game.get("catalogNs", {}).get("mappings", []) if x.get("pageType") == "productHome" ] + [ x["value"] for x in game.get("customAttributes", []) if "productSlug" in x.get("key") ] ) game_url = "https://store.epicgames.com/zh-CN{}".format( f"/p/{slugs[0]}" if len(slugs) else "" ) if 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) else: msg = "[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, ) msg_list.append(msg) except TypeError as e: # logger.info(str(e)) pass return msg_list, 200
null
188,302
from nonebot import on_command from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent from nonebot.typing import T_State import re async def _(bot: Bot, event: GroupMessageEvent, state: T_State): if event.reply: await bot.delete_msg(message_id=event.reply.message_id)
null
188,303
import random from pathlib import Path from typing import Optional, Tuple, Union from nonebot.adapters.onebot.v11 import ActionFailed from configs.config import Config from configs.path_config import DATA_PATH from models.ban_user import BanUser from models.group_member_info import GroupInfoUser from services.log import logger from utils.http_utils import AsyncHttpx from utils.utils import cn2py, get_bot from .model import BlackWord async def _punish_handle( user_id: str, group_id: Optional[str], punish_level: int, black_word: str ): """ 惩罚措施,级别越低惩罚越严 :param user_id: 用户id :param group_id: 群号 :param black_word: 触发的黑名单词汇 """ logger.info(f"BlackWord USER {user_id} 触发 {punish_level} 级惩罚...") # 周期天数 cycle_days = Config.get_config("black_word", "CYCLE_DAYS") or 7 # 用户周期内触发punish_level级惩罚的次数 user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level) # 获取最近一次的惩罚等级,将在此基础上增加 punish_level = ( await BlackWord.get_user_punish_level(user_id, cycle_days) or punish_level ) # 容忍次数:List[int] tolerate_count = Config.get_config("black_word", "TOLERATE_COUNT") if not tolerate_count or len(tolerate_count) < 5: tolerate_count = [5, 2, 2, 2, 2] if punish_level == 1 and user_count > tolerate_count[punish_level - 1]: # 永久ban await _get_punish(1, user_id, group_id) await BlackWord.set_user_punish(user_id, "永久ban 删除好友", black_word) elif punish_level == 2 and user_count > tolerate_count[punish_level - 1]: # 删除好友 await _get_punish(2, user_id, group_id) await BlackWord.set_user_punish(user_id, "删除好友", black_word) elif punish_level == 3 and user_count > tolerate_count[punish_level - 1]: # 永久ban ban_day = await _get_punish(3, user_id, group_id) await BlackWord.set_user_punish(user_id, f"ban {ban_day} 天", black_word) elif punish_level == 4 and user_count > tolerate_count[punish_level - 1]: # ban指定时长 ban_time = await _get_punish(4, user_id, group_id) await BlackWord.set_user_punish(user_id, f"ban {ban_time} 分钟", black_word) elif punish_level == 5 and user_count > tolerate_count[punish_level - 1]: # 口头警告 warning_result = await _get_punish(5, user_id, group_id) await BlackWord.set_user_punish(user_id, f"口头警告:{warning_result}", black_word) else: await BlackWord.set_user_punish(user_id, f"提示!", black_word) await send_msg( user_id, group_id, f"BlackWordChecker:该条发言已被记录,目前你在{cycle_days}天内的发表{punish_level}级" f"言论记录次数为:{user_count}次,请注意你的发言\n" f"* 如果你不清楚惩罚机制,请发送“惩罚机制” *", ) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class BlackWord(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" plant_text = fields.TextField() """检测文本""" black_word = fields.TextField() """黑名单词语""" punish = fields.TextField(default="") """惩罚内容""" punish_level = fields.IntField() """惩罚等级""" create_time = fields.DatetimeField(auto_now_add=True) """创建时间""" class Meta: table = "black_word" table_description = "惩罚机制数据表" async def set_user_punish( cls, user_id: str, punish: str, black_word: Optional[str] = None, id_: Optional[int] = None, ) -> bool: """ 说明: 设置处罚 参数: :param user_id: 用户id :param punish: 处罚 :param black_word: 黑名单词汇 :param id_: 记录下标 """ user = None if (not black_word and id_ is None) or not punish: return False if black_word: user = ( await cls.filter(user_id=user_id, black_word=black_word, punish="") .order_by("id") .first() ) elif id_ is not None: user_list = await cls.filter(user_id=user_id).order_by("id").all() if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)): return False user = user_list[id_] if not user: return False user.punish = f"{user.punish}{punish} " await user.save(update_fields=["punish"]) return True async def get_user_count( cls, user_id: str, days: int = 7, punish_level: Optional[int] = None ) -> int: """ 说明: 获取用户规定周期内的犯事次数 参数: :param user_id: 用户id :param days: 周期天数 :param punish_level: 惩罚等级 """ query = cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), punish_level__not_in=[-1], ) if punish_level is not None: query = query.filter(punish_level=punish_level) return await query.count() async def get_user_punish_level(cls, user_id: str, days: int = 7) -> Optional[int]: """ 说明: 获取用户最近一次的惩罚记录等级 参数: :param user_id: 用户id :param days: 周期天数 """ if ( user := await cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), ) .order_by("id") .first() ): return user.punish_level return None async def get_black_data( cls, user_id: Optional[str], group_id: Optional[str], date: Optional[datetime], date_type: str = "=", ) -> List["BlackWord"]: """ 说明: 通过指定条件查询数据 参数: :param user_id: 用户id :param group_id: 群号 :param date: 日期 :param date_type: 日期查询类型 """ query = cls if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if date: if date_type == "=": query = query.filter( create_time__range=[date, date + timedelta(days=1)] ) elif date_type == ">": query = query.filter(create_time__gte=date) elif date_type == "<": query = query.filter(create_time__lte=date) return await query.all().order_by("id") # type: ignore async def _run_script(cls): return [ "ALTER TABLE black_word RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE black_word ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE black_word ALTER COLUMN group_id TYPE character varying(255);", ] The provided code snippet includes necessary dependencies for implementing the `_add_user_black_word` function. Write a Python function `async def _add_user_black_word( user_id: str, group_id: Optional[str], black_word: str, message: str, punish_level: int, )` to solve the following problem: 添加敏感词数据 :param user_id: 用户id :param group_id: 群号 :param black_word: 触发的黑名单词汇 :param message: 原始文本 :param punish_level: 惩罚等级 Here is the function: async def _add_user_black_word( user_id: str, group_id: Optional[str], black_word: str, message: str, punish_level: int, ): """ 添加敏感词数据 :param user_id: 用户id :param group_id: 群号 :param black_word: 触发的黑名单词汇 :param message: 原始文本 :param punish_level: 惩罚等级 """ cycle_days = Config.get_config("black_word", "CYCLE_DAYS") or 7 user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level) add_punish_level_to_count = Config.get_config( "black_word", "ADD_PUNISH_LEVEL_TO_COUNT" ) # 周期内超过次数直接提升惩罚 if ( Config.get_config("black_word", "AUTO_ADD_PUNISH_LEVEL") and add_punish_level_to_count ): punish_level -= 1 await BlackWord.create( user_id=user_id, group_id=group_id, plant_text=message, black_word=black_word, punish_level=punish_level, ) logger.info( f"已将 USER {user_id} GROUP {group_id} 添加至黑名单词汇记录 Black_word:{black_word} Plant_text:{message}" ) # 自动惩罚 if Config.get_config("black_word", "AUTO_PUNISH") and punish_level != -1: await _punish_handle(user_id, group_id, punish_level, black_word)
添加敏感词数据 :param user_id: 用户id :param group_id: 群号 :param black_word: 触发的黑名单词汇 :param message: 原始文本 :param punish_level: 惩罚等级
188,304
import random from pathlib import Path from typing import Optional, Tuple, Union from nonebot.adapters.onebot.v11 import ActionFailed from configs.config import Config from configs.path_config import DATA_PATH from models.ban_user import BanUser from models.group_member_info import GroupInfoUser from services.log import logger from utils.http_utils import AsyncHttpx from utils.utils import cn2py, get_bot from .model import BlackWord class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ The provided code snippet includes necessary dependencies for implementing the `check_text` function. Write a Python function `async def check_text(text: str) -> bool` to solve the following problem: ALAPI文本检测,检测输入违规 :param text: 回复 Here is the function: async def check_text(text: str) -> bool: """ ALAPI文本检测,检测输入违规 :param text: 回复 """ if not Config.get_config("alapi", "ALAPI_TOKEN"): return True params = {"token": Config.get_config("alapi", "ALAPI_TOKEN"), "text": text} try: data = ( await AsyncHttpx.get( "https://v2.alapi.cn/api/censor/text", timeout=4, params=params ) ).json() if data["code"] == 200: return data["data"]["conclusion_type"] == 2 except Exception as e: logger.error(f"检测违规文本错误...{type(e)}:{e}") return True
ALAPI文本检测,检测输入违规 :param text: 回复
188,305
from datetime import datetime from typing import Optional from nonebot.adapters.onebot.v11 import Bot from services.log import logger from utils.image_utils import BuildImage, text2image from .model import BlackWord from .utils import Config, _get_punish class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) class BuildImage: """ 快捷生成图片与操作图片的工具类 """ def __init__( self, w: int, h: int, paste_image_width: int = 0, paste_image_height: int = 0, paste_space: int = 0, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = None, image_mode: ModeType = "RGBA", font_size: int = 10, background: Union[Optional[str], BytesIO, Path] = None, font: str = "yz.ttf", ratio: float = 1, is_alpha: bool = False, plain_text: Optional[str] = None, font_color: Optional[Union[str, Tuple[int, int, int]]] = None, **kwargs, ): """ 参数: :param w: 自定义图片的宽度,w=0时为图片原本宽度 :param h: 自定义图片的高度,h=0时为图片原本高度 :param paste_image_width: 当图片做为背景图时,设置贴图的宽度,用于贴图自动换行 :param paste_image_height: 当图片做为背景图时,设置贴图的高度,用于贴图自动换行 :param paste_space: 自动贴图间隔 :param color: 生成图片的颜色 :param image_mode: 图片的类型 :param font_size: 文字大小 :param background: 打开图片的路径 :param font: 字体,默认在 resource/ttf/ 路径下 :param ratio: 倍率压缩 :param is_alpha: 是否背景透明 :param plain_text: 纯文字文本 """ self.w = int(w) self.h = int(h) self.paste_image_width = int(paste_image_width) self.paste_image_height = int(paste_image_height) self.paste_space = int(paste_space) self._current_w = 0 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) self.background = background if not background: if plain_text: if not color: color = (255, 255, 255, 0) ttf_w, ttf_h = self.getsize(str(plain_text)) self.w = self.w if self.w > ttf_w else ttf_w self.h = self.h if self.h > ttf_h else ttf_h self.markImg = Image.new(image_mode, (self.w, self.h), color) self.markImg.convert(image_mode) else: if not w and not h: self.markImg = Image.open(background) w, h = self.markImg.size if ratio and ratio > 0 and ratio != 1: self.w = int(ratio * w) self.h = int(ratio * h) self.markImg = self.markImg.resize( (self.w, self.h), Image.ANTIALIAS ) else: self.w = w self.h = h else: self.markImg = Image.open(background).resize( (self.w, self.h), Image.ANTIALIAS ) if is_alpha: try: 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) self.size = self.w, self.h if plain_text: fill = font_color if font_color else (0, 0, 0) self.text((0, 0), str(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() def load_font(cls, font: str, font_size: Optional[int]) -> FreeTypeFont: """ 说明: 加载字体 参数: :param font: 字体名称 :param font_size: 字体大小 """ return ImageFont.truetype(str(FONT_PATH / font), font_size or cls.font_size) async def apaste( self, img: "BuildImage" or Image, pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 异步 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ await self.loop.run_in_executor( None, self.paste, img, pos, alpha, center_type, allow_negative ) def paste( self, img: "BuildImage", pos: Optional[Tuple[int, int]] = None, alpha: bool = False, center_type: Optional[Literal["center", "by_height", "by_width"]] = None, allow_negative: bool = False, ): """ 说明: 贴图 参数: :param img: 已打开的图片文件,可以为 BuildImage 或 Image :param pos: 贴图位置(左上角) :param alpha: 图片背景是否为透明 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param allow_negative: 允许使用负数作为坐标且不超出图片范围,从右侧开始计算 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) width, height = 0, 0 if not pos: pos = (0, 0) if center_type == "center": width = int((self.w - img.w) / 2) height = int((self.h - img.h) / 2) elif center_type == "by_width": width = int((self.w - img.w) / 2) height = pos[1] elif center_type == "by_height": width = pos[0] height = int((self.h - img.h) / 2) pos = (width, height) if pos and allow_negative: 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: self._current_w = 0 self._current_h += self.paste_image_height + self.paste_space if not pos: pos = (self._current_w, self._current_h) if alpha: try: self.markImg.paste(img, pos, img) except ValueError: img = img.convert("RGBA") self.markImg.paste(img, pos, img) else: self.markImg.paste(img, pos) self._current_w += self.paste_image_width + self.paste_space def get_text_size(cls, msg: str, font: str, font_size: int) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 :param font: 字体 :param font_size: 字体大小 """ font_ = cls.load_font(font, font_size) return font_.getsize(msg) # type: ignore def getsize(self, msg: Any) -> Tuple[int, int]: """ 说明: 获取文字在该图片 font_size 下所需要的空间 参数: :param msg: 文字内容 """ return self.font.getsize(str(msg)) # type: ignore 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): """ 说明: 绘制多个或单独的像素 参数: :param pos: 坐标 :param fill: 填错颜色 """ 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], 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: 描线宽度 """ self.draw.ellipse(pos, fill, outline, width) async def atext( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 异步 在图片上添加文字 参数: :param pos: 文字位置 :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ await self.loop.run_in_executor( None, self.text, pos, text, fill, center_type, font, font_size, **kwargs ) def text( self, pos: Union[Tuple[int, int], Tuple[float, float]], text: str, fill: Union[str, Tuple[int, int, int]] = (0, 0, 0), center_type: Optional[Literal["center", "by_height", "by_width"]] = None, font: Optional[Union[FreeTypeFont, str]] = None, font_size: Optional[int] = None, **kwargs, ): """ 说明: 在图片上添加文字 参数: :param pos: 文字位置(使用center_type中的center后会失效,使用by_width后x失效,使用by_height后y失效) :param text: 文字内容 :param fill: 文字颜色 :param center_type: 居中类型,可能的值 center: 完全居中,by_width: 水平居中,by_height: 垂直居中 :param font: 字体 :param font_size: 字体大小 """ if center_type: if center_type not in ["center", "by_height", "by_width"]: raise ValueError( "center_type must be 'center', 'by_width' or 'by_height'" ) w, h = self.w, self.h longgest_text = "" sentence = text.split("\n") for x in sentence: longgest_text = x if len(x) > len(longgest_text) else longgest_text ttf_w, ttf_h = self.getsize(longgest_text) ttf_h = ttf_h * len(sentence) if center_type == "center": w = int((w - ttf_w) / 2) h = int((h - ttf_h) / 2) elif center_type == "by_width": w = int((w - ttf_w) / 2) h = pos[1] elif center_type == "by_height": h = int((h - ttf_h) / 2) w = pos[0] pos = (w, h) if font: if isinstance(font, str): font = self.load_font(font, font_size) elif font_size: font = self.load_font(self.font_name, font_size) self.draw.text(pos, text, fill=fill, font=font or self.font, **kwargs) async def asave(self, path: Optional[Union[str, Path]] = None): """ 说明: 异步 保存图片 参数: :param path: 图片路径 """ await self.loop.run_in_executor(None, self.save, path) def save(self, path: Optional[Union[str, Path]] = None): """ 说明: 保存图片 参数: :param path: 图片路径 """ self.markImg.save(path or self.background) # type: ignore def show(self): """ 说明: 显示图片 """ self.markImg.show() 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): """ 说明: 压缩图片 参数: :param ratio: 压缩倍率 :param w: 压缩图片宽度至 w :param h: 压缩图片高度至 h """ if not w and not h and not ratio: raise Exception("缺少参数...") if not w and not h and ratio: w = int(self.w * ratio) h = int(self.h * ratio) self.markImg = self.markImg.resize((w, h), Image.ANTIALIAS) self.w, self.h = self.markImg.size 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]): """ 说明: 裁剪图片 参数: :param box: 左上角坐标,右下角坐标 (left, upper, right, lower) """ self.markImg = self.markImg.crop(box) self.w, self.h = self.markImg.size self.size = self.w, self.h self.draw = ImageDraw.Draw(self.markImg) def check_font_size(self, word: str) -> bool: """ 说明: 检查文本所需宽度是否大于图片宽度 参数: :param word: 文本内容 """ 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): """ 说明: 图片透明化 参数: :param alpha_ratio: 透明化程度 :param n: 透明化大小内边距 """ self.markImg = self.markImg.convert("RGBA") x, y = self.markImg.size for i in range(n, x - n): for k in range(n, y - n): color = self.markImg.getpixel((i, k)) color = color[:-1] + (int(100 * alpha_ratio),) self.markImg.putpixel((i, k), color) self.draw = ImageDraw.Draw(self.markImg) def pic2bs4(self) -> str: """ 说明: BuildImage 转 base64 """ buf = BytesIO() self.markImg.save(buf, format="PNG") base64_str = base64.b64encode(buf.getvalue()).decode() return "base64://" + base64_str def convert(self, type_: ModeType): """ 说明: 修改图片类型 参数: :param type_: 类型 """ self.markImg = self.markImg.convert(type_) async def arectangle( self, xy: Tuple[int, int, int, int], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[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], fill: Optional[Tuple[int, int, int]] = None, outline: Optional[str] = None, width: int = 1, ): """ 说明: 画框 参数: :param xy: 坐标 :param fill: 填充颜色 :param outline: 轮廓颜色 :param width: 线宽 """ 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[Union[str, 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], fill: Optional[Union[Tuple[int, int, int], str]] = None, width: int = 1, ): """ 说明: 画线 参数: :param xy: 坐标 :param fill: 填充 :param width: 线宽 """ self.draw.line(xy, fill, width) async def acircle(self): """ 说明: 异步 将 BuildImage 图片变为圆形 """ await self.loop.run_in_executor(None, self.circle) def circle(self): """ 说明: 使图像变圆 """ self.markImg.convert("RGBA") size = self.markImg.size r2 = min(size[0], size[1]) if size[0] != size[1]: self.markImg = self.markImg.resize((r2, r2), Image.ANTIALIAS) width = 1 antialias = 4 ellipse_box = [0, 0, r2 - 2, r2 - 2] mask = Image.new( size=[int(dim * antialias) for dim in self.markImg.size], mode="L", color="black", ) draw = ImageDraw.Draw(mask) for offset, fill in (width / -2.0, "black"), (width / 2.0, "white"): left, top = [(value + offset) * antialias for value in ellipse_box[:2]] right, bottom = [(value - offset) * antialias for value in ellipse_box[2:]] draw.ellipse([left, top, right, bottom], fill=fill) mask = mask.resize(self.markImg.size, Image.LANCZOS) try: self.markImg.putalpha(mask) except ValueError: pass async def acircle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 异步 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ await self.loop.run_in_executor(None, self.circle_corner, radii, point_list) def circle_corner( self, radii: int = 30, point_list: List[Literal["lt", "rt", "lb", "rb"]] = ["lt", "rt", "lb", "rb"], ): """ 说明: 矩形四角变圆 参数: :param radii: 半径 :param point_list: 需要变化的角 """ # 画圆(用于分离4个角) img = self.markImg.convert("RGBA") alpha = img.split()[-1] circle = Image.new("L", (radii * 2, radii * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, radii * 2, radii * 2), fill=255) # 黑色方形内切白色圆形 w, h = img.size if "lt" in point_list: alpha.paste(circle.crop((0, 0, radii, radii)), (0, 0)) if "rt" in point_list: alpha.paste(circle.crop((radii, 0, radii * 2, radii)), (w - radii, 0)) if "lb" in point_list: alpha.paste(circle.crop((0, radii, radii, radii * 2)), (0, h - radii)) if "rb" in point_list: alpha.paste( circle.crop((radii, radii, radii * 2, radii * 2)), (w - radii, h - radii), ) img.putalpha(alpha) self.markImg = img self.draw = ImageDraw.Draw(self.markImg) 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): """ 说明: 旋转图片 参数: :param angle: 角度 :param expand: 放大图片适应角度 """ self.markImg = self.markImg.rotate(angle, expand=expand) async def atranspose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 异步 旋转图片(包括边框) 参数: :param angle: 角度 """ await self.loop.run_in_executor(None, self.transpose, angle) def transpose(self, angle: Literal[0, 1, 2, 3, 4, 5, 6]): """ 说明: 旋转图片(包括边框) 参数: :param angle: 角度 """ self.markImg.transpose(angle) async def afilter(self, filter_: str, aud: Optional[int] = None): """ 说明: 异步 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ await self.loop.run_in_executor(None, self.filter, filter_, aud) def filter(self, filter_: str, aud: Optional[int] = None): """ 说明: 图片变化 参数: :param filter_: 变化效果 :param aud: 利率 """ _x = None if filter_ == "GaussianBlur": # 高斯模糊 _x = ImageFilter.GaussianBlur elif filter_ == "EDGE_ENHANCE": # 锐化效果 _x = ImageFilter.EDGE_ENHANCE elif filter_ == "BLUR": # 模糊效果 _x = ImageFilter.BLUR elif filter_ == "CONTOUR": # 铅笔滤镜 _x = ImageFilter.CONTOUR elif filter_ == "FIND_EDGES": # 边缘检测 _x = ImageFilter.FIND_EDGES if _x: if aud: self.markImg = self.markImg.filter(_x(aud)) else: self.markImg = self.markImg.filter(_x) self.draw = ImageDraw.Draw(self.markImg) async def areplace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 异步 颜色替换 参数: :param src_color: 目标颜色,或者使用列表,设置阈值 :param replace_color: 替换颜色 """ self.loop.run_in_executor( None, self.replace_color_tran, src_color, replace_color ) def replace_color_tran( self, src_color: Union[ Tuple[int, int, int], Tuple[Tuple[int, int, int], Tuple[int, int, int]] ], replace_color: Tuple[int, int, int], ): """ 说明: 颜色替换 参数: :param src_color: 目标颜色,或者使用元祖,设置阈值 :param replace_color: 替换颜色 """ if isinstance(src_color, tuple): start_ = src_color[0] end_ = src_color[1] else: start_ = src_color end_ = None for i in range(self.w): for j in range(self.h): r, g, b = self.markImg.getpixel((i, j)) if not end_: if r == start_[0] and g == start_[1] and b == start_[2]: self.markImg.putpixel((i, j), replace_color) else: if ( start_[0] <= r <= end_[0] and start_[1] <= g <= end_[1] and start_[2] <= b <= end_[2] ): self.markImg.putpixel((i, j), replace_color) # def getchannel(self, type_): self.markImg = self.markImg.getchannel(type_) async def text2image( text: str, auto_parse: bool = True, font_size: int = 20, color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white", font: str = "CJGaoDeGuo.otf", font_color: Union[str, Tuple[int, int, int]] = "black", padding: Union[int, Tuple[int, int, int, int]] = 0, _add_height: float = 0, ) -> BuildImage: """ 说明: 解析文本并转为图片 使用标签 <f> </f> 可选配置项 font: str -> 特殊文本字体 fs / font_size: int -> 特殊文本大小 fc / font_color: Union[str, Tuple[int, int, int]] -> 特殊文本颜色 示例 在不在,<f font=YSHaoShenTi-2.ttf font_size=30 font_color=red>HibiKi小姐</f>, 你最近还好吗,<f font_size=15 font_color=black>我非常想你</f>,这段时间我非常不好过, <f font_size=25>抽卡抽不到金色</f>,这让我很痛苦 参数: :param text: 文本 :param auto_parse: 是否自动解析,否则原样发送 :param font_size: 普通字体大小 :param color: 背景颜色 :param font: 普通字体 :param font_color: 普通字体颜色 :param padding: 文本外边距,元组类型时为 (上,左,下,右) :param _add_height: 由于get_size无法返回正确的高度,采用手动方式额外添加高度 """ pw = ph = top_padding = left_padding = 0 if padding: if isinstance(padding, int): pw = padding * 2 ph = padding * 2 top_padding = left_padding = padding elif isinstance(padding, tuple): pw = padding[0] + padding[2] ph = padding[1] + padding[3] top_padding = padding[0] left_padding = padding[1] if auto_parse and re.search(r"<f(.*)>(.*)</f>", text): _data = [] new_text = "" placeholder_index = 0 for s in text.split("</f>"): r = re.search(r"<f(.*)>(.*)", s) if r: start, end = r.span() if start != 0 and (t := s[:start]): new_text += t _data.append( [ (start, end), f"[placeholder_{placeholder_index}]", r.group(1).strip(), r.group(2), ] ) new_text += f"[placeholder_{placeholder_index}]" placeholder_index += 1 new_text += text.split("</f>")[-1] image_list = [] current_placeholder_index = 0 # 切分换行,每行为单张图片 for s in new_text.split("\n"): _tmp_text = s img_height = BuildImage(0, 0, font_size=font_size).getsize("正")[1] img_width = 0 _tmp_index = current_placeholder_index for _ in range(s.count("[placeholder_")): placeholder = _data[_tmp_index] if "font_size" in placeholder[2]: r = re.search(r"font_size=['\"]?(\d+)", placeholder[2]) if r: w, h = BuildImage(0, 0, font_size=int(r.group(1))).getsize( placeholder[3] ) img_height = img_height if img_height > h else h img_width += w else: img_width += BuildImage(0, 0, font_size=font_size).getsize( placeholder[3] )[0] _tmp_text = _tmp_text.replace(f"[placeholder_{_tmp_index}]", "") _tmp_index += 1 img_width += BuildImage(0, 0, font_size=font_size).getsize(_tmp_text)[0] # img_width += len(_tmp_text) * font_size # 开始画图 A = BuildImage( img_width, img_height, color=color, font=font, font_size=font_size ) basic_font_h = A.getsize("正")[1] current_width = 0 # 遍历占位符 for _ in range(s.count("[placeholder_")): if not s.startswith(f"[placeholder_{current_placeholder_index}]"): slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext( (current_width, A.h - basic_font_h - 1), slice_[0], font_color ) current_width += A.getsize(slice_[0])[0] placeholder = _data[current_placeholder_index] # 解析配置 _font = font _font_size = font_size _font_color = font_color for e in placeholder[2].split(): if e.startswith("font="): _font = e.split("=")[-1] if e.startswith("font_size=") or e.startswith("fs="): _font_size = int(e.split("=")[-1]) if _font_size > 1000: _font_size = 1000 if _font_size < 1: _font_size = 1 if e.startswith("font_color") or e.startswith("fc="): _font_color = e.split("=")[-1] text_img = BuildImage( 0, 0, plain_text=placeholder[3], font_size=_font_size, font_color=_font_color, font=_font, ) _img_h = ( int(A.h / 2 - text_img.h / 2) if new_text == "[placeholder_0]" else A.h - text_img.h ) await A.apaste(text_img, (current_width, _img_h - 1), True) current_width += text_img.w s = s[ s.index(f"[placeholder_{current_placeholder_index}]") + len(f"[placeholder_{current_placeholder_index}]") : ] current_placeholder_index += 1 if s: slice_ = s.split(f"[placeholder_{current_placeholder_index}]") await A.atext((current_width, A.h - basic_font_h), slice_[0]) current_width += A.getsize(slice_[0])[0] A.crop((0, 0, current_width, A.h)) # A.show() image_list.append(A) height = 0 width = 0 for img in image_list: height += img.h width = width if width > img.w else img.w width += pw height += ph A = BuildImage(width + left_padding, height + top_padding, color=color) current_height = top_padding for img in image_list: await A.apaste(img, (left_padding, current_height), True) current_height += img.h else: width = 0 height = 0 _tmp = BuildImage(0, 0, font=font, font_size=font_size) _, h = _tmp.getsize("正") line_height = int(font_size / 3) image_list = [] for x in text.split("\n"): w, _ = _tmp.getsize(x.strip() or "正") height += h + line_height width = width if width > w else w image_list.append( BuildImage( w, h, font=font, font_size=font_size, plain_text=x.strip(), color=color, ) ) width += pw height += ph A = BuildImage( width + left_padding, height + top_padding + 2, color=color, ) cur_h = ph for img in image_list: await A.apaste(img, (pw, cur_h), True) cur_h += img.h + line_height return A class BlackWord(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" plant_text = fields.TextField() """检测文本""" black_word = fields.TextField() """黑名单词语""" punish = fields.TextField(default="") """惩罚内容""" punish_level = fields.IntField() """惩罚等级""" create_time = fields.DatetimeField(auto_now_add=True) """创建时间""" class Meta: table = "black_word" table_description = "惩罚机制数据表" async def set_user_punish( cls, user_id: str, punish: str, black_word: Optional[str] = None, id_: Optional[int] = None, ) -> bool: """ 说明: 设置处罚 参数: :param user_id: 用户id :param punish: 处罚 :param black_word: 黑名单词汇 :param id_: 记录下标 """ user = None if (not black_word and id_ is None) or not punish: return False if black_word: user = ( await cls.filter(user_id=user_id, black_word=black_word, punish="") .order_by("id") .first() ) elif id_ is not None: user_list = await cls.filter(user_id=user_id).order_by("id").all() if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)): return False user = user_list[id_] if not user: return False user.punish = f"{user.punish}{punish} " await user.save(update_fields=["punish"]) return True async def get_user_count( cls, user_id: str, days: int = 7, punish_level: Optional[int] = None ) -> int: """ 说明: 获取用户规定周期内的犯事次数 参数: :param user_id: 用户id :param days: 周期天数 :param punish_level: 惩罚等级 """ query = cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), punish_level__not_in=[-1], ) if punish_level is not None: query = query.filter(punish_level=punish_level) return await query.count() async def get_user_punish_level(cls, user_id: str, days: int = 7) -> Optional[int]: """ 说明: 获取用户最近一次的惩罚记录等级 参数: :param user_id: 用户id :param days: 周期天数 """ if ( user := await cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), ) .order_by("id") .first() ): return user.punish_level return None async def get_black_data( cls, user_id: Optional[str], group_id: Optional[str], date: Optional[datetime], date_type: str = "=", ) -> List["BlackWord"]: """ 说明: 通过指定条件查询数据 参数: :param user_id: 用户id :param group_id: 群号 :param date: 日期 :param date_type: 日期查询类型 """ query = cls if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if date: if date_type == "=": query = query.filter( create_time__range=[date, date + timedelta(days=1)] ) elif date_type == ">": query = query.filter(create_time__gte=date) elif date_type == "<": query = query.filter(create_time__lte=date) return await query.all().order_by("id") # type: ignore async def _run_script(cls): return [ "ALTER TABLE black_word RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE black_word ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE black_word ALTER COLUMN group_id TYPE character varying(255);", ] The provided code snippet includes necessary dependencies for implementing the `show_black_text_image` function. Write a Python function `async def show_black_text_image( bot: Bot, user_id: Optional[str], group_id: Optional[str], date: Optional[datetime], data_type: str = "=", ) -> BuildImage` to solve the following problem: 展示记录名单 :param bot: bot :param user: 用户qq :param group_id: 群聊 :param date: 日期 :param data_type: 日期搜索类型 :return: Here is the function: async def show_black_text_image( bot: Bot, user_id: Optional[str], group_id: Optional[str], date: Optional[datetime], data_type: str = "=", ) -> BuildImage: """ 展示记录名单 :param bot: bot :param user: 用户qq :param group_id: 群聊 :param date: 日期 :param data_type: 日期搜索类型 :return: """ data = await BlackWord.get_black_data(user_id, group_id, date, data_type) A = BuildImage(0, 0, color="#f9f6f2", font_size=20) image_list = [] friend_str = await bot.get_friend_list() id_str = "" uname_str = "" uid_str = "" gid_str = "" plant_text_str = "" black_word_str = "" punish_str = "" punish_level_str = "" create_time_str = "" for i, x in enumerate(data): try: if x.group_id: user_name = ( await bot.get_group_member_info( group_id=int(x.group_id), user_id=int(x.user_id) ) )["card"] else: user_name = [ u["nickname"] for u in friend_str if u["user_id"] == int(x.user_id) ][0] except Exception as e: logger.warning( f"show_black_text_image 获取 USER {x.user_id} user_name 失败", e=e ) user_name = x.user_id id_str += f"{i}\n" uname_str += f"{user_name}\n" uid_str += f"{x.user_id}\n" gid_str += f"{x.group_id}\n" plant_text = " ".join(x.plant_text.split("\n")) if A.getsize(plant_text)[0] > 200: plant_text = plant_text[:20] + "..." plant_text_str += f"{plant_text}\n" black_word_str += f"{x.black_word}\n" punish_str += f"{x.punish}\n" punish_level_str += f"{x.punish_level}\n" create_time_str += f"{x.create_time.replace(microsecond=0)}\n" _tmp_img = BuildImage(0, 0, font_size=35, font="CJGaoDeGuo.otf") for s, type_ in [ (id_str, "Id"), (uname_str, "昵称"), (uid_str, "UID"), (gid_str, "GID"), (plant_text_str, "文本"), (black_word_str, "检测"), (punish_str, "惩罚"), (punish_level_str, "等级"), (create_time_str, "记录日期"), ]: img = await text2image(s, color="#f9f6f2", _add_height=2.1) w = _tmp_img.getsize(type_)[0] if _tmp_img.getsize(type_)[0] > img.w else img.w A = BuildImage(w + 11, img.h + 50, color="#f9f6f2", font_size=35, font="CJGaoDeGuo.otf") await A.atext((10, 10), type_) await A.apaste(img, (0, 50)) image_list.append(A) horizontal_line = [] w, h = 0, 0 for img in image_list: w += img.w + 20 h = img.h if img.h > h else h horizontal_line.append(img.w) A = BuildImage(w, h, color="#f9f6f2") current_w = 0 for img in image_list: await A.apaste(img, (current_w, 0)) current_w += img.w + 20 return A
展示记录名单 :param bot: bot :param user: 用户qq :param group_id: 群聊 :param date: 日期 :param data_type: 日期搜索类型 :return:
188,306
from datetime import datetime from typing import Optional from nonebot.adapters.onebot.v11 import Bot from services.log import logger from utils.image_utils import BuildImage, text2image from .model import BlackWord from .utils import Config, _get_punish class BlackWord(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" plant_text = fields.TextField() """检测文本""" black_word = fields.TextField() """黑名单词语""" punish = fields.TextField(default="") """惩罚内容""" punish_level = fields.IntField() """惩罚等级""" create_time = fields.DatetimeField(auto_now_add=True) """创建时间""" class Meta: table = "black_word" table_description = "惩罚机制数据表" async def set_user_punish( cls, user_id: str, punish: str, black_word: Optional[str] = None, id_: Optional[int] = None, ) -> bool: """ 说明: 设置处罚 参数: :param user_id: 用户id :param punish: 处罚 :param black_word: 黑名单词汇 :param id_: 记录下标 """ user = None if (not black_word and id_ is None) or not punish: return False if black_word: user = ( await cls.filter(user_id=user_id, black_word=black_word, punish="") .order_by("id") .first() ) elif id_ is not None: user_list = await cls.filter(user_id=user_id).order_by("id").all() if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)): return False user = user_list[id_] if not user: return False user.punish = f"{user.punish}{punish} " await user.save(update_fields=["punish"]) return True async def get_user_count( cls, user_id: str, days: int = 7, punish_level: Optional[int] = None ) -> int: """ 说明: 获取用户规定周期内的犯事次数 参数: :param user_id: 用户id :param days: 周期天数 :param punish_level: 惩罚等级 """ query = cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), punish_level__not_in=[-1], ) if punish_level is not None: query = query.filter(punish_level=punish_level) return await query.count() async def get_user_punish_level(cls, user_id: str, days: int = 7) -> Optional[int]: """ 说明: 获取用户最近一次的惩罚记录等级 参数: :param user_id: 用户id :param days: 周期天数 """ if ( user := await cls.filter( user_id=user_id, create_time__gte=datetime.now() - timedelta(days=days), ) .order_by("id") .first() ): return user.punish_level return None async def get_black_data( cls, user_id: Optional[str], group_id: Optional[str], date: Optional[datetime], date_type: str = "=", ) -> List["BlackWord"]: """ 说明: 通过指定条件查询数据 参数: :param user_id: 用户id :param group_id: 群号 :param date: 日期 :param date_type: 日期查询类型 """ query = cls if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if date: if date_type == "=": query = query.filter( create_time__range=[date, date + timedelta(days=1)] ) elif date_type == ">": query = query.filter(create_time__gte=date) elif date_type == "<": query = query.filter(create_time__lte=date) return await query.all().order_by("id") # type: ignore async def _run_script(cls): return [ "ALTER TABLE black_word RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE black_word ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE black_word ALTER COLUMN group_id TYPE character varying(255);", ] async def _get_punish( id_: int, user_id: str, group_id: Optional[str] = None ) -> Optional[Union[int, str]]: """ 通过id_获取惩罚 :param id_: id :param user_id: 用户id :param group_id: 群号 """ bot = get_bot() # 忽略的群聊 # _ignore_group = Config.get_config("black_word", "IGNORE_GROUP") # 处罚 id 4 ban 时间:int,List[int] ban_3_duration = Config.get_config("black_word", "BAN_3_DURATION") or 7 # 处罚 id 4 ban 时间:int,List[int] ban_4_duration = Config.get_config("black_word", "BAN_4_DURATION") or 360 # 口头警告内容 warning_result = Config.get_config("black_word", "WARNING_RESULT") if user := await GroupInfoUser.get_or_none(user_id=user_id, group_id=group_id): uname = user.user_name else: uname = user_id # 永久ban if id_ == 1: if str(user_id) not in bot.config.superusers: await BanUser.ban(user_id, 10, 99999999) await send_msg( user_id, group_id, f"BlackWordChecker 永久ban USER {uname}({user_id})" ) logger.info(f"BlackWord 永久封禁 USER {user_id}...") # 删除好友(有的话 elif id_ == 2: if str(user_id) not in bot.config.superusers: try: await bot.delete_friend(user_id=user_id) await send_msg( user_id, group_id, f"BlackWordChecker 删除好友 USER {uname}({user_id})" ) logger.info(f"BlackWord 删除好友 {user_id}...") except ActionFailed: pass # 封禁用户指定时间,默认7天 elif id_ == 3: if isinstance(ban_3_duration, list): ban_3_duration = random.randint(ban_3_duration[0], ban_3_duration[1]) await BanUser.ban(user_id, 9, ban_4_duration * 60 * 60 * 24) await send_msg( user_id, group_id, f"BlackWordChecker 对用户 USER {uname}({user_id}) 进行封禁 {ban_3_duration} 天处罚。", ) logger.info(f"BlackWord 封禁 USER {uname}({user_id}) {ban_3_duration} 天...") return ban_3_duration # 封禁用户指定时间,默认360分钟 elif id_ == 4: if isinstance(ban_4_duration, list): ban_4_duration = random.randint(ban_4_duration[0], ban_4_duration[1]) await BanUser.ban(user_id, 9, ban_4_duration * 60) await send_msg( user_id, group_id, f"BlackWordChecker 对用户 USER {uname}({user_id}) 进行封禁 {ban_4_duration} 分钟处罚。", ) logger.info(f"BlackWord 封禁 USER {uname}({user_id}) {ban_4_duration} 分钟...") return ban_4_duration # 口头警告 elif id_ == 5: if group_id: await bot.send_group_msg(group_id=int(group_id), message=warning_result) else: await bot.send_private_msg(user_id=int(user_id), message=warning_result) logger.info(f"BlackWord 口头警告 USER {user_id}") return warning_result return None The provided code snippet includes necessary dependencies for implementing the `set_user_punish` function. Write a Python function `async def set_user_punish(user_id: str, id_: int, punish_level: int) -> str` to solve the following problem: 设置惩罚 :param user_id: 用户id :param id_: 记录下标 :param punish_level: 惩罚等级 Here is the function: async def set_user_punish(user_id: str, id_: int, punish_level: int) -> str: """ 设置惩罚 :param user_id: 用户id :param id_: 记录下标 :param punish_level: 惩罚等级 """ result = await _get_punish(punish_level, user_id) punish = { 1: "永久ban", 2: "删除好友", 3: f"ban {result} 天", 4: f"ban {result} 分钟", 5: "口头警告" } if await BlackWord.set_user_punish(user_id, punish[punish_level], id_=id_): return f"已对 USER {user_id} 进行 {punish[punish_level]} 处罚。" else: return "操作失败,可能未找到用户,id或敏感词"
设置惩罚 :param user_id: 用户id :param id_: 记录下标 :param punish_level: 惩罚等级
188,307
The provided code snippet includes necessary dependencies for implementing the `cn2py` function. Write a Python function `def cn2py(word) -> str` to solve the following problem: 保存声调,防止出现类似方舟干员红与吽拼音相同声调不同导致红照片无法保存的问题 Here is the function: def cn2py(word) -> str: """保存声调,防止出现类似方舟干员红与吽拼音相同声调不同导致红照片无法保存的问题""" temp = "" for i in pypinyin.pinyin(word, style=pypinyin.Style.TONE3): temp += "".join(i) return temp
保存声调,防止出现类似方舟干员红与吽拼音相同声调不同导致红照片无法保存的问题
188,308
import platform import pypinyin from pathlib import Path from PIL.ImageFont import FreeTypeFont from PIL import Image, ImageDraw, ImageFont from PIL.Image import Image as IMG from configs.path_config import FONT_PATH dir_path = Path(__file__).parent.absolute() ibited_str(name: str) -> str: if platform.system().lower() == "windows": tmp = "" for i in name: if i not in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]: tmp += i name = tmp else: name = name.replace("/", "\\") return name def load_font(fontname: str = "msyh.ttf", fontsize: int = 16) -> FreeTypeFont: return ImageFont.truetype( str(FONT_PATH / f"{fontname}"), fontsize, encoding="utf-8" ) def circled_number(num: int) -> IMG: font = load_font(fontsize=450) text = str(num) text_w = font.getsize(text)[0] w = 240 + text_w w = w if w >= 500 else 500 img = Image.new("RGBA", (w, 500)) draw = ImageDraw.Draw(img) draw.ellipse(((0, 0), (500, 500)), fill="red") draw.ellipse(((w - 500, 0), (w, 500)), fill="red") draw.rectangle(((250, 0), (w - 250, 500)), fill="red") draw.text( (120, -60), text, font=font, fill="white", stroke_width=10, stroke_fill="white", ) return img def remove_prohibited_str(name: str) -> str: if platform.system().lower() == "windows": tmp = "" for i in name: if i not in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]: tmp += i name = tmp else: name = name.replace("/", "\\") return name
null
188,309
def circled_number(num: int) -> IMG: font = load_font(fontsize=450) text = str(num) text_w = font.getsize(text)[0] w = 240 + text_w w = w if w >= 500 else 500 img = Image.new("RGBA", (w, 500)) draw = ImageDraw.Draw(img) draw.ellipse(((0, 0), (500, 500)), fill="red") draw.ellipse(((w - 500, 0), (w, 500)), fill="red") draw.rectangle(((250, 0), (w - 250, 500)), fill="red") draw.text( (120, -60), text, font=font, fill="white", stroke_width=10, stroke_fill="white", ) return img
null
188,310
from nonebot.internal.rule import Rule from configs.config import Config def rule(game) -> Rule: async def _rule() -> bool: return Config.get_config("draw_card", game.config_name, True) return Rule(_rule)
null
188,311
from pathlib import Path import nonebot from nonebot.log import logger from pydantic import BaseModel, Extra, ValidationError from configs.config import Config as AConfig from configs.path_config import DATA_PATH, IMAGE_PATH class Config(BaseModel, extra=Extra.ignore): config_path = DATA_PATH / "draw_card" / "draw_card_config" / "draw_card_config.json" draw_config: Config = Config() def check_config(): global draw_config if not config_path.exists(): config_path.parent.mkdir(parents=True, exist_ok=True) draw_config = Config() logger.warning("draw_card:配置文件不存在,已重新生成配置文件.....") else: with config_path.open("r", encoding="utf8") as fp: data = json.load(fp) try: draw_config = Config.parse_obj({**data}) except ValidationError: draw_config = Config() logger.warning("draw_card:配置文件格式错误,已重新生成配置文件.....") with config_path.open("w", encoding="utf8") as fp: json.dump( draw_config.dict(), fp, indent=4, ensure_ascii=False, )
null
188,312
from typing import Optional from utils.data_utils import init_rank from utils.image_utils import BuildMat from .model import RussianUser async def init_rank( title: str, all_user_id: List[str], all_user_data: List[Union[int, float]], group_id: int, total_count: int = 10, ) -> BuildMat: """ 说明: 初始化通用的数据排行榜 参数: :param title: 排行榜标题 :param all_user_id: 所有用户的qq号 :param all_user_data: 所有用户需要排行的对应数据 :param group_id: 群号,用于从数据库中获取该用户在此群的昵称 :param total_count: 获取人数总数 """ _uname_lst = [] _num_lst = [] for i in range(min(len(all_user_id), total_count)): _max = max(all_user_data) max_user_id = all_user_id[all_user_data.index(_max)] all_user_id.remove(max_user_id) all_user_data.remove(_max) if user := await GroupInfoUser.get_or_none( user_id=str(max_user_id), group_id=str(group_id) ): user_name = user.user_name else: user_name = f"{max_user_id}" _uname_lst.append(user_name) _num_lst.append(_max) _uname_lst.reverse() _num_lst.reverse() return await asyncio.get_event_loop().run_in_executor( None, _init_rank_graph, title, _uname_lst, _num_lst ) class BuildMat: """ 针对 折线图/柱状图,基于 BuildImage 编写的 非常难用的 自定义画图工具 目前仅支持 正整数 """ def __init__( self, y: List[int], mat_type: str = "line", *, x_name: Optional[str] = None, y_name: Optional[str] = None, x_index: List[Union[str, int, float]] = None, y_index: List[Union[str, int, float]] = None, x_min_spacing: Optional[int] = None, x_rotate: int = 0, title: Optional[str] = None, size: Tuple[int, int] = (1000, 1000), font: str = "msyh.ttf", font_size: Optional[int] = None, display_num: bool = False, is_grid: bool = False, background: Optional[List[str]] = None, background_filler_type: Optional[str] = "center", bar_color: Optional[List[Union[str, Tuple[int, int, int]]]] = None, ): """ 说明: 初始化 BuildMat 参数: :param y: 坐标值 :param mat_type: 图像类型 可能的值:[line]: 折线图,[bar]: 柱状图,[barh]: 横向柱状图 :param x_name: 横坐标名称 :param y_name: 纵坐标名称 :param x_index: 横坐标值 :param y_index: 纵坐标值 :param x_min_spacing: x轴最小间距 :param x_rotate: 横坐标旋转角度 :param title: 标题 :param size: 图像大小,建议默认 :param font: 字体 :param font_size: 字体大小,建议默认 :param display_num: 是否显示数值 :param is_grid: 是否添加栅格 :param background: 背景图片 :param background_filler_type: 图像填充类型 :param bar_color: 柱状图颜色,位 ['*'] 时替换位彩虹随机色 """ self.mat_type = mat_type self.markImg = None self._check_value(y, y_index) self.w = size[0] self.h = size[1] self.y = y self.x_name = x_name self.y_name = y_name self.x_index = x_index self.y_index = y_index self.x_min_spacing = x_min_spacing self.x_rotate = x_rotate self.title = title self.font = font self.display_num = display_num self.is_grid = is_grid self.background = background self.background_filler_type = background_filler_type self.bar_color = bar_color if bar_color else [(0, 0, 0)] self.size = size self.padding_w = 120 self.padding_h = 120 self.line_length = 760 self._deviation = 0.905 self._color = {} if not font_size: self.font_size = int(25 * (1 - len(x_index) / 100)) else: self.font_size = font_size if self.bar_color == ["*"]: self.bar_color = [ "#FF0000", "#FF7F00", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#8B00FF", ] if not x_index: raise ValueError("缺少 x_index [横坐标值]...") if x_min_spacing: self._x_interval = x_min_spacing else: self._x_interval = int((self.line_length - 70) / len(x_index)) self._bar_width = int(30 * (1 - (len(x_index) + 10) / 100)) # 没有 y_index 时自动生成 if not y_index: _y_index = [] _max_value = int(max(y)) _max_value = ceil( _max_value / eval("1" + "0" * (len(str(_max_value)) - 1)) ) * eval("1" + "0" * (len(str(_max_value)) - 1)) _max_value = _max_value if _max_value >= 10 else 100 _step = int(_max_value / 10) for i in range(_step, _max_value + _step, _step): _y_index.append(i) self.y_index = _y_index self._p = self.line_length / max(self.y_index) self._y_interval = int((self.line_length - 70) / len(self.y_index)) def gen_graph(self): """ 说明: 生成图像 """ self.markImg = self._init_graph( x_name=self.x_name, y_name=self.y_name, x_index=self.x_index, y_index=self.y_index, font_size=self.font_size, is_grid=self.is_grid, ) if self.mat_type == "line": self._gen_line_graph(y=self.y, display_num=self.display_num) elif self.mat_type == "bar": self._gen_bar_graph(y=self.y, display_num=self.display_num) elif self.mat_type == "barh": self._gen_bar_graph(y=self.y, display_num=self.display_num, is_barh=True) def set_y(self, y: List[int]): """ 说明: 给坐标点设置新值 参数: :param y: 坐标点 """ self._check_value(y, self.y_index) self.y = y def set_y_index(self, y_index: List[Union[str, int, float]]): """ 说明: 设置y轴坐标值 参数: :param y_index: y轴坐标值 """ self._check_value(self.y, y_index) self.y_index = y_index def set_title(self, title: str, color: Optional[Union[str, Tuple[int, int, int]]]): """ 说明: 设置标题 参数: :param title: 标题 :param color: 字体颜色 """ self.title = title if color: self._color["title"] = color def set_background( self, background: Optional[List[str]], type_: Optional[str] = None ): """ 说明: 设置背景图片 参数: :param background: 图片路径列表 :param type_: 填充类型 """ self.background = background self.background_filler_type = type_ if type_ else self.background_filler_type def show(self): """ 说明: 展示图像 """ self.markImg.show() def pic2bs4(self) -> str: """ 说明: 转base64 """ return self.markImg.pic2bs4() def resize(self, ratio: float = 0.9): """ 说明: 调整图像大小 参数: :param ratio: 比例 """ self.markImg.resize(ratio) def save(self, path: Union[str, Path]): """ 说明: 保存图片 参数: :param path: 路径 """ self.markImg.save(path) def _check_value( self, y: List[int], y_index: List[Union[str, int, float]] = None, x_index: List[Union[str, int, float]] = None, ): """ 说明: 检查值合法性 参数: :param y: 坐标值 :param y_index: y轴坐标值 :param x_index: x轴坐标值 """ if y_index: _value = x_index if self.mat_type == "barh" else y_index if max(y) > max(y_index): raise ValueError("坐标点的值必须小于y轴坐标的最大值...") i = -9999999999 for y in y_index: if y > i: i = y else: raise ValueError("y轴坐标值必须有序...") def _gen_line_graph( self, y: List[Union[int, float]], display_num: bool = False, ): """ 说明: 生成折线图 参数: :param y: 坐标点 :param display_num: 显示该点的值 """ _black_point = BuildImage(11, 11, color=random.choice(self.bar_color)) _black_point.circle() x_interval = self._x_interval current_w = self.padding_w + x_interval current_h = self.padding_h + self.line_length for i in range(len(y)): if display_num: w = int(self.markImg.getsize(str(y[i]))[0] / 2) self.markImg.text( ( current_w - w, current_h - int(y[i] * self._p * self._deviation) - 25 - 5, ), f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}", ) if i != len(y) - 1: self.markImg.line( ( current_w, current_h - int(y[i] * self._p * self._deviation), current_w + x_interval, current_h - int(y[i + 1] * self._p * self._deviation), ), fill=(0, 0, 0), width=2, ) self.markImg.paste( _black_point, ( current_w - 3, current_h - int(y[i] * self._p * self._deviation) - 3, ), True, ) current_w += x_interval def _gen_bar_graph( self, y: List[Union[int, float]], display_num: bool = False, is_barh: bool = False, ): """ 说明: 生成柱状图 参数: :param y: 坐标值 :param display_num: 是否显示数值 :param is_barh: 横柱状图 """ _interval = self._x_interval if is_barh: current_h = self.padding_h + self.line_length - _interval current_w = self.padding_w else: current_w = self.padding_w + _interval current_h = self.padding_h + self.line_length for i in range(len(y)): # 画出显示数字 if display_num: # 横柱状图 if is_barh: font_h = self.markImg.getsize(str(y[i]))[1] self.markImg.text( ( self.padding_w + int(y[i] * self._p * self._deviation) + 2 + 5, current_h - int(font_h / 2) - 1, ), f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}", ) else: w = int(self.markImg.getsize(str(y[i]))[0] / 2) self.markImg.text( ( current_w - w, current_h - int(y[i] * self._p * self._deviation) - 25, ), f"{y[i]:.2f}" if isinstance(y[i], float) else f"{y[i]}", ) if i != len(y): bar_color = random.choice(self.bar_color) if is_barh: A = BuildImage( int(y[i] * self._p * self._deviation), self._bar_width, color=bar_color, ) self.markImg.paste( A, ( current_w + 2, current_h - int(self._bar_width / 2), ), ) else: A = BuildImage( self._bar_width, int(y[i] * self._p * self._deviation), color=bar_color, ) self.markImg.paste( A, ( current_w - int(self._bar_width / 2), current_h - int(y[i] * self._p * self._deviation), ), ) if is_barh: current_h -= _interval else: current_w += _interval def _init_graph( self, x_name: Optional[str] = None, y_name: Optional[str] = None, x_index: List[Union[str, int, float]] = None, y_index: List[Union[str, int, float]] = None, font_size: Optional[int] = None, is_grid: bool = False, ) -> BuildImage: """ 说明: 初始化图像,生成xy轴 参数: :param x_name: x轴名称 :param y_name: y轴名称 :param x_index: x轴坐标值 :param y_index: y轴坐标值 :param is_grid: 添加栅格 """ padding_w = self.padding_w padding_h = self.padding_h line_length = self.line_length background = random.choice(self.background) if self.background else None if self.x_min_spacing: length = (len(self.x_index) + 1) * self.x_min_spacing if 2 * padding_w + length > self.w: self.w = 2 * padding_w + length background = None A = BuildImage( self.w, self.h, font_size=font_size, font=self.font, background=background ) if background: _tmp = BuildImage(self.w, self.h) _tmp.transparent(2) A.paste(_tmp, alpha=True) if self.title: title = BuildImage( 0, 0, plain_text=self.title, color=(255, 255, 255, 0), font_size=35, font_color=self._color.get("title"), font=self.font, ) A.paste(title, (0, 25), True, "by_width") A.line( ( padding_w, padding_h + line_length, self.w - padding_w, padding_h + line_length, ), (0, 0, 0), 2, ) A.line( ( padding_w, padding_h, padding_w, padding_h + line_length, ), (0, 0, 0), 2, ) _interval = self._x_interval if self.mat_type == "barh": tmp = x_index x_index = y_index y_index = tmp _interval = self._y_interval current_w = padding_w + _interval _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 = 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 = BuildImage( 0, 0, plain_text=f"{_x}", font_size=self.font_size, color=(255, 255, 255, 0), font=self.font, ) text.rotate(self.x_rotate, True) A.paste(text, (current_w - w, padding_h + line_length + 10), alpha=True) current_w += _interval 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 = BuildImage(0, 0, font_size=self.font_size, font=self.font) for _y in y_index: _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 = BuildImage( 0, 0, plain_text=f"{_y}", font_size=self.font_size, color=(255, 255, 255, 0), font=self.font, ) idx = 0 while text.size[0] > self.padding_w - 10 and idx < 3: text = BuildImage( 0, 0, plain_text=f"{_y}", font_size=int(self.font_size * 0.75), color=(255, 255, 255, 0), font=self.font, ) w, _ = text.getsize(f"{_y}") idx += 1 A.paste(text, (padding_w - w - 10, current_h - h), alpha=True) current_h -= _interval if x_name: A.text((int(padding_w / 2), int(padding_w / 2)), x_name) if y_name: A.text( ( int(padding_w + line_length + 50 - A.getsize(y_name)[0]), int(padding_h + line_length + 50 + x_rotate_height), ), y_name, ) return A class RussianUser(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255) """群聊id""" win_count = fields.IntField(default=0) """胜利次数""" fail_count = fields.IntField(default=0) """失败次数""" make_money = fields.IntField(default=0) """赢得金币""" lose_money = fields.IntField(default=0) """输得金币""" winning_streak = fields.IntField(default=0) """当前连胜""" losing_streak = fields.IntField(default=0) """当前连败""" max_winning_streak = fields.IntField(default=0) """最大连胜""" max_losing_streak = fields.IntField(default=0) """最大连败""" class Meta: table = "russian_users" table_description = "俄罗斯轮盘数据表" unique_together = ("user_id", "group_id") async def add_count(cls, user_id: str, group_id: str, itype: str): """ 说明: 添加用户输赢次数 说明: :param user_id: qq号 :param group_id: 群号 :param itype: 输或赢 'win' or 'lose' """ user, _ = await cls.get_or_create(user_id=user_id, group_id=group_id) if itype == "win": _max = ( user.max_winning_streak if user.max_winning_streak > user.winning_streak + 1 else user.winning_streak + 1 ) user.win_count = user.win_count + 1 user.winning_streak = user.winning_streak + 1 user.losing_streak = 0 user.max_winning_streak = _max await user.save( update_fields=[ "win_count", "winning_streak", "losing_streak", "max_winning_streak", ] ) elif itype == "lose": _max = ( user.max_losing_streak if user.max_losing_streak > user.losing_streak + 1 else user.losing_streak + 1 ) user.fail_count = user.fail_count + 1 user.losing_streak = user.losing_streak + 1 user.winning_streak = 0 user.max_losing_streak = _max await user.save( update_fields=[ "fail_count", "winning_streak", "losing_streak", "max_losing_streak", ] ) async def money(cls, user_id: str, group_id: str, itype: str, count: int) -> bool: """ 说明: 添加用户输赢金钱 参数: :param user_id: qq号 :param group_id: 群号 :param itype: 输或赢 'win' or 'lose' :param count: 金钱数量 """ user, _ = await cls.get_or_create(user_id=str(user_id), group_id=group_id) if itype == "win": user.make_money = user.make_money + count elif itype == "lose": user.lose_money = user.lose_money + count await user.save(update_fields=["make_money", "lose_money"]) async def _run_script(cls): return [ "ALTER TABLE russian_users RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE russian_users ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE russian_users ALTER COLUMN group_id TYPE character varying(255);", ] async def rank(group_id: int, itype: str, num: int) -> Optional[BuildMat]: all_users = await RussianUser.filter(group_id=group_id).all() all_user_id = [user.user_id for user in all_users] if itype == "win_rank": rank_name = "胜场排行榜" all_user_data = [user.win_count for user in all_users] elif itype == "lose_rank": rank_name = "败场排行榜" all_user_data = [user.fail_count for user in all_users] elif itype == "make_money": rank_name = "赢取金币排行榜" all_user_data = [user.make_money for user in all_users] elif itype == "spend_money": rank_name = "输掉金币排行榜" all_user_data = [user.lose_money for user in all_users] elif itype == "max_winning_streak": rank_name = "最高连胜排行榜" all_user_data = [user.max_winning_streak for user in all_users] else: rank_name = "最高连败排行榜" all_user_data = [user.max_losing_streak for user in all_users] rst = None if all_users: rst = await init_rank(rank_name, all_user_id, all_user_data, group_id, num) return rst
null
188,313
from bs4 import BeautifulSoup from configs.config import Config from utils.http_utils import AsyncHttpx url = "http://www.eclzz.ink" async def get_download_link(_url: str) -> str: """ 获取资源下载地址 :param _url: 链接 """ text = (await AsyncHttpx.get(f"{url}{_url}")).text soup = BeautifulSoup(text, "lxml") return soup.find("a", {"id": "down-url"})["href"] class AsyncHttpx: proxy = {"http://": get_local_proxy(), "https://": get_local_proxy()} async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: """ 说明: Get 参数: :param url: url :param params: params :param headers: 请求头 :param cookies: cookies :param verify: verify :param use_proxy: 使用默认代理 :param proxy: 指定代理 :param timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.get( url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, 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 timeout: 超时时间 """ if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None async with httpx.AsyncClient(proxies=proxy_, verify=verify) as client: return await client.post( url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: """ 说明: 下载文件 参数: :param url: url :param path: 存储路径 :param params: params :param verify: verify :param use_proxy: 使用代理 :param proxy: 指定代理 :param headers: 请求头 :param cookies: cookies :param timeout: 超时时间 :param stream: 是否使用流式下载(流式写入+进度条,适用于下载大文件) """ if isinstance(path, str): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) try: for _ in range(3): if not stream: try: content = ( await cls.get( url, params=params, headers=headers, cookies=cookies, 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()}") return True except (TimeoutError, ConnectTimeout): pass else: if not headers: headers = get_user_agent() proxy_ = proxy if proxy else cls.proxy if use_proxy else None try: async with httpx.AsyncClient( proxies=proxy_, verify=verify ) as client: async with client.stream( "GET", url, params=params, headers=headers, cookies=cookies, timeout=timeout, **kwargs, ) as response: logger.info( f"开始下载 {path.name}.. Path: {path.absolute()}" ) async with aiofiles.open(path, "wb") as wf: total = int(response.headers["Content-Length"]) with rich.progress.Progress( rich.progress.TextColumn(path.name), "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(bar_width=None), rich.progress.DownloadColumn(), rich.progress.TransferSpeedColumn(), ) as progress: download_task = progress.add_task( "Download", total=total ) async for chunk in response.aiter_bytes(): await wf.write(chunk) await wf.flush() progress.update( download_task, completed=response.num_bytes_downloaded, ) logger.info(f"下载 {url} 成功.. Path:{path.absolute()}") return True except (TimeoutError, ConnectTimeout): pass else: logger.error(f"下载 {url} 下载超时.. Path:{path.absolute()}") except Exception as e: logger.error(f"下载 {url} 错误 Path:{path.absolute()}", e=e) return False async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, 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: 超时时间 """ if n := len(url_list) != len(path_list): raise UrlPathNumberNotEqual( f"Url数量与Path数量不对等,Url:{len(url_list)},Path:{len(path_list)}" ) if limit_async_number and n > limit_async_number: m = float(n) / limit_async_number x = 0 j = limit_async_number _split_url_list = [] _split_path_list = [] for _ in range(int(m)): _split_url_list.append(url_list[x:j]) _split_path_list.append(path_list[x:j]) x += limit_async_number j += limit_async_number if int(m) < m: _split_url_list.append(url_list[j:]) _split_path_list.append(path_list[j:]) else: _split_url_list = [url_list] _split_path_list = [path_list] tasks = [] result_ = [] for x, y in zip(_split_url_list, _split_path_list): for url, path in zip(x, y): tasks.append( asyncio.create_task( cls.download_file( url, path, params=params, headers=headers, cookies=cookies, use_proxy=use_proxy, timeout=timeout, proxy=proxy, **kwargs, ) ) ) _x = await asyncio.gather(*tasks) result_ = result_ + list(_x) tasks.clear() return result_ The provided code snippet includes necessary dependencies for implementing the `get_bt_info` function. Write a Python function `async def get_bt_info(keyword: str, page: int)` to solve the following problem: 获取资源信息 :param keyword: 关键词 :param page: 页数 Here is the function: async def get_bt_info(keyword: str, page: int): """ 获取资源信息 :param keyword: 关键词 :param page: 页数 """ text = (await AsyncHttpx.get(f"{url}/s/{keyword}_rel_{page}.html", timeout=5)).text if "大约0条结果" in text: return soup = BeautifulSoup(text, "lxml") item_lst = soup.find_all("div", {"class": "search-item"}) bt_max_num = Config.get_config("bt", "BT_MAX_NUM") or 10 bt_max_num = bt_max_num if bt_max_num < len(item_lst) else len(item_lst) for item in item_lst[:bt_max_num]: divs = item.find_all("div") title = ( str(divs[0].find("a").text).replace("<em>", "").replace("</em>", "").strip() ) spans = divs[2].find_all("span") type_ = spans[0].text create_time = spans[1].find("b").text file_size = spans[2].find("b").text link = await get_download_link(divs[0].find("a")["href"]) yield title, type_, create_time, file_size, link
获取资源信息 :param keyword: 关键词 :param page: 页数
188,314
from io import BytesIO from typing import List import imagehash from nonebot.adapters.onebot.v11 import Bot, MessageEvent from nonebot.typing import T_State from PIL import Image from services.log import logger from utils.depends import ImageList from utils.http_utils import AsyncHttpx from utils.utils import get_message_at, get_message_img, get_message_text from ._model import WordBank class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: class AsyncHttpx: async def get( cls, url: str, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: async def post( cls, url: str, *, data: Optional[Dict[str, str]] = None, content: Any = None, files: Any = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, json: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> Response: async def download_file( cls, url: str, path: Union[str, Path], *, params: Optional[Dict[str, str]] = None, verify: bool = True, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, stream: bool = False, **kwargs, ) -> bool: async def gather_download_file( cls, url_list: List[str], path_list: List[Union[str, Path]], *, limit_async_number: Optional[int] = None, params: Optional[Dict[str, str]] = None, use_proxy: bool = True, proxy: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, cookies: Optional[Dict[str, str]] = None, timeout: Optional[int] = 30, **kwargs, ) -> List[bool]: { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def get_message_at(data: Union[str, Message]) -> List[int]: def get_message_img(data: Union[str, Message]) -> List[str]: def get_message_text(data: Union[str, Message]) -> str: class WordBank(Model): async def exists( cls, user_id: Optional[str], group_id: Optional[str], problem: str, answer: Optional[str], word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> bool: async def add_problem_answer( cls, user_id: str, group_id: Optional[str], word_scope: int, word_type: int, problem: Union[str, Message], answer: Union[str, Message], to_me_nickname: Optional[str] = None, ): async def _answer2format( cls, answer: Union[str, Message], user_id: str, group_id: Optional[str] ) -> Tuple[str, List[Any]]: async def _format2answer( cls, problem: str, answer: Union[str, Message], user_id: int, group_id: int, query: Optional["WordBank"] = None, ) -> Union[str, Message]: async def check_problem( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Any]: async def get_answer( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Union[str, Message]]: async def get_problem_all_answer( cls, problem: str, index: Optional[int] = None, group_id: Optional[str] = None, word_scope: Optional[int] = 0, ) -> List[Union[str, Message]]: async def delete_group_problem( cls, problem: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): async def update_group_problem( cls, problem: str, replace_str: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): async def get_group_all_problem( cls, group_id: str ) -> List[Tuple[Any, Union[MessageSegment, str]]]: async def get_problem_by_scope(cls, word_scope: int): async def get_problem_by_type(cls, word_type: int): def _handle_problem(cls, msg_list: List["WordBank"]): async def _move( cls, user_id: str, group_id: Optional[str], problem: Union[str, Message], answer: Union[str, Message], placeholder: str, ): async def _run_script(cls): async def check( bot: Bot, event: MessageEvent, state: T_State, ) -> bool: text = get_message_text(event.message) img_list = get_message_img(event.message) problem = text if not text and len(img_list) == 1: try: r = await AsyncHttpx.get(img_list[0]) problem = str(imagehash.average_hash(Image.open(BytesIO(r.content)))) except Exception as e: logger.warning(f"获取图片失败", "词条检测", e=e) if get_message_at(event.message): temp = "" for seg in event.message: if seg.type == "at": temp += f"[at:{seg.data['qq']}]" elif seg.type == "text": temp += seg.data["text"] problem = temp if event.to_me and bot.config.nickname: if str(event.original_message).startswith("[CQ:at"): problem = f"[at:{bot.self_id}]" + problem else: if problem and bot.config.nickname: nickname = [ nk for nk in bot.config.nickname if str(event.original_message).startswith(nk) ] problem = nickname[0] + problem if nickname else problem if problem and (await WordBank.check_problem(event, problem) is not None): state["problem"] = problem return True return False
null
188,315
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank add_word = on_regex( r"^(全局|私聊)?添加词条\s*?(模糊|正则|图片)?问\s*?(\S*\s?\S*)\s*?答\s?(\S*)", priority=5, block=True ) def ImageList(msg: Optional[str] = None, contain_reply: bool = True) -> List[str]: def AtList(msg: Optional[str] = None, contain_reply: bool = True) -> List[int]: async def _( bot: Bot, event: MessageEvent, state: T_State, reg_group: Tuple[Any, ...] = RegexGroup(), img_list: List[str] = ImageList(), at_list: List[int] = AtList(), ): if ( isinstance(event, PrivateMessageEvent) and str(event.user_id) not in bot.config.superusers ): await add_word.finish("权限不足捏") word_scope, word_type, problem, answer = reg_group if not word_scope and isinstance(event, PrivateMessageEvent): word_scope = "私聊" if ( word_scope and word_scope in ["全局", "私聊"] and str(event.user_id) not in bot.config.superusers ): await add_word.finish("权限不足,无法添加该范围词条") if (not problem or not problem.strip()) and word_type != "图片": await add_word.finish("词条问题不能为空!") if (not answer or not answer.strip()) and not len(img_list) and not len(at_list): await add_word.finish("词条回答不能为空!") if word_type != "图片": state["problem_image"] = "YES" answer = event.message # 对at问题对额外处理 if at_list: is_first = True cur_p = None answer = "" problem = "" for index, seg in enumerate(event.message): r = re.search("添加词条(模糊|正则|图片)?问", str(seg)) if seg.type == "text" and r and is_first: is_first = False seg_ = str(seg).split(f"添加词条{r.group(1) or ''}问")[-1] cur_p = "problem" # 纯文本 if "答" in seg_: answer_index = seg_.index("答") problem = unescape(seg_[:answer_index]).strip() answer = unescape(seg_[answer_index + 1 :]).strip() cur_p = "answer" else: problem = unescape(seg_) continue if cur_p == "problem": if seg.type == "text" and "答" in str(seg): seg_ = str(seg) answer_index = seg_.index("答") problem += seg_[:answer_index] answer += seg_[answer_index + 1 :] cur_p = "answer" else: if seg.type == "at": problem += f"[at:{seg.data['qq']}]" else: problem += ( unescape(str(seg)).strip() if seg.type == "text" else seg ) else: if seg.type == "text": answer += unescape(str(seg)) else: answer += seg event.message[0] = event.message[0].data["text"].split("答", maxsplit=1)[-1].strip() state["word_scope"] = word_scope state["word_type"] = word_type state["problem"] = problem state["answer"] = answer
null
188,316
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank add_word = on_regex( r"^(全局|私聊)?添加词条\s*?(模糊|正则|图片)?问\s*?(\S*\s?\S*)\s*?答\s?(\S*)", priority=5, block=True ) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) scope2int = { "全局": 0, "群聊": 1, "私聊": 2, } type2int = { "精准": 0, "模糊": 1, "正则": 2, "图片": 3, } class WordBank(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" word_scope = fields.IntField(default=0) """生效范围 0: 全局 1: 群聊 2: 私聊""" word_type = fields.IntField(default=0) """词条类型 0: 完全匹配 1: 模糊 2: 正则 3: 图片""" status = fields.BooleanField() """词条状态""" problem = fields.TextField() """问题,为图片时使用图片hash""" answer = fields.TextField() """回答""" placeholder = fields.TextField(null=True) """占位符""" image_path = fields.TextField(null=True) """使用图片作为问题时图片存储的路径""" to_me = fields.CharField(255, null=True) """昵称开头时存储的昵称""" create_time = fields.DatetimeField(auto_now=True) """创建时间""" update_time = fields.DatetimeField(auto_now_add=True) """更新时间""" class Meta: table = "word_bank2" table_description = "词条数据库" async def exists( cls, user_id: Optional[str], group_id: Optional[str], problem: str, answer: Optional[str], word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> bool: """ 说明: 检测问题是否存在 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls.filter(problem=problem) if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if answer: query = query.filter(answer=answer) if word_type is not None: query = query.filter(word_type=word_type) if word_scope is not None: query = query.filter(word_scope=word_scope) return bool(await query.first()) async def add_problem_answer( cls, user_id: str, group_id: Optional[str], word_scope: int, word_type: int, problem: Union[str, Message], answer: Union[str, Message], to_me_nickname: Optional[str] = None, ): """ 说明: 添加或新增一个问答 参数: :param user_id: 用户id :param group_id: 群号 :param word_scope: 词条范围, :param word_type: 词条类型, :param problem: 问题 :param answer: 回答 :param to_me_nickname: at真寻名称 """ # 对图片做额外处理 image_path = None if word_type == 3: url = get_message_img(problem)[0] _file = ( path / "problem" / f"{group_id}" / f"{user_id}_{int(time.time())}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(url, _file) problem = str(get_img_hash(_file)) image_path = f"problem/{group_id}/{user_id}_{int(time.time())}.jpg" answer, _list = await cls._answer2format(answer, user_id, group_id) if not await cls.exists( user_id, group_id, str(problem), answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=str(problem).strip(), answer=answer, image_path=image_path, placeholder=",".join(_list), create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), to_me=to_me_nickname, ) async def _answer2format( cls, answer: Union[str, Message], user_id: str, group_id: Optional[str] ) -> Tuple[str, List[Any]]: """ 说明: 将CQ码转化为占位符 参数: :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if isinstance(answer, str): return answer, [] _list = [] text = "" index = 0 for seg in answer: placeholder = uuid.uuid1() if isinstance(seg, str): text += seg elif seg.type == "text": text += seg.data["text"] elif seg.type == "face": text += f"[face:placeholder_{placeholder}]" _list.append(seg.data["id"]) elif seg.type == "at": text += f"[at:placeholder_{placeholder}]" _list.append(seg.data["qq"]) else: text += f"[image:placeholder_{placeholder}]" index += 1 _file = ( path / "answer" / f"{group_id or user_id}" / f"{user_id}_{placeholder}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(seg.data["url"], _file) _list.append( f"answer/{group_id or user_id}/{user_id}_{placeholder}.jpg" ) return text, _list async def _format2answer( cls, problem: str, answer: Union[str, Message], user_id: int, group_id: int, query: Optional["WordBank"] = None, ) -> Union[str, Message]: """ 说明: 将占位符转换为CQ码 参数: :param problem: 问题内容 :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if not query: query = await cls.get_or_none( problem=problem, user_id=user_id, group_id=group_id, answer=answer, ) if not answer: answer = query.answer # type: ignore if query and query.placeholder: type_list = re.findall(rf"\[(.*?):placeholder_.*?]", str(answer)) temp_answer = re.sub(rf"\[(.*?):placeholder_.*?]", "{}", str(answer)) seg_list = [] for t, p in zip(type_list, query.placeholder.split(",")): if t == "image": seg_list.append(image(path / p)) elif t == "face": seg_list.append(face(int(p))) elif t == "at": seg_list.append(at(p)) return MessageTemplate(temp_answer, Message).format(*seg_list) # type: ignore return answer async def check_problem( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Any]: """ 说明: 检测是否包含该问题并获取所有回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls if isinstance(event, GroupMessageEvent): if word_scope: query = query.filter(word_scope=word_scope) else: query = query.filter(Q(group_id=event.group_id) | Q(word_scope=0)) else: query = query.filter(Q(word_scope=2) | Q(word_scope=0)) if word_type: query = query.filter(word_scope=word_type) # 完全匹配 if data_list := await query.filter( Q(Q(word_type=0) | Q(word_type=3)), Q(problem=problem) ).all(): return data_list db = Tortoise.get_connection("default") # 模糊匹配 sql = query.filter(word_type=1).sql() + " and POSITION(problem in $1) > 0" data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] # 正则 sql = ( query.filter(word_type=2, word_scope__not=999).sql() + " and $1 ~ problem;" ) data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] return None async def get_answer( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Union[str, Message]]: """ 说明: 根据问题内容获取随机回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ data_list = await cls.check_problem(event, problem, word_scope, word_type) if data_list: random_answer = random.choice(data_list) temp_answer = random_answer.answer if random_answer.word_type == 2: r = re.search(random_answer.problem, problem) has_placeholder = re.search(rf"\$(\d)", random_answer.answer) if r and r.groups() and has_placeholder: pats = re.sub(r"\$(\d)", r"\\\1", random_answer.answer) random_answer.answer = re.sub(random_answer.problem, pats, problem) return ( await cls._format2answer( random_answer.problem, random_answer.answer, random_answer.user_id, random_answer.group_id, random_answer, ) if random_answer.placeholder else random_answer.answer ) async def get_problem_all_answer( cls, problem: str, index: Optional[int] = None, group_id: Optional[str] = None, word_scope: Optional[int] = 0, ) -> List[Union[str, Message]]: """ 说明: 获取指定问题所有回答 参数: :param problem: 问题 :param index: 下标 :param group_id: 群号 :param word_scope: 词条范围 """ if index is not None: if group_id: problem_ = (await cls.filter(group_id=group_id).all())[index] else: problem_ = (await cls.filter(word_scope=(word_scope or 0)).all())[index] problem = problem_.problem answer = cls.filter(problem=problem) if group_id: answer = answer.filter(group_id=group_id) return [await cls._format2answer("", "", 0, 0, x) for x in (await answer.all())] async def delete_group_problem( cls, problem: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 删除指定问题全部或指定回答 参数: :param problem: 问题文本 :param group_id: 群号 :param index: 回答下标 :param word_scope: 词条范围 """ if await cls.exists(None, group_id, problem, None, word_scope): if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=0, problem=problem).all() await query[index].delete() else: if group_id: await WordBank.filter(group_id=group_id, problem=problem).delete() else: await WordBank.filter( word_scope=word_scope, problem=problem ).delete() return True return False async def update_group_problem( cls, problem: str, replace_str: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 修改词条问题 参数: :param problem: 问题 :param replace_str: 替换问题 :param group_id: 群号 :param index: 下标 :param word_scope: 词条范围 """ if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=word_scope, problem=problem).all() query[index].problem = replace_str await query[index].save(update_fields=["problem"]) else: if group_id: await cls.filter(group_id=group_id, problem=problem).update( problem=replace_str ) else: await cls.filter(word_scope=word_scope, problem=problem).update( problem=replace_str ) async def get_group_all_problem( cls, group_id: str ) -> List[Tuple[Any, Union[MessageSegment, str]]]: """ 说明: 获取群聊所有词条 参数: :param group_id: 群号 """ return cls._handle_problem( await cls.filter(group_id=group_id).all() # type: ignore ) async def get_problem_by_scope(cls, word_scope: int): """ 说明: 通过词条范围获取词条 参数: :param word_scope: 词条范围 """ return cls._handle_problem( await cls.filter(word_scope=word_scope).all() # type: ignore ) async def get_problem_by_type(cls, word_type: int): """ 说明: 通过词条类型获取词条 参数: :param word_type: 词条类型 """ return cls._handle_problem( await cls.filter(word_type=word_type).all() # type: ignore ) def _handle_problem(cls, msg_list: List["WordBank"]): """ 说明: 格式化处理问题 参数: :param msg_list: 消息列表 """ _tmp = [] problem_list = [] for q in msg_list: if q.problem not in _tmp: problem = ( q.problem, image(path / q.image_path) if q.image_path else f"[{int2type[q.word_type]}] " + q.problem, ) problem_list.append(problem) _tmp.append(q.problem) return problem_list async def _move( cls, user_id: str, group_id: Optional[str], problem: Union[str, Message], answer: Union[str, Message], placeholder: str, ): """ 说明: 旧词条图片移动方法 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param placeholder: 占位符 """ word_scope = 0 word_type = 0 # 对图片做额外处理 if not await cls.exists( user_id, group_id, problem, answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=problem, answer=answer, image_path=None, placeholder=placeholder, create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), ) async def _run_script(cls): return [ "ALTER TABLE word_bank2 ADD to_me varchar(255);", # 添加 to_me 字段 "ALTER TABLE word_bank2 ALTER COLUMN create_time TYPE timestamp with time zone USING create_time::timestamp with time zone;", "ALTER TABLE word_bank2 ALTER COLUMN update_time TYPE timestamp with time zone USING update_time::timestamp with time zone;", "ALTER TABLE word_bank2 RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE word_bank2 ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE word_bank2 ALTER COLUMN group_id TYPE character varying(255);", ] async def _( bot: Bot, event: MessageEvent, word_scope: Optional[str] = ArgStr("word_scope"), word_type: Optional[str] = ArgStr("word_type"), problem: Optional[str] = ArgStr("problem"), answer: Message = Arg("answer"), problem_image: Message = Arg("problem_image"), ): try: if word_type == "正则" and problem: problem = unescape(problem) try: re.compile(problem) except re.error: await add_word.finish(f"添加词条失败,正则表达式 {problem} 非法!") # 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)] await WordBank.add_problem_answer( str(event.user_id), str(event.group_id) if isinstance(event, GroupMessageEvent) and (not word_scope or word_scope == "私聊") else "0", scope2int[word_scope] if word_scope else 1, type2int[word_type] if word_type else 0, problem or problem_image, answer, nickname[0] if nickname else None, ) except Exception as e: if isinstance(e, FinishedException): await add_word.finish() logger.error( f"添加词条 {problem} 错误...", "添加词条", event.user_id, getattr(event, "group_id", None), e=e, ) await add_word.finish(f"添加词条 {problem} 发生错误!") await add_word.send("添加词条 " + (problem or problem_image) + " 成功!") logger.info( f"添加词条 {problem} 成功!", "添加词条", event.user_id, getattr(event, "group_id", None) )
null
188,317
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank delete_word_matcher = on_command("删除词条", aliases={"删除全局词条"}, priority=5, block=True) class logger: def info( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ): def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: async def delete_word( params: str, group_id: Optional[str] = None, word_scope: int = 1 ) -> str: async def _(event: GroupMessageEvent, arg: Message = CommandArg()): if not (msg := arg.extract_plain_text().strip()): await delete_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") result = await delete_word(msg, str(event.group_id)) await delete_word_matcher.send(result) logger.info(f"删除词条:" + msg, "删除词条", event.user_id, event.group_id)
null
188,318
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank delete_word_matcher = on_command("删除词条", aliases={"删除全局词条"}, priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def delete_word( params: str, group_id: Optional[str] = None, word_scope: int = 1 ) -> str: """ 说明: 删除群词条 参数: :param params: 参数 :param group_id: 群号 :param word_scope: 词条范围 """ return await word_handle(params, group_id, "delete", word_scope) async def _( bot: Bot, event: PrivateMessageEvent, arg: Message = CommandArg(), cmd: Tuple[str, ...] = Command(), ): if str(event.user_id) not in bot.config.superusers: await delete_word_matcher.finish("权限不足捏!") if not (msg := arg.extract_plain_text().strip()): await delete_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") result = await delete_word(msg, word_scope=2 if cmd[0] == "删除词条" else 0) await delete_word_matcher.send(result) logger.info(f"删除词条:" + msg, "删除词条", event.user_id)
null
188,319
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank r = on_command("修改词条", aliases={"修改全局词条"}, priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def update_word( params: str, group_id: Optional[str] = None, word_scope: int = 1 ) -> str: """ 说明: 修改群词条 参数: :param params: 参数 :param group_id: 群号 :param word_scope: 词条范围 """ return await word_handle(params, group_id, "update", word_scope) async def _(event: GroupMessageEvent, arg: Message = CommandArg()): if not (msg := arg.extract_plain_text().strip()): await update_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") if len(msg.split()) < 2: await update_word_matcher.finish("此命令需要两个参数,请查看帮助") result = await update_word(msg, str(event.group_id)) await update_word_matcher.send(result) logger.info(f"更新词条词条:" + msg, "更新词条", event.user_id, event.group_id)
null
188,320
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank delete_word_matcher = on_command("删除词条", aliases={"删除全局词条"}, priority=5, block=True) update_word_matcher = on_command("修改词条", aliases={"修改全局词条"}, priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) async def update_word( params: str, group_id: Optional[str] = None, word_scope: int = 1 ) -> str: """ 说明: 修改群词条 参数: :param params: 参数 :param group_id: 群号 :param word_scope: 词条范围 """ return await word_handle(params, group_id, "update", word_scope) async def _( bot: Bot, event: PrivateMessageEvent, arg: Message = CommandArg(), cmd: Tuple[str, ...] = Command(), ): if str(event.user_id) not in bot.config.superusers: await delete_word_matcher.finish("权限不足捏!") if not (msg := arg.extract_plain_text().strip()): await update_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") if len(msg.split()) < 2: await update_word_matcher.finish("此命令需要两个参数,请查看帮助") result = await update_word(msg, word_scope=2 if cmd[0] == "修改词条" else 0) await update_word_matcher.send(result) logger.info(f"更新词条词条:" + msg, "更新词条", event.user_id)
null
188,321
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank = on_command("显示词条", aliases={"查看词条"}, priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) def custom_forward_msg( msg_list: List[Union[str, Message]], uin: Union[int, str], name: str = f"这里是{NICKNAME}", ) -> List[dict]: """ 说明: 生成自定义合并消息 参数: :param msg_list: 消息列表 :param uin: 发送者 QQ :param name: 自定义名称 """ uin = int(uin) 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 { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False def show_word( problem: str, id_: Optional[int], gid: Optional[int], group_id: Optional[str] = None, word_scope: Optional[int] = None, ) -> Union[str, List[Union[str, Message]]]: if problem: msg_list = [] if word_scope is not None: problem = (await WordBank.get_problem_by_scope(word_scope))[id_][0] # type: ignore id_ = None _problem_list = await WordBank.get_problem_all_answer( problem, id_ if id_ is not None else gid, group_id if gid is None else None, word_scope, ) for index, msg in enumerate(_problem_list): if isinstance(msg, Message): tmp = "" for seg in msg: tmp += seg msg = tmp msg_list.append(f"{index}." + msg) msg_list = [ f'词条:{problem or (f"id: {id_}" if id_ is not None else f"gid: {gid}")} 的回答' ] + msg_list return msg_list # type: ignore else: if group_id: _problem_list = await WordBank.get_group_all_problem(group_id) elif word_scope is not None: _problem_list = await WordBank.get_problem_by_scope(word_scope) else: raise Exception("群组id和词条范围不能都为空") global_problem_list = await WordBank.get_problem_by_scope(0) if not _problem_list and not global_problem_list: return "未收录任何词条.." msg_list = await build_message(_problem_list) global_msg_list = await build_message(global_problem_list) if global_msg_list: msg_list.append("###以下为全局词条###") msg_list = msg_list + global_msg_list return msg_list class WordBank(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" word_scope = fields.IntField(default=0) """生效范围 0: 全局 1: 群聊 2: 私聊""" word_type = fields.IntField(default=0) """词条类型 0: 完全匹配 1: 模糊 2: 正则 3: 图片""" status = fields.BooleanField() """词条状态""" problem = fields.TextField() """问题,为图片时使用图片hash""" answer = fields.TextField() """回答""" placeholder = fields.TextField(null=True) """占位符""" image_path = fields.TextField(null=True) """使用图片作为问题时图片存储的路径""" to_me = fields.CharField(255, null=True) """昵称开头时存储的昵称""" create_time = fields.DatetimeField(auto_now=True) """创建时间""" update_time = fields.DatetimeField(auto_now_add=True) """更新时间""" class Meta: table = "word_bank2" table_description = "词条数据库" async def exists( cls, user_id: Optional[str], group_id: Optional[str], problem: str, answer: Optional[str], word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> bool: """ 说明: 检测问题是否存在 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls.filter(problem=problem) if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if answer: query = query.filter(answer=answer) if word_type is not None: query = query.filter(word_type=word_type) if word_scope is not None: query = query.filter(word_scope=word_scope) return bool(await query.first()) async def add_problem_answer( cls, user_id: str, group_id: Optional[str], word_scope: int, word_type: int, problem: Union[str, Message], answer: Union[str, Message], to_me_nickname: Optional[str] = None, ): """ 说明: 添加或新增一个问答 参数: :param user_id: 用户id :param group_id: 群号 :param word_scope: 词条范围, :param word_type: 词条类型, :param problem: 问题 :param answer: 回答 :param to_me_nickname: at真寻名称 """ # 对图片做额外处理 image_path = None if word_type == 3: url = get_message_img(problem)[0] _file = ( path / "problem" / f"{group_id}" / f"{user_id}_{int(time.time())}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(url, _file) problem = str(get_img_hash(_file)) image_path = f"problem/{group_id}/{user_id}_{int(time.time())}.jpg" answer, _list = await cls._answer2format(answer, user_id, group_id) if not await cls.exists( user_id, group_id, str(problem), answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=str(problem).strip(), answer=answer, image_path=image_path, placeholder=",".join(_list), create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), to_me=to_me_nickname, ) async def _answer2format( cls, answer: Union[str, Message], user_id: str, group_id: Optional[str] ) -> Tuple[str, List[Any]]: """ 说明: 将CQ码转化为占位符 参数: :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if isinstance(answer, str): return answer, [] _list = [] text = "" index = 0 for seg in answer: placeholder = uuid.uuid1() if isinstance(seg, str): text += seg elif seg.type == "text": text += seg.data["text"] elif seg.type == "face": text += f"[face:placeholder_{placeholder}]" _list.append(seg.data["id"]) elif seg.type == "at": text += f"[at:placeholder_{placeholder}]" _list.append(seg.data["qq"]) else: text += f"[image:placeholder_{placeholder}]" index += 1 _file = ( path / "answer" / f"{group_id or user_id}" / f"{user_id}_{placeholder}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(seg.data["url"], _file) _list.append( f"answer/{group_id or user_id}/{user_id}_{placeholder}.jpg" ) return text, _list async def _format2answer( cls, problem: str, answer: Union[str, Message], user_id: int, group_id: int, query: Optional["WordBank"] = None, ) -> Union[str, Message]: """ 说明: 将占位符转换为CQ码 参数: :param problem: 问题内容 :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if not query: query = await cls.get_or_none( problem=problem, user_id=user_id, group_id=group_id, answer=answer, ) if not answer: answer = query.answer # type: ignore if query and query.placeholder: type_list = re.findall(rf"\[(.*?):placeholder_.*?]", str(answer)) temp_answer = re.sub(rf"\[(.*?):placeholder_.*?]", "{}", str(answer)) seg_list = [] for t, p in zip(type_list, query.placeholder.split(",")): if t == "image": seg_list.append(image(path / p)) elif t == "face": seg_list.append(face(int(p))) elif t == "at": seg_list.append(at(p)) return MessageTemplate(temp_answer, Message).format(*seg_list) # type: ignore return answer async def check_problem( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Any]: """ 说明: 检测是否包含该问题并获取所有回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls if isinstance(event, GroupMessageEvent): if word_scope: query = query.filter(word_scope=word_scope) else: query = query.filter(Q(group_id=event.group_id) | Q(word_scope=0)) else: query = query.filter(Q(word_scope=2) | Q(word_scope=0)) if word_type: query = query.filter(word_scope=word_type) # 完全匹配 if data_list := await query.filter( Q(Q(word_type=0) | Q(word_type=3)), Q(problem=problem) ).all(): return data_list db = Tortoise.get_connection("default") # 模糊匹配 sql = query.filter(word_type=1).sql() + " and POSITION(problem in $1) > 0" data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] # 正则 sql = ( query.filter(word_type=2, word_scope__not=999).sql() + " and $1 ~ problem;" ) data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] return None async def get_answer( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Union[str, Message]]: """ 说明: 根据问题内容获取随机回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ data_list = await cls.check_problem(event, problem, word_scope, word_type) if data_list: random_answer = random.choice(data_list) temp_answer = random_answer.answer if random_answer.word_type == 2: r = re.search(random_answer.problem, problem) has_placeholder = re.search(rf"\$(\d)", random_answer.answer) if r and r.groups() and has_placeholder: pats = re.sub(r"\$(\d)", r"\\\1", random_answer.answer) random_answer.answer = re.sub(random_answer.problem, pats, problem) return ( await cls._format2answer( random_answer.problem, random_answer.answer, random_answer.user_id, random_answer.group_id, random_answer, ) if random_answer.placeholder else random_answer.answer ) async def get_problem_all_answer( cls, problem: str, index: Optional[int] = None, group_id: Optional[str] = None, word_scope: Optional[int] = 0, ) -> List[Union[str, Message]]: """ 说明: 获取指定问题所有回答 参数: :param problem: 问题 :param index: 下标 :param group_id: 群号 :param word_scope: 词条范围 """ if index is not None: if group_id: problem_ = (await cls.filter(group_id=group_id).all())[index] else: problem_ = (await cls.filter(word_scope=(word_scope or 0)).all())[index] problem = problem_.problem answer = cls.filter(problem=problem) if group_id: answer = answer.filter(group_id=group_id) return [await cls._format2answer("", "", 0, 0, x) for x in (await answer.all())] async def delete_group_problem( cls, problem: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 删除指定问题全部或指定回答 参数: :param problem: 问题文本 :param group_id: 群号 :param index: 回答下标 :param word_scope: 词条范围 """ if await cls.exists(None, group_id, problem, None, word_scope): if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=0, problem=problem).all() await query[index].delete() else: if group_id: await WordBank.filter(group_id=group_id, problem=problem).delete() else: await WordBank.filter( word_scope=word_scope, problem=problem ).delete() return True return False async def update_group_problem( cls, problem: str, replace_str: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 修改词条问题 参数: :param problem: 问题 :param replace_str: 替换问题 :param group_id: 群号 :param index: 下标 :param word_scope: 词条范围 """ if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=word_scope, problem=problem).all() query[index].problem = replace_str await query[index].save(update_fields=["problem"]) else: if group_id: await cls.filter(group_id=group_id, problem=problem).update( problem=replace_str ) else: await cls.filter(word_scope=word_scope, problem=problem).update( problem=replace_str ) async def get_group_all_problem( cls, group_id: str ) -> List[Tuple[Any, Union[MessageSegment, str]]]: """ 说明: 获取群聊所有词条 参数: :param group_id: 群号 """ return cls._handle_problem( await cls.filter(group_id=group_id).all() # type: ignore ) async def get_problem_by_scope(cls, word_scope: int): """ 说明: 通过词条范围获取词条 参数: :param word_scope: 词条范围 """ return cls._handle_problem( await cls.filter(word_scope=word_scope).all() # type: ignore ) async def get_problem_by_type(cls, word_type: int): """ 说明: 通过词条类型获取词条 参数: :param word_type: 词条类型 """ return cls._handle_problem( await cls.filter(word_type=word_type).all() # type: ignore ) def _handle_problem(cls, msg_list: List["WordBank"]): """ 说明: 格式化处理问题 参数: :param msg_list: 消息列表 """ _tmp = [] problem_list = [] for q in msg_list: if q.problem not in _tmp: problem = ( q.problem, image(path / q.image_path) if q.image_path else f"[{int2type[q.word_type]}] " + q.problem, ) problem_list.append(problem) _tmp.append(q.problem) return problem_list async def _move( cls, user_id: str, group_id: Optional[str], problem: Union[str, Message], answer: Union[str, Message], placeholder: str, ): """ 说明: 旧词条图片移动方法 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param placeholder: 占位符 """ word_scope = 0 word_type = 0 # 对图片做额外处理 if not await cls.exists( user_id, group_id, problem, answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=problem, answer=answer, image_path=None, placeholder=placeholder, create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), ) async def _run_script(cls): return [ "ALTER TABLE word_bank2 ADD to_me varchar(255);", # 添加 to_me 字段 "ALTER TABLE word_bank2 ALTER COLUMN create_time TYPE timestamp with time zone USING create_time::timestamp with time zone;", "ALTER TABLE word_bank2 ALTER COLUMN update_time TYPE timestamp with time zone USING update_time::timestamp with time zone;", "ALTER TABLE word_bank2 RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE word_bank2 ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE word_bank2 ALTER COLUMN group_id TYPE character varying(255);", ] async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()): if problem := arg.extract_plain_text().strip(): id_ = None gid = None if problem.startswith("id:"): id_ = problem.split(":")[-1] if ( not is_number(id_) or int(id_) < 0 or int(id_) >= len(await WordBank.get_group_all_problem(str(event.group_id))) ): await show_word_matcher.finish("id必须为数字且在范围内") id_ = int(id_) if problem.startswith("gid:"): gid = problem.split(":")[-1] if ( not is_number(gid) or int(gid) < 0 or int(gid) >= len(await WordBank.get_problem_by_scope(0)) ): await show_word_matcher.finish("gid必须为数字且在范围内") gid = int(gid) msg_list = await show_word( problem, id_, gid, None if gid else str(event.group_id) ) else: msg_list = await show_word(problem, None, None, str(event.group_id)) if isinstance(msg_list, str): await show_word_matcher.send(msg_list) else: await bot.send_group_forward_msg( group_id=event.group_id, messages=custom_forward_msg(msg_list, bot.self_id) ) logger.info( f"查看词条回答:" + problem, "显示词条", event.user_id, getattr(event, "group_id", None) )
null
188,322
import re from typing import Any, List, Optional, Tuple from nonebot import on_command, on_regex from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, Message, MessageEvent, PrivateMessageEvent, unescape, ) from nonebot.exception import FinishedException from nonebot.internal.params import Arg, ArgStr from nonebot.params import Command, CommandArg, RegexGroup from nonebot.typing import T_State from configs.config import Config from configs.path_config import DATA_PATH from services.log import logger from utils.depends import AtList, ImageList from utils.message_builder import custom_forward_msg from utils.utils import get_message_at, get_message_img, is_number from ._config import scope2int, type2int from ._data_source import delete_word, show_word, update_word from ._model import WordBank = on_command("显示词条", aliases={"查看词条"}, priority=5, block=True) class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) { "run_sql": [], # 需要启动前运行的sql语句 "_shop_before_handle": {}, # 商品使用前函数 "_shop_after_handle": {}, # 商品使用后函数 } def is_number(s: Union[int, str]) -> bool: """ 说明: 检测 s 是否为数字 参数: :param s: 文本 """ if isinstance(s, int): return True try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False def show_word( problem: str, id_: Optional[int], gid: Optional[int], group_id: Optional[str] = None, word_scope: Optional[int] = None, ) -> Union[str, List[Union[str, Message]]]: if problem: msg_list = [] if word_scope is not None: problem = (await WordBank.get_problem_by_scope(word_scope))[id_][0] # type: ignore id_ = None _problem_list = await WordBank.get_problem_all_answer( problem, id_ if id_ is not None else gid, group_id if gid is None else None, word_scope, ) for index, msg in enumerate(_problem_list): if isinstance(msg, Message): tmp = "" for seg in msg: tmp += seg msg = tmp msg_list.append(f"{index}." + msg) msg_list = [ f'词条:{problem or (f"id: {id_}" if id_ is not None else f"gid: {gid}")} 的回答' ] + msg_list return msg_list # type: ignore else: if group_id: _problem_list = await WordBank.get_group_all_problem(group_id) elif word_scope is not None: _problem_list = await WordBank.get_problem_by_scope(word_scope) else: raise Exception("群组id和词条范围不能都为空") global_problem_list = await WordBank.get_problem_by_scope(0) if not _problem_list and not global_problem_list: return "未收录任何词条.." msg_list = await build_message(_problem_list) global_msg_list = await build_message(global_problem_list) if global_msg_list: msg_list.append("###以下为全局词条###") msg_list = msg_list + global_msg_list return msg_list class WordBank(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" word_scope = fields.IntField(default=0) """生效范围 0: 全局 1: 群聊 2: 私聊""" word_type = fields.IntField(default=0) """词条类型 0: 完全匹配 1: 模糊 2: 正则 3: 图片""" status = fields.BooleanField() """词条状态""" problem = fields.TextField() """问题,为图片时使用图片hash""" answer = fields.TextField() """回答""" placeholder = fields.TextField(null=True) """占位符""" image_path = fields.TextField(null=True) """使用图片作为问题时图片存储的路径""" to_me = fields.CharField(255, null=True) """昵称开头时存储的昵称""" create_time = fields.DatetimeField(auto_now=True) """创建时间""" update_time = fields.DatetimeField(auto_now_add=True) """更新时间""" class Meta: table = "word_bank2" table_description = "词条数据库" async def exists( cls, user_id: Optional[str], group_id: Optional[str], problem: str, answer: Optional[str], word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> bool: """ 说明: 检测问题是否存在 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls.filter(problem=problem) if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if answer: query = query.filter(answer=answer) if word_type is not None: query = query.filter(word_type=word_type) if word_scope is not None: query = query.filter(word_scope=word_scope) return bool(await query.first()) async def add_problem_answer( cls, user_id: str, group_id: Optional[str], word_scope: int, word_type: int, problem: Union[str, Message], answer: Union[str, Message], to_me_nickname: Optional[str] = None, ): """ 说明: 添加或新增一个问答 参数: :param user_id: 用户id :param group_id: 群号 :param word_scope: 词条范围, :param word_type: 词条类型, :param problem: 问题 :param answer: 回答 :param to_me_nickname: at真寻名称 """ # 对图片做额外处理 image_path = None if word_type == 3: url = get_message_img(problem)[0] _file = ( path / "problem" / f"{group_id}" / f"{user_id}_{int(time.time())}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(url, _file) problem = str(get_img_hash(_file)) image_path = f"problem/{group_id}/{user_id}_{int(time.time())}.jpg" answer, _list = await cls._answer2format(answer, user_id, group_id) if not await cls.exists( user_id, group_id, str(problem), answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=str(problem).strip(), answer=answer, image_path=image_path, placeholder=",".join(_list), create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), to_me=to_me_nickname, ) async def _answer2format( cls, answer: Union[str, Message], user_id: str, group_id: Optional[str] ) -> Tuple[str, List[Any]]: """ 说明: 将CQ码转化为占位符 参数: :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if isinstance(answer, str): return answer, [] _list = [] text = "" index = 0 for seg in answer: placeholder = uuid.uuid1() if isinstance(seg, str): text += seg elif seg.type == "text": text += seg.data["text"] elif seg.type == "face": text += f"[face:placeholder_{placeholder}]" _list.append(seg.data["id"]) elif seg.type == "at": text += f"[at:placeholder_{placeholder}]" _list.append(seg.data["qq"]) else: text += f"[image:placeholder_{placeholder}]" index += 1 _file = ( path / "answer" / f"{group_id or user_id}" / f"{user_id}_{placeholder}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(seg.data["url"], _file) _list.append( f"answer/{group_id or user_id}/{user_id}_{placeholder}.jpg" ) return text, _list async def _format2answer( cls, problem: str, answer: Union[str, Message], user_id: int, group_id: int, query: Optional["WordBank"] = None, ) -> Union[str, Message]: """ 说明: 将占位符转换为CQ码 参数: :param problem: 问题内容 :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if not query: query = await cls.get_or_none( problem=problem, user_id=user_id, group_id=group_id, answer=answer, ) if not answer: answer = query.answer # type: ignore if query and query.placeholder: type_list = re.findall(rf"\[(.*?):placeholder_.*?]", str(answer)) temp_answer = re.sub(rf"\[(.*?):placeholder_.*?]", "{}", str(answer)) seg_list = [] for t, p in zip(type_list, query.placeholder.split(",")): if t == "image": seg_list.append(image(path / p)) elif t == "face": seg_list.append(face(int(p))) elif t == "at": seg_list.append(at(p)) return MessageTemplate(temp_answer, Message).format(*seg_list) # type: ignore return answer async def check_problem( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Any]: """ 说明: 检测是否包含该问题并获取所有回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls if isinstance(event, GroupMessageEvent): if word_scope: query = query.filter(word_scope=word_scope) else: query = query.filter(Q(group_id=event.group_id) | Q(word_scope=0)) else: query = query.filter(Q(word_scope=2) | Q(word_scope=0)) if word_type: query = query.filter(word_scope=word_type) # 完全匹配 if data_list := await query.filter( Q(Q(word_type=0) | Q(word_type=3)), Q(problem=problem) ).all(): return data_list db = Tortoise.get_connection("default") # 模糊匹配 sql = query.filter(word_type=1).sql() + " and POSITION(problem in $1) > 0" data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] # 正则 sql = ( query.filter(word_type=2, word_scope__not=999).sql() + " and $1 ~ problem;" ) data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] return None async def get_answer( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Union[str, Message]]: """ 说明: 根据问题内容获取随机回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ data_list = await cls.check_problem(event, problem, word_scope, word_type) if data_list: random_answer = random.choice(data_list) temp_answer = random_answer.answer if random_answer.word_type == 2: r = re.search(random_answer.problem, problem) has_placeholder = re.search(rf"\$(\d)", random_answer.answer) if r and r.groups() and has_placeholder: pats = re.sub(r"\$(\d)", r"\\\1", random_answer.answer) random_answer.answer = re.sub(random_answer.problem, pats, problem) return ( await cls._format2answer( random_answer.problem, random_answer.answer, random_answer.user_id, random_answer.group_id, random_answer, ) if random_answer.placeholder else random_answer.answer ) async def get_problem_all_answer( cls, problem: str, index: Optional[int] = None, group_id: Optional[str] = None, word_scope: Optional[int] = 0, ) -> List[Union[str, Message]]: """ 说明: 获取指定问题所有回答 参数: :param problem: 问题 :param index: 下标 :param group_id: 群号 :param word_scope: 词条范围 """ if index is not None: if group_id: problem_ = (await cls.filter(group_id=group_id).all())[index] else: problem_ = (await cls.filter(word_scope=(word_scope or 0)).all())[index] problem = problem_.problem answer = cls.filter(problem=problem) if group_id: answer = answer.filter(group_id=group_id) return [await cls._format2answer("", "", 0, 0, x) for x in (await answer.all())] async def delete_group_problem( cls, problem: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 删除指定问题全部或指定回答 参数: :param problem: 问题文本 :param group_id: 群号 :param index: 回答下标 :param word_scope: 词条范围 """ if await cls.exists(None, group_id, problem, None, word_scope): if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=0, problem=problem).all() await query[index].delete() else: if group_id: await WordBank.filter(group_id=group_id, problem=problem).delete() else: await WordBank.filter( word_scope=word_scope, problem=problem ).delete() return True return False async def update_group_problem( cls, problem: str, replace_str: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 修改词条问题 参数: :param problem: 问题 :param replace_str: 替换问题 :param group_id: 群号 :param index: 下标 :param word_scope: 词条范围 """ if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=word_scope, problem=problem).all() query[index].problem = replace_str await query[index].save(update_fields=["problem"]) else: if group_id: await cls.filter(group_id=group_id, problem=problem).update( problem=replace_str ) else: await cls.filter(word_scope=word_scope, problem=problem).update( problem=replace_str ) async def get_group_all_problem( cls, group_id: str ) -> List[Tuple[Any, Union[MessageSegment, str]]]: """ 说明: 获取群聊所有词条 参数: :param group_id: 群号 """ return cls._handle_problem( await cls.filter(group_id=group_id).all() # type: ignore ) async def get_problem_by_scope(cls, word_scope: int): """ 说明: 通过词条范围获取词条 参数: :param word_scope: 词条范围 """ return cls._handle_problem( await cls.filter(word_scope=word_scope).all() # type: ignore ) async def get_problem_by_type(cls, word_type: int): """ 说明: 通过词条类型获取词条 参数: :param word_type: 词条类型 """ return cls._handle_problem( await cls.filter(word_type=word_type).all() # type: ignore ) def _handle_problem(cls, msg_list: List["WordBank"]): """ 说明: 格式化处理问题 参数: :param msg_list: 消息列表 """ _tmp = [] problem_list = [] for q in msg_list: if q.problem not in _tmp: problem = ( q.problem, image(path / q.image_path) if q.image_path else f"[{int2type[q.word_type]}] " + q.problem, ) problem_list.append(problem) _tmp.append(q.problem) return problem_list async def _move( cls, user_id: str, group_id: Optional[str], problem: Union[str, Message], answer: Union[str, Message], placeholder: str, ): """ 说明: 旧词条图片移动方法 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param placeholder: 占位符 """ word_scope = 0 word_type = 0 # 对图片做额外处理 if not await cls.exists( user_id, group_id, problem, answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=problem, answer=answer, image_path=None, placeholder=placeholder, create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), ) async def _run_script(cls): return [ "ALTER TABLE word_bank2 ADD to_me varchar(255);", # 添加 to_me 字段 "ALTER TABLE word_bank2 ALTER COLUMN create_time TYPE timestamp with time zone USING create_time::timestamp with time zone;", "ALTER TABLE word_bank2 ALTER COLUMN update_time TYPE timestamp with time zone USING update_time::timestamp with time zone;", "ALTER TABLE word_bank2 RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE word_bank2 ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE word_bank2 ALTER COLUMN group_id TYPE character varying(255);", ] async def _(event: PrivateMessageEvent, arg: Message = CommandArg()): if problem := arg.extract_plain_text().strip(): id_ = None gid = None if problem.startswith("id:"): id_ = problem.split(":")[-1] if ( not is_number(id_) or int(id_) < 0 or int(id_) > len(await WordBank.get_problem_by_scope(2)) ): await show_word_matcher.finish("id必须为数字且在范围内") id_ = int(id_) if problem.startswith("gid:"): gid = problem.split(":")[-1] if ( not is_number(gid) or int(gid) < 0 or int(gid) > len(await WordBank.get_problem_by_scope(0)) ): await show_word_matcher.finish("gid必须为数字且在范围内") gid = int(gid) msg_list = await show_word( problem, id_, gid, word_scope=2 if id_ is not None else None ) else: msg_list = await show_word(problem, None, None, word_scope=2) if isinstance(msg_list, str): await show_word_matcher.send(msg_list) else: t = "" for msg in msg_list: t += msg + "\n" await show_word_matcher.send(t[:-1]) logger.info( f"查看词条回答:" + problem, "显示词条", event.user_id, getattr(event, "group_id", None) )
null
188,323
from nonebot import on_message from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent from nonebot.typing import T_State from configs.path_config import DATA_PATH from services import logger from ._model import WordBank from ._rule import check message_handle = on_message(priority=6, block=True, rule=check) class WordBank(Model): id = fields.IntField(pk=True, generated=True, auto_increment=True) """自增id""" user_id = fields.CharField(255) """用户id""" group_id = fields.CharField(255, null=True) """群聊id""" word_scope = fields.IntField(default=0) """生效范围 0: 全局 1: 群聊 2: 私聊""" word_type = fields.IntField(default=0) """词条类型 0: 完全匹配 1: 模糊 2: 正则 3: 图片""" status = fields.BooleanField() """词条状态""" problem = fields.TextField() """问题,为图片时使用图片hash""" answer = fields.TextField() """回答""" placeholder = fields.TextField(null=True) """占位符""" image_path = fields.TextField(null=True) """使用图片作为问题时图片存储的路径""" to_me = fields.CharField(255, null=True) """昵称开头时存储的昵称""" create_time = fields.DatetimeField(auto_now=True) """创建时间""" update_time = fields.DatetimeField(auto_now_add=True) """更新时间""" class Meta: table = "word_bank2" table_description = "词条数据库" async def exists( cls, user_id: Optional[str], group_id: Optional[str], problem: str, answer: Optional[str], word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> bool: """ 说明: 检测问题是否存在 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls.filter(problem=problem) if user_id: query = query.filter(user_id=user_id) if group_id: query = query.filter(group_id=group_id) if answer: query = query.filter(answer=answer) if word_type is not None: query = query.filter(word_type=word_type) if word_scope is not None: query = query.filter(word_scope=word_scope) return bool(await query.first()) async def add_problem_answer( cls, user_id: str, group_id: Optional[str], word_scope: int, word_type: int, problem: Union[str, Message], answer: Union[str, Message], to_me_nickname: Optional[str] = None, ): """ 说明: 添加或新增一个问答 参数: :param user_id: 用户id :param group_id: 群号 :param word_scope: 词条范围, :param word_type: 词条类型, :param problem: 问题 :param answer: 回答 :param to_me_nickname: at真寻名称 """ # 对图片做额外处理 image_path = None if word_type == 3: url = get_message_img(problem)[0] _file = ( path / "problem" / f"{group_id}" / f"{user_id}_{int(time.time())}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(url, _file) problem = str(get_img_hash(_file)) image_path = f"problem/{group_id}/{user_id}_{int(time.time())}.jpg" answer, _list = await cls._answer2format(answer, user_id, group_id) if not await cls.exists( user_id, group_id, str(problem), answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=str(problem).strip(), answer=answer, image_path=image_path, placeholder=",".join(_list), create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), to_me=to_me_nickname, ) async def _answer2format( cls, answer: Union[str, Message], user_id: str, group_id: Optional[str] ) -> Tuple[str, List[Any]]: """ 说明: 将CQ码转化为占位符 参数: :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if isinstance(answer, str): return answer, [] _list = [] text = "" index = 0 for seg in answer: placeholder = uuid.uuid1() if isinstance(seg, str): text += seg elif seg.type == "text": text += seg.data["text"] elif seg.type == "face": text += f"[face:placeholder_{placeholder}]" _list.append(seg.data["id"]) elif seg.type == "at": text += f"[at:placeholder_{placeholder}]" _list.append(seg.data["qq"]) else: text += f"[image:placeholder_{placeholder}]" index += 1 _file = ( path / "answer" / f"{group_id or user_id}" / f"{user_id}_{placeholder}.jpg" ) _file.parent.mkdir(exist_ok=True, parents=True) await AsyncHttpx.download_file(seg.data["url"], _file) _list.append( f"answer/{group_id or user_id}/{user_id}_{placeholder}.jpg" ) return text, _list async def _format2answer( cls, problem: str, answer: Union[str, Message], user_id: int, group_id: int, query: Optional["WordBank"] = None, ) -> Union[str, Message]: """ 说明: 将占位符转换为CQ码 参数: :param problem: 问题内容 :param answer: 回答内容 :param user_id: 用户id :param group_id: 群号 """ if not query: query = await cls.get_or_none( problem=problem, user_id=user_id, group_id=group_id, answer=answer, ) if not answer: answer = query.answer # type: ignore if query and query.placeholder: type_list = re.findall(rf"\[(.*?):placeholder_.*?]", str(answer)) temp_answer = re.sub(rf"\[(.*?):placeholder_.*?]", "{}", str(answer)) seg_list = [] for t, p in zip(type_list, query.placeholder.split(",")): if t == "image": seg_list.append(image(path / p)) elif t == "face": seg_list.append(face(int(p))) elif t == "at": seg_list.append(at(p)) return MessageTemplate(temp_answer, Message).format(*seg_list) # type: ignore return answer async def check_problem( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Any]: """ 说明: 检测是否包含该问题并获取所有回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ query = cls if isinstance(event, GroupMessageEvent): if word_scope: query = query.filter(word_scope=word_scope) else: query = query.filter(Q(group_id=event.group_id) | Q(word_scope=0)) else: query = query.filter(Q(word_scope=2) | Q(word_scope=0)) if word_type: query = query.filter(word_scope=word_type) # 完全匹配 if data_list := await query.filter( Q(Q(word_type=0) | Q(word_type=3)), Q(problem=problem) ).all(): return data_list db = Tortoise.get_connection("default") # 模糊匹配 sql = query.filter(word_type=1).sql() + " and POSITION(problem in $1) > 0" data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] # 正则 sql = ( query.filter(word_type=2, word_scope__not=999).sql() + " and $1 ~ problem;" ) data_list = await db.execute_query_dict(sql, [problem]) if data_list: return [cls(**data) for data in data_list] return None async def get_answer( cls, event: MessageEvent, problem: str, word_scope: Optional[int] = None, word_type: Optional[int] = None, ) -> Optional[Union[str, Message]]: """ 说明: 根据问题内容获取随机回答 参数: :param event: event :param problem: 问题内容 :param word_scope: 词条范围 :param word_type: 词条类型 """ data_list = await cls.check_problem(event, problem, word_scope, word_type) if data_list: random_answer = random.choice(data_list) temp_answer = random_answer.answer if random_answer.word_type == 2: r = re.search(random_answer.problem, problem) has_placeholder = re.search(rf"\$(\d)", random_answer.answer) if r and r.groups() and has_placeholder: pats = re.sub(r"\$(\d)", r"\\\1", random_answer.answer) random_answer.answer = re.sub(random_answer.problem, pats, problem) return ( await cls._format2answer( random_answer.problem, random_answer.answer, random_answer.user_id, random_answer.group_id, random_answer, ) if random_answer.placeholder else random_answer.answer ) async def get_problem_all_answer( cls, problem: str, index: Optional[int] = None, group_id: Optional[str] = None, word_scope: Optional[int] = 0, ) -> List[Union[str, Message]]: """ 说明: 获取指定问题所有回答 参数: :param problem: 问题 :param index: 下标 :param group_id: 群号 :param word_scope: 词条范围 """ if index is not None: if group_id: problem_ = (await cls.filter(group_id=group_id).all())[index] else: problem_ = (await cls.filter(word_scope=(word_scope or 0)).all())[index] problem = problem_.problem answer = cls.filter(problem=problem) if group_id: answer = answer.filter(group_id=group_id) return [await cls._format2answer("", "", 0, 0, x) for x in (await answer.all())] async def delete_group_problem( cls, problem: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 删除指定问题全部或指定回答 参数: :param problem: 问题文本 :param group_id: 群号 :param index: 回答下标 :param word_scope: 词条范围 """ if await cls.exists(None, group_id, problem, None, word_scope): if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=0, problem=problem).all() await query[index].delete() else: if group_id: await WordBank.filter(group_id=group_id, problem=problem).delete() else: await WordBank.filter( word_scope=word_scope, problem=problem ).delete() return True return False async def update_group_problem( cls, problem: str, replace_str: str, group_id: Optional[str], index: Optional[int] = None, word_scope: int = 1, ): """ 说明: 修改词条问题 参数: :param problem: 问题 :param replace_str: 替换问题 :param group_id: 群号 :param index: 下标 :param word_scope: 词条范围 """ if index is not None: if group_id: query = await cls.filter(group_id=group_id, problem=problem).all() else: query = await cls.filter(word_scope=word_scope, problem=problem).all() query[index].problem = replace_str await query[index].save(update_fields=["problem"]) else: if group_id: await cls.filter(group_id=group_id, problem=problem).update( problem=replace_str ) else: await cls.filter(word_scope=word_scope, problem=problem).update( problem=replace_str ) async def get_group_all_problem( cls, group_id: str ) -> List[Tuple[Any, Union[MessageSegment, str]]]: """ 说明: 获取群聊所有词条 参数: :param group_id: 群号 """ return cls._handle_problem( await cls.filter(group_id=group_id).all() # type: ignore ) async def get_problem_by_scope(cls, word_scope: int): """ 说明: 通过词条范围获取词条 参数: :param word_scope: 词条范围 """ return cls._handle_problem( await cls.filter(word_scope=word_scope).all() # type: ignore ) async def get_problem_by_type(cls, word_type: int): """ 说明: 通过词条类型获取词条 参数: :param word_type: 词条类型 """ return cls._handle_problem( await cls.filter(word_type=word_type).all() # type: ignore ) def _handle_problem(cls, msg_list: List["WordBank"]): """ 说明: 格式化处理问题 参数: :param msg_list: 消息列表 """ _tmp = [] problem_list = [] for q in msg_list: if q.problem not in _tmp: problem = ( q.problem, image(path / q.image_path) if q.image_path else f"[{int2type[q.word_type]}] " + q.problem, ) problem_list.append(problem) _tmp.append(q.problem) return problem_list async def _move( cls, user_id: str, group_id: Optional[str], problem: Union[str, Message], answer: Union[str, Message], placeholder: str, ): """ 说明: 旧词条图片移动方法 参数: :param user_id: 用户id :param group_id: 群号 :param problem: 问题 :param answer: 回答 :param placeholder: 占位符 """ word_scope = 0 word_type = 0 # 对图片做额外处理 if not await cls.exists( user_id, group_id, problem, answer, word_scope, word_type ): await cls.create( user_id=user_id, group_id=group_id, word_scope=word_scope, word_type=word_type, status=True, problem=problem, answer=answer, image_path=None, placeholder=placeholder, create_time=datetime.now().replace(microsecond=0), update_time=datetime.now().replace(microsecond=0), ) async def _run_script(cls): return [ "ALTER TABLE word_bank2 ADD to_me varchar(255);", # 添加 to_me 字段 "ALTER TABLE word_bank2 ALTER COLUMN create_time TYPE timestamp with time zone USING create_time::timestamp with time zone;", "ALTER TABLE word_bank2 ALTER COLUMN update_time TYPE timestamp with time zone USING update_time::timestamp with time zone;", "ALTER TABLE word_bank2 RENAME COLUMN user_qq TO user_id;", # 将user_qq改为user_id "ALTER TABLE word_bank2 ALTER COLUMN user_id TYPE character varying(255);", "ALTER TABLE word_bank2 ALTER COLUMN group_id TYPE character varying(255);", ] async def _(event: MessageEvent, state: T_State): if problem := state.get("problem"): if msg := await WordBank.get_answer(event, problem): await message_handle.send(msg) logger.info( f" 触发词条 {problem}", "词条检测", event.user_id, getattr(event, "group_id", None), )
null
188,324
from nonebot import on_command from nonebot.adapters.onebot.v11 import GroupMessageEvent from nonebot.adapters.onebot.v11.permission import GROUP from configs.path_config import DATA_PATH from utils.message_builder import image view_custom_welcome = on_command( "群欢迎消息", aliases={"查看群欢迎消息", "查看当前群欢迎消息"}, permission=GROUP, priority=5, block=True ) def image( file: Optional[Union[str, Path, bytes, BuildImage, io.BytesIO, BuildMat]] = None, b64: Optional[str] = None, ) -> MessageSegment: """ 说明: 生成一个 MessageSegment.image 消息 生成顺序:绝对路径(abspath) > base64(b64) > img_name 参数: :param file: 图片文件 :param b64: 图片base64(兼容旧方法) """ if b64: file = b64 if b64.startswith("base64://") else ("base64://" + b64) if isinstance(file, str): if file.startswith(("http", "base64://")): return MessageSegment.image(file) else: if (IMAGE_PATH / file).exists(): return MessageSegment.image(IMAGE_PATH / file) logger.warning(f"图片 {(IMAGE_PATH / file).absolute()}缺失...") return "" if isinstance(file, Path): if file.exists(): return MessageSegment.image(file) logger.warning(f"图片 {file.absolute()}缺失...") if isinstance(file, (bytes, io.BytesIO)): return MessageSegment.image(file) if isinstance(file, (BuildImage, BuildMat)): return MessageSegment.image(file.pic2bs4()) return MessageSegment.image("") async def _(event: GroupMessageEvent): img = "" msg = "" if (DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg").exists(): img = image(DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg") custom_welcome_msg_json = ( DATA_PATH / "custom_welcome_msg" / "custom_welcome_msg.json" ) if custom_welcome_msg_json.exists(): data = json.load(open(custom_welcome_msg_json, "r")) if data.get(str(event.group_id)): msg = data[str(event.group_id)] if msg.find("[at]") != -1: msg = msg.replace("[at]", "") if img or msg: await view_custom_welcome.finish(msg + img, at_sender=True) else: await view_custom_welcome.finish("当前还没有自定义群欢迎消息哦", at_sender=True)
null
188,325
import time from collections import defaultdict from datetime import datetime from pathlib import Path from typing import Any, Callable, List, Optional, Set, Type, Union import httpx import nonebot import pypinyin import pytz from nonebot import require from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.matcher import Matcher, matchers from configs.config import SYSTEM_PROXY, Config from services.log import logger from nonebot_plugin_apscheduler import scheduler try: import ujson as json except ModuleNotFoundError: import json The provided code snippet includes necessary dependencies for implementing the `get_message_face` function. Write a Python function `def get_message_face(data: Union[str, Message]) -> List[str]` to solve the following problem: 说明: 获取消息中所有的 face Id 参数: :param data: event.json() Here is the function: def get_message_face(data: Union[str, Message]) -> List[str]: """ 说明: 获取消息中所有的 face Id 参数: :param data: event.json() """ face_list = [] if isinstance(data, str): event = json.loads(data) if data and (message := event.get("message")): for msg in message: if msg["type"] == "face": face_list.append(msg["data"]["id"]) else: for seg in data["face"]: face_list.append(seg.data["id"]) return face_list
说明: 获取消息中所有的 face Id 参数: :param data: event.json()
188,326
import time from collections import defaultdict from datetime import datetime from pathlib import Path from typing import Any, Callable, List, Optional, Set, Type, Union import httpx import nonebot import pypinyin import pytz from nonebot import require from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.matcher import Matcher, matchers from configs.config import SYSTEM_PROXY, Config from services.log import logger from nonebot_plugin_apscheduler import scheduler try: import ujson as json except ModuleNotFoundError: import json The provided code snippet includes necessary dependencies for implementing the `get_message_img_file` function. Write a Python function `def get_message_img_file(data: Union[str, Message]) -> List[str]` to solve the following problem: 说明: 获取消息中所有的 图片file 参数: :param data: event.json() Here is the function: def get_message_img_file(data: Union[str, Message]) -> List[str]: """ 说明: 获取消息中所有的 图片file 参数: :param data: event.json() """ file_list = [] if isinstance(data, str): event = json.loads(data) if data and (message := event.get("message")): for msg in message: if msg["type"] == "image": file_list.append(msg["data"]["file"]) else: for seg in data["image"]: file_list.append(seg.data["file"]) return file_list
说明: 获取消息中所有的 图片file 参数: :param data: event.json()
188,327
import time from collections import defaultdict from datetime import datetime from pathlib import Path from typing import Any, Callable, List, Optional, Set, Type, Union import httpx import nonebot import pypinyin import pytz from nonebot import require from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.matcher import Matcher, matchers from configs.config import SYSTEM_PROXY, Config from services.log import logger from nonebot_plugin_apscheduler import scheduler try: import ujson as json except ModuleNotFoundError: import json The provided code snippet includes necessary dependencies for implementing the `get_message_record` function. Write a Python function `def get_message_record(data: Union[str, Message]) -> List[str]` to solve the following problem: 说明: 获取消息中所有 语音 的链接 参数: :param data: event.json() Here is the function: def get_message_record(data: Union[str, Message]) -> List[str]: """ 说明: 获取消息中所有 语音 的链接 参数: :param data: event.json() """ record_list = [] if isinstance(data, str): event = json.loads(data) if data and (message := event.get("message")): for msg in message: if msg["type"] == "record": record_list.append(msg["data"]["url"]) else: for seg in data["record"]: record_list.append(seg.data["url"]) return record_list
说明: 获取消息中所有 语音 的链接 参数: :param data: event.json()
188,328
import time from collections import defaultdict from datetime import datetime from pathlib import Path from typing import Any, Callable, List, Optional, Set, Type, Union import httpx import nonebot import pypinyin import pytz from nonebot import require from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.matcher import Matcher, matchers from configs.config import SYSTEM_PROXY, Config from services.log import logger from nonebot_plugin_apscheduler import scheduler class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) The provided code snippet includes necessary dependencies for implementing the `get_group_avatar` function. Write a Python function `async def get_group_avatar(group_id: int) -> Optional[bytes]` to solve the following problem: 说明: 快捷获取用群头像 参数: :param group_id: 群号 Here is the function: async def get_group_avatar(group_id: int) -> Optional[bytes]: """ 说明: 快捷获取用群头像 参数: :param group_id: 群号 """ url = f"http://p.qlogo.cn/gh/{group_id}/{group_id}/640/" async with httpx.AsyncClient() as client: for _ in range(3): try: return (await client.get(url)).content except Exception as e: logger.error("获取群头像错误", "Util", target=group_id) return None
说明: 快捷获取用群头像 参数: :param group_id: 群号
188,329
import time from collections import defaultdict from datetime import datetime from pathlib import Path from typing import Any, Callable, List, Optional, Set, Type, Union import httpx import nonebot import pypinyin import pytz from nonebot import require from nonebot.adapters import Bot from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.matcher import Matcher, matchers from configs.config import SYSTEM_PROXY, Config from services.log import logger from nonebot_plugin_apscheduler import scheduler class logger: TEMPLATE_A = "{}" TEMPLATE_B = "[<u><c>{}</c></u>]: {}" TEMPLATE_C = "用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_D = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>]: {}" TEMPLATE_E = "群聊[<u><e>{}</e></u>] 用户[<u><e>{}</e></u>] 触发 [<u><c>{}</c></u>] [Target](<u><e>{}</e></u>): {}" TEMPLATE_USER = "用户[<u><e>{}</e></u>] " TEMPLATE_GROUP = "群聊[<u><e>{}</e></u>] " TEMPLATE_COMMAND = "CMD[<u><c>{}</c></u>] " TEMPLATE_TARGET = "[Target]([<u><e>{}</e></u>]) " SUCCESS_TEMPLATE = "[<u><c>{}</c></u>]: {} | 参数[{}] 返回: [<y>{}</y>]" WARNING_TEMPLATE = "[<u><y>{}</y></u>]: {}" ERROR_TEMPLATE = "[<u><r>{}</r></u>]: {}" def info( cls, info: str, command: Optional[str] = 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) logger_.opt(colors=True).info(template) def success( cls, info: str, command: str, param: Optional[Dict[str, Any]] = None, result: Optional[str] = "", ): param_str = "" if param: param_str = ",".join([f"<m>{k}</m>:<g>{v}</g>" for k, v in param.items()]) logger_.opt(colors=True).success( cls.SUCCESS_TEMPLATE.format(command, info, param_str, result) ) def warning( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误<r>{type(e)}: {e}</r>" logger_.opt(colors=True).warning(template) def error( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).error(template) def debug( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, e: Optional[Exception] = None, ): template = cls.__parser_template(info, command, user_id, group_id, target) if e: template += f" || 错误 <r>{type(e)}: {e}</r>" logger_.opt(colors=True).debug(template) def __parser_template( cls, info: str, command: Optional[str] = None, user_id: Optional[Union[int, str]] = None, group_id: Optional[Union[int, str]] = None, target: Optional[Any] = None, ) -> str: arg_list = [] template = "" if group_id is not None: template += cls.TEMPLATE_GROUP arg_list.append(group_id) if user_id is not None: template += cls.TEMPLATE_USER arg_list.append(user_id) if command is not None: template += cls.TEMPLATE_COMMAND arg_list.append(command) if target is not None: template += cls.TEMPLATE_TARGET arg_list.append(target) arg_list.append(info) template += "{}" return template.format(*arg_list) The provided code snippet includes necessary dependencies for implementing the `broadcast_superuser` function. Write a Python function `async def broadcast_superuser( message: Union[str, Message, MessageSegment], bot: Optional[Union[Bot, List[Bot]]] = None, bot_id: Optional[Union[str, Set[str]]] = None, ignore_superuser: Optional[Set[int]] = None, check_func: Optional[Callable[[int], bool]] = None, log_cmd: Optional[str] = None, )` to solve the following problem: 获取所有Bot或指定Bot对象广播超级用户 Args: message (Any): 广播消息内容 bot (Optional[Bot], optional): 指定bot对象. Defaults to None. bot_id (Optional[str], optional): 指定bot id. Defaults to None. ignore_superuser (Optional[List[int]], optional): 忽略的超级用户id. Defaults to None. check_func (Optional[Callable[[int], bool]], optional): 发送前对群聊检测方法,判断是否发送. Defaults to None. log_cmd (Optional[str], optional): 日志标记. Defaults to None. Here is the function: async def broadcast_superuser( message: Union[str, Message, MessageSegment], bot: Optional[Union[Bot, List[Bot]]] = None, bot_id: Optional[Union[str, Set[str]]] = None, ignore_superuser: Optional[Set[int]] = None, check_func: Optional[Callable[[int], bool]] = None, log_cmd: Optional[str] = None, ): """获取所有Bot或指定Bot对象广播超级用户 Args: message (Any): 广播消息内容 bot (Optional[Bot], optional): 指定bot对象. Defaults to None. bot_id (Optional[str], optional): 指定bot id. Defaults to None. ignore_superuser (Optional[List[int]], optional): 忽略的超级用户id. Defaults to None. check_func (Optional[Callable[[int], bool]], optional): 发送前对群聊检测方法,判断是否发送. Defaults to None. log_cmd (Optional[str], optional): 日志标记. Defaults to None. """ if not message: raise ValueError("超级用户广播消息不能为空") bot_dict = nonebot.get_bots() bot_list: List[Bot] = [] if bot: if isinstance(bot, list): bot_list = bot else: bot_list.append(bot) elif bot_id: _bot_id_list = bot_id if isinstance(bot_id, str): _bot_id_list = [bot_id] for id_ in _bot_id_list: if bot_id in bot_dict: bot_list.append(bot_dict[bot_id]) else: logger.warning(f"Bot:{id_} 对象未连接或不存在") else: bot_list = list(bot_dict.values()) _used_user = [] for _bot in bot_list: try: for user_id in _bot.config.superusers: try: if ( ignore_superuser and int(user_id) in ignore_superuser ) or user_id in _used_user: continue if check_func and not check_func(int(user_id)): continue _used_user.append(user_id) await _bot.send_private_message( user_id=int(user_id), message=message ) except Exception as e: logger.error( f"广播超级用户发消息失败: {message}", command=log_cmd, user_id=user_id, e=e, ) except Exception as e: logger.error(f"Bot: {_bot.self_id} 获取群聊列表失败", command=log_cmd, e=e)
获取所有Bot或指定Bot对象广播超级用户 Args: message (Any): 广播消息内容 bot (Optional[Bot], optional): 指定bot对象. Defaults to None. bot_id (Optional[str], optional): 指定bot id. Defaults to None. ignore_superuser (Optional[List[int]], optional): 忽略的超级用户id. Defaults to None. check_func (Optional[Callable[[int], bool]], optional): 发送前对群聊检测方法,判断是否发送. Defaults to None. log_cmd (Optional[str], optional): 日志标记. Defaults to None.
188,330
import asyncio import base64 import os import random import re import uuid from io import BytesIO from math import ceil from pathlib import Path from typing import Any, Awaitable, Callable, List, Literal, Optional, Tuple, Union import cv2 import imagehash from imagehash import ImageHash from matplotlib import pyplot as plt from nonebot.utils import is_coroutine_callable from PIL import Image, ImageDraw, ImageFile, ImageFilter, ImageFont from PIL.ImageFont import FreeTypeFont from configs.path_config import FONT_PATH, IMAGE_PATH from services import logger ImageFile.LOAD_TRUNCATED_IMAGES = True def get_img_hash(image_file: Union[str, Path]) -> ImageHash: """ 说明: 获取图片的hash值 参数: :param image_file: 图片文件路径 """ with open(image_file, "rb") as fp: hash_value = imagehash.average_hash(Image.open(fp)) return hash_value The provided code snippet includes necessary dependencies for implementing the `compare_image_with_hash` function. Write a Python function `def compare_image_with_hash( image_file1: str, image_file2: str, max_dif: float = 1.5 ) -> bool` to solve the following problem: 说明: 比较两张图片的hash值是否相同 参数: :param image_file1: 图片文件路径 :param image_file2: 图片文件路径 :param max_dif: 允许最大hash差值, 越小越精确,最小为0 Here is the function: def compare_image_with_hash( image_file1: str, image_file2: str, max_dif: float = 1.5 ) -> bool: """ 说明: 比较两张图片的hash值是否相同 参数: :param image_file1: 图片文件路径 :param image_file2: 图片文件路径 :param max_dif: 允许最大hash差值, 越小越精确,最小为0 """ ImageFile.LOAD_TRUNCATED_IMAGES = True hash_1 = get_img_hash(image_file1) hash_2 = get_img_hash(image_file2) dif = hash_1 - hash_2 if dif < 0: dif = -dif if dif <= max_dif: return True else: return False
说明: 比较两张图片的hash值是否相同 参数: :param image_file1: 图片文件路径 :param image_file2: 图片文件路径 :param max_dif: 允许最大hash差值, 越小越精确,最小为0