修复静态资源可能因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 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'])

View File

@ -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'))

View File

@ -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

View File

@ -1,5 +1,5 @@
<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>
<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>
@ -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>
<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>
<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>
<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>
<summary>模拟抽卡</summary>
<img src="https://static.cherishmoon.fun/LittlePaimon/readme/十连.jpg" alt="十连">
<img src="http://static.cherishmoon.fun/LittlePaimon/readme/十连.jpg" alt="十连">
</details>
<details>
<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>
<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>
<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>
<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>
## 丨更新日志
@ -73,6 +73,8 @@
- 修复`ysc`缺少资源问题
- 封装部分常用方法,优化导包
- `Paimon_Chat`新增`更新派蒙语音`,实时更新语音
+ 5.21
- 修复可能因ssl证书导致的静态资源下载问题
## 丨功能列表

View File

@ -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()

View File

@ -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

View File

@ -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)