Coverage for aipyapp/plugin.py: 76%
49 statements
« prev ^ index » next coverage.py v7.10.3, created at 2025-08-11 12:02 +0200
« prev ^ index » next coverage.py v7.10.3, created at 2025-08-11 12:02 +0200
1from typing import Any, Callable, Dict
2import inspect
3from enum import Enum
5from loguru import logger
7from .interface import EventListener
9class PluginType(Enum):
10 """插件类型"""
11 BASE = "base"
12 TASK = "task"
13 DISPLAY = "display"
15class PluginError(Exception):
16 """插件异常"""
17 pass
19class PluginConfigError(PluginError):
20 """插件配置异常"""
21 pass
23class PluginInitError(PluginError):
24 """插件初始化异常"""
25 pass
27class Plugin(EventListener):
28 """插件基类"""
29 name: str = None
30 version: str = None
31 description: str = None
32 author: str = None
34 def __init__(self):
35 self.logger = logger.bind(src=f"plugin.{self.name}")
37 @property
38 def description(self) -> str:
39 """插件描述"""
40 return self.description or self.__doc__
42 @property
43 def version(self) -> str:
44 """插件版本"""
45 return self.version or "1.0.0"
47 @property
48 def author(self) -> str:
49 """插件作者"""
50 return self.author or "Unknown"
52 def init(self):
53 """插件初始化逻辑
55 Raises:
56 PluginInitError: 插件初始化异常
57 """
58 pass
60 @classmethod
61 def get_type(cls) -> PluginType:
62 """Get plugin type
64 Returns:
65 Plugin type
66 """
67 return PluginType.BASE
69 def _get_methods(self, prefix: str = "fn_") -> Dict[str, Callable]:
70 """Get all functions
72 Returns:
73 All functions
74 """
75 return {
76 name[len(prefix):]: method
77 for name, method in inspect.getmembers(self, predicate=inspect.ismethod)
78 if name.startswith(prefix) and len(name) > len(prefix)
79 }
81 def get_handlers(self) -> Dict[str, Callable]:
82 """Get all handlers
84 Returns:
85 All handlers
86 """
87 return self._get_methods(prefix='on_')
89class TaskPlugin(Plugin):
90 """任务插件"""
91 def __init__(self, config: Dict[str, Any] = None):
92 super().__init__()
93 self.config = config or {}
95 @classmethod
96 def get_type(cls) -> PluginType:
97 """Get plugin type
99 Returns:
100 Plugin type
101 """
102 return PluginType.TASK
104 def get_functions(self) -> Dict[str, Callable]:
105 """Get all functions
107 Returns:
108 All functions
109 """
110 return self._get_methods(prefix='fn_')