Merge pull request #66 from EillesWan/main

👻新增内置的页面渲染组件
This commit is contained in:
远野千束 2024-08-23 20:50:57 +08:00 committed by GitHub
commit a7d0560932
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
31 changed files with 1955 additions and 168 deletions

View File

@ -25,7 +25,6 @@
### 感谢
- [NoneBot2](https://nonebot.dev)提供的框架支持
- [nonebot-plugin-htmlrender](https://github.com/kexue-z/nonebot-plugin-htmlrender)提供的渲染功能
- [nonebot-plugin-alconna](https://github.com/ArcletProject/nonebot-plugin-alconna)提供的命令解析功能

View File

@ -53,6 +53,5 @@ tag:
## **鸣谢**
- [Nonebot2](https://nonebot.dev)提供的框架支持
- [nonebot-plugin-htmlrender](https://github.com/kexue-z/nonebot-plugin-htmlrender/tree/master)提供的渲染功能
- [nonebot-plugin-alconna](https://github.com/ArcletProject/nonebot-plugin-alconna)提供的命令解析功能
- [MiSans](https://hyperos.mi.com/font/zh/)[MapleMono](https://gitee.com/mirrors/Maple-Mono)提供的字体,且遵守了相关字体开源协议

View File

@ -52,6 +52,5 @@ tag:
## **鸣谢**
- [Nonebot2](https://nonebot.dev)提供的框架支持
- [nonebot-plugin-htmlrender](https://github.com/kexue-z/nonebot-plugin-htmlrender/tree/master)提供的渲染功能
- [nonebot-plugin-alconna](https://github.com/ArcletProject/nonebot-plugin-alconna)提供的命令解析功能
- [MiSans](https://hyperos.mi.com/font/zh/)[MapleMono](https://gitee.com/mirrors/Maple-Mono)提供的字体,且遵守了相关字体开源协议

View File

@ -7,9 +7,11 @@
4.注意冲突时的优先级: 项目目录下的配置文件优先级高于config目录下的配置文件
5.请不要将需要动态加载的内容写入配置文件你应该使用其他储存方式
"""
import copy
import json
import os
import json
import copy
import platform
from typing import Any, List
import toml
@ -21,6 +23,10 @@ from liteyuki.log import logger
_SUPPORTED_CONFIG_FORMATS = (".yaml", ".yml", ".json", ".toml")
# 以下这三个 Config 和 src/utils/base/config.py 中重复
# 应尽快整理
class SatoriNodeConfig(BaseModel):
host: str = ""
port: str = "5500"
@ -29,7 +35,9 @@ class SatoriNodeConfig(BaseModel):
class SatoriConfig(BaseModel):
comment: str = "These features are still in development. Do not enable in production environment."
comment: str = (
"These features are still in development. Do not enable in production environment."
)
enable: bool = False
hosts: List[SatoriNodeConfig] = [SatoriNodeConfig()]
@ -42,6 +50,15 @@ class BasicConfig(BaseModel):
nickname: list[str] = [f"LiteyukiBot"]
satori: SatoriConfig = SatoriConfig()
data_path: str = "data/liteyuki"
chromium_path: str = (
"/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome" # type: ignore
if platform.system() == "Darwin"
else (
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
if platform.system() == "Windows"
else "/usr/bin/chromium-browser"
)
)
def flat_config(config: dict[str, Any]) -> dict[str, Any]:
@ -63,31 +80,31 @@ def flat_config(config: dict[str, Any]) -> dict[str, Any]:
return new_config
def load_from_yaml(file: str) -> dict[str, Any]:
def load_from_yaml(file_: str) -> dict[str, Any]:
"""
Load config from yaml file
"""
logger.debug(f"Loading YAML config from {file}")
config = yaml.safe_load(open(file, "r", encoding="utf-8"))
logger.debug(f"Loading YAML config from {file_}")
config = yaml.safe_load(open(file_, "r", encoding="utf-8"))
return flat_config(config if config is not None else {})
def load_from_json(file: str) -> dict[str, Any]:
def load_from_json(file_: str) -> dict[str, Any]:
"""
Load config from json file
"""
logger.debug(f"Loading JSON config from {file}")
config = json.load(open(file, "r", encoding="utf-8"))
logger.debug(f"Loading JSON config from {file_}")
config = json.load(open(file_, "r", encoding="utf-8"))
return flat_config(config if config is not None else {})
def load_from_toml(file: str) -> dict[str, Any]:
def load_from_toml(file_: str) -> dict[str, Any]:
"""
Load config from toml file
"""
logger.debug(f"Loading TOML config from {file}")
config = toml.load(open(file, "r", encoding="utf-8"))
logger.debug(f"Loading TOML config from {file_}")
config = toml.load(open(file_, "r", encoding="utf-8"))
return flat_config(config if config is not None else {})
@ -114,7 +131,9 @@ def load_from_files(*files: str, no_warning: bool = False) -> dict[str, Any]:
return config
def load_configs_from_dirs(*directories: str, no_waring: bool = False) -> dict[str, Any]:
def load_configs_from_dirs(
*directories: str, no_waring: bool = False
) -> dict[str, Any]:
"""
从目录下加载配置文件不递归
按照读取文件的优先级反向覆盖
@ -128,7 +147,9 @@ def load_configs_from_dirs(*directories: str, no_waring: bool = False) -> dict[s
continue
for file in os.listdir(directory):
if file.endswith(_SUPPORTED_CONFIG_FORMATS):
config.update(load_from_files(os.path.join(directory, file), no_warning=no_waring))
config.update(
load_from_files(os.path.join(directory, file), no_warning=no_waring)
)
return config
@ -139,5 +160,13 @@ def load_config_in_default(no_waring: bool = False) -> dict[str, Any]:
项目目录下的配置文件优先
"""
config = load_configs_from_dirs("config", no_waring=no_waring)
config.update(load_from_files("config.yaml", "config.toml", "config.json", "config.yml", no_warning=no_waring))
config.update(
load_from_files(
"config.yaml",
"config.toml",
"config.json",
"config.yml",
no_warning=no_waring,
)
)
return config

View File

@ -25,7 +25,9 @@ _queue: Queue = Queue()
async def _(event: MessageEvent):
current_priority = -1
for i, matcher in enumerate(_matcher_list):
logger.info(f"Running matcher {matcher} for event: {event}")
# 刷屏
logger.debug(f"Running matcher {matcher} for event: {event}")
await matcher.run(event)
# 同优先级不阻断,不同优先级阻断
if current_priority != matcher.priority:

View File

@ -5,12 +5,14 @@ GitPython~=3.1.42
httpx~=0.27.0
nb-cli~=1.4.1
nonebot2[fastapi,httpx,websockets]~=2.3.3
nonebot-plugin-htmlrender~=0.3.1
nonebot-adapter-onebot~=2.4.3
nonebot-plugin-alconna~=0.46.3
nonebot_plugin_apscheduler~=0.4.0
nonebot-adapter-satori~=0.11.5
numpy~=2.0.0
pyppeteer~=2.0.0
markdown>=3.3.6
zhDateTime>=1.0.3
numpy<2.0.0
packaging~=23.1
psutil~=5.9.8
py-cpuinfo~=9.0.0

View File

@ -18,6 +18,7 @@ from src.utils.base.config import get_config
from src.utils.base.data_manager import TempConfig, common_db
from src.utils.base.language import get_user_lang
from src.utils.base.ly_typing import T_Bot, T_MessageEvent
from src.utils.htmlrender import md_to_pic
from src.utils.message.message import MarkdownMessage as md, broadcast_to_superusers
from .api import update_liteyuki
from ..utils.base import reload
@ -25,11 +26,10 @@ from ..utils.base.ly_function import get_function
require("nonebot_plugin_alconna")
require("nonebot_plugin_apscheduler")
require("nonebot_plugin_htmlrender")
from nonebot_plugin_htmlrender import md_to_pic
from nonebot_plugin_alconna import UniMessage, on_alconna, Alconna, Args, Arparma, MultiVar
from nonebot_plugin_apscheduler import scheduler
driver = get_driver()

View File

@ -18,15 +18,15 @@ from nonebot.utils import run_sync
from src.utils.base.data_manager import InstalledPlugin
from src.utils.base.language import get_user_lang
from src.utils.base.ly_typing import T_Bot
from src.utils.message.message import MarkdownMessage as md
from src.utils.message.markdown import MarkdownComponent as mdc, compile_md, escape_md
from src.utils.base.permission import GROUP_ADMIN, GROUP_OWNER
from src.utils.message.tools import clamp
from src.utils.message.message import MarkdownMessage as md
from src.utils.message.markdown import MarkdownComponent as mdc, compile_md, escape_md
from src.utils.htmlrender import md_to_pic
from .common import *
require("nonebot_plugin_alconna")
require("nonebot_plugin_htmlrender")
from nonebot_plugin_htmlrender import md_to_pic
from nonebot_plugin_alconna import (
UniMessage, on_alconna,
Alconna,

View File

@ -8,13 +8,14 @@ from src.utils.base.data_manager import User, user_db, group_db
from src.utils.base.language import Language, change_user_lang, get_all_lang, get_user_lang
from src.utils.base.ly_typing import T_Bot, T_MessageEvent
from src.utils.message.message import MarkdownMessage as md
from src.utils.htmlrender import md_to_pic
from .const import representative_timezones_list
from src.utils import event as event_utils
require("nonebot_plugin_alconna")
require("nonebot_plugin_htmlrender")
from nonebot_plugin_alconna import Alconna, Args, Arparma, Subcommand, on_alconna
from nonebot_plugin_htmlrender import md_to_pic
profile_alc = on_alconna(
Alconna(
@ -67,6 +68,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot):
# 未输入值,尝试呼出菜单
menu = get_profile_menu(result.args["key"], ulang)
if menu:
# 请问这是在做什么?
img_bytes = await md_to_pic(menu)
await profile_alc.finish(menu)
else:
@ -100,6 +102,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot):
reply += (f"\n**{key_text}** **{val}**\n"
f"\n> {ulang.get(f'user.profile.{key}.desc')}"
f"\n> {btn_set} \n\n***\n")
# 这又是在做什么
img_bytes = await md_to_pic(reply)
await profile_alc.finish(reply)

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 kexue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,3 @@
name: 页面渲染组件资源包
description: 拷贝自nonebot-plugin-htmlrender,依照其协议开源
version: 2024.8.23

View File

@ -0,0 +1,940 @@
.markdown-body {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
margin: 0;
color: #24292f;
background-color: #ffffff;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";
font-size: 16px;
line-height: 1.5;
word-wrap: break-word;
}
.markdown-body .octicon {
display: inline-block;
fill: currentColor;
vertical-align: text-bottom;
}
.markdown-body h1:hover .anchor .octicon-link:before,
.markdown-body h2:hover .anchor .octicon-link:before,
.markdown-body h3:hover .anchor .octicon-link:before,
.markdown-body h4:hover .anchor .octicon-link:before,
.markdown-body h5:hover .anchor .octicon-link:before,
.markdown-body h6:hover .anchor .octicon-link:before {
width: 16px;
height: 16px;
content: ' ';
display: inline-block;
background-color: currentColor;
-webkit-mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>");
mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>");
}
.markdown-body details,
.markdown-body figcaption,
.markdown-body figure {
display: block;
}
.markdown-body summary {
display: list-item;
}
.markdown-body [hidden] {
display: none !important;
}
.markdown-body a {
background-color: transparent;
color: #0969da;
text-decoration: none;
}
.markdown-body a:active,
.markdown-body a:hover {
outline-width: 0;
}
.markdown-body abbr[title] {
border-bottom: none;
text-decoration: underline dotted;
}
.markdown-body b,
.markdown-body strong {
font-weight: 600;
}
.markdown-body dfn {
font-style: italic;
}
.markdown-body h1 {
margin: .67em 0;
font-weight: 600;
padding-bottom: .3em;
font-size: 2em;
border-bottom: 1px solid hsla(210,18%,87%,1);
}
.markdown-body mark {
background-color: #fff8c5;
color: #24292f;
}
.markdown-body small {
font-size: 90%;
}
.markdown-body sub,
.markdown-body sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
.markdown-body sub {
bottom: -0.25em;
}
.markdown-body sup {
top: -0.5em;
}
.markdown-body img {
border-style: none;
max-width: 100%;
box-sizing: content-box;
background-color: #ffffff;
}
.markdown-body code,
.markdown-body kbd,
.markdown-body pre,
.markdown-body samp {
font-family: monospace,monospace;
font-size: 1em;
}
.markdown-body figure {
margin: 1em 40px;
}
.markdown-body hr {
box-sizing: content-box;
overflow: hidden;
background: transparent;
border-bottom: 1px solid hsla(210,18%,87%,1);
height: .25em;
padding: 0;
margin: 24px 0;
background-color: #d0d7de;
border: 0;
}
.markdown-body input {
font: inherit;
margin: 0;
overflow: visible;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
.markdown-body [type=button],
.markdown-body [type=reset],
.markdown-body [type=submit] {
-webkit-appearance: button;
}
.markdown-body [type=button]::-moz-focus-inner,
.markdown-body [type=reset]::-moz-focus-inner,
.markdown-body [type=submit]::-moz-focus-inner {
border-style: none;
padding: 0;
}
.markdown-body [type=button]:-moz-focusring,
.markdown-body [type=reset]:-moz-focusring,
.markdown-body [type=submit]:-moz-focusring {
outline: 1px dotted ButtonText;
}
.markdown-body [type=checkbox],
.markdown-body [type=radio] {
box-sizing: border-box;
padding: 0;
}
.markdown-body [type=number]::-webkit-inner-spin-button,
.markdown-body [type=number]::-webkit-outer-spin-button {
height: auto;
}
.markdown-body [type=search] {
-webkit-appearance: textfield;
outline-offset: -2px;
}
.markdown-body [type=search]::-webkit-search-cancel-button,
.markdown-body [type=search]::-webkit-search-decoration {
-webkit-appearance: none;
}
.markdown-body ::-webkit-input-placeholder {
color: inherit;
opacity: .54;
}
.markdown-body ::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit;
}
.markdown-body a:hover {
text-decoration: underline;
}
.markdown-body hr::before {
display: table;
content: "";
}
.markdown-body hr::after {
display: table;
clear: both;
content: "";
}
.markdown-body table {
border-spacing: 0;
border-collapse: collapse;
display: block;
width: max-content;
max-width: 100%;
overflow: auto;
}
.markdown-body td,
.markdown-body th {
padding: 0;
}
.markdown-body details summary {
cursor: pointer;
}
.markdown-body details:not([open])>*:not(summary) {
display: none !important;
}
.markdown-body kbd {
display: inline-block;
padding: 3px 5px;
font: 11px ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
line-height: 10px;
color: #24292f;
vertical-align: middle;
background-color: #f6f8fa;
border: solid 1px rgba(175,184,193,0.2);
border-bottom-color: rgba(175,184,193,0.2);
border-radius: 6px;
box-shadow: inset 0 -1px 0 rgba(175,184,193,0.2);
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: 600;
line-height: 1.25;
}
.markdown-body h2 {
font-weight: 600;
padding-bottom: .3em;
font-size: 1.5em;
border-bottom: 1px solid hsla(210,18%,87%,1);
}
.markdown-body h3 {
font-weight: 600;
font-size: 1.25em;
}
.markdown-body h4 {
font-weight: 600;
font-size: 1em;
}
.markdown-body h5 {
font-weight: 600;
font-size: .875em;
}
.markdown-body h6 {
font-weight: 600;
font-size: .85em;
color: #57606a;
}
.markdown-body p {
margin-top: 0;
margin-bottom: 10px;
}
.markdown-body blockquote {
margin: 0;
padding: 0 1em;
color: #57606a;
border-left: .25em solid #d0d7de;
}
.markdown-body ul,
.markdown-body ol {
margin-top: 0;
margin-bottom: 0;
padding-left: 2em;
}
.markdown-body ol ol,
.markdown-body ul ol {
list-style-type: lower-roman;
}
.markdown-body ul ul ol,
.markdown-body ul ol ol,
.markdown-body ol ul ol,
.markdown-body ol ol ol {
list-style-type: lower-alpha;
}
.markdown-body dd {
margin-left: 0;
}
.markdown-body tt,
.markdown-body code {
font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
font-size: 12px;
}
.markdown-body pre {
margin-top: 0;
margin-bottom: 0;
font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
font-size: 12px;
word-wrap: normal;
}
.markdown-body .octicon {
display: inline-block;
overflow: visible !important;
vertical-align: text-bottom;
fill: currentColor;
}
.markdown-body ::placeholder {
color: #6e7781;
opacity: 1;
}
.markdown-body input::-webkit-outer-spin-button,
.markdown-body input::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
appearance: none;
}
.markdown-body .pl-c {
color: #6e7781;
}
.markdown-body .pl-c1,
.markdown-body .pl-s .pl-v {
color: #0550ae;
}
.markdown-body .pl-e,
.markdown-body .pl-en {
color: #8250df;
}
.markdown-body .pl-smi,
.markdown-body .pl-s .pl-s1 {
color: #24292f;
}
.markdown-body .pl-ent {
color: #116329;
}
.markdown-body .pl-k {
color: #cf222e;
}
.markdown-body .pl-s,
.markdown-body .pl-pds,
.markdown-body .pl-s .pl-pse .pl-s1,
.markdown-body .pl-sr,
.markdown-body .pl-sr .pl-cce,
.markdown-body .pl-sr .pl-sre,
.markdown-body .pl-sr .pl-sra {
color: #0a3069;
}
.markdown-body .pl-v,
.markdown-body .pl-smw {
color: #953800;
}
.markdown-body .pl-bu {
color: #82071e;
}
.markdown-body .pl-ii {
color: #f6f8fa;
background-color: #82071e;
}
.markdown-body .pl-c2 {
color: #f6f8fa;
background-color: #cf222e;
}
.markdown-body .pl-sr .pl-cce {
font-weight: bold;
color: #116329;
}
.markdown-body .pl-ml {
color: #3b2300;
}
.markdown-body .pl-mh,
.markdown-body .pl-mh .pl-en,
.markdown-body .pl-ms {
font-weight: bold;
color: #0550ae;
}
.markdown-body .pl-mi {
font-style: italic;
color: #24292f;
}
.markdown-body .pl-mb {
font-weight: bold;
color: #24292f;
}
.markdown-body .pl-md {
color: #82071e;
background-color: #FFEBE9;
}
.markdown-body .pl-mi1 {
color: #116329;
background-color: #dafbe1;
}
.markdown-body .pl-mc {
color: #953800;
background-color: #ffd8b5;
}
.markdown-body .pl-mi2 {
color: #eaeef2;
background-color: #0550ae;
}
.markdown-body .pl-mdr {
font-weight: bold;
color: #8250df;
}
.markdown-body .pl-ba {
color: #57606a;
}
.markdown-body .pl-sg {
color: #8c959f;
}
.markdown-body .pl-corl {
text-decoration: underline;
color: #0a3069;
}
.markdown-body [data-catalyst] {
display: block;
}
.markdown-body g-emoji {
font-family: "Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
font-size: 1em;
font-style: normal !important;
font-weight: 400;
line-height: 1;
vertical-align: -0.075em;
}
.markdown-body g-emoji img {
width: 1em;
height: 1em;
}
.markdown-body::before {
display: table;
content: "";
}
.markdown-body::after {
display: table;
clear: both;
content: "";
}
.markdown-body>*:first-child {
margin-top: 0 !important;
}
.markdown-body>*:last-child {
margin-bottom: 0 !important;
}
.markdown-body a:not([href]) {
color: inherit;
text-decoration: none;
}
.markdown-body .absent {
color: #cf222e;
}
.markdown-body .anchor {
float: left;
padding-right: 4px;
margin-left: -20px;
line-height: 1;
}
.markdown-body .anchor:focus {
outline: none;
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body details {
margin-top: 0;
margin-bottom: 16px;
}
.markdown-body blockquote>:first-child {
margin-top: 0;
}
.markdown-body blockquote>:last-child {
margin-bottom: 0;
}
.markdown-body sup>a::before {
content: "[";
}
.markdown-body sup>a::after {
content: "]";
}
.markdown-body h1 .octicon-link,
.markdown-body h2 .octicon-link,
.markdown-body h3 .octicon-link,
.markdown-body h4 .octicon-link,
.markdown-body h5 .octicon-link,
.markdown-body h6 .octicon-link {
color: #24292f;
vertical-align: middle;
visibility: hidden;
}
.markdown-body h1:hover .anchor,
.markdown-body h2:hover .anchor,
.markdown-body h3:hover .anchor,
.markdown-body h4:hover .anchor,
.markdown-body h5:hover .anchor,
.markdown-body h6:hover .anchor {
text-decoration: none;
}
.markdown-body h1:hover .anchor .octicon-link,
.markdown-body h2:hover .anchor .octicon-link,
.markdown-body h3:hover .anchor .octicon-link,
.markdown-body h4:hover .anchor .octicon-link,
.markdown-body h5:hover .anchor .octicon-link,
.markdown-body h6:hover .anchor .octicon-link {
visibility: visible;
}
.markdown-body h1 tt,
.markdown-body h1 code,
.markdown-body h2 tt,
.markdown-body h2 code,
.markdown-body h3 tt,
.markdown-body h3 code,
.markdown-body h4 tt,
.markdown-body h4 code,
.markdown-body h5 tt,
.markdown-body h5 code,
.markdown-body h6 tt,
.markdown-body h6 code {
padding: 0 .2em;
font-size: inherit;
}
.markdown-body ul.no-list,
.markdown-body ol.no-list {
padding: 0;
list-style-type: none;
}
.markdown-body ol[type="1"] {
list-style-type: decimal;
}
.markdown-body ol[type=a] {
list-style-type: lower-alpha;
}
.markdown-body ol[type=i] {
list-style-type: lower-roman;
}
.markdown-body div>ol:not([type]) {
list-style-type: decimal;
}
.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ol,
.markdown-body ol ul {
margin-top: 0;
margin-bottom: 0;
}
.markdown-body li>p {
margin-top: 16px;
}
.markdown-body li+li {
margin-top: .25em;
}
.markdown-body dl {
padding: 0;
}
.markdown-body dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: 600;
}
.markdown-body dl dd {
padding: 0 16px;
margin-bottom: 16px;
}
.markdown-body table th {
font-weight: 600;
}
.markdown-body table th,
.markdown-body table td {
padding: 6px 13px;
border: 1px solid #d0d7de;
}
.markdown-body table tr {
background-color: #ffffff;
border-top: 1px solid hsla(210,18%,87%,1);
}
.markdown-body table tr:nth-child(2n) {
background-color: #f6f8fa;
}
.markdown-body table img {
background-color: transparent;
}
.markdown-body img[align=right] {
padding-left: 20px;
}
.markdown-body img[align=left] {
padding-right: 20px;
}
.markdown-body .emoji {
max-width: none;
vertical-align: text-top;
background-color: transparent;
}
.markdown-body span.frame {
display: block;
overflow: hidden;
}
.markdown-body span.frame>span {
display: block;
float: left;
width: auto;
padding: 7px;
margin: 13px 0 0;
overflow: hidden;
border: 1px solid #d0d7de;
}
.markdown-body span.frame span img {
display: block;
float: left;
}
.markdown-body span.frame span span {
display: block;
padding: 5px 0 0;
clear: both;
color: #24292f;
}
.markdown-body span.align-center {
display: block;
overflow: hidden;
clear: both;
}
.markdown-body span.align-center>span {
display: block;
margin: 13px auto 0;
overflow: hidden;
text-align: center;
}
.markdown-body span.align-center span img {
margin: 0 auto;
text-align: center;
}
.markdown-body span.align-right {
display: block;
overflow: hidden;
clear: both;
}
.markdown-body span.align-right>span {
display: block;
margin: 13px 0 0;
overflow: hidden;
text-align: right;
}
.markdown-body span.align-right span img {
margin: 0;
text-align: right;
}
.markdown-body span.float-left {
display: block;
float: left;
margin-right: 13px;
overflow: hidden;
}
.markdown-body span.float-left span {
margin: 13px 0 0;
}
.markdown-body span.float-right {
display: block;
float: right;
margin-left: 13px;
overflow: hidden;
}
.markdown-body span.float-right>span {
display: block;
margin: 13px auto 0;
overflow: hidden;
text-align: right;
}
.markdown-body code,
.markdown-body tt {
padding: .2em .4em;
margin: 0;
font-size: 85%;
background-color: rgba(175,184,193,0.2);
border-radius: 6px;
}
.markdown-body code br,
.markdown-body tt br {
display: none;
}
.markdown-body del code {
text-decoration: inherit;
}
.markdown-body pre code {
font-size: 100%;
}
.markdown-body pre>code {
padding: 0;
margin: 0;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}
.markdown-body .highlight {
margin-bottom: 16px;
}
.markdown-body .highlight pre {
margin-bottom: 0;
word-break: normal;
}
.markdown-body .highlight pre,
.markdown-body pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f6f8fa;
border-radius: 6px;
}
.markdown-body pre code,
.markdown-body pre tt {
display: inline;
max-width: auto;
padding: 0;
margin: 0;
overflow: visible;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}
.markdown-body .csv-data td,
.markdown-body .csv-data th {
padding: 5px;
overflow: hidden;
font-size: 12px;
line-height: 1;
text-align: left;
/* white-space: nowrap; */
}
.markdown-body .csv-data .blob-num {
padding: 10px 8px 9px;
text-align: right;
background: #ffffff;
border: 0;
}
.markdown-body .csv-data tr {
border-top: 0;
}
.markdown-body .csv-data th {
font-weight: 600;
background: #f6f8fa;
border-top: 0;
}
.markdown-body .footnotes {
font-size: 12px;
color: #57606a;
border-top: 1px solid #d0d7de;
}
.markdown-body .footnotes ol {
padding-left: 16px;
}
.markdown-body .footnotes li {
position: relative;
}
.markdown-body .footnotes li:target::before {
position: absolute;
top: -8px;
right: -8px;
bottom: -8px;
left: -24px;
pointer-events: none;
content: "";
border: 2px solid #0969da;
border-radius: 6px;
}
.markdown-body .footnotes li:target {
color: #24292f;
}
.markdown-body .footnotes .data-footnote-backref g-emoji {
font-family: monospace;
}
.markdown-body .task-list-item {
list-style-type: none;
}
.markdown-body .task-list-item label {
font-weight: 400;
}
.markdown-body .task-list-item.enabled label {
cursor: pointer;
}
.markdown-body .task-list-item+.task-list-item {
margin-top: 3px;
}
.markdown-body .task-list-item .handle {
display: none;
}
.markdown-body .task-list-item-checkbox {
margin: 0 .2em .25em -1.6em;
vertical-align: middle;
}
.markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox {
margin: 0 -1.6em .25em .2em;
}
.markdown-body ::-webkit-calendar-picker-indicator {
filter: invert(50%);
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("katex"));else if("function"==typeof define&&define.amd)define(["katex"],t);else{var r="object"==typeof exports?t(require("katex")):t(e.katex);for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={771:function(t){t.exports=e}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var o,i,a,u={};return o=n(771),i=n.n(o),a=document.body.getElementsByTagName("script"),(a=Array.prototype.slice.call(a)).forEach((function(e){if(!e.type||!e.type.match(/math\/tex/i))return-1;var t=null!=e.type.match(/mode\s*=\s*display(;|\s|\n|$)/),r=document.createElement(t?"div":"span");r.setAttribute("class",t?"equation":"inline-equation");try{i().render(e.text,r,{displayMode:t})}catch(t){r.textContent=e.text}e.parentNode.replaceChild(r,e)})),u=u.default}()}));

View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<style type="text/css">
{{ css }}
</style>
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
</style>
</head>
<body>
<article class="markdown-body">
{{ md }}
</article>
</body>
{{ extra }}

View File

@ -0,0 +1,74 @@
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.codehilite .hll { background-color: #ffffcc }
.codehilite { background: #f8f8f8; }
.codehilite .c { color: #408080; font-style: italic } /* Comment */
.codehilite .err { border: 1px solid #FF0000 } /* Error */
.codehilite .k { color: #008000; font-weight: bold } /* Keyword */
.codehilite .o { color: #666666 } /* Operator */
.codehilite .ch { color: #408080; font-style: italic } /* Comment.Hashbang */
.codehilite .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.codehilite .cp { color: #BC7A00 } /* Comment.Preproc */
.codehilite .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */
.codehilite .c1 { color: #408080; font-style: italic } /* Comment.Single */
.codehilite .cs { color: #408080; font-style: italic } /* Comment.Special */
.codehilite .gd { color: #A00000 } /* Generic.Deleted */
.codehilite .ge { font-style: italic } /* Generic.Emph */
.codehilite .gr { color: #FF0000 } /* Generic.Error */
.codehilite .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.codehilite .gi { color: #00A000 } /* Generic.Inserted */
.codehilite .go { color: #888888 } /* Generic.Output */
.codehilite .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.codehilite .gs { font-weight: bold } /* Generic.Strong */
.codehilite .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.codehilite .gt { color: #0044DD } /* Generic.Traceback */
.codehilite .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.codehilite .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.codehilite .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.codehilite .kp { color: #008000 } /* Keyword.Pseudo */
.codehilite .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.codehilite .kt { color: #B00040 } /* Keyword.Type */
.codehilite .m { color: #666666 } /* Literal.Number */
.codehilite .s { color: #BA2121 } /* Literal.String */
.codehilite .na { color: #7D9029 } /* Name.Attribute */
.codehilite .nb { color: #008000 } /* Name.Builtin */
.codehilite .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.codehilite .no { color: #880000 } /* Name.Constant */
.codehilite .nd { color: #AA22FF } /* Name.Decorator */
.codehilite .ni { color: #999999; font-weight: bold } /* Name.Entity */
.codehilite .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.codehilite .nf { color: #0000FF } /* Name.Function */
.codehilite .nl { color: #A0A000 } /* Name.Label */
.codehilite .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.codehilite .nt { color: #008000; font-weight: bold } /* Name.Tag */
.codehilite .nv { color: #19177C } /* Name.Variable */
.codehilite .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.codehilite .w { color: #bbbbbb } /* Text.Whitespace */
.codehilite .mb { color: #666666 } /* Literal.Number.Bin */
.codehilite .mf { color: #666666 } /* Literal.Number.Float */
.codehilite .mh { color: #666666 } /* Literal.Number.Hex */
.codehilite .mi { color: #666666 } /* Literal.Number.Integer */
.codehilite .mo { color: #666666 } /* Literal.Number.Oct */
.codehilite .sa { color: #BA2121 } /* Literal.String.Affix */
.codehilite .sb { color: #BA2121 } /* Literal.String.Backtick */
.codehilite .sc { color: #BA2121 } /* Literal.String.Char */
.codehilite .dl { color: #BA2121 } /* Literal.String.Delimiter */
.codehilite .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.codehilite .s2 { color: #BA2121 } /* Literal.String.Double */
.codehilite .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.codehilite .sh { color: #BA2121 } /* Literal.String.Heredoc */
.codehilite .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.codehilite .sx { color: #008000 } /* Literal.String.Other */
.codehilite .sr { color: #BB6688 } /* Literal.String.Regex */
.codehilite .s1 { color: #BA2121 } /* Literal.String.Single */
.codehilite .ss { color: #19177C } /* Literal.String.Symbol */
.codehilite .bp { color: #008000 } /* Name.Builtin.Pseudo */
.codehilite .fm { color: #0000FF } /* Name.Function.Magic */
.codehilite .vc { color: #19177C } /* Name.Variable.Class */
.codehilite .vg { color: #19177C } /* Name.Variable.Global */
.codehilite .vi { color: #19177C } /* Name.Variable.Instance */
.codehilite .vm { color: #19177C } /* Name.Variable.Magic */
.codehilite .il { color: #666666 } /* Literal.Number.Integer.Long */

View File

@ -0,0 +1,9 @@
.text {
margin-top: 5px;
word-break: break-all;
white-space: pre-wrap;
}
.main-box {
padding: 5px;
}

View File

@ -0,0 +1,13 @@
<head>
<meta charset="utf-8" />
{% if css %}
<style type="text/css">
{{ css }}
</style>
{% endif %}
</head>
<body>
<div id="main" class="main-box">
<div class="text">{{ text }}</div>
</div>
</body>

Binary file not shown.

After

Width:  |  Height:  |  Size: 465 KiB

View File

@ -837,22 +837,6 @@
"time": "2023-06-20T16:04:40.706727Z",
"skip_test": false
},
{
"module_name": "nonebot_plugin_htmlrender",
"project_link": "nonebot-plugin-htmlrender",
"name": "nonebot-plugin-htmlrender",
"desc": "通过浏览器渲染图片",
"author": "kexue-z",
"homepage": "https://github.com/kexue-z/nonebot-plugin-htmlrender",
"tags": [],
"is_official": false,
"type": "library",
"supported_adapters": null,
"valid": true,
"version": "0.3.1",
"time": "2024-03-14T08:47:15.010445Z",
"skip_test": false
},
{
"module_name": "nonebot_plugin_admin",
"project_link": "nonebot-plugin-admin",
@ -8718,31 +8702,6 @@
"time": "2023-07-14T10:32:08.006009Z",
"skip_test": false
},
{
"module_name": "nonebot_plugin_templates",
"project_link": "nonebot-plugin-templates",
"name": "templates_render",
"desc": "使用htmlrender和jinja2渲染,使用构建的menu,card或dict进行模板渲染",
"author": "canxin121",
"homepage": "https://github.com/canxin121/nonebot_plugin_templates",
"tags": [
{
"label": "模板渲染",
"color": "#eacd52"
},
{
"label": "图片生成",
"color": "#adea52"
}
],
"is_official": false,
"type": "library",
"supported_adapters": null,
"valid": true,
"version": "0.1.6",
"time": "2023-08-24T09:56:33.184091Z",
"skip_test": false
},
{
"module_name": "nonebot_plugin_pokesomeone",
"project_link": "nonebot-plugin-pokesomeone",

View File

@ -1,4 +1,5 @@
import os
import platform
from typing import List
import nonebot
@ -7,6 +8,7 @@ from pydantic import BaseModel
from ..message.tools import random_hex_string
config = {} # 全局配置,确保加载后读取
@ -18,7 +20,9 @@ class SatoriNodeConfig(BaseModel):
class SatoriConfig(BaseModel):
comment: str = "These features are still in development. Do not enable in production environment."
comment: str = (
"These features are still in development. Do not enable in production environment."
)
enable: bool = False
hosts: List[SatoriNodeConfig] = [SatoriNodeConfig()]
@ -31,21 +35,34 @@ class BasicConfig(BaseModel):
nickname: list[str] = [f"LiteyukiBot-{random_hex_string(6)}"]
satori: SatoriConfig = SatoriConfig()
data_path: str = "data/liteyuki"
chromium_path: str = (
"/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome" # type: ignore
if platform.system() == "Darwin"
else (
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
if platform.system() == "Windows"
else "/usr/bin/chromium-browser"
)
)
def load_from_yaml(file: str) -> dict:
def load_from_yaml(file_: str) -> dict:
global config
nonebot.logger.debug("Loading config from %s" % file)
if not os.path.exists(file):
nonebot.logger.warning(f"Config file {file} not found, created default config, please modify it and restart")
with open(file, "w", encoding="utf-8") as f:
nonebot.logger.debug("Loading config from %s" % file_)
if not os.path.exists(file_):
nonebot.logger.warning(
f"Config file {file_} not found, created default config, please modify it and restart"
)
with open(file_, "w", encoding="utf-8") as f:
yaml.dump(BasicConfig().dict(), f, default_flow_style=False)
with open(file, "r", encoding="utf-8") as f:
with open(file_, "r", encoding="utf-8") as f:
conf = init_conf(yaml.load(f, Loader=yaml.FullLoader))
config = conf
if conf is None:
nonebot.logger.warning(f"Config file {file} is empty, use default config. please modify it and restart")
nonebot.logger.warning(
f"Config file {file_} is empty, use default config. please modify it and restart"
)
conf = BasicConfig().dict()
return conf
@ -75,7 +92,6 @@ def get_config(key: str, default=None):
return default
def init_conf(conf: dict) -> dict:
"""
初始化配置文件确保配置文件中的必要字段存在且不会冲突

View File

@ -3,7 +3,9 @@ import os
import shutil
import zipfile
from typing import Any
from pathlib import Path
import aiofiles
import nonebot
import yaml
@ -12,11 +14,13 @@ from .language import Language, get_default_lang_code
from .ly_function import loaded_functions
_loaded_resource_packs: list["ResourceMetadata"] = [] # 按照加载顺序排序
temp_resource_root = "data/liteyuki/resources"
temp_extract_root = "data/liteyuki/temp"
temp_resource_root = Path("data/liteyuki/resources")
temp_extract_root = Path("data/liteyuki/temp")
lang = Language(get_default_lang_code())
class ResourceMetadata(LiteModel):
name: str = "Unknown"
version: str = "0.0.1"
@ -50,60 +54,139 @@ def load_resource_from_dir(path: str):
for root, dirs, files in os.walk(path):
for file in files:
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))
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 src.utils.base.language import load_from_dir
load_from_dir(os.path.join(path, "lang"))
if os.path.exists(os.path.join(path, "functions")):
# 加载功能
from src.utils.base.ly_function import load_from_dir
load_from_dir(os.path.join(path, "functions"))
if os.path.exists(os.path.join(path, "word_bank")):
# 加载词库
from src.utils.base.word_bank import load_from_dir
load_from_dir(os.path.join(path, "word_bank"))
_loaded_resource_packs.insert(0, ResourceMetadata(**metadata))
def get_path(path: str, abs_path: bool = True, default: Any = None, debug: bool = False) -> str | Any:
def get_path(
path: os.PathLike[str,] | Path | str,
abs_path: bool = True,
default: Any = None,
debug: bool = False,
) -> str | Any:
"""
获取资源包中的文件
获取资源包中的路径且该路径必须存在
Args:
debug: 启用调试每次都会先重载资源
path: 相对路径
abs_path: 是否返回绝对路径
default: 默认
path: 文件相对路径
Returns: 文件绝对路径
default: 默认当该路径不存在时使用
debug: 启用调试每次都会先重载资源
Returns: 所需求之路径
"""
if debug:
nonebot.logger.debug("Enable resource debug, Reloading resources")
nonebot.logger.debug("Resource path debug enabled, reloading")
load_resources()
resource_relative_path = os.path.join(temp_resource_root, path)
if os.path.exists(resource_relative_path):
return os.path.abspath(resource_relative_path) if abs_path else resource_relative_path
resource_relative_path = temp_resource_root / path
if resource_relative_path.exists():
return str(
resource_relative_path.resolve() if abs_path else resource_relative_path
)
else:
return default
def get_files(path: str, abs_path: bool = False) -> list[str]:
def get_resource_path(
path: os.PathLike[str,] | Path | str,
abs_path: bool = True,
only_exist: bool = False,
default: Any = None,
debug: bool = False,
) -> Path:
"""
获取资源包中一个文件夹的所有文件
获取资源包中的路径
Args:
abs_path:
path: 文件夹相对路径
Returns: 文件绝对路径
path: 相对路径
abs_path: 是否返回绝对路径
only_exist: 检查该路径是否存在
default: [ `only_exist` **** 时启用]默认解当该路径不存在时使用
debug: 启用调试每次都会先重载资源
Returns: 所需求之路径
"""
resource_relative_path = os.path.join(temp_resource_root, path)
if os.path.exists(resource_relative_path):
return [os.path.abspath(os.path.join(resource_relative_path, file)) if abs_path else os.path.join(resource_relative_path, file) for file in
os.listdir(resource_relative_path)]
if debug:
nonebot.logger.debug("Resource path debug enabled, reloading")
load_resources()
resource_relative_path = (
(temp_resource_root / path).resolve()
if abs_path
else (temp_resource_root / path)
)
if only_exist:
if resource_relative_path.exists():
return resource_relative_path
else:
return default
else:
return resource_relative_path
def get_files(
path: os.PathLike[str,] | Path | str, abs_path: bool = False
) -> list[str]:
"""
获取资源包中一个目录的所有内容
Args:
path: 该目录的相对路径
abs_path: 是否返回绝对路径
Returns: 目录内容路径所构成之列表
"""
resource_relative_path = temp_resource_root / path
if resource_relative_path.exists():
return [
(
str((resource_relative_path / file_).resolve())
if abs_path
else str((resource_relative_path / file_))
)
for file_ in os.listdir(resource_relative_path)
]
else:
return []
def get_resource_files(
path: os.PathLike[str,] | Path | str, abs_path: bool = False
) -> list[Path]:
"""
获取资源包中一个目录的所有内容
Args:
path: 该目录的相对路径
abs_path: 是否返回绝对路径
Returns: 目录内容路径所构成之列表
"""
resource_relative_path = temp_resource_root / path
if resource_relative_path.exists():
return [
(
(resource_relative_path / file_).resolve()
if abs_path
else (resource_relative_path / file_)
)
for file_ in os.listdir(resource_relative_path)
]
else:
return []
@ -150,7 +233,9 @@ def load_resources():
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: 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))
@ -174,7 +259,9 @@ def check_exist(name: str) -> bool:
Returns: 是否存在
"""
path = os.path.join("resources", name)
return os.path.exists(os.path.join(path, "metadata.yml")) or (os.path.isfile(path) and name.endswith(".zip"))
return os.path.exists(os.path.join(path, "metadata.yml")) or (
os.path.isfile(path) and name.endswith(".zip")
)
def add_resource_pack(name: str) -> bool:
@ -185,7 +272,9 @@ def add_resource_pack(name: str) -> bool:
Returns:
"""
if check_exist(name):
old_index: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
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"))
@ -207,7 +296,9 @@ def remove_resource_pack(name: str) -> bool:
Returns:
"""
if check_exist(name):
old_index: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
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"))
@ -229,7 +320,9 @@ def change_priority(name: str, delta: int) -> bool:
Returns:
"""
# 正数表示前移,负数表示后移
old_resource_list: list[str] = json.load(open("resources/index.json", "r", encoding="utf-8"))
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)
@ -237,7 +330,9 @@ def change_priority(name: str, delta: int) -> bool:
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"))
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")

View File

@ -0,0 +1,155 @@
**当前目录htmlrender内之全部文件除 Licenses\ 目录下的文件外) 须依照此文件所规定之特别声明进行授权**\
**该目录下所有文件(除 Licenses\ 目录下的文件外)所形成的整体(后文称“页面渲染组件”) 不可以从 轻雪(Liteyuki) 分离而单独运行**\
**且 页面渲染组件 本身为一不可割裂之整体独立存在**
**当文件所规定之本协议与 轻雪 项目之协议存在冲突,应遵循本文件中所述的协议进行行为**
**当前目录内 Licenses 目录下的文件,系 页面渲染组件 之制作过程中所使用、参考或改写的第三方项目所采用的协议。**\
**二次分发时应予以保留,并遵循相关协议的规定**\
**本文件所规定之协议与上述协议若存在冲突部分,应遵循本文件中所述的协议进行行为**
--------
版权所有 © 2024 金羿Eilles(EillesWan@outlook.com)
Copyright (R) 2024 EillesWan(EillesWan@outlook.com)
页面渲染组件 的 协议颁发者 是 金羿Eilles(EillesWan@outlook.com)
页面渲染组件 根据 第一版 汉钰律许可协议(“本协议”)授权。
任何人皆可从以下地址获得本协议副本:[轻雪仓库](https://github.com/LiteyukiStudio/LiteyukiBot/tree/main/src/utils/htmlrender/LICENSE.md)。
若非因法律要求或经过了特殊准许,此作品在根据本协议“原样”提供的基础上,不予提供任何形式的担保、任何明示、任何暗示或类似承诺。也就是说,用户将自行承担因此作品的质量或性能问题而产生的全部风险。
详细的准许和限制条款请见原协议文本。
--------
以下为协议源文本
--------
# 汉钰律许可协议
**总第一版 · 二〇二四年七月七日编**
## 一、重要须知
1. 为保护采用本协议的作品在开源过程中,其著作权人所应有的权益,根据**中华人民共和国著作权法和相关法律法规**,制定本协议。
2. 本协议履行过程中,请注意本协议中**免除或限制**民事主体**责任或权利**的条款、法律适用和争议解决条款(尤其是加有特殊标记的条款),这些条款应在中国法律所允许的范围内最大程度地适用。
3. 若本协议所涉及的自然人**未满 18 周岁**,该自然人应在监护人的陪同下阅读本协议及有关本协议的条款内容,并在取得其监护人同意后开始或继续应用本协议所授权的行为。
4. 由于互联网服务、互联网内容的特殊性,若本协议以电子协议形式分发并签订,其依然有效。您一旦开始对本协议所授权之作品进行本协议所授权的行为,即视为您已经阅读、理解并同意并已经接受本协议的全部条款。
5. 本协议的订立、履行、解释及争议的解决均**适用中华人民共和国法律并排除其他一切冲突法的适用**。_本协议订立于许可证最初的颁发者的地址。若其为自然人则订立于该自然人户籍所在地若为法人或非法人组织则订立于其注册地_。本协议的订立各方应友好协商解决于协议所规定之行为的履行相关的争议如协商不成任何一方均可向合同签订地有管辖权的人民法院提起诉讼。
6. 本协议的原本仅为现代汉语,书写于简体中文。若存在其他语言的翻译或其他同等语言但非简体中文文本的版本,应当无法律效力。
## 二、术语定义
1. “**许可证**”、“**协议**”(后文称“本协议”)是指根据本文档中所列举的全部术语、定义、条款、限制等文本,是本合同的简称称谓。本合同全称是“汉钰律许可协议”。
2. “**协议颁发者**”(后文称“颁发者”)是将条款或协议应用于其拥有著作财产权的作品的民事主体,或由其指定从而拥有颁发者身份的民事主体。
3. “**源**”形式是指对包括但不限于 软件、硬件、文档、配置项 等种类的作品进行修改、编辑的首选形式;若不存在首选形式,则初次编辑该作品所需的形式即为源形式。
4. “**目标**”形式是指对源形式进行机械转换、翻译、打印、制造、加工等同类型活动后形成的结果形式,包括但不限于源代码编译后的目标软件、生成的文件、转换出的媒体、制造出的机械、打印出的实体文本、加工后的零件。
5. “**采用本协议的作品**”(后文称“此作品”)是指经颁发者授权而使用本协议进行授权的任何作品,该作品应在自然人可见处明确附加一个自然人可读的版权通知(可以参考文末附录中提供的示例);若在一个可分割的作品中,部分地采用本协议进行授权,则该部分应当视为一个独立的采用本协议的作品,该作品应当在自然人可见处明确附加一个自然人可读的范围限定和版权通知(同样可以参考文末附录中提供的示例)。
6. “**贡献**”是指对作品进行的,意在提交给此作品颁发者以让著作权人包含在其作品中的任何修订或补充,该修订或补充同样属于一种作品。依据此定义,“提交”一词表示经由此作品颁发者所指定的形式,将其所进行的修改发送给此作品颁发者。该形式应当包括在此作品颁发者指定的平台内发送易于编辑的修改信息、在此作品颁发者指定的电子邮箱中发送易于编辑的修改信息、在此作品颁发者指定的源码控制系统或发布跟踪系统上提交的易于编辑的修改信息,但由著作权人以明显标注或指定为“非贡献”的活动除外。颁发者自己对作品进行的修改同样视作对作品的贡献。
7. “**贡献者**”是指此作品颁发者接受的贡献的提交者,或包含在作品的贡献清单中的民事主体。贡献者在提交贡献并经此作品颁发者通过且该贡献已经被应用于此作品中后,该贡献者应当视为此作品的著作权人之一,但不应视为此作品非其贡献的部分的著作权人。一个作品的颁发者同样属于其贡献者。**请注意**,针对贡献者提交的贡献,该贡献者应被视为该贡献的协议颁发者,但不应视作本作品的颁发者。
8. “**用户**”、“**使用者**”是指行使本协议所授权之行为的民事主体。据此,贡献者亦属于用户。
9. “**商业性使用**”、“**商用**”是指任何以谋取利益为目的的使用,包括但不限于以贩卖、出租的形式对作品进行使用;但若将该牟利活动明确指示为“捐赠”,且在牟利者进行本协议所授权的活动时不以捐赠数额为标准,则此种的获取利益的“捐赠”行为不属于商业性使用。
## 三、权利授予
1. 任何由颁发者所进行的特殊声明、特别注意等此类内容,应当在法律效力上高于本协议的条款或声明;这些声明若与本协议冲突,本协议的该冲突部分无效;本协议与这些声明共同构成颁发者与用户之间的合同。
2. 此作品的贡献者享有其贡献的完整著作权。
3. 此作品的贡献者将自己的贡献的全部著作财产权,免费、公开、不可撤销、无限期、非专有地授予此作品的全部著作权人,并准许其在全世界范围内使用上述权利;若无明确的标识,贡献者允许此作品的颁发者对其贡献进行免费、公开、不可撤销、无限期、非专有、世界范围内的商业性使用。
4. 此作品的著作权人及贡献者授予用户**免费、公开、不可撤销、非专有、非商用**地以任意形式**复制、发行、展览、表演、放映、广播、信息网络传播、摄制、改编、翻译、汇编、二次授权**的权利,准许其在此作品颁发者所指定的区域与时间内行使上述权利;若此作品颁发者未特别指定的,则视作在全世界范围内无限期地授权;若此作品颁发者特别指定在特定情况下可以商用,则应当按照其所指定的条件进行商业性使用,商用的过程中,应当明确标识此作品的著作权人。
5. 一旦此作品有任意由非贡献形式而产生的更改,更改的部分将不视为此作品的一部分,除非该部分不可离开此作品单独存在;若该部分必须依赖此作品而不可与此作品分离从而单独存在,则更改后的作品不视作此作品,在这种情况下,除非此更改后的作品已获得此作品颁发者的特殊许可、或更改者即为此作品颁发者本人,否则对该作品进行的任何活动都应当遵守本协议。
6. 经贡献而产生的对此作品的更改,属于此作品的一部分;在此情况下,更改后的作品,依旧视作此作品。
7. 依据本款的第 4 条,若用户在本协议的授权下,将此作品授予他人进行任何形式的活动(即“二次授权”、“二次分发”),则应确保其使用的协议或授权内容,与本协议的条款不冲突;当存在与本协议条款的冲突时,则该冲突内容无效,被授权的第三方应依照本协议的条款进行活动;除非该用户获得了此作品颁发者的特殊许可、或该用户即为此作品颁发者本人。
8. 依据本款的第 5 条,若由非贡献形式而产生更改的部分是可分割而不需依赖此作品即可单独存在的,若该部分明确注明不使用本协议进行授权或明确声明了其他授权条款,则该部分不视作采用本协议;但未更改的部分仍应视作原此作品的一部分,需要采用本协议进行授权,除非此更改后的作品已获得此作品颁发者的特殊许可、或更改者即为此作品颁发者本人。
9. 若此作品或所提交的贡献包含其著作权人的专利,则该专利所有人即此作品的著作权人应准许此作品全体著作权人**免费、公开、不可撤销、非专有、无版权费的专利许可**,以便贡献者对作品进行本协议所授权进行的活动。
10. 上述专利许可的授予,仅适用于在所提交的贡献中,可由专利所有者授予的,且在对此作品进行本协议所授权的活动中,必须使用的专利。
11. 如果用户对任何民事主体,因其在进行本协议所授权进行的活动中侵犯该用户的专利而提起诉讼,那么根据本协议授予该用户的所有关于此作品的任何其他专利许可将在提起上述诉讼之日起终止。
12. 如果本作品作为用户的其他作品的不可分割的一部分进行任何民事活动,本协议依旧对本作品(即该用户的其他作品的一部分)生效;若本作品完全融入该用户的其他作品之中而不可独立存在,则该用户需要保证其作品存在与本协议冲突的条款;除非该作品已获得此作品颁发者的特殊许可、或该用户即为此作品颁发者本人。
## 四、使用条件
在对此作品进行本协议所授权的民事活动中,应当同时满足以下条款:
1. 用户必须为此作品的任何其他接收者提供本协议的副本,在不得已无法提供副本的情况下,也应明确指示其他接收者可查阅本协议的位置。
2. 用户必须在修改后的作品中附带明显的通知,声明用户已更改文件,并注明更改位置。
3. 若用户二次分发此作品,可以选择向此作品的接收者提供无偿或有偿的担保维修、支持服务或其他责任、义务。但是,该用户只可以其自己的名义提供上述内容,不得以任何其他贡献者的名义。且该用户必须明确表明任何此类责任或义务是由其个人独立提供,且其同意并应当承担赔偿此作品的全体贡献者因其个人承担上述责任义务而产生的任何赔偿责任。
4. 用户不得删除或更改此作品中包含的任何许可声明(包括版权声明,专利声明,免责声明,或赔偿责任限制),除非该更改是对已知事实错误的修补、或其已获得此作品颁发者的特殊许可、或更改者即为此作品颁发者本人。
5. 若此作品将权益的声明通知作为一部分,那么由用户分发的任何版本的作品中须至少在下列三处之一包含该声明通知的自然人可读副本:
- 该作品的权益声明通知中
- 在源形式的文件中(当且仅当该作品开放源代码)
- 在惯例中作为第三方通知出现之处(当且仅当该作品会产生画面,且该画面可被自然人详细观察)
该通知的内容仅供信息提供,不应对许可证进行任何文字上的修改。用户可在其分发的作品中,在不构成修改本协议的前提下,在作品自身的声明通知或属性描述后或作为附录添加。
6. 依据本款第3条若用户二次分发此作品时选择向作品的接收者提供收费的担保服务则必须明确告知该接收者本协议全部内容与此作品原出处并确保其知悉上述内容但若用户在二次分发此作品是不选择提供任何服务则该用户不允许向作品的接收者收取任何费用除非该用户获得了此作品颁发者的特殊许可、或该用户即为此作品颁发者本人。
## 五、提交贡献
除非贡献者明确声明,在本作品中由该贡献者向颁发者的提供的提交,必须符合本协议的条款,并与本协议的条款不存在冲突;除非此贡献中与本协议冲突的附加条款已获得颁发者的特殊许可、或贡献者即为此作品颁发者本人。
## 六、商标相关
本协议并未授予用户,将颁发者的商标、专属标记或特定产品名称,用于合理的或惯例性的描述或此类声明之外其他任何位置的权利。
## 七、免责声明
1. 若非因法律要求或经过了特殊准许,此作品在根据本协议“原样”提供的基础上,**不予提供任何形式的担保、任何明示、任何暗示或类似承诺**,此类包括但不限于担保此作品毫无缺陷、担保此作品适于贩卖、担保此作品适于特定目的、担保使用此作品绝不侵权。用户将自行承担因此作品的质量或性能问题而产生的全部风险。若此作品在任何方面欠妥,将由用户(而非任何贡献者、而非任何颁发者)承担所有必要的服务、维修或除错的任何成本。本免责声明本许可的重要组成部分。当且仅当遵守本免责声明时,本协议的其他条款中对本作品的使用授权方可生效。
2. 无论是因何种原因,如果不是在法律规定的特殊情况(如,确为贡献者的故意或重大过失)下或者经过了特殊准许,即使贡献者事先已知发生损害的可能,在使用本作品时,用户产生的任何直接、间接、特殊、偶然或必然造成的损失(包括但不限于商誉损失、工作延误、计算机系统故障等),**均不由任一贡献者承担**。
**以上是本许可协议的全部条款**
---
附录
**如何在自己的作品中应用 汉钰律许可协议**
若要在自己源形式的作品应用本协议,请在其中附加下面的通知模板,并将六角括号“〔〕”中的字段替换成自身的实际信息来替换(不包括括号本身)。这些文本必须以对应文件格式适当的注释句法包含在其中,可以是实体的纸质文档、也可以是网络公告或者计算机文件;或者脱离该源之外,另起一个新的文件,使之指向要应用本协议的那个作品。同时也建议将作品名或类别名以及目的说明之类的声明囊括在同一个可被打印的页面上作为版权通知的整体,这样更加容易的区分出第三方内容。
若需要在自己以目标形式存在的作品中应用本协议,同样需要附加下面的通知模板并更改六角括号中的字样。但是,这些文本可以是位于作品的标签上、位于作品的用户可见且能被自然人详细观察的画面之中、或者按照惯例中许可协议应该出现的位置;同时,这些文本的所处位置应当能够明确指示到本协议应用的那个作品。另外,建议将作品名或类别名以及目的说明之类的声明囊括在同一个可被打印的位置上作为版权通知的整体,这样更加容易的区分出第三方内容。
**通知模板**
```
版权所有 © 〔年份〕 〔著作权人〕
〔或者:版权所有 (C) 〔年份〕 〔著作权人〕〕
〔该作品〕根据 第一版 汉钰律许可协议(“本协议”)授权。
任何人皆可从以下地址获得本协议副本:〔本协议副本所在地址〕。
若非因法律要求或经过了特殊准许,此作品在根据本协议“原样”提供的基础上,不予提供任何形式的担保、任何明示、任何暗示或类似承诺。也就是说,用户将自行承担因此作品的质量或性能问题而产生的全部风险。
详细的准许和限制条款请见原协议文本。
```

View File

@ -0,0 +1,31 @@
LSO license
LiteyukiStudio Opensource license
---
版权所有 © 2024 Snowykami
---
免费向任何获得副本的人或组织授予以相同许可为基础的权利
包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件的副本
本软件及相关文档文件(以下简称"本软件")在相同方式许可为基础, 以开源的形式发布于互联网抑或其他媒体介质平台
任何人都有权利获取副本并以上述方式获取许可传播和/或使用
但获取副本时仍需注意:
- 上述版权声明和本许可声明应包含在本软件的副本中
- 使用本软件及其副本时仍需保持与原有形式相同
- 在使用时仍需将本软件的副本以相同许可公开表现:
- 不得未经原作者允许将本软件的副本以非原许可的形式对外盈利
---
该软件按"原样"之副本提供,不提供任何形式的任意保证,明示或暗示:
包括但不限于适销性保证, 适用于特定目的非侵权
在任何情况下, 作者或版权所有者对任何非因作者或版权所有者使用该软件造成的索赔、损害或其他责任, 无论是在合同诉讼、侵权行为还是其他诉讼中都不具有责任, 作者及其版权所有者有权利驳回使用者因个人原因造成的任何损失之赔付

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 kexue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,3 @@
# from .control import *
from .function import *

View File

@ -0,0 +1,95 @@
import platform
from contextlib import asynccontextmanager
from typing import Optional, AsyncIterator
import pyppeteer
import pyppeteer.browser
import pyppeteer.errors
import pyppeteer.page
from liteyuki.log import logger
# from liteyuki.plugin import PluginMetadata, PluginType
from src.utils.base.config import get_config
# __plugin_meta__ = PluginMetadata(
# name="页面渲染组件",
# description="提供跨平台的多用途页面渲染功能是nontbot-plugin-htmlrender的高级替代",
# type=PluginType.MODULE,
# author="金羿Eilles",
# extra={
# "license": "汉钰律许可协议 第一版",
# },
# )
_browser: Optional[pyppeteer.browser.Browser] = None
async def init(**kwargs) -> pyppeteer.browser.Browser:
global _browser
logger.info("正在初始化浏览器")
chromium_path = get_config("chromium_path")
if chromium_path:
try:
_browser = await pyppeteer.launch(executablePath=chromium_path, **kwargs)
except pyppeteer.errors.PyppeteerError as e:
logger.error(f"浏览器启动失败:{e}")
raise
logger.success("浏览器注册成功")
return _browser
else:
logger.error("请在配置文件中设置 chromium_path")
raise pyppeteer.errors.BrowserError(
"未配置浏览器地址若曾用过nonebot-plugin-htmlrender则可在 {} 处寻得一可用之chromium".format(
"%USERPROFILE%\\AppData\\Local\\ms-playwright"
if platform.system() == "Windows"
else (
"~/Library/Caches/ms-playwright"
if platform.system() == "Darwin"
else "~/.cache/ms-playwright"
)
)
)
async def get_browser(**kwargs) -> pyppeteer.browser.Browser:
return (
_browser
if _browser and _browser._connection._connected
else await init(**kwargs)
)
@asynccontextmanager
async def get_new_page(
viewport: Optional[dict] = None,
cookie: Optional[dict] = None,
useragent: Optional[str] = None,
) -> AsyncIterator[pyppeteer.page.Page]:
browser = await get_browser()
page = await browser.newPage()
# device_scale_factor=device_scale_factor, **kwargs
if viewport:
await page.setViewport(viewport)
if cookie:
await page.setCookie(cookie)
if useragent:
await page.setUserAgent(useragent)
try:
yield page
finally:
await page.close()
async def shutdown_browser():
global _browser
if _browser:
if _browser._connection._connected:
await _browser.close()
_browser = None

View File

@ -0,0 +1,319 @@
import os
import uuid
from typing import Any, Dict, Literal, Optional, Union
import jinja2
import aiofiles
import markdown
import pyppeteer.errors
# from pathlib import Path
from liteyuki.log import logger
from src.utils.base.resource import get_resource_path # , temp_extract_root
from .control import get_new_page
TEMPLATES_PATH = get_resource_path("templates", abs_path=True)
env = jinja2.Environment( # noqa: S701
extensions=["jinja2.ext.loopcontrols"],
loader=jinja2.FileSystemLoader(TEMPLATES_PATH),
enable_async=True,
)
async def read_any(path: str | os.PathLike[str], mode_: str = "r") -> str | bytes:
async with aiofiles.open(path, mode=mode_) as f: # type: ignore
return await f.read()
async def read_template(path: str) -> str:
return await read_any(TEMPLATES_PATH / path) # type: ignore
async def write_any(path: str | os.PathLike[str], content: str):
async with aiofiles.open(path, mode="w", encoding="utf-8") as f:
await f.write(content)
async def template_to_html(
template_path: str,
template_name: str,
**kwargs,
) -> str:
"""使用jinja2模板引擎通过html生成图片
Args:
template_path (str): 模板路径
template_name (str): 模板名
**kwargs: 模板内容
Returns:
str: html
"""
template_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path),
enable_async=True,
)
template = template_env.get_template(template_name)
return await template.render_async(**kwargs)
async def html_to_pic(
html_path: str,
html: str = "",
wait: int = 0,
# template_path: str = "file://{}".format(os.getcwd()),
type_: Literal["jpeg", "png"] = "png", # noqa: A002
quality: Union[int, None] = None,
viewport: Optional[Dict[str, Any]] = None,
cookie: Optional[Dict[str, Any]] = None,
user_agent: Optional[str] = None,
device_scale_factor: float = 2,
) -> bytes:
"""html转图片
Args:
html (str): html文本若存在 JavaScript 脚本则无效
html_path (str, optional): HTML路径 "file:///path/to/template.html"
wait (int, optional): 等待时间单位毫秒默认为 0.
type (Literal["jpeg", "png"]): 图片类型默认 png
quality (int, optional): 图片质量 0-100 当为`png`时无效
viewport: (Dict[str, Any], optional): viewport 参数
cookie: (Dict[str, Any], optional): 页面 cookie
user_agent: (str, optional): 页面 UA
device_scale_factor: 缩放比例类型为float值越大越清晰(真正想让图片清晰更优先请调整此选项)
**kwargs: 传入 page 的参数
Returns:
bytes: 图片, 可直接发送
"""
# logger.debug(f"html:\n{html}")
if "file:" not in html_path:
raise Exception("html_path 应为 file:/// 协议之文件传递")
# open(
# filename := os.path.join(
# template_path,
# str(uuid.uuid4()) + ".html",
# ),
# "w",
# ).write(html)
logger.info("截入浏览器运作")
try:
async with get_new_page(viewport, cookie, user_agent) as page:
page.on("console", lambda msg: logger.debug(f"浏览器控制台: {msg.text}"))
await page.goto(html_path, waitUntil="networkidle0")
if html:
await page.setContent(
html,
)
await page.waitFor(wait)
logger.info("页面截屏")
return await page.screenshot(
fullPage=True,
type=type_,
quality=quality,
scale=device_scale_factor,
encoding="binary",
) # type: ignore
except pyppeteer.errors.PyppeteerError as e:
logger.error(f"浏览器页面获取出错: {e}")
return await read_any(TEMPLATES_PATH / "chromium_error.png", "rb") # type: ignore
async def template_to_pic(
template_path: str,
template_name: str,
templates: Dict[Any, Any],
pages: Optional[Dict[Any, Any]] = None,
wait: int = 0,
type_: Literal["jpeg", "png"] = "png", # noqa: A002
quality: Union[int, None] = None,
viewport: Optional[Dict[str, Any]] = None,
cookie: Optional[Dict[str, Any]] = None,
user_agent: Optional[str] = None,
device_scale_factor: float = 2,
) -> bytes:
"""使用jinja2模板引擎通过html生成图片
Args:
template_path (str): 模板路径
template_name (str): 模板名
templates (Dict[Any, Any]): 模板内参数 : {"name": "abc"}
pages (Optional[Dict[Any, Any]]): 网页参数已弃用
wait (int, optional): 网页载入等待时间. Defaults to 0.
type (Literal["jpeg", "png"]): 图片类型, 默认 png
quality (int, optional): 图片质量 0-100 当为`png`时无效
viewport: (Dict[str, Any], optional): viewport 参数
cookie: (Dict[str, Any], optional): 页面 cookie
user_agent: (str, optional): 页面 UA
device_scale_factor: 缩放比例,类型为float,值越大越清晰(真正想让图片清晰更优先请调整此选项)
Returns:
bytes: 图片 可直接发送
"""
if not viewport:
viewport = {"width": 500, "height": 10}
if pages and "viewport" in pages:
viewport.update(pages["viewport"])
if device_scale_factor:
viewport["deviceScaleFactor"] = device_scale_factor
template_env = jinja2.Environment( # noqa: S701
loader=jinja2.FileSystemLoader(template_path),
enable_async=True,
)
logger.info(
"template_name:{},template_path:{}".format(template_name, template_path)
)
template = template_env.get_template(template_name, template_path)
await write_any(
html_path_ := os.path.join(template_path, "{}.html".format(uuid.uuid4())),
await template.render_async(**templates),
)
picture_raw = await html_to_pic(
# html=html_content,
html_path="file://{}".format(html_path_),
wait=wait,
type_=type_,
quality=quality,
viewport=viewport,
cookie=cookie,
user_agent=user_agent,
)
os.remove(html_path_)
return picture_raw
async def text_to_pic(
text: str,
css_path: str = "",
width: int = 500,
type_: Literal["jpeg", "png"] = "png", # noqa: A002
quality: Union[int, None] = None,
device_scale_factor: float = 2,
) -> bytes:
"""多行文本转图片
Args:
text (str): 纯文本, 可多行
css_path (str, optional): css文件
width (int, optional): 图片宽度默认为 500
type (Literal["jpeg", "png"]): 图片类型, 默认 png
quality (int, optional): 图片质量 0-100 当为`png`时无效
device_scale_factor: 缩放比例,类型为float,值越大越清晰(真正想让图片清晰更优先请调整此选项)
Returns:
bytes: 图片, 可直接发送
"""
template = env.get_template("text.html")
return await html_to_pic(
html=await template.render_async(
text=text,
css=(
await read_any(css_path)
if css_path
else await read_template("text.css")
),
),
html_path=f"file://{css_path if css_path else TEMPLATES_PATH}",
viewport={
"width": width,
"height": 10,
"deviceScaleFactor": device_scale_factor,
},
type_=type_,
quality=quality,
)
async def md_to_pic(
md: str = "",
md_path: str = "",
css_path: str = "",
width: int = 500,
type_: Literal["jpeg", "png"] = "png", # noqa: A002
quality: Union[int, None] = None,
device_scale_factor: float = 2,
) -> bytes:
"""markdown 转 图片
Args:
md (str, optional): markdown 格式文本
md_path (str, optional): markdown 文件路径
css_path (str, optional): css文件路径. Defaults to None.
width (int, optional): 图片宽度默认为 500
type (Literal["jpeg", "png"]): 图片类型, 默认 png
quality (int, optional): 图片质量 0-100 当为`png`时无效
device_scale_factor: 缩放比例,类型为float,值越大越清晰(真正想让图片清晰更优先请调整此选项)
Returns:
bytes: 图片, 可直接发送
"""
template = env.get_template("markdown.html")
if not md:
if md_path:
md = await read_any(md_path) # type: ignore
else:
raise Exception("必须输入 md 或 md_path")
logger.debug(md)
md = markdown.markdown(
md,
extensions=[
"pymdownx.tasklist",
"tables",
"fenced_code",
"codehilite",
"mdx_math",
"pymdownx.tilde",
],
extension_configs={"mdx_math": {"enable_dollar_delimiter": True}},
)
logger.debug(md)
extra = ""
if "math/tex" in md:
katex_css = await read_template("katex/katex.min.b64_fonts.css")
katex_js = await read_template("katex/katex.min.js")
mathtex_js = await read_template("katex/mathtex-script-type.min.js")
extra = (
f'<style type="text/css">{katex_css}</style>'
f"<script defer>{katex_js}</script>"
f"<script defer>{mathtex_js}</script>"
)
if css_path:
css = await read_any(css_path)
else:
css = await read_template("github-markdown-light.css") + await read_template(
"pygments-default.css",
)
return await html_to_pic(
html=await template.render_async(md=md, css=css, extra=extra),
html_path=f"file://{css_path if css_path else TEMPLATES_PATH}",
viewport={
"width": width,
"height": 10,
"deviceScaleFactor": device_scale_factor,
},
type_=type_,
quality=quality,
)

View File

@ -1,23 +1,21 @@
import os.path
import time
from os import getcwd
import os
# import time
# from typing import Literal
import aiofiles
import nonebot
from nonebot_plugin_htmlrender import *
from src.utils.htmlrender import (
template_to_html,
template_to_pic,
# get_new_page,
)
from .tools import random_hex_string
async def html2image(
html: str,
wait: int = 0,
):
pass
async def template2html(
template: str,
templates: dict,
template: str,
templates: dict,
) -> str:
"""
Args:
@ -32,12 +30,11 @@ async def template2html(
async def template2image(
template: str,
templates: dict,
pages=None,
wait: int = 0,
scale_factor: float = 1,
debug: bool = False,
template: str,
templates: dict,
wait: int = 1,
scale_factor: float = 1,
debug: bool = False,
) -> bytes:
"""
template -> html -> image
@ -51,14 +48,6 @@ async def template2image(
Returns:
图片二进制数据
"""
if pages is None:
pages = {
"viewport": {
"width" : 1080,
"height": 10
},
"base_url": f"file://{getcwd()}",
}
template_path = os.path.dirname(template)
template_name = os.path.basename(template)
@ -70,7 +59,9 @@ async def template2image(
**templates,
)
random_file_name = f"debug-{random_hex_string(6)}.html"
async with aiofiles.open(os.path.join(template_path, random_file_name), "w", encoding="utf-8") as f:
async with aiofiles.open(
os.path.join(template_path, random_file_name), "w", encoding="utf-8"
) as f:
await f.write(raw_html)
nonebot.logger.info("Debug HTML: %s" % f"{random_file_name}")
@ -78,36 +69,10 @@ async def template2image(
template_name=template_name,
template_path=template_path,
templates=templates,
pages=pages,
wait=wait,
device_scale_factor=scale_factor,
viewport={
"width": 1080,
"height": 10,
"deviceScaleFactor": scale_factor,
},
)
async def url2image(
url: str,
wait: int = 0,
scale_factor: float = 1,
type: str = "png",
quality: int = 100,
**kwargs
) -> bytes:
"""
Args:
quality:
type:
url: str: URL
wait: int: 等待时间
scale_factor: float: 缩放因子
**kwargs: page 参数
Returns:
图片二进制数据
"""
async with get_new_page(scale_factor) as page:
await page.goto(url)
await page.wait_for_timeout(wait)
return await page.screenshot(
full_page=True,
type=type,
quality=quality
)

View File

@ -11,11 +11,11 @@ from nonebot import require
from nonebot.adapters import satori
from nonebot.adapters.onebot import v11
from src.utils.htmlrender import md_to_pic
from .. import load_from_yaml
from ..base.ly_typing import T_Bot, T_Message, T_MessageEvent
require("nonebot_plugin_htmlrender")
from nonebot_plugin_htmlrender import md_to_pic
config = load_from_yaml("config.yml")