nonebot2/nonebot/plugin/plugin.py

93 lines
2.1 KiB
Python
Raw Normal View History

2021-11-08 01:02:35 +08:00
from types import ModuleType
from dataclasses import field, dataclass
2021-12-20 00:28:17 +08:00
from typing import TYPE_CHECKING, Set, Dict, Type, Optional
2021-11-08 01:02:35 +08:00
from .export import Export
2021-11-11 17:33:30 +08:00
from nonebot.matcher import Matcher
2021-11-08 01:02:35 +08:00
2021-12-20 00:28:17 +08:00
if TYPE_CHECKING:
from .manager import PluginManager
2021-11-08 01:02:35 +08:00
plugins: Dict[str, "Plugin"] = {}
"""
2022-01-12 18:16:05 +08:00
已加载的插件
2021-11-08 01:02:35 +08:00
"""
@dataclass(eq=False)
class Plugin(object):
"""存储插件信息"""
2021-11-08 01:02:35 +08:00
name: str
"""
2022-01-12 18:16:05 +08:00
插件名称使用 文件/文件夹 名称作为插件名
2021-11-08 01:02:35 +08:00
"""
module: ModuleType
"""
2022-01-12 18:16:05 +08:00
插件模块对象
2021-11-08 01:02:35 +08:00
"""
module_name: str
"""
2022-01-12 18:16:05 +08:00
点分割模块路径
2021-11-08 01:02:35 +08:00
"""
2021-12-20 00:28:17 +08:00
manager: "PluginManager"
"""
2022-01-12 18:16:05 +08:00
导入该插件的插件管理器
2021-12-20 00:28:17 +08:00
"""
2021-11-08 01:02:35 +08:00
export: Export = field(default_factory=Export)
"""
2022-01-12 18:16:05 +08:00
插件内定义的导出内容
2021-11-08 01:02:35 +08:00
"""
matcher: Set[Type[Matcher]] = field(default_factory=set)
"""
2022-01-12 18:16:05 +08:00
插件内定义的 ``Matcher``
2021-11-08 01:02:35 +08:00
"""
parent_plugin: Optional["Plugin"] = None
2021-11-11 18:10:39 +08:00
"""
2022-01-12 18:16:05 +08:00
父插件
2021-11-11 18:10:39 +08:00
"""
2021-11-08 01:02:35 +08:00
sub_plugins: Set["Plugin"] = field(default_factory=set)
2021-11-11 18:10:39 +08:00
"""
2022-01-12 18:16:05 +08:00
子插件集合
2021-11-11 18:10:39 +08:00
"""
2021-11-08 01:02:35 +08:00
def get_plugin(name: str) -> Optional[Plugin]:
"""
2022-01-12 18:16:05 +08:00
获取当前导入的某个插件
2021-11-08 01:02:35 +08:00
:参数:
* ``name: str``: 插件名 ``load_plugin`` 参数一致如果为 ``load_plugins`` 导入的插件则为文件()
:返回:
- ``Optional[Plugin]``
"""
return plugins.get(name)
def get_loaded_plugins() -> Set[Plugin]:
"""
2022-01-12 18:16:05 +08:00
获取当前已导入的所有插件
2021-11-08 01:02:35 +08:00
:返回:
- ``Set[Plugin]``
"""
return set(plugins.values())
2021-12-20 00:28:17 +08:00
def _new_plugin(fullname: str, module: ModuleType, manager: "PluginManager") -> Plugin:
2021-11-11 17:33:30 +08:00
name = fullname.rsplit(".", 1)[-1] if "." in fullname else fullname
2021-11-08 01:02:35 +08:00
if name in plugins:
raise RuntimeError("Plugin already exists! Check your plugin name.")
2021-12-20 00:28:17 +08:00
plugin = Plugin(name, module, fullname, manager)
2021-11-08 01:02:35 +08:00
return plugin
2022-01-09 23:15:33 +08:00
def _confirm_plugin(plugin: Plugin) -> None:
if plugin.name in plugins:
raise RuntimeError("Plugin already exists! Check your plugin name.")
plugins[plugin.name] = plugin