🐛 detect runtime plugin (#1857)

This commit is contained in:
Ju4tCode
2023-03-29 12:22:50 +08:00
committed by GitHub
parent 17c86f7da2
commit 2a2f7b6dce
6 changed files with 163 additions and 85 deletions

View File

@ -28,13 +28,26 @@ from nonebot.rule import (
shell_command,
)
from .plugin import Plugin
from . import get_plugin_by_module_name
from .manager import _current_plugin_chain
def _store_matcher(matcher: Type[Matcher]) -> None:
# only store the matcher defined in the plugin
if plugins := _current_plugin_chain.get():
plugins[-1].matcher.add(matcher)
# only store the matcher defined when plugin loading
if plugin_chain := _current_plugin_chain.get():
plugin_chain[-1].matcher.add(matcher)
def _get_matcher_plugin(depth: int = 1) -> Optional[Plugin]:
# matcher defined when plugin loading
if plugin_chain := _current_plugin_chain.get():
return plugin_chain[-1]
# matcher defined when plugin running
if module := _get_matcher_module(depth + 1):
if plugin := get_plugin_by_module_name(module.__name__):
return plugin
def _get_matcher_module(depth: int = 1) -> Optional[ModuleType]:
@ -71,7 +84,6 @@ def on(
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
plugin_chain = _current_plugin_chain.get()
matcher = Matcher.new(
type,
Rule() & rule,
@ -81,7 +93,7 @@ def on(
priority=priority,
block=block,
handlers=handlers,
plugin=plugin_chain[-1] if plugin_chain else None,
plugin=_get_matcher_plugin(_depth + 1),
module=_get_matcher_module(_depth + 1),
default_state=state,
)

View File

@ -47,7 +47,7 @@ class Plugin:
manager: "PluginManager"
"""导入该插件的插件管理器"""
matcher: Set[Type[Matcher]] = field(default_factory=set)
"""插件定义的 `Matcher`"""
"""插件加载时定义的 `Matcher`"""
parent_plugin: Optional["Plugin"] = None
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)