修复静态资源可能因ssl导致的问题

This commit is contained in:
CMHopeSunshine 2022-05-21 14:55:23 +08:00
parent 4423de3fd4
commit ef00094b8f
7 changed files with 122 additions and 66 deletions

View File

@ -1,6 +1,7 @@
import random import random
import requests import requests
from ssl import SSLCertVerificationError
from nonebot import on_regex, on_command, logger from nonebot import on_regex, on_command, logger
from nonebot.matcher import matchers from nonebot.matcher import matchers
from nonebot.rule import Rule from nonebot.rule import Rule
@ -27,7 +28,10 @@ async def update_paimon_voice(event: MessageEvent):
try: try:
old_len = len([m for m in matchers[10] if m.plugin_name == 'Paimon_Chat']) 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'] matchers[10] = [m for m in matchers[10] if m.plugin_name != 'Paimon_Chat']
try:
voice_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() 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(): for key, value in voice_list.items():
create_matcher(key, value['pattern'], value['cooldown'], value['pro'], value['files']) create_matcher(key, value['pattern'], value['cooldown'], value['pro'], value['files'])
new_len = len(voice_list) - old_len 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): 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.plugin_name = 'Paimon_Chat'
@hammer.handle() @hammer.handle()
async def handler(event: GroupMessageEvent): async def handler(event: GroupMessageEvent):
if not chat_lmt.check(event.group_id, chat_word):
return
else:
if not random.random() < pro:
return
else:
try: try:
chat_lmt.start_cd(event.group_id, chat_word, cooldown) chat_lmt.start_cd(event.group_id, chat_word, cooldown)
response = random.choice(responses) response = random.choice(responses)
if '.mp3' not in response: if '.mp3' not in response:
await hammer.finish(response) await hammer.finish(response)
else: else:
try:
await hammer.finish(MessageSegment.record(file=voice_url + response)) 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: except FinishedException:
raise raise
except Exception as e: except Exception as e:
logger.error('派蒙发送语音失败', e) logger.error('派蒙发送语音失败', e)
chat_list = requests.get('https://static.cherishmoon.fun/LittlePaimon/voice/voice_list.json').json() try:
for k, v in chat_list.items(): 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']) create_matcher(k, v['pattern'], v['cooldown'], v['pro'], v['files'])

View File

@ -2,6 +2,8 @@ import os
import re import re
import time import time
from ssl import SSLCertVerificationError
from nonebot import on_endswith, on_command, on_regex from nonebot import on_endswith, on_command, on_regex
from nonebot.adapters.onebot.v11 import MessageSegment, MessageEvent from nonebot.adapters.onebot.v11 import MessageSegment, MessageEvent
from nonebot.params import RegexDict from nonebot.params import RegexDict
@ -43,8 +45,12 @@ async def genshin_guide(event: MessageEvent):
realname = get_id_by_alias(name) realname = get_id_by_alias(name)
if name in ['风主', '岩主', '雷主'] or realname: if name in ['风主', '岩主', '雷主'] or realname:
name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name
img = MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/XFGuide/{name}.jpg') try:
await guide.finish(img) 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: else:
await guide.finish(f'没有找到{name}的攻略', at_sender=True) await guide.finish(f'没有找到{name}的攻略', at_sender=True)
@ -56,10 +62,12 @@ async def genshin_material(event: MessageEvent):
realname = get_id_by_alias(name) realname = get_id_by_alias(name)
if name in ['夜兰', '久岐忍'] or realname: if name in ['夜兰', '久岐忍'] or realname:
name = realname[1][0] if realname else name name = realname[1][0] if realname else name
print(name) try:
img = MessageSegment.image( await material.finish(
file=f'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg') MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg'))
await material.finish(img) except SSLCertVerificationError:
await material.finish(
MessageSegment.image(file=f'http://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{name}材料.jpg'))
else: else:
await material.finish(f'没有找到{name}的材料', at_sender=True) await material.finish(f'没有找到{name}的材料', at_sender=True)
@ -84,8 +92,13 @@ async def genshinAttribute2(event: MessageEvent):
realname = get_id_by_alias(name) realname = get_id_by_alias(name)
if name in ['风主', '岩主', '雷主'] or realname: if name in ['风主', '岩主', '雷主'] or realname:
name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name name = realname[1][0] if name not in ['风主', '岩主', '雷主'] else name
img = MessageSegment.image(file=f'https://static.cherishmoon.fun/LittlePaimon/blue/{name}.jpg') try:
await attribute2.finish(img) 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: else:
await attribute2.finish(f'没有找到{name}的收益曲线', at_sender=True) await attribute2.finish(f'没有找到{name}的收益曲线', at_sender=True)
@ -114,15 +127,15 @@ async def daily_material_handle(event: MessageEvent):
if week == "0": if week == "0":
await daily_material.finish('周日所有材料都可以刷哦!', at_sender=True) await daily_material.finish('周日所有材料都可以刷哦!', at_sender=True)
elif week in ['1', '4']: elif week in ['1', '4']:
img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周一周四.jpg'
'/DailyMaterials/周一周四.jpg')
elif week in ['2', '5']: elif week in ['2', '5']:
img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周二周五.jpg'
'/DailyMaterials/周二周五.jpg')
else: else:
img = MessageSegment.image(file='https://static.cherishmoon.fun/LittlePaimon' url = 'https://static.cherishmoon.fun/LittlePaimon/DailyMaterials/周三周六.jpg'
'/DailyMaterials/周三周六.jpg') try:
await daily_material.finish(img) await daily_material.finish(MessageSegment.image(file=url))
except SSLCertVerificationError:
await daily_material.finish(MessageSegment.image(file=url.replace('https', 'http')))
@abyss_rate.handle() @abyss_rate.handle()
@ -143,4 +156,9 @@ async def abyss_team_handler(event: MessageEvent, reGroup=RegexDict()):
@exception_handler() @exception_handler()
async def weapon_guide_handler(event: MessageEvent): async def weapon_guide_handler(event: MessageEvent):
name: str = event.message.extract_plain_text().replace('武器攻略', '').strip() 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'))

View File

@ -60,7 +60,6 @@ blue = {
async def get_blue_pic(name): async def get_blue_pic(name):
for c in blue.items(): for c in blue.items():
if c[0] == name: if c[0] == name:
img = await aiorequests.get_img(url=f'https://static.cherishmoon.fun/LittlePaimon/blue/{c[1][0]}.jpg') 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])))
img = img.crop((0, int(c[1][1][0]), 1080, int(c[1][1][1])))
return MessageBuild.Image(img) return MessageBuild.Image(img)
return None return None

View File

@ -1,5 +1,5 @@
<p align="center" > <p align="center" >
<a href="https://github.com/CMHopeSunshine/LittlePaimon/tree/nonebot2"><img src="https://static.cherishmoon.fun/LittlePaimon/readme/logo.png" width="256" height="256" alt="LittlePaimon"></a> <a href="https://github.com/CMHopeSunshine/LittlePaimon/tree/nonebot2"><img src="http://static.cherishmoon.fun/LittlePaimon/readme/logo.png" width="256" height="256" alt="LittlePaimon"></a>
</p> </p>
<h1 align="center">小派蒙|LittlePaimon</h1> <h1 align="center">小派蒙|LittlePaimon</h1>
<h4 align="center">✨基于<a href="https://github.com/Ice-Cirno/HoshinoBot" target="_blank">HoshinoBot</a>|<a href="https://github.com/nonebot/nonebot2" target="_blank">NoneBot2</a><a href="https://github.com/Mrs4s/go-cqhttp" target="_blank">go-cqhttp</a>的原神Q群机器人✨</h4> <h4 align="center">✨基于<a href="https://github.com/Ice-Cirno/HoshinoBot" target="_blank">HoshinoBot</a>|<a href="https://github.com/nonebot/nonebot2" target="_blank">NoneBot2</a><a href="https://github.com/Mrs4s/go-cqhttp" target="_blank">go-cqhttp</a>的原神Q群机器人✨</h4>
@ -21,46 +21,46 @@
## 丨功能示例 ## 丨功能示例
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/ys.jpg" alt="ys"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/ys.jpg" alt="ys">
<details> <details>
<summary>角色背包</summary> <summary>角色背包</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/ysa.jpg" alt="ysa"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/ysa.jpg" alt="ysa">
</details> </details>
<details> <details>
<summary>角色详情</summary> <summary>角色详情</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/ysc.jpg" alt="ysc"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/ysc.jpg" alt="ysc">
</details> </details>
<details> <details>
<summary>深渊信息</summary> <summary>深渊信息</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/sy12.jpg" alt="sy"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/sy12.jpg" alt="sy">
</details> </details>
<details> <details>
<summary>模拟抽卡</summary> <summary>模拟抽卡</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/十连.jpg" alt="十连"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/十连.jpg" alt="十连">
</details> </details>
<details> <details>
<summary>实时便签</summary> <summary>实时便签</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/ssbq.jpg" alt="ssbq"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/ssbq.jpg" alt="ssbq">
</details> </details>
<details> <details>
<summary>每月札记</summary> <summary>每月札记</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/myzj.jpg" alt="myzj"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/myzj.jpg" alt="myzj">
</details> </details>
<details> <details>
<summary>角色材料</summary> <summary>角色材料</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/material.png" alt="material"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/material.png" alt="material">
</details> </details>
<details> <details>
<summary>抽卡记录</summary> <summary>抽卡记录</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/gachalog.jpg" alt="gachalog"> <img src="http://static.cherishmoon.fun/LittlePaimon/readme/gachalog.jpg" alt="gachalog">
</details> </details>
## 丨更新日志 ## 丨更新日志
@ -73,6 +73,8 @@
- 修复`ysc`缺少资源问题 - 修复`ysc`缺少资源问题
- 封装部分常用方法,优化导包 - 封装部分常用方法,优化导包
- `Paimon_Chat`新增`更新派蒙语音`,实时更新语音 - `Paimon_Chat`新增`更新派蒙语音`,实时更新语音
+ 5.21
- 修复可能因ssl证书导致的静态资源下载问题
## 丨功能列表 ## 丨功能列表

View File

@ -1,9 +1,11 @@
import base64 import traceback
from typing import Dict, Optional, Any, Union, Tuple
from pathlib import Path
from io import BytesIO 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 import httpx
from PIL import Image
async def get(url: str, async def get(url: str,
@ -66,7 +68,7 @@ async def get_img(url: str,
save_path: Optional[Union[str, Path]] = None, save_path: Optional[Union[str, Path]] = None,
size: Optional[Tuple[int, int]] = None, size: Optional[Tuple[int, int]] = None,
mode: Optional[str] = None, mode: Optional[str] = None,
to_b64: bool = False, crop: Optional[Tuple[int, int, int, int]] = None,
**kwargs) -> Union[str, Image.Image]: **kwargs) -> Union[str, Image.Image]:
""" """
说明 说明
@ -79,26 +81,47 @@ async def get_img(url: str,
:param save_path: 保存路径为空则不保存 :param save_path: 保存路径为空则不保存
:param size: 图片尺寸为空则不做修改 :param size: 图片尺寸为空则不做修改
:param mode: 图片模式为空则不做修改 :param mode: 图片模式为空则不做修改
:param to_b64: 是否转b64 :param crop: 图片裁剪为空则不做修改
""" """
try:
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
resp = await client.get(url, resp = await client.get(url,
headers=headers, headers=headers,
params=params, params=params,
timeout=timeout, timeout=timeout,
**kwargs) **kwargs)
if to_b64:
return 'base64://' + base64.b64encode(resp.read()).decode()
else:
img = Image.open(BytesIO(resp.read())) img = Image.open(BytesIO(resp.read()))
if size: if size:
img = img.resize(size, Image.ANTIALIAS) img = img.resize(size, Image.ANTIALIAS)
if mode: if mode:
img = img.convert(mode) img = img.convert(mode)
if crop:
img = img.crop(crop)
if save_path: if save_path:
if isinstance(save_path, str): if isinstance(save_path, str):
save_path = Path(save_path) save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True) save_path.parent.mkdir(parents=True, exist_ok=True)
img.save(save_path) img.save(save_path)
return img 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()

View File

@ -8,6 +8,7 @@ def load_image(
path: Union[Path, str], path: Union[Path, str],
*, *,
size: Optional[Union[Tuple[int, int], float]] = None, size: Optional[Union[Tuple[int, int], float]] = None,
crop: Optional[Tuple[int, int, int, int]] = None,
mode: Optional[str] = 'RGB' mode: Optional[str] = 'RGB'
): ):
img = Image.open(path) 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) img = img.resize((int(img.size[0] * size), int(img.size[1] * size)), Image.ANTIALIAS)
elif isinstance(size, tuple): elif isinstance(size, tuple):
img = img.resize(size, Image.ANTIALIAS) img = img.resize(size, Image.ANTIALIAS)
if crop:
img = img.crop(crop)
img = img.convert(mode) img = img.convert(mode)
return img return img

View File

@ -1,4 +1,3 @@
# 获取message中的艾特对象
import re import re
import base64 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 .db_util import get_last_query, update_last_query
from .file_handler import load_image from .file_handler import load_image
from . import aiorequests
class MessageBuild: class MessageBuild:
@ -21,13 +21,13 @@ class MessageBuild:
img: Union[Image.Image, Path, str], img: Union[Image.Image, Path, str],
*, *,
size: Optional[Union[Tuple[int, int], float]] = None, size: Optional[Union[Tuple[int, int], float]] = None,
crop: Optional[Tuple[int, int, int, int]] = None,
quality: Optional[int] = 100, quality: Optional[int] = 100,
mode: Optional[str] = 'RGB' mode: Optional[str] = 'RGB'
) -> MessageSegment: ) -> MessageSegment:
if isinstance(img, str) or isinstance(img, Path): 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() bio = BytesIO()
img = img.convert(mode)
img.save(bio, format='JPEG' if mode == 'RGB' else 'PNG', quality=quality) img.save(bio, format='JPEG' if mode == 'RGB' else 'PNG', quality=quality)
img_b64 = 'base64://' + base64.b64encode(bio.getvalue()).decode() img_b64 = 'base64://' + base64.b64encode(bio.getvalue()).decode()
return MessageSegment.image(img_b64) return MessageSegment.image(img_b64)