Files
NeoBot/main.py

85 lines
2.2 KiB
Python

"""
NEO Bot 主程序入口
"""
import asyncio
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import base_plugins # noqa: F401 别动这里是加载插件的
from core import WS
class PluginReloadHandler(FileSystemEventHandler):
"""
文件变更处理器,用于热重载插件
"""
def __init__(self):
self.last_reload_time = 0
self.cooldown = 1.0 # 冷却时间,防止短时间内多次重载
def on_any_event(self, event):
"""
处理所有文件事件
"""
if event.is_directory:
return
# 只监控 py 文件
if not event.src_path.endswith(".py"):
return
# 过滤掉一些临时文件
if "__pycache__" in event.src_path:
return
# 简单的防抖动
current_time = time.time()
if current_time - self.last_reload_time < self.cooldown:
return
self.last_reload_time = current_time
print(f"\n[HotReload] 检测到文件变更: {event.src_path}")
print("[HotReload] 正在重载插件...")
try:
# 重新扫描并加载插件
base_plugins.load_all_plugins()
print("[HotReload] 插件重载完成")
except Exception as e:
print(f"[HotReload] 重载失败: {e}")
async def main():
"""
主函数,启动 WebSocket 连接
"""
# 启动文件监控
# 监控 base_plugins 目录
plugin_path = os.path.join(os.path.dirname(__file__), "base_plugins")
event_handler = PluginReloadHandler()
observer = Observer()
if os.path.exists(plugin_path):
observer.schedule(event_handler, plugin_path, recursive=True)
observer.start()
print(f"[HotReload] 已启动插件热重载监控: {plugin_path}")
else:
print(f"[HotReload] 警告: 插件目录不存在 {plugin_path}")
try:
bot = WS()
await bot.connect()
finally:
if observer.is_alive():
observer.stop()
observer.join()
if __name__ == "__main__":
asyncio.run(main())