fix: npm对插件无法启用的bug

feat: 资源包的管理器
This commit is contained in:
2024-04-07 00:35:53 +08:00
parent 72742d805c
commit 9743868cce
15 changed files with 540 additions and 288 deletions

View File

@ -6,7 +6,7 @@ import sys
import nonebot
__NAME__ = "LiteyukiBot"
__VERSION__ = "6.2.6" # 60201
__VERSION__ = "6.2.7" # 60201
import requests

View File

@ -10,27 +10,6 @@ require("nonebot_plugin_htmlrender")
from nonebot_plugin_htmlrender import *
# async def html2image(
# html: str,
# wait: int = 0,
# template_path: str = None,
# scale_factor: float = 2,
# **kwargs
# ) -> bytes:
# """
# Args:
# html: str: HTML 正文
# wait: 等待时间
# template_path: 模板路径
# scale_factor: 缩放因子,越高越清晰
# **kwargs: page 参数
#
# Returns:
#
# """
# return await html_to_pic(html, wait=wait, template_path=template_path, scale_factor=scale_factor)
async def template2html(
template: str,
templates: dict,
@ -77,6 +56,7 @@ async def template2image(
}
template_path = os.path.dirname(template)
template_name = os.path.basename(template)
print(template_path, template_name)
if debug:
raw_html = await template_to_html(

View File

@ -12,7 +12,6 @@ import nonebot
from .config import config
from .data_manager import User, user_db
_default_lang_code = "en"
_language_data = {
"en": {
"name": "English",
@ -102,7 +101,7 @@ def load_from_dict(data: dict, lang_code: str):
class Language:
def __init__(self, lang_code: str = None, fallback_lang_code: str = "en"):
def __init__(self, lang_code: str = None, fallback_lang_code: str = "zh-CN"):
if lang_code is None:
lang_code = config.get("default_language", get_default_lang())
self.lang_code = lang_code

View File

@ -185,7 +185,7 @@ class Markdown:
# 等林文轩修好Lagrange.OneBot再说
@staticmethod
def cmd(name: str, cmd: str, reply: bool = False, enter: bool = True) -> str:
def btn_cmd(name: str, cmd: str, reply: bool = False, enter: bool = True) -> str:
"""生成点击回调按钮
Args:
name: 按钮显示内容
@ -202,7 +202,7 @@ class Markdown:
return f"[{name}](mqqapi://aio/inlinecmd?command={quote(cmd)}&reply={str(reply).lower()}&enter={str(enter).lower()})"
@staticmethod
def link(name: str, url: str) -> str:
def btn_link(name: str, url: str) -> str:
"""生成点击链接按钮
Args:
name: 链接显示内容

View File

@ -1,21 +1,25 @@
import json
import os
import shutil
from typing import Any
import nonebot
import yaml
from typing import Any
from liteyuki.utils.data import LiteModel
from .data import LiteModel
from .language import get_default_lang
_loaded_resource_packs: list["ResourceMetadata"] = [] # 按照加载顺序排序
temp_resource_root = "data/liteyuki/resources"
lang = get_default_lang()
class ResourceMetadata(LiteModel):
name: str = "Unknown"
version: str = "0.0.1"
description: str = "Unknown"
path: str
path: str = ""
folder: str = ""
def load_resource_from_dir(path: str):
@ -36,10 +40,11 @@ def load_resource_from_dir(path: str):
relative_path = os.path.relpath(os.path.join(root, file), path)
copy_file(os.path.join(root, file), os.path.join(temp_resource_root, relative_path))
metadata["path"] = path
metadata["folder"] = os.path.basename(path)
if os.path.exists(os.path.join(path, "lang")):
from liteyuki.utils.language import load_from_dir
load_from_dir(os.path.join(path, "lang"))
_loaded_resource_packs.append(ResourceMetadata(**metadata))
_loaded_resource_packs.insert(0, ResourceMetadata(**metadata))
def get_path(path: str, abs_path: bool = False, default: Any = None) -> str | Any:
@ -76,7 +81,7 @@ def get_files(path: str, abs_path: bool = False) -> list[str]:
def get_loaded_resource_packs() -> list[ResourceMetadata]:
"""
获取已加载的资源包
获取已加载的资源包,优先级从前到后
Returns: 资源包列表
"""
return _loaded_resource_packs
@ -106,6 +111,117 @@ def load_resources():
standard_resource_path = "liteyuki/resources"
load_resource_from_dir(standard_resource_path)
# 加载其他资源包
if os.path.exists("resources"):
for resource in os.listdir("resources"):
load_resource_from_dir(os.path.join("resources", resource))
if not os.path.exists("resources"):
os.makedirs("resources", exist_ok=True)
if not os.path.exists("resources/index.json"):
json.dump([], open("resources/index.json", "w", encoding="utf-8"))
resource_index: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
resource_index.reverse() # 优先级高的后加载,但是排在前面
for resource in resource_index:
load_resource_from_dir(os.path.join("resources", resource))
def check_status(name: str) -> bool:
"""
检查资源包是否已加载
Args:
name: 资源包名称,文件夹名
Returns: 是否已加载
"""
return name in [rp.folder for rp in get_loaded_resource_packs()]
def check_exist(name: str) -> bool:
"""
检查资源包文件夹是否存在于resources文件夹
Args:
name: 资源包名称,文件夹名
Returns: 是否存在
"""
return os.path.exists(os.path.join("resources", name, "metadata.yml"))
def add_resource_pack(name: str) -> bool:
"""
添加资源包该操作仅修改index.json文件不会加载资源包要生效请重载资源
Args:
name: 资源包名称,文件夹名
Returns:
"""
if check_exist(name):
old_index: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
if name not in old_index:
old_index.append(name)
json.dump(old_index, open("resources/index.json", "w", encoding="utf-8"))
load_resource_from_dir(os.path.join("resources", name))
return True
else:
nonebot.logger.warning(lang.get("liteyuki.resource_loaded", name=name))
return False
else:
nonebot.logger.warning(lang.get("liteyuki.resource_not_exist", name=name))
return False
def remove_resource_pack(name: str) -> bool:
"""
移除资源包,该操作仅修改加载索引,要生效请重载资源
Args:
name: 资源包名称,文件夹名
Returns:
"""
if check_exist(name):
old_index: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
if name in old_index:
old_index.remove(name)
json.dump(old_index, open("resources/index.json", "w", encoding="utf-8"))
return True
else:
nonebot.logger.warning(lang.get("liteyuki.resource_not_loaded", name=name))
return False
else:
nonebot.logger.warning(lang.get("liteyuki.resource_not_exist", name=name))
return False
def change_priority(name: str, delta: int) -> bool:
"""
修改资源包优先级
Args:
name: 资源包名称,文件夹名
delta: 优先级变化正数表示后移负数表示前移0表示移到最前
Returns:
"""
# 正数表示前移,负数表示后移
old_resource_list: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
new_resource_list = old_resource_list.copy()
if name in old_resource_list:
index = old_resource_list.index(name)
if 0 <= index + delta < len(old_resource_list):
new_index = index + delta
new_resource_list.remove(name)
new_resource_list.insert(new_index, name)
json.dump(new_resource_list, open("resources/index.json", "w", encoding="utf-8"))
return True
else:
nonebot.logger.warning("Priority change failed, out of range")
return False
else:
nonebot.logger.debug("Priority change failed, resource not loaded")
return False
def get_resource_metadata(name: str) -> ResourceMetadata:
"""
获取资源包元数据
Args:
name: 资源包名称,文件夹名
Returns:
"""
for rp in get_loaded_resource_packs():
if rp.folder == name:
return rp
return ResourceMetadata()