1
0
forked from bot/app

添加进程及生命周期管理器,添加轻雪框架支持

This commit is contained in:
2024-07-24 02:36:46 +08:00
parent 6ef3b09ec9
commit c137f2f916
41 changed files with 988 additions and 206 deletions

View File

@ -32,6 +32,7 @@ class BasicConfig(BaseModel):
command_start: list[str] = ["/", ""]
nickname: list[str] = [f"LiteyukiBot-{random_hex_string(6)}"]
satori: SatoriConfig = SatoriConfig()
data_path: str = "data/liteyuki"
def load_from_yaml(file: str) -> dict:
@ -95,6 +96,8 @@ def init_conf(conf: dict) -> dict:
"""
# 若command_start中无""则添加必要命令头开启alconna_use_command_start防止冲突
if "" not in conf.get("command_start", []):
conf["alconna_use_command_start"] = True
# 以下内容由于issue #53 被注释
# if "" not in conf.get("command_start", []):
# conf["alconna_use_command_start"] = True
return conf
pass

View File

@ -20,8 +20,9 @@ class LiteyukiAPI:
self.data = json.loads(f.read())
self.liteyuki_id = self.data.get("liteyuki_id")
self.report = load_from_yaml("config.yml").get("auto_report", True)
if self.report:
nonebot.logger.info("Auto bug report is enabled")
nonebot.logger.info("Auto report enabled")
@property
def device_info(self) -> dict:
@ -37,10 +38,10 @@ class LiteyukiAPI:
"python" : f"{platform.python_implementation()} {platform.python_version()}",
"os" : f"{platform.system()} {platform.version()} {platform.machine()}",
"cpu" : f"{psutil.cpu_count(logical=False)}c{psutil.cpu_count()}t{psutil.cpu_freq().current}MHz",
"memory_total": f"{psutil.virtual_memory().total / 1024 / 1024 / 1024:.2f}GB",
"memory_used" : f"{psutil.virtual_memory().used / 1024 / 1024 / 1024:.2f}GB",
"memory_bot" : f"{psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024:.2f}MB",
"disk" : f"{psutil.disk_usage('/').total / 1024 / 1024 / 1024:.2f}GB"
"memory_total": f"{psutil.virtual_memory().total / 1024 ** 3:.2f}GB",
"memory_used" : f"{psutil.virtual_memory().used / 1024 ** 3:.2f}GB",
"memory_bot" : f"{psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2:.2f}MB",
"disk" : f"{psutil.disk_usage('/').total / 1024 ** 3:.2f}GB"
}
def bug_report(self, content: str):
@ -77,14 +78,11 @@ class LiteyukiAPI:
url = "https://api.liteyuki.icu/heartbeat"
data = {
"liteyuki_id": self.liteyuki_id,
"version": __VERSION__,
"version" : __VERSION__,
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as resp:
if resp.status == 200:
nonebot.logger.success("Heartbeat sent successfully")
else:
nonebot.logger.error(f"Heartbeat failed: {await resp.text()}")
liteyuki_api = LiteyukiAPI()
nonebot.logger.error(f"Heartbeat failed: {await resp.text()}")

View File

@ -1,61 +0,0 @@
import threading
from multiprocessing import get_context
import nonebot
from nonebot import logger
reboot_grace_time_limit: int = 20
_nb_run = nonebot.run
class Reloader:
event: threading.Event = None
@classmethod
def reload(cls, delay: int = 0):
if cls.event is None:
raise RuntimeError()
if delay > 0:
threading.Timer(delay, function=cls.event.set).start()
return
cls.event.set()
def _run(ev: threading.Event, *args, **kwargs):
Reloader.event = ev
_nb_run(*args, **kwargs)
def run(*args, **kwargs):
should_exit = False
ctx = get_context("spawn")
while not should_exit:
event = ctx.Event()
process = ctx.Process(
target=_run,
args=(
event,
*args,
),
kwargs=kwargs,
)
process.start()
while not should_exit:
if event.wait(1):
logger.info("Receive reboot event")
process.terminate()
process.join(reboot_grace_time_limit)
if process.is_alive():
logger.warning(
f"Cannot shutdown gracefully in {reboot_grace_time_limit} second, force kill process."
)
process.kill()
break
elif process.is_alive():
continue
else:
should_exit = True
nonebot.run = run

View File

@ -9,7 +9,6 @@ from .defines import *
def auto_set_env(config: dict):
dotenv.load_dotenv(".env")
if os.getenv("DRIVER", None) is not None:
print(os.getenv("DRIVER"))
nonebot.logger.info("Driver already set in environment variable, skip auto configure.")
return
if config.get("satori", {'enable': False}).get("enable", False):

View File

@ -1,15 +1,17 @@
from aiohttp import ClientSession
async def simple_get(url: str) -> str:
"""
简单异步get请求
Args:
url:
Returns:
"""
async with ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
from aiohttp import ClientSession
from .net import *
from .file import *
async def simple_get(url: str) -> str:
"""
简单异步get请求
Args:
url:
Returns:
"""
async with ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()

29
src/utils/io/file.py Normal file
View File

@ -0,0 +1,29 @@
import aiofiles
async def write_file(
file_path: str,
content: str | bytes,
mode: str = "w"
):
"""
写入文件
Args:
mode: 写入模式
file_path: 文件路径
content: 内容
"""
async with aiofiles.open(file_path, mode) as f:
await f.write(content)
async def read_file(file_path: str, mode: str = "r") -> str:
"""
读取文件
Args:
file_path: 文件路径
mode: 读取模式
Returns:
"""
async with aiofiles.open(file_path, mode) as f:
return await f.read()

12
src/utils/io/net.py Normal file
View File

@ -0,0 +1,12 @@
async def fetch(url: str) -> str:
"""
异步get请求
Args:
url:
Returns:
"""
async with ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()