From ef00094b8fdb8f2d5f22662e0da666b0b337a63e Mon Sep 17 00:00:00 2001 From: CMHopeSunshine <277073121@qq.com> Date: Sat, 21 May 2022 14:55:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=9D=99=E6=80=81=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8F=AF=E8=83=BD=E5=9B=A0ssl=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Paimon_Chat/__init__.py | 49 ++++++++++++++++++++++-------------- Paimon_Wiki/__init__.py | 50 +++++++++++++++++++++++++------------ Paimon_Wiki/blue.py | 3 +-- README.md | 22 +++++++++-------- utils/aiorequests.py | 55 +++++++++++++++++++++++++++++------------ utils/file_handler.py | 3 +++ utils/message_util.py | 6 ++--- 7 files changed, 122 insertions(+), 66 deletions(-) diff --git a/Paimon_Chat/__init__.py b/Paimon_Chat/__init__.py index 1af6dd5..bc037fe 100644 --- a/Paimon_Chat/__init__.py +++ b/Paimon_Chat/__init__.py @@ -1,6 +1,7 @@ import random import requests +from ssl import SSLCertVerificationError from nonebot import on_regex, on_command, logger from nonebot.matcher import matchers from nonebot.rule import Rule @@ -27,7 +28,10 @@ async def update_paimon_voice(event: MessageEvent): try: old_len = len([m for m in matchers[10] if m.plugin_name == 'Paimon_Chat']) matchers[10] = [m for m in matchers[10] if m.plugin_name != 'Paimon_Chat'] - voice_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() + try: + voice_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() + except SSLCertVerificationError: + voice_list = requests.get('http://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() for key, value in voice_list.items(): create_matcher(key, value['pattern'], value['cooldown'], value['pro'], value['files']) new_len = len(voice_list) - old_len @@ -39,30 +43,37 @@ async def update_paimon_voice(event: MessageEvent): def create_matcher(chat_word: str, pattern: str, cooldown: int, pro: float, responses): - hammer = on_regex(pattern, priority=10, rule=Rule(check_group)) + + def check_pro() -> bool: + return random.random() < pro + + def check_cooldown(event: GroupMessageEvent) -> bool: + return chat_lmt.check(event.group_id, chat_word) + + hammer = on_regex(pattern, priority=10, rule=Rule(check_group, check_pro, check_cooldown)) hammer.plugin_name = 'Paimon_Chat' @hammer.handle() async def handler(event: GroupMessageEvent): - if not chat_lmt.check(event.group_id, chat_word): - return - else: - if not random.random() < pro: - return + try: + chat_lmt.start_cd(event.group_id, chat_word, cooldown) + response = random.choice(responses) + if '.mp3' not in response: + await hammer.finish(response) else: try: - chat_lmt.start_cd(event.group_id, chat_word, cooldown) - response = random.choice(responses) - if '.mp3' not in response: - await hammer.finish(response) - else: - await hammer.finish(MessageSegment.record(file=voice_url + response)) - except FinishedException: - raise - except Exception as e: - logger.error('派蒙发送语音失败', e) + await hammer.finish(MessageSegment.record(file=voice_url + response)) + except SSLCertVerificationError: + await hammer.finish(MessageSegment.record(file=voice_url.replace('https', 'http') + response)) + except FinishedException: + raise + except Exception as e: + logger.error('派蒙发送语音失败', e) -chat_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() -for k, v in chat_list.items(): +try: + voice_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() +except SSLCertVerificationError: + voice_list = requests.get('http://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() +for k, v in voice_list.items(): create_matcher(k, v['pattern'], v['cooldown'], v['pro'], v['files']) diff --git a/Paimon_Wiki/__init__.py b/Paimon_Wiki/__init__.py index 47bb52c..c20053f 100644 --- a/Paimon_Wiki/__init__.py +++ b/Paimon_Wiki/__init__.py @@ -2,6 +2,8 @@ import os import re import time +from ssl import SSLCertVerificationError + from nonebot import on_endswith, on_command, on_regex from nonebot.adapters.onebot.v11 import MessageSegment, MessageEvent from nonebot.params import RegexDict @@ -43,8 +45,12 @@ async def genshin_guide(event: MessageEvent): realname = get_id_by_alias(name) if name in ['风主', '岩主', '雷主'] or realname: name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name - img = MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/XFGuide/{name}.jpg') - await guide.finish(img) + try: + await guide.finish( + MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/XFGuide/{name}.jpg')) + except SSLCertVerificationError: + await guide.finish( + MessageSegment.image(file=f'http://static.cherishmoon.fun/LittlePaimon/XFGuide/{name}.jpg')) else: await guide.finish(f'没有找到{name}的攻略', at_sender=True) @@ -56,10 +62,12 @@ async def genshin_material(event: MessageEvent): realname = get_id_by_alias(name) if name in ['夜兰', '久岐忍'] or realname: name = realname[1][0] if realname else name - print(name) - img = MessageSegment.image( - file=f'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg') - await material.finish(img) + try: + await material.finish( + MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg')) + except SSLCertVerificationError: + await material.finish( + MessageSegment.image(file=f'http://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg')) else: await material.finish(f'没有找到{name}的材料', at_sender=True) @@ -84,8 +92,13 @@ async def genshinAttribute2(event: MessageEvent): realname = get_id_by_alias(name) if name in ['风主', '岩主', '雷主'] or realname: name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name - img = MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/blue/{name}.jpg') - await attribute2.finish(img) + try: + await attribute2.finish( + MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/blue/{name}.jpg')) + except SSLCertVerificationError: + await attribute2.finish( + MessageSegment.image(file=f'http://static.cherishmoon.fun/LittlePaimon/blue/{name}.jpg')) + else: await attribute2.finish(f'没有找到{name}的收益曲线', at_sender=True) @@ -114,15 +127,15 @@ async def daily_material_handle(event: MessageEvent): if week == "0": await daily_material.finish('周日所有材料都可以刷哦!', at_sender=True) elif week in ['1', '4']: - img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' - '/DailyMaterials/周一周四.jpg') + url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周一周四.jpg' elif week in ['2', '5']: - img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' - '/DailyMaterials/周二周五.jpg') + url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周二周五.jpg' else: - img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' - '/DailyMaterials/周三周六.jpg') - await daily_material.finish(img) + url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周三周六.jpg' + try: + await daily_material.finish(MessageSegment.image(file=url)) + except SSLCertVerificationError: + await daily_material.finish(MessageSegment.image(file=url.replace('https', 'http'))) @abyss_rate.handle() @@ -143,4 +156,9 @@ async def abyss_team_handler(event: MessageEvent, reGroup=RegexDict()): @exception_handler() async def weapon_guide_handler(event: MessageEvent): name: str = event.message.extract_plain_text().replace('武器攻略', '').strip() - await weapon_guide.finish(MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/WeaponGuild/{name}.png')) + try: + await weapon_guide.finish( + MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/WeaponGuild/{name}.png')) + except SSLCertVerificationError: + await weapon_guide.finish( + MessageSegment.image(file=f'http://static.cherishmoon.fun/LittlePaimon/WeaponGuild/{name}.png')) \ No newline at end of file diff --git a/Paimon_Wiki/blue.py b/Paimon_Wiki/blue.py index deeffac..75d4d3f 100644 --- a/Paimon_Wiki/blue.py +++ b/Paimon_Wiki/blue.py @@ -60,7 +60,6 @@ blue = { async def get_blue_pic(name): for c in blue.items(): if c[0] == name: - img = await aiorequests.get_img(url=f'https://static.cherishmoon.fun/LittlePaimon/blue/{c[1][0]}.jpg') - img = img.crop((0, int(c[1][1][0]), 1080, int(c[1][1][1]))) + img = await aiorequests.get_img(url=f'https://static.cherishmoon.fun/LittlePaimon/blue/{c[1][0]}.jpg', crop=(0, int(c[1][1][0]), 1080, int(c[1][1][1]))) return MessageBuild.Image(img) return None diff --git a/README.md b/README.md index c1f4408..6b87daf 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- LittlePaimon + LittlePaimon

小派蒙|LittlePaimon

✨基于HoshinoBot|NoneBot2go-cqhttp的原神Q群机器人✨

@@ -21,46 +21,46 @@ ## 丨功能示例 -ys +ys
角色背包 -ysa +ysa
角色详情 -ysc +ysc
深渊信息 -sy +sy
模拟抽卡 -十连 +十连
实时便签 -ssbq +ssbq
每月札记 -myzj +myzj
角色材料 -material +material
抽卡记录 -gachalog +gachalog
## 丨更新日志 @@ -73,6 +73,8 @@ - 修复`ysc`缺少资源问题 - 封装部分常用方法,优化导包 - `Paimon_Chat`新增`更新派蒙语音`,实时更新语音 ++ 5.21 + - 修复可能因ssl证书导致的静态资源下载问题 ## 丨功能列表 diff --git a/utils/aiorequests.py b/utils/aiorequests.py index 0c38d2f..90a20ab 100644 --- a/utils/aiorequests.py +++ b/utils/aiorequests.py @@ -1,9 +1,11 @@ -import base64 -from typing import Dict, Optional, Any, Union, Tuple -from pathlib import Path +import traceback from io import BytesIO -from PIL import Image +from pathlib import Path +from ssl import SSLCertVerificationError +from typing import Dict, Optional, Any, Union, Tuple + import httpx +from PIL import Image async def get(url: str, @@ -66,7 +68,7 @@ async def get_img(url: str, save_path: Optional[Union[str, Path]] = None, size: Optional[Tuple[int, int]] = None, mode: Optional[str] = None, - to_b64: bool = False, + crop: Optional[Tuple[int, int, int, int]] = None, **kwargs) -> Union[str, Image.Image]: """ 说明: @@ -79,26 +81,47 @@ async def get_img(url: str, :param save_path: 保存路径,为空则不保存 :param size: 图片尺寸,为空则不做修改 :param mode: 图片模式,为空则不做修改 - :param to_b64: 是否转b64 + :param crop: 图片裁剪,为空则不做修改 """ - async with httpx.AsyncClient() as client: - resp = await client.get(url, - - headers=headers, - params=params, - timeout=timeout, - **kwargs) - if to_b64: - return 'base64://' + base64.b64encode(resp.read()).decode() - else: + try: + async with httpx.AsyncClient() as client: + resp = await client.get(url, + headers=headers, + params=params, + timeout=timeout, + **kwargs) img = Image.open(BytesIO(resp.read())) if size: img = img.resize(size, Image.ANTIALIAS) if mode: img = img.convert(mode) + if crop: + img = img.crop(crop) if save_path: if isinstance(save_path, str): save_path = Path(save_path) save_path.parent.mkdir(parents=True, exist_ok=True) img.save(save_path) return img + except SSLCertVerificationError: + async with httpx.AsyncClient() as client: + resp = await client.get(url.replace('https', 'http'), + headers=headers, + params=params, + timeout=timeout, + **kwargs) + img = Image.open(BytesIO(resp.read())) + if size: + img = img.resize(size, Image.ANTIALIAS) + if mode: + img = img.convert(mode) + if crop: + img = img.crop(crop) + if save_path: + if isinstance(save_path, str): + save_path = Path(save_path) + save_path.parent.mkdir(parents=True, exist_ok=True) + img.save(save_path) + return img + except Exception: + traceback.print_exc() diff --git a/utils/file_handler.py b/utils/file_handler.py index a721c57..38ac89d 100644 --- a/utils/file_handler.py +++ b/utils/file_handler.py @@ -8,6 +8,7 @@ def load_image( path: Union[Path, str], *, size: Optional[Union[Tuple[int, int], float]] = None, + crop: Optional[Tuple[int, int, int, int]] = None, mode: Optional[str] = 'RGB' ): img = Image.open(path) @@ -16,6 +17,8 @@ def load_image( img = img.resize((int(img.size[0] * size), int(img.size[1] * size)), Image.ANTIALIAS) elif isinstance(size, tuple): img = img.resize(size, Image.ANTIALIAS) + if crop: + img = img.crop(crop) img = img.convert(mode) return img diff --git a/utils/message_util.py b/utils/message_util.py index 121ebf5..fe63a2c 100644 --- a/utils/message_util.py +++ b/utils/message_util.py @@ -1,4 +1,3 @@ -# 获取message中的艾特对象 import re import base64 @@ -12,6 +11,7 @@ from nonebot.adapters.onebot.v11 import MessageEvent, Message, MessageSegment from .db_util import get_last_query, update_last_query from .file_handler import load_image +from . import aiorequests class MessageBuild: @@ -21,13 +21,13 @@ class MessageBuild: img: Union[Image.Image, Path, str], *, size: Optional[Union[Tuple[int, int], float]] = None, + crop: Optional[Tuple[int, int, int, int]] = None, quality: Optional[int] = 100, mode: Optional[str] = 'RGB' ) -> MessageSegment: if isinstance(img, str) or isinstance(img, Path): - img = load_image(path=img, size=size, mode=mode) + img = load_image(path=img, size=size, mode=mode, crop=crop) bio = BytesIO() - img = img.convert(mode) img.save(bio, format='JPEG' if mode == 'RGB' else 'PNG', quality=quality) img_b64 = 'base64://' + base64.b64encode(bio.getvalue()).decode() return MessageSegment.image(img_b64)