import{_ as s,c as i,o as e,a9 as a}from"./chunks/framework.C4_mTacX.js";const g=JSON.parse('{"title":"liteyuki.dev.observer","description":"","frontmatter":{"title":"liteyuki.dev.observer"},"headers":[],"relativePath":"en/dev/api/dev/observer.md","filePath":"en/dev/api/dev/observer.md","lastUpdated":1725101868000}'),n={name:"en/dev/api/dev/observer.md"},t=a(`
liteyuki.dev.observer
此模块用于注册观察者函数,使用watchdog监控文件变化并重启bot 启用该模块需要在配置文件中设置dev_mode
为True
CALLBACK_FUNC
Description: 位置1为FileSystemEvent
Type: TypeAlias
Default: Callable[[FileSystemEvent], None]
FILTER_FUNC
Description: 位置1为FileSystemEvent
Type: TypeAlias
Default: Callable[[FileSystemEvent], bool]
debounce(wait)
Description: 防抖函数
def debounce(wait):
"""
防抖函数
"""
def decorator(func):
def wrapper(*args, **kwargs):
nonlocal last_call_time
current_time = time.time()
if current_time - last_call_time > wait:
last_call_time = current_time
return func(*args, **kwargs)
last_call_time = None
return wrapper
return decorator
CodeModifiedHandler(FileSystemEventHandler)
@debounce(1)
on_modified(self, event)
@debounce(1)
def on_modified(self, event):
raise NotImplementedError('on_modified must be implemented')
on_created(self, event)
def on_created(self, event):
self.on_modified(event)
on_deleted(self, event)
def on_deleted(self, event):
self.on_modified(event)
on_moved(self, event)
def on_moved(self, event):
self.on_modified(event)
on_any_event(self, event)
def on_any_event(self, event):
self.on_modified(event)
on_file_system_event(directories: tuple[str], recursive: bool = True, event_filter: FILTER_FUNC = None) -> Callable[[CALLBACK_FUNC], CALLBACK_FUNC]
Description: 注册文件系统变化监听器
Arguments:
- directories: 监听目录们
- recursive: 是否递归监听子目录
- event_filter: 事件过滤器, 返回True则执行回调函数
Return: 装饰器,装饰一个函数在接收到数据后执行
def on_file_system_event(directories: tuple[str], recursive: bool=True, event_filter: FILTER_FUNC=None) -> Callable[[CALLBACK_FUNC], CALLBACK_FUNC]:
"""
注册文件系统变化监听器
Args:
directories: 监听目录们
recursive: 是否递归监听子目录
event_filter: 事件过滤器, 返回True则执行回调函数
Returns:
装饰器,装饰一个函数在接收到数据后执行
"""
def decorator(func: CALLBACK_FUNC) -> CALLBACK_FUNC:
def wrapper(event: FileSystemEvent):
if event_filter is not None and (not event_filter(event)):
return
func(event)
code_modified_handler = CodeModifiedHandler()
code_modified_handler.on_modified = wrapper
for directory in directories:
observer.schedule(code_modified_handler, directory, recursive=recursive)
return func
return decorator