From 1fda9c81e951c8c961e4eee65d9d9aced0cb6420 Mon Sep 17 00:00:00 2001
From: CMHopeSunshine <277073121@qq.com>
Date: Tue, 6 Dec 2022 23:07:34 +0800
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E4=BF=AE=E6=94=B9=E8=B5=84?=
=?UTF-8?q?=E6=BA=90=E6=9B=B4=E6=96=B0=E5=9C=B0=E5=9D=80=EF=BC=8C=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0`github=E8=B5=84=E6=BA=90=E5=9C=B0=E5=9D=80`=E9=85=8D?=
=?UTF-8?q?=E7=BD=AE=E9=A1=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
LittlePaimon/config/config/model.py | 2 ++
.../plugins/Learning_Chat/web_page.py | 8 ++---
LittlePaimon/plugins/Paimon_Wiki/__init__.py | 31 ++++++++--------
LittlePaimon/plugins/Paimon_Wiki/card.py | 7 ++--
LittlePaimon/utils/tool.py | 35 +++++++++++--------
LittlePaimon/web/pages/config_manage.py | 25 +++++++++++++
matcher_patch.py | 2 +-
7 files changed, 72 insertions(+), 38 deletions(-)
diff --git a/LittlePaimon/config/config/model.py b/LittlePaimon/config/config/model.py
index 25d7a89..252dc0f 100644
--- a/LittlePaimon/config/config/model.py
+++ b/LittlePaimon/config/config/model.py
@@ -47,6 +47,8 @@ class ConfigModel(BaseModel):
command_alias_enable: bool = Field(True, alias='启用命令别名')
+ github_proxy: str = Field('https://ghproxy.com/', alias='github资源地址')
+
@property
def alias_dict(self):
return {v.alias: k for k, v in self.__fields__.items()}
diff --git a/LittlePaimon/plugins/Learning_Chat/web_page.py b/LittlePaimon/plugins/Learning_Chat/web_page.py
index 400b9da..d6b66e8 100644
--- a/LittlePaimon/plugins/Learning_Chat/web_page.py
+++ b/LittlePaimon/plugins/Learning_Chat/web_page.py
@@ -239,7 +239,7 @@ context_table = TableCRUD(mode='table',
message_page = PageSchema(url='/chat/messages', icon='fa fa-comments', label='群聊消息',
schema=Page(title='群聊消息', body=[
Alert(level=LevelEnum.info,
- className='white-space-pre',
+ className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}收到的除指令外的聊天记录。\n'
'· 点击"禁用"可以将某条聊天记录进行禁用,这样其相关的学习就会列入禁用列表。\n'
'· 点击"删除"可以删除某条记录,但不会影响它的学习。\n'
@@ -248,7 +248,7 @@ message_page = PageSchema(url='/chat/messages', icon='fa fa-comments', label='
context_page = PageSchema(url='/chat/contexts', icon='fa fa-comment', label='学习内容',
schema=Page(title='内容',
body=[Alert(level=LevelEnum.info,
- className='white-space-pre',
+ className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}所学习的内容。\n'
'· 点击"回复列表"可以查看该条内容已学习到的可能的回复。\n'
'· 点击"禁用"可以将该学习进行禁用,以后不会再学。\n'
@@ -257,7 +257,7 @@ context_page = PageSchema(url='/chat/contexts', icon='fa fa-comment', label='学
answer_page = PageSchema(url='/chat/answers', icon='fa fa-commenting-o', label='内容回复',
schema=Page(title='回复',
body=[Alert(level=LevelEnum.info,
- className='white-space-pre',
+ className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}已学习到的所有回复,但看不到这些回复属于哪些内容,推荐到"学习内容"表进行操作。\n'
'· 点击"禁用"可以将该回复进行禁用,以后不会再学。\n'
'· 点击"删除"可以删除该回复,让它重新开始学习。')),
@@ -265,7 +265,7 @@ answer_page = PageSchema(url='/chat/answers', icon='fa fa-commenting-o', label='
blacklist_page = PageSchema(url='/chat/blacklist', icon='fa fa-ban', label='禁用列表',
schema=Page(title='禁用列表',
body=[Alert(level=LevelEnum.info,
- className='white-space-pre',
+ className='white-space-pre-wrap',
body=f'此数据库记录了{NICKNAME}被禁用的内容/关键词。\n'
'· 可以取消禁用,使其能够重新继续学习。\n'
'· 不能在此添加禁用,只能在群中回复[不可以]或者在<配置>中添加屏蔽词来达到禁用效果。'),
diff --git a/LittlePaimon/plugins/Paimon_Wiki/__init__.py b/LittlePaimon/plugins/Paimon_Wiki/__init__.py
index 3c841b5..0d26720 100644
--- a/LittlePaimon/plugins/Paimon_Wiki/__init__.py
+++ b/LittlePaimon/plugins/Paimon_Wiki/__init__.py
@@ -11,6 +11,7 @@ from nonebot.typing import T_State
from LittlePaimon.database import PlayerAlias
from LittlePaimon.utils import NICKNAME
+from LittlePaimon.config import config
from LittlePaimon.utils.alias import get_match_alias
from LittlePaimon.utils.message import MessageBuild, fullmatch_rule
from LittlePaimon.utils.path import RESOURCE_BASE_PATH
@@ -216,7 +217,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
if '武器' in state['type']:
state['type'] = '武器'
# state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/WeaponMaps/{}.jpg'
- state['img_url'] = 'https://github.cherishmoon.fun/https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/weapon/{}.png'
+ state['img_url'] = '{}https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/weapon/{}.png'
elif '圣遗物' in state['type']:
state['type'] = '圣遗物'
state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/ArtifactMaps/{}.jpg'
@@ -230,10 +231,10 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
state['type'] = '角色'
# state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{}材料.jpg'
state[
- 'img_url'] = 'https://github.cherishmoon.fun/https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/material%20for%20role/{}.png'
+ 'img_url'] = '{}https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/material%20for%20role/{}.png'
elif state['type'] == '角色图鉴':
state['type'] = '角色'
- state['img_url'] = 'https://github.cherishmoon.fun/https://raw.githubusercontent.com/CMHopeSunshine/GenshinWikiMap/master/results/character_map/{}.jpg'
+ state['img_url'] = '{}https://raw.githubusercontent.com/CMHopeSunshine/GenshinWikiMap/master/results/character_map/{}.jpg'
elif state['type'] == '收益曲线':
state['type'] = '角色'
state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/blue/{}.jpg'
@@ -252,7 +253,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
if state['type'] == '角色' and (
match_alias := await PlayerAlias.get_or_none(user_id=str(event.user_id), alias=name)):
try:
- await maps.finish(MessageSegment.image(state['img_url'].format(match_alias.character)))
+ await maps.finish(MessageSegment.image(state['img_url'].format(config.github_proxy, match_alias.character)))
except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴'))
match_alias = get_match_alias(name, state['type'])
@@ -261,7 +262,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
str) else None
if true_name:
try:
- await maps.finish(MessageSegment.image(state['img_url'].format(match_alias)))
+ await maps.finish(MessageSegment.image(state['img_url'].format(config.github_proxy, match_alias)))
except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴'))
elif match_alias:
@@ -281,7 +282,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
match_alias = state['match_alias']
if choice.isdigit() and (1 <= int(choice) <= len(match_alias)):
try:
- await maps.finish(MessageSegment.image(state['img_url'].format(match_alias[int(choice) - 1])))
+ await maps.finish(MessageSegment.image(state['img_url'].format(config.github_proxy, match_alias[int(choice) - 1])))
except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{match_alias[int(choice) - 1]}的图鉴'))
if choice not in match_alias:
@@ -295,7 +296,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
await maps.finish(
MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}吧') + MessageSegment.face(146))
try:
- await maps.finish(MessageSegment.image(state['img_url'].format(choice)))
+ await maps.finish(MessageSegment.image(state['img_url'].format(config.github_proxy, choice)))
except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{choice}的图鉴'))
@@ -320,9 +321,9 @@ async def _(state: T_State, name: str = ArgPlainText('name')):
if not (matches := await get_match_card(name)):
await card_wiki.finish(MessageBuild.Text(f'暂时没有{name}的卡牌图鉴'))
if name in matches:
- await card_wiki.finish(MessageSegment.image(CARD_API.format(name)))
+ await card_wiki.finish(MessageSegment.image(CARD_API.format(config.github_proxy, name)))
if len(matches) == 1:
- await card_wiki.finish(MessageSegment.image(CARD_API.format(matches[0])))
+ await card_wiki.finish(MessageSegment.image(CARD_API.format(config.github_proxy, matches[0])))
if 'choice' not in state:
msg = f'你要查询的卡牌是:\n'
msg += '\n'.join([f'{int(i) + 1}. {name}' for i, name in enumerate(matches)])
@@ -335,9 +336,9 @@ async def _(state: T_State, choice: str = ArgPlainText('choice')):
matches = state['matches']
if choice.isdigit() and (1 <= int(choice) <= len(matches)):
try:
- await card_wiki.finish(MessageSegment.image(CARD_API.format(matches[int(choice) - 1])))
+ await card_wiki.finish(MessageSegment.image(CARD_API.format(config.github_proxy, matches[int(choice) - 1])))
except ActionFailed:
- await card_wiki.finish(MessageBuild.Text(f'暂时没有{matches[int(choice) - 1]}的卡牌图鉴'))
+ await card_wiki.finish(MessageBuild.Text(f'获取{matches[int(choice) - 1]}的卡牌图鉴失败,请检查网络或更换资源地址'))
if choice not in matches:
state['times'] = state['times'] + 1 if 'times' in state else 1
if state['times'] == 1:
@@ -349,9 +350,9 @@ async def _(state: T_State, choice: str = ArgPlainText('choice')):
await card_wiki.finish(
MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}吧') + MessageSegment.face(146))
try:
- await card_wiki.finish(MessageSegment.image(CARD_API.format(choice)))
+ await card_wiki.finish(MessageSegment.image(CARD_API.format(config.github_proxy, choice)))
except ActionFailed:
- await card_wiki.finish(MessageBuild.Text(f'暂时没有{choice}的卡牌图鉴'))
+ await card_wiki.finish(MessageBuild.Text(f'获取{choice}的卡牌图鉴失败,请检查网络或更换资源地址'))
@card_wiki_list.handle()
@@ -369,7 +370,7 @@ async def _(bot: Bot, event: MessageEvent):
else:
msg = '七圣召唤卡牌列表:'
for type, cards in result.items():
- msg += f'{type}:\n' + '\n'.join([' '.join(cards[i:i + 3]) for i in range(0, len(cards), 3)])
- await card_wiki_list.send(msg + '\n')
+ msg += f'{type}:\n' + '\n'.join([' '.join(cards[i:i + 3]) for i in range(0, len(cards), 3)]) + '\n'
+ await card_wiki_list.send(msg)
except ActionFailed:
await card_wiki_list.finish('七圣召唤卡牌列表发送失败,账号可能被风控')
diff --git a/LittlePaimon/plugins/Paimon_Wiki/card.py b/LittlePaimon/plugins/Paimon_Wiki/card.py
index 069d631..be5ac82 100644
--- a/LittlePaimon/plugins/Paimon_Wiki/card.py
+++ b/LittlePaimon/plugins/Paimon_Wiki/card.py
@@ -3,15 +3,16 @@ import difflib
from typing import Optional
from ruamel import yaml
+from LittlePaimon.config import config
from LittlePaimon.utils.requests import aiorequests
-CARD_RESOURCES_API = 'https://github.cherishmoon.fun/https://raw.githubusercontent.com/Nwflower/Atlas/master/resource/text/card.yaml'
-CARD_API = 'https://github.cherishmoon.fun/https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/card/{}.png'
+CARD_RESOURCES_API = '{}https://raw.githubusercontent.com/Nwflower/Atlas/master/resource/text/card.yaml'
+CARD_API = '{}https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/card/{}.png'
async def get_card_resources() -> Optional[dict]:
with contextlib.suppress(Exception):
- resp = await aiorequests.get(CARD_RESOURCES_API)
+ resp = await aiorequests.get(CARD_RESOURCES_API.format(config.github_proxy))
data = yaml.load(resp.content, Loader=yaml.Loader)
data.pop('召唤')
return data
diff --git a/LittlePaimon/utils/tool.py b/LittlePaimon/utils/tool.py
index f2ac657..0256e77 100644
--- a/LittlePaimon/utils/tool.py
+++ b/LittlePaimon/utils/tool.py
@@ -7,10 +7,11 @@ import time
from collections import defaultdict
from pathlib import Path
+from LittlePaimon.config import config
from .logger import logger
from .requests import aiorequests
-RESOURCE_BASE_PATH = Path() / 'resources' / 'LittlePaimon'
+RESOURCE_BASE_PATH = Path() / 'resources'
class FreqLimiter:
@@ -27,24 +28,24 @@ class FreqLimiter:
def check(self, key: str) -> bool:
"""
检查是否冷却结束
- :param key: key
- :return: 布尔值
+ :param key: key
+ :return: 布尔值
"""
return time.time() >= self.next_time[key]
def start(self, key: str, cooldown_time: int = 0):
"""
开始冷却
- :param key: key
- :param cooldown_time: 冷却时间(秒)
+ :param key: key
+ :param cooldown_time: 冷却时间(秒)
"""
self.next_time[key] = time.time() + (cooldown_time if cooldown_time > 0 else 60)
def left(self, key: str) -> int:
"""
剩余冷却时间
- :param key: key
- :return: 剩余冷却时间
+ :param key: key
+ :return: 剩余冷却时间
"""
return int(self.next_time[key] - time.time()) + 1
@@ -55,7 +56,7 @@ freq_limiter = FreqLimiter()
def cache(ttl=datetime.timedelta(hours=1)):
"""
缓存装饰器
- :param ttl: 过期时间
+ :param ttl: 过期时间
"""
def wrap(func):
cache_data = {}
@@ -85,11 +86,15 @@ def cache(ttl=datetime.timedelta(hours=1)):
async def check_resource():
logger.info('资源检查', '开始检查资源')
- resource_list = await aiorequests.get('http://img.genshin.cherishmoon.fun/resources/resources_list')
- resource_list = resource_list.json()
+ try:
+ resource_list = await aiorequests.get(f'{config.github_proxy}https://raw.githubusercontent.com/CMHopeSunshine/LittlePaimonRes/main/resources_list.json')
+ resource_list = resource_list.json()
+ except Exception:
+ logger.info('资源检查', '读取资源列表失败,请尝试更换github资源地址')
+ return
flag = False
for resource in resource_list:
- file_path = RESOURCE_BASE_PATH.parent / resource['path']
+ file_path = RESOURCE_BASE_PATH / resource['path']
if file_path.exists():
if not resource['lock'] or hashlib.md5(file_path.read_bytes()).hexdigest() == resource['hash']:
continue
@@ -97,12 +102,12 @@ async def check_resource():
file_path.unlink()
flag = True
try:
- await aiorequests.download(url=f'http://img.genshin.cherishmoon.fun/resources/{resource["path"]}',
+ await aiorequests.download(url=f'{config.github_proxy}https://raw.githubusercontent.com/CMHopeSunshine/LittlePaimonRes/main/{resource["path"]}',
save_path=file_path, exclude_json=resource['path'].split('.')[-1] != 'json')
await asyncio.sleep(0.5)
- except Exception as e:
- logger.warning('资源检查', f'下载{resource["path"].split("/")[-1]}时出错: {e}')
+ except Exception:
+ logger.warning('资源检查', f'下载{resource["path"]}时出错,请尝试更换github资源地址')
if flag:
logger.info('资源检查', '资源下载完成')
else:
- logger.info('资源检查', '资源完好,无需下载')
+ logger.info('资源检查', '资源完好,无需下载')
\ No newline at end of file
diff --git a/LittlePaimon/web/pages/config_manage.py b/LittlePaimon/web/pages/config_manage.py
index 8be2138..9d25cbd 100644
--- a/LittlePaimon/web/pages/config_manage.py
+++ b/LittlePaimon/web/pages/config_manage.py
@@ -293,6 +293,31 @@ other_form = Form(
displayMode='enhance',
suffix='秒',
min=5,
+ ),
+ Select(
+ label='github资源地址',
+ name='github资源地址',
+ value='${github资源地址}',
+ labelRemark=Remark(shape='circle', content='本bot部分资源托管在github,如果下载缓慢或无法正常访问,可以尝试更换地址,或者添加你自己的代理地址,注意最后要有/'),
+ creatable=True,
+ options=[
+ {
+ 'label': 'ghproxy.com代理',
+ 'value': 'https://ghproxy.com/'
+ },
+ {
+ 'label': 'github.cherishmoon.fun代理',
+ 'value': 'https://github.cherishmoon.fun/'
+ },
+ {
+ 'label': 'github.91chi.fun代理',
+ 'value': 'https://github.91chi.fun/'
+ },
+ {
+ 'label': 'github原地址',
+ 'value': ''
+ }
+ ]
)
],
actions=action_button
diff --git a/matcher_patch.py b/matcher_patch.py
index 4df31f7..b32d7ee 100644
--- a/matcher_patch.py
+++ b/matcher_patch.py
@@ -79,4 +79,4 @@ nonebot.on_regex = on_regex_
nonebot.on_startswith = on_startswith_
nonebot.on_endswith = on_endswith_
nonebot.on_keyword = on_keyword_
-v11.bot._check_nickname = _check_nickname
+# v11.bot._check_nickname = _check_nickname