mirror of
https://github.com/LiteyukiStudio/LiteyukiBot.git
synced 2025-07-28 08:00:56 +00:00
🐛 fix: Channel的接收者过滤器的问题,优化重启部分
This commit is contained in:
@ -1,3 +1,11 @@
|
||||
import multiprocessing
|
||||
|
||||
from .spawn_process import *
|
||||
from .manager import *
|
||||
|
||||
__all__ = [
|
||||
"IS_MAIN_PROCESS"
|
||||
]
|
||||
|
||||
IS_MAIN_PROCESS = multiprocessing.current_process().name == "MainProcess"
|
||||
|
||||
|
93
liteyuki/core/manager.py
Normal file
93
liteyuki/core/manager.py
Normal file
@ -0,0 +1,93 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
|
||||
|
||||
@Time : 2024/7/27 上午11:12
|
||||
@Author : snowykami
|
||||
@Email : snowykami@outlook.com
|
||||
@File : manager.py
|
||||
@Software: PyCharm
|
||||
"""
|
||||
import threading
|
||||
from multiprocessing import Process
|
||||
|
||||
from liteyuki.comm import Channel
|
||||
from liteyuki.log import logger
|
||||
|
||||
TIMEOUT = 10
|
||||
|
||||
__all__ = [
|
||||
"ProcessManager"
|
||||
]
|
||||
|
||||
|
||||
class ProcessManager:
|
||||
"""
|
||||
在主进程中被调用
|
||||
"""
|
||||
|
||||
def __init__(self, bot, chan: Channel):
|
||||
self.bot = bot
|
||||
self.chan = chan
|
||||
self.processes: dict[str, tuple[callable, tuple, dict]] = {}
|
||||
|
||||
def start(self, name: str, delay: int = 0):
|
||||
"""
|
||||
开启后自动监控进程
|
||||
Args:
|
||||
name:
|
||||
delay:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
|
||||
if name not in self.processes:
|
||||
raise KeyError(f"Process {name} not found.")
|
||||
|
||||
def _start():
|
||||
should_exit = False
|
||||
while not should_exit:
|
||||
process = Process(target=self.processes[name][0], args=(self.chan, *self.processes[name][1]), kwargs=self.processes[name][2])
|
||||
process.start()
|
||||
while not should_exit:
|
||||
# 0退出 1重启
|
||||
data = self.chan.receive(name)
|
||||
print("Received data: ", data)
|
||||
if data == 1:
|
||||
logger.info("Restarting LiteyukiBot...")
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
break
|
||||
|
||||
elif data == 0:
|
||||
logger.info("Stopping LiteyukiBot...")
|
||||
should_exit = True
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
else:
|
||||
logger.warning("Unknown data received, ignored.")
|
||||
|
||||
if delay:
|
||||
threading.Timer(delay, _start).start()
|
||||
else:
|
||||
threading.Thread(target=_start).start()
|
||||
|
||||
def add_target(self, name: str, target, *args, **kwargs):
|
||||
self.processes[name] = (target, args, kwargs)
|
||||
|
||||
def join(self):
|
||||
for name, process in self.processes:
|
||||
process.join()
|
||||
|
||||
def terminate(self):
|
||||
for name, process in self.processes:
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
self.processes = []
|
14
liteyuki/core/nb/adapter_manager/__init__.py
Normal file
14
liteyuki/core/nb/adapter_manager/__init__.py
Normal file
@ -0,0 +1,14 @@
|
||||
from . import (
|
||||
satori,
|
||||
onebot
|
||||
)
|
||||
|
||||
|
||||
def init(config: dict):
|
||||
onebot.init()
|
||||
satori.init(config)
|
||||
|
||||
|
||||
def register():
|
||||
onebot.register()
|
||||
satori.register()
|
12
liteyuki/core/nb/adapter_manager/onebot.py
Normal file
12
liteyuki/core/nb/adapter_manager/onebot.py
Normal file
@ -0,0 +1,12 @@
|
||||
import nonebot
|
||||
from nonebot.adapters.onebot import v11, v12
|
||||
|
||||
|
||||
def init():
|
||||
pass
|
||||
|
||||
|
||||
def register():
|
||||
driver = nonebot.get_driver()
|
||||
driver.register_adapter(v11.Adapter)
|
||||
driver.register_adapter(v12.Adapter)
|
26
liteyuki/core/nb/adapter_manager/satori.py
Normal file
26
liteyuki/core/nb/adapter_manager/satori.py
Normal file
@ -0,0 +1,26 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
import nonebot
|
||||
from nonebot.adapters import satori
|
||||
|
||||
|
||||
def init(config: dict):
|
||||
if config.get("satori", None) is None:
|
||||
nonebot.logger.info("Satori config not found, skip Satori init.")
|
||||
return None
|
||||
satori_config = config.get("satori")
|
||||
if not satori_config.get("enable", False):
|
||||
nonebot.logger.info("Satori not enabled, skip Satori init.")
|
||||
return None
|
||||
if os.getenv("SATORI_CLIENTS", None) is not None:
|
||||
nonebot.logger.info("Satori clients already set in environment variable, skip.")
|
||||
os.environ["SATORI_CLIENTS"] = json.dumps(satori_config.get("hosts", []), ensure_ascii=False)
|
||||
config['satori_clients'] = satori_config.get("hosts", [])
|
||||
return
|
||||
|
||||
|
||||
def register():
|
||||
if os.getenv("SATORI_CLIENTS", None) is not None:
|
||||
driver = nonebot.get_driver()
|
||||
driver.register_adapter(satori.Adapter)
|
6
liteyuki/core/nb/driver_manager/__init__.py
Normal file
6
liteyuki/core/nb/driver_manager/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
from .auto_set_env import auto_set_env
|
||||
|
||||
|
||||
def init(config: dict):
|
||||
auto_set_env(config)
|
||||
return
|
20
liteyuki/core/nb/driver_manager/auto_set_env.py
Normal file
20
liteyuki/core/nb/driver_manager/auto_set_env.py
Normal file
@ -0,0 +1,20 @@
|
||||
import os
|
||||
|
||||
import dotenv
|
||||
import nonebot
|
||||
|
||||
from .defines import *
|
||||
|
||||
|
||||
def auto_set_env(config: dict):
|
||||
dotenv.load_dotenv(".env")
|
||||
if os.getenv("DRIVER", None) is not None:
|
||||
nonebot.logger.info("Driver already set in environment variable, skip auto configure.")
|
||||
return
|
||||
if config.get("satori", {'enable': False}).get("enable", False):
|
||||
os.environ["DRIVER"] = get_driver_string(ASGI_DRIVER, HTTPX_DRIVER, WEBSOCKETS_DRIVER)
|
||||
nonebot.logger.info("Enable Satori, set driver to ASGI+HTTPX+WEBSOCKETS")
|
||||
else:
|
||||
os.environ["DRIVER"] = get_driver_string(ASGI_DRIVER)
|
||||
nonebot.logger.info("Disable Satori, set driver to ASGI")
|
||||
return
|
17
liteyuki/core/nb/driver_manager/defines.py
Normal file
17
liteyuki/core/nb/driver_manager/defines.py
Normal file
@ -0,0 +1,17 @@
|
||||
ASGI_DRIVER = "~fastapi"
|
||||
HTTPX_DRIVER = "~httpx"
|
||||
WEBSOCKETS_DRIVER = "~websockets"
|
||||
|
||||
|
||||
def get_driver_string(*argv):
|
||||
output_string = ""
|
||||
if ASGI_DRIVER in argv:
|
||||
output_string += ASGI_DRIVER
|
||||
for arg in argv:
|
||||
if arg != ASGI_DRIVER:
|
||||
output_string = f"{output_string}+{arg}"
|
||||
return output_string
|
||||
|
||||
|
||||
def get_driver_full_string(*argv):
|
||||
return f"DRIVER={get_driver_string(argv)}"
|
@ -1,37 +1,50 @@
|
||||
import threading
|
||||
from multiprocessing import get_context, Event
|
||||
from multiprocessing import Event, Queue
|
||||
from typing import Optional
|
||||
|
||||
import nonebot
|
||||
from nonebot import logger
|
||||
|
||||
from liteyuki.plugin.load import load_plugins
|
||||
import liteyuki
|
||||
from liteyuki.core.nb import adapter_manager, driver_manager
|
||||
|
||||
timeout_limit: int = 20
|
||||
__all__ = [
|
||||
"ProcessingManager",
|
||||
"nb_run",
|
||||
]
|
||||
|
||||
"""导出对象,用于进程通信"""
|
||||
chan_in_spawn: Optional["liteyuki.Channel"] = None
|
||||
|
||||
|
||||
class ProcessingManager:
|
||||
event: Event = None
|
||||
def nb_run(chan, *args, **kwargs):
|
||||
"""
|
||||
初始化NoneBot并运行在子进程
|
||||
Args:
|
||||
|
||||
@classmethod
|
||||
def restart(cls, delay: int = 0):
|
||||
"""
|
||||
发送终止信号
|
||||
Args:
|
||||
delay: 延迟时间,默认为0,单位秒
|
||||
Returns:
|
||||
"""
|
||||
if cls.event is None:
|
||||
raise RuntimeError("ProcessingManager has not been initialized.")
|
||||
if delay > 0:
|
||||
threading.Timer(delay, function=cls.event.set).start()
|
||||
return
|
||||
cls.event.set()
|
||||
*args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
global chan_in_spawn
|
||||
chan_in_spawn = chan
|
||||
nonebot.init(**kwargs)
|
||||
driver_manager.init(config=kwargs)
|
||||
adapter_manager.init(kwargs)
|
||||
adapter_manager.register()
|
||||
nonebot.load_plugin("src.liteyuki_main")
|
||||
nonebot.run()
|
||||
|
||||
|
||||
def nb_run(event, *args, **kwargs):
|
||||
ProcessingManager.event = event
|
||||
nonebot.run(*args, **kwargs)
|
||||
def mb_run(chan, *args, **kwargs):
|
||||
"""
|
||||
初始化MeloBot并运行在子进程
|
||||
Args:
|
||||
chan
|
||||
*args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
# bot = MeloBot(__name__)
|
||||
# bot.init(AbstractConnector(cd_time=0))
|
||||
# bot.run()
|
||||
|
Reference in New Issue
Block a user