修改资源更新地址,增加github资源地址配置项

This commit is contained in:
CMHopeSunshine 2022-12-06 23:07:34 +08:00
parent 59015cfd44
commit 1fda9c81e9
7 changed files with 72 additions and 38 deletions

View File

@ -47,6 +47,8 @@ class ConfigModel(BaseModel):
command_alias_enable: bool = Field(True, alias='启用命令别名') command_alias_enable: bool = Field(True, alias='启用命令别名')
github_proxy: str = Field('https://ghproxy.com/', alias='github资源地址')
@property @property
def alias_dict(self): def alias_dict(self):
return {v.alias: k for k, v in self.__fields__.items()} return {v.alias: k for k, v in self.__fields__.items()}

View File

@ -239,7 +239,7 @@ context_table = TableCRUD(mode='table',
message_page = PageSchema(url='/chat/messages', icon='fa fa-comments', label='群聊消息', message_page = PageSchema(url='/chat/messages', icon='fa fa-comments', label='群聊消息',
schema=Page(title='群聊消息', body=[ schema=Page(title='群聊消息', body=[
Alert(level=LevelEnum.info, Alert(level=LevelEnum.info,
className='white-space-pre', className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}收到的除指令外的聊天记录。\n' body=(f'此数据库记录了{NICKNAME}收到的除指令外的聊天记录。\n'
'· 点击"禁用"可以将某条聊天记录进行禁用,这样其相关的学习就会列入禁用列表。\n' '· 点击"禁用"可以将某条聊天记录进行禁用,这样其相关的学习就会列入禁用列表。\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='学习内容', context_page = PageSchema(url='/chat/contexts', icon='fa fa-comment', label='学习内容',
schema=Page(title='内容', schema=Page(title='内容',
body=[Alert(level=LevelEnum.info, body=[Alert(level=LevelEnum.info,
className='white-space-pre', className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}所学习的内容。\n' body=(f'此数据库记录了{NICKNAME}所学习的内容。\n'
'· 点击"回复列表"可以查看该条内容已学习到的可能的回复。\n' '· 点击"回复列表"可以查看该条内容已学习到的可能的回复。\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='内容回复', answer_page = PageSchema(url='/chat/answers', icon='fa fa-commenting-o', label='内容回复',
schema=Page(title='回复', schema=Page(title='回复',
body=[Alert(level=LevelEnum.info, body=[Alert(level=LevelEnum.info,
className='white-space-pre', className='white-space-pre-wrap',
body=(f'此数据库记录了{NICKNAME}已学习到的所有回复,但看不到这些回复属于哪些内容,推荐到"学习内容"表进行操作。\n' body=(f'此数据库记录了{NICKNAME}已学习到的所有回复,但看不到这些回复属于哪些内容,推荐到"学习内容"表进行操作。\n'
'· 点击"禁用"可以将该回复进行禁用,以后不会再学。\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='禁用列表', blacklist_page = PageSchema(url='/chat/blacklist', icon='fa fa-ban', label='禁用列表',
schema=Page(title='禁用列表', schema=Page(title='禁用列表',
body=[Alert(level=LevelEnum.info, body=[Alert(level=LevelEnum.info,
className='white-space-pre', className='white-space-pre-wrap',
body=f'此数据库记录了{NICKNAME}被禁用的内容/关键词。\n' body=f'此数据库记录了{NICKNAME}被禁用的内容/关键词。\n'
'· 可以取消禁用,使其能够重新继续学习。\n' '· 可以取消禁用,使其能够重新继续学习。\n'
'· 不能在此添加禁用,只能在群中回复[不可以]或者在<配置>中添加屏蔽词来达到禁用效果。'), '· 不能在此添加禁用,只能在群中回复[不可以]或者在<配置>中添加屏蔽词来达到禁用效果。'),

View File

@ -11,6 +11,7 @@ from nonebot.typing import T_State
from LittlePaimon.database import PlayerAlias from LittlePaimon.database import PlayerAlias
from LittlePaimon.utils import NICKNAME from LittlePaimon.utils import NICKNAME
from LittlePaimon.config import config
from LittlePaimon.utils.alias import get_match_alias from LittlePaimon.utils.alias import get_match_alias
from LittlePaimon.utils.message import MessageBuild, fullmatch_rule from LittlePaimon.utils.message import MessageBuild, fullmatch_rule
from LittlePaimon.utils.path import RESOURCE_BASE_PATH 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']: if '武器' in state['type']:
state['type'] = '武器' state['type'] = '武器'
# state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/WeaponMaps/{}.jpg' # 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']: elif '圣遗物' in state['type']:
state['type'] = '圣遗物' state['type'] = '圣遗物'
state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/ArtifactMaps/{}.jpg' 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['type'] = '角色'
# state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{}材料.jpg' # state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/RoleMaterials/{}材料.jpg'
state[ 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'] == '角色图鉴': elif state['type'] == '角色图鉴':
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'] == '收益曲线': elif state['type'] == '收益曲线':
state['type'] = '角色' state['type'] = '角色'
state['img_url'] = 'https://static.cherishmoon.fun/LittlePaimon/blue/{}.jpg' 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 ( if state['type'] == '角色' and (
match_alias := await PlayerAlias.get_or_none(user_id=str(event.user_id), alias=name)): match_alias := await PlayerAlias.get_or_none(user_id=str(event.user_id), alias=name)):
try: 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: except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴')) await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴'))
match_alias = get_match_alias(name, state['type']) 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 str) else None
if true_name: if true_name:
try: 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: except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴')) await maps.finish(MessageBuild.Text(f'没有找到{name}的图鉴'))
elif match_alias: elif match_alias:
@ -281,7 +282,7 @@ def create_wiki_matcher(pattern: str, help_fun: str, help_name: str):
match_alias = state['match_alias'] match_alias = state['match_alias']
if choice.isdigit() and (1 <= int(choice) <= len(match_alias)): if choice.isdigit() and (1 <= int(choice) <= len(match_alias)):
try: 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: except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{match_alias[int(choice) - 1]}的图鉴')) await maps.finish(MessageBuild.Text(f'没有找到{match_alias[int(choice) - 1]}的图鉴'))
if choice not in match_alias: 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( await maps.finish(
MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}') + MessageSegment.face(146)) MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}') + MessageSegment.face(146))
try: 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: except ActionFailed:
await maps.finish(MessageBuild.Text(f'没有找到{choice}的图鉴')) 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)): if not (matches := await get_match_card(name)):
await card_wiki.finish(MessageBuild.Text(f'暂时没有{name}的卡牌图鉴')) await card_wiki.finish(MessageBuild.Text(f'暂时没有{name}的卡牌图鉴'))
if name in matches: 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: 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: if 'choice' not in state:
msg = f'你要查询的卡牌是:\n' msg = f'你要查询的卡牌是:\n'
msg += '\n'.join([f'{int(i) + 1}. {name}' for i, name in enumerate(matches)]) 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'] matches = state['matches']
if choice.isdigit() and (1 <= int(choice) <= len(matches)): if choice.isdigit() and (1 <= int(choice) <= len(matches)):
try: 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: 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: if choice not in matches:
state['times'] = state['times'] + 1 if 'times' in state else 1 state['times'] = state['times'] + 1 if 'times' in state else 1
if state['times'] == 1: if state['times'] == 1:
@ -349,9 +350,9 @@ async def _(state: T_State, choice: str = ArgPlainText('choice')):
await card_wiki.finish( await card_wiki.finish(
MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}') + MessageSegment.face(146)) MessageSegment.text(f'看来旅行者您有点神志不清哦(,下次再问{NICKNAME}') + MessageSegment.face(146))
try: 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: except ActionFailed:
await card_wiki.finish(MessageBuild.Text(f'暂时没有{choice}的卡牌图鉴')) await card_wiki.finish(MessageBuild.Text(f'获取{choice}的卡牌图鉴失败,请检查网络或更换资源地址'))
@card_wiki_list.handle() @card_wiki_list.handle()
@ -369,7 +370,7 @@ async def _(bot: Bot, event: MessageEvent):
else: else:
msg = '七圣召唤卡牌列表:' msg = '七圣召唤卡牌列表:'
for type, cards in result.items(): 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)]) 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 + '\n') await card_wiki_list.send(msg)
except ActionFailed: except ActionFailed:
await card_wiki_list.finish('七圣召唤卡牌列表发送失败,账号可能被风控') await card_wiki_list.finish('七圣召唤卡牌列表发送失败,账号可能被风控')

View File

@ -3,15 +3,16 @@ import difflib
from typing import Optional from typing import Optional
from ruamel import yaml from ruamel import yaml
from LittlePaimon.config import config
from LittlePaimon.utils.requests import aiorequests 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_RESOURCES_API = '{}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_API = '{}https://raw.githubusercontent.com/Nwflower/genshin-atlas/master/card/{}.png'
async def get_card_resources() -> Optional[dict]: async def get_card_resources() -> Optional[dict]:
with contextlib.suppress(Exception): 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 = yaml.load(resp.content, Loader=yaml.Loader)
data.pop('召唤') data.pop('召唤')
return data return data

View File

@ -7,10 +7,11 @@ import time
from collections import defaultdict from collections import defaultdict
from pathlib import Path from pathlib import Path
from LittlePaimon.config import config
from .logger import logger from .logger import logger
from .requests import aiorequests from .requests import aiorequests
RESOURCE_BASE_PATH = Path() / 'resources' / 'LittlePaimon' RESOURCE_BASE_PATH = Path() / 'resources'
class FreqLimiter: class FreqLimiter:
@ -85,11 +86,15 @@ def cache(ttl=datetime.timedelta(hours=1)):
async def check_resource(): async def check_resource():
logger.info('资源检查', '开始检查资源') logger.info('资源检查', '开始检查资源')
resource_list = await aiorequests.get('http://img.genshin.cherishmoon.fun/resources/resources_list') 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() resource_list = resource_list.json()
except Exception:
logger.info('资源检查', '读取资源列表<r>失败</r>,请尝试更换<m>github资源地址</m>')
return
flag = False flag = False
for resource in resource_list: 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 file_path.exists():
if not resource['lock'] or hashlib.md5(file_path.read_bytes()).hexdigest() == resource['hash']: if not resource['lock'] or hashlib.md5(file_path.read_bytes()).hexdigest() == resource['hash']:
continue continue
@ -97,11 +102,11 @@ async def check_resource():
file_path.unlink() file_path.unlink()
flag = True flag = True
try: 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') save_path=file_path, exclude_json=resource['path'].split('.')[-1] != 'json')
await asyncio.sleep(0.5) await asyncio.sleep(0.5)
except Exception as e: except Exception:
logger.warning('资源检查', f'下载<m>{resource["path"].split("/")[-1]}</m>时<r>出错: {e}</r>') logger.warning('资源检查', f'下载<m>{resource["path"]}</m>时<r>出错</r>,请尝试更换<m>github资源地址</m>')
if flag: if flag:
logger.info('资源检查', '<g>资源下载完成</g>') logger.info('资源检查', '<g>资源下载完成</g>')
else: else:

View File

@ -293,6 +293,31 @@ other_form = Form(
displayMode='enhance', displayMode='enhance',
suffix='', suffix='',
min=5, 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 actions=action_button

View File

@ -79,4 +79,4 @@ nonebot.on_regex = on_regex_
nonebot.on_startswith = on_startswith_ nonebot.on_startswith = on_startswith_
nonebot.on_endswith = on_endswith_ nonebot.on_endswith = on_endswith_
nonebot.on_keyword = on_keyword_ nonebot.on_keyword = on_keyword_
v11.bot._check_nickname = _check_nickname # v11.bot._check_nickname = _check_nickname