We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: 部分情况下，加载失败的插件依然会出现在当前已导入的所有插件中
**描述问题：**

通过 nonebot.get_loaded_plugins() 获取当前已导入的所有插件，加载失败的插件也出现在其中

**如何复现？**

1. 复制 2.0.0 a16 版本文档的[注册事件响应器](https://61d3d9dbcadf413fd3238e89--nonebot2.netlify.app/guide/creating-a-matcher.html)一节的 weather.py 的代码作为插件，并在 2.0.0 beta1 版本导入它（很显然，这会发生错误）
2. 通过 nonebot.get_loaded_plugins() 获取已导入的插件，可以发现这个加载失败的插件出现在了已导入的插件中

**期望的结果**

加载失败的插件不出现在已导入的所有插件中

**环境信息：**

 - OS: [Windows]
 - Python Version: [3.10]
 - Nonebot Version: [2.0.0 b1]

**协议端信息：**

 - 协议端: [go-cqhttp]
 - 协议端版本: [1.0.0]

**截图或日志**

```
[ERROR] nonebot | Failed to import "kirami.plugins.weather"
ValueError: Unknown parameter state for function <function handle_first_receive at 0x000001924056AB90> with type typing.Dict[typing.Any, typing.Any]

{Plugin(name='weather', module=<module 'kirami.plugins.weather' from 'D:\\Users\\Documents\\gitee\\KiramiBot\\kirami\\plugins\\weather\\__init__.py'>, module_name='kirami.plugins.weather', manager=<nonebot.plugin.manager.PluginManager object at 0x000002140ECEF130>, export={}, matcher=set(), parent_plugin=None, sub_plugins=set())}
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nonebot/plugin/plugin.py`
Content:
```
1 from types import ModuleType
2 from dataclasses import field, dataclass
3 from typing import TYPE_CHECKING, Set, Dict, Type, Optional
4 
5 from .export import Export
6 from nonebot.matcher import Matcher
7 
8 if TYPE_CHECKING:
9     from .manager import PluginManager
10 
11 plugins: Dict[str, "Plugin"] = {}
12 """
13 :类型: ``Dict[str, Plugin]``
14 :说明: 已加载的插件
15 """
16 
17 
18 @dataclass(eq=False)
19 class Plugin(object):
20     """存储插件信息"""
21 
22     name: str
23     """
24     - **类型**: ``str``
25     - **说明**: 插件名称，使用 文件/文件夹 名称作为插件名
26     """
27     module: ModuleType
28     """
29     - **类型**: ``ModuleType``
30     - **说明**: 插件模块对象
31     """
32     module_name: str
33     """
34     - **类型**: ``str``
35     - **说明**: 点分割模块路径
36     """
37     manager: "PluginManager"
38     """
39     - **类型**: ``PluginManager``
40     - **说明**: 导入该插件的插件管理器
41     """
42     export: Export = field(default_factory=Export)
43     """
44     - **类型**: ``Export``
45     - **说明**: 插件内定义的导出内容
46     """
47     matcher: Set[Type[Matcher]] = field(default_factory=set)
48     """
49     - **类型**: ``Set[Type[Matcher]]``
50     - **说明**: 插件内定义的 ``Matcher``
51     """
52     parent_plugin: Optional["Plugin"] = None
53     """
54     - **类型**: ``Optional[Plugin]``
55     - **说明**: 父插件
56     """
57     sub_plugins: Set["Plugin"] = field(default_factory=set)
58     """
59     - **类型**: ``Set[Plugin]``
60     - **说明**: 子插件集合
61     """
62 
63 
64 def get_plugin(name: str) -> Optional[Plugin]:
65     """
66     :说明:
67 
68       获取当前导入的某个插件。
69 
70     :参数:
71 
72       * ``name: str``: 插件名，与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件，则为文件(夹)名。
73 
74     :返回:
75 
76       - ``Optional[Plugin]``
77     """
78     return plugins.get(name)
79 
80 
81 def get_loaded_plugins() -> Set[Plugin]:
82     """
83     :说明:
84 
85       获取当前已导入的所有插件。
86 
87     :返回:
88 
89       - ``Set[Plugin]``
90     """
91     return set(plugins.values())
92 
93 
94 def _new_plugin(fullname: str, module: ModuleType, manager: "PluginManager") -> Plugin:
95     name = fullname.rsplit(".", 1)[-1] if "." in fullname else fullname
96     if name in plugins:
97         raise RuntimeError("Plugin already exists! Check your plugin name.")
98     plugin = Plugin(name, module, fullname, manager)
99     plugins[name] = plugin
100     return plugin
101
```

Path: `nonebot/plugin/manager.py`
Content:
```
1 import sys
2 import pkgutil
3 import importlib
4 from pathlib import Path
5 from itertools import chain
6 from types import ModuleType
7 from importlib.abc import MetaPathFinder
8 from importlib.machinery import PathFinder, SourceFileLoader
9 from typing import Set, Dict, List, Union, Iterable, Optional, Sequence
10 
11 from nonebot.log import logger
12 from nonebot.utils import escape_tag
13 from .plugin import Plugin, _new_plugin
14 from . import _managers, _current_plugin
15 
16 
17 class PluginManager:
18     def __init__(
19         self,
20         plugins: Optional[Iterable[str]] = None,
21         search_path: Optional[Iterable[str]] = None,
22     ):
23 
24         # simple plugin not in search path
25         self.plugins: Set[str] = set(plugins or [])
26         self.search_path: Set[str] = set(search_path or [])
27         # cache plugins
28         self.searched_plugins: Dict[str, Path] = {}
29         self.list_plugins()
30 
31     def _path_to_module_name(self, path: Path) -> str:
32         rel_path = path.resolve().relative_to(Path(".").resolve())
33         if rel_path.stem == "__init__":
34             return ".".join(rel_path.parts[:-1])
35         else:
36             return ".".join(rel_path.parts[:-1] + (rel_path.stem,))
37 
38     def _previous_plugins(self) -> List[str]:
39         _pre_managers: List[PluginManager]
40         if self in _managers:
41             _pre_managers = _managers[: _managers.index(self)]
42         else:
43             _pre_managers = _managers[:]
44 
45         return [
46             *chain.from_iterable(
47                 [*manager.plugins, *manager.searched_plugins.keys()]
48                 for manager in _pre_managers
49             )
50         ]
51 
52     def list_plugins(self) -> Set[str]:
53         # get all previous ready to load plugins
54         previous_plugins = self._previous_plugins()
55         searched_plugins: Dict[str, Path] = {}
56         third_party_plugins: Set[str] = set()
57 
58         for plugin in self.plugins:
59             name = plugin.rsplit(".", 1)[-1] if "." in plugin else plugin
60             if name in third_party_plugins or name in previous_plugins:
61                 raise RuntimeError(
62                     f"Plugin already exists: {name}! Check your plugin name"
63                 )
64             third_party_plugins.add(plugin)
65 
66         for module_info in pkgutil.iter_modules(self.search_path):
67             if module_info.name.startswith("_"):
68                 continue
69             if (
70                 module_info.name in searched_plugins.keys()
71                 or module_info.name in previous_plugins
72                 or module_info.name in third_party_plugins
73             ):
74                 raise RuntimeError(
75                     f"Plugin already exists: {module_info.name}! Check your plugin name"
76                 )
77             module_spec = module_info.module_finder.find_spec(module_info.name, None)
78             if not module_spec:
79                 continue
80             module_path = module_spec.origin
81             if not module_path:
82                 continue
83             searched_plugins[module_info.name] = Path(module_path).resolve()
84 
85         self.searched_plugins = searched_plugins
86 
87         return third_party_plugins | set(self.searched_plugins.keys())
88 
89     def load_plugin(self, name) -> Optional[Plugin]:
90         try:
91             if name in self.plugins:
92                 module = importlib.import_module(name)
93             elif name not in self.searched_plugins:
94                 raise RuntimeError(f"Plugin not found: {name}! Check your plugin name")
95             else:
96                 module = importlib.import_module(
97                     self._path_to_module_name(self.searched_plugins[name])
98                 )
99 
100             logger.opt(colors=True).success(
101                 f'Succeeded to import "<y>{escape_tag(name)}</y>"'
102             )
103             return getattr(module, "__plugin__", None)
104         except Exception as e:
105             logger.opt(colors=True, exception=e).error(
106                 f'<r><bg #f8bbd0>Failed to import "{escape_tag(name)}"</bg #f8bbd0></r>'
107             )
108 
109     def load_all_plugins(self) -> Set[Plugin]:
110         return set(
111             filter(None, (self.load_plugin(name) for name in self.list_plugins()))
112         )
113 
114 
115 class PluginFinder(MetaPathFinder):
116     def find_spec(
117         self,
118         fullname: str,
119         path: Optional[Sequence[Union[bytes, str]]],
120         target: Optional[ModuleType] = None,
121     ):
122         if _managers:
123             index = -1
124             module_spec = PathFinder.find_spec(fullname, path, target)
125             if not module_spec:
126                 return
127             module_origin = module_spec.origin
128             if not module_origin:
129                 return
130             module_path = Path(module_origin).resolve()
131 
132             while -index <= len(_managers):
133                 manager = _managers[index]
134 
135                 if (
136                     fullname in manager.plugins
137                     or module_path in manager.searched_plugins.values()
138                 ):
139                     module_spec.loader = PluginLoader(manager, fullname, module_origin)
140                     return module_spec
141 
142                 index -= 1
143         return
144 
145 
146 class PluginLoader(SourceFileLoader):
147     def __init__(self, manager: PluginManager, fullname: str, path) -> None:
148         self.manager = manager
149         self.loaded = False
150         super().__init__(fullname, path)
151 
152     def create_module(self, spec) -> Optional[ModuleType]:
153         if self.name in sys.modules:
154             self.loaded = True
155             return sys.modules[self.name]
156         # return None to use default module creation
157         return super().create_module(spec)
158 
159     def exec_module(self, module: ModuleType) -> None:
160         if self.loaded:
161             return
162 
163         plugin = _new_plugin(self.name, module, self.manager)
164         parent_plugin = _current_plugin.get()
165         if parent_plugin and _managers.index(parent_plugin.manager) < _managers.index(
166             self.manager
167         ):
168             plugin.parent_plugin = parent_plugin
169             parent_plugin.sub_plugins.add(plugin)
170 
171         _plugin_token = _current_plugin.set(plugin)
172 
173         setattr(module, "__plugin__", plugin)
174 
175         # try:
176         #     super().exec_module(module)
177         # except Exception as e:
178         #     raise ImportError(
179         #         f"Error when executing module {module_name} from {module.__file__}."
180         #     ) from e
181         super().exec_module(module)
182 
183         _current_plugin.reset(_plugin_token)
184         return
185 
186 
187 sys.meta_path.insert(0, PluginFinder())
188
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nonebot/plugin/manager.py b/nonebot/plugin/manager.py
--- a/nonebot/plugin/manager.py
+++ b/nonebot/plugin/manager.py
@@ -10,8 +10,8 @@
 
 from nonebot.log import logger
 from nonebot.utils import escape_tag
-from .plugin import Plugin, _new_plugin
 from . import _managers, _current_plugin
+from .plugin import Plugin, _new_plugin, _confirm_plugin
 
 
 class PluginManager:
@@ -180,6 +180,8 @@
         #     ) from e
         super().exec_module(module)
 
+        _confirm_plugin(plugin)
+
         _current_plugin.reset(_plugin_token)
         return
 
diff --git a/nonebot/plugin/plugin.py b/nonebot/plugin/plugin.py
--- a/nonebot/plugin/plugin.py
+++ b/nonebot/plugin/plugin.py
@@ -96,5 +96,10 @@
     if name in plugins:
         raise RuntimeError("Plugin already exists! Check your plugin name.")
     plugin = Plugin(name, module, fullname, manager)
-    plugins[name] = plugin
     return plugin
+
+
+def _confirm_plugin(plugin: Plugin) -> None:
+    if plugin.name in plugins:
+        raise RuntimeError("Plugin already exists! Check your plugin name.")
+    plugins[plugin.name] = plugin

{"golden_diff": "diff --git a/nonebot/plugin/manager.py b/nonebot/plugin/manager.py\n--- a/nonebot/plugin/manager.py\n+++ b/nonebot/plugin/manager.py\n@@ -10,8 +10,8 @@\n \n from nonebot.log import logger\n from nonebot.utils import escape_tag\n-from .plugin import Plugin, _new_plugin\n from . import _managers, _current_plugin\n+from .plugin import Plugin, _new_plugin, _confirm_plugin\n \n \n class PluginManager:\n@@ -180,6 +180,8 @@\n         #     ) from e\n         super().exec_module(module)\n \n+        _confirm_plugin(plugin)\n+\n         _current_plugin.reset(_plugin_token)\n         return\n \ndiff --git a/nonebot/plugin/plugin.py b/nonebot/plugin/plugin.py\n--- a/nonebot/plugin/plugin.py\n+++ b/nonebot/plugin/plugin.py\n@@ -96,5 +96,10 @@\n     if name in plugins:\n         raise RuntimeError(\"Plugin already exists! Check your plugin name.\")\n     plugin = Plugin(name, module, fullname, manager)\n-    plugins[name] = plugin\n     return plugin\n+\n+\n+def _confirm_plugin(plugin: Plugin) -> None:\n+    if plugin.name in plugins:\n+        raise RuntimeError(\"Plugin already exists! Check your plugin name.\")\n+    plugins[plugin.name] = plugin\n", "issue": "Bug: \u90e8\u5206\u60c5\u51b5\u4e0b\uff0c\u52a0\u8f7d\u5931\u8d25\u7684\u63d2\u4ef6\u4f9d\u7136\u4f1a\u51fa\u73b0\u5728\u5f53\u524d\u5df2\u5bfc\u5165\u7684\u6240\u6709\u63d2\u4ef6\u4e2d\n**\u63cf\u8ff0\u95ee\u9898\uff1a**\r\n\r\n\u901a\u8fc7 nonebot.get_loaded_plugins() \u83b7\u53d6\u5f53\u524d\u5df2\u5bfc\u5165\u7684\u6240\u6709\u63d2\u4ef6\uff0c\u52a0\u8f7d\u5931\u8d25\u7684\u63d2\u4ef6\u4e5f\u51fa\u73b0\u5728\u5176\u4e2d\r\n\r\n**\u5982\u4f55\u590d\u73b0\uff1f**\r\n\r\n1. \u590d\u5236 2.0.0 a16 \u7248\u672c\u6587\u6863\u7684[\u6ce8\u518c\u4e8b\u4ef6\u54cd\u5e94\u5668](https://61d3d9dbcadf413fd3238e89--nonebot2.netlify.app/guide/creating-a-matcher.html)\u4e00\u8282\u7684 weather.py \u7684\u4ee3\u7801\u4f5c\u4e3a\u63d2\u4ef6\uff0c\u5e76\u5728 2.0.0 beta1 \u7248\u672c\u5bfc\u5165\u5b83\uff08\u5f88\u663e\u7136\uff0c\u8fd9\u4f1a\u53d1\u751f\u9519\u8bef\uff09\r\n2. \u901a\u8fc7 nonebot.get_loaded_plugins() \u83b7\u53d6\u5df2\u5bfc\u5165\u7684\u63d2\u4ef6\uff0c\u53ef\u4ee5\u53d1\u73b0\u8fd9\u4e2a\u52a0\u8f7d\u5931\u8d25\u7684\u63d2\u4ef6\u51fa\u73b0\u5728\u4e86\u5df2\u5bfc\u5165\u7684\u63d2\u4ef6\u4e2d\r\n\r\n**\u671f\u671b\u7684\u7ed3\u679c**\r\n\r\n\u52a0\u8f7d\u5931\u8d25\u7684\u63d2\u4ef6\u4e0d\u51fa\u73b0\u5728\u5df2\u5bfc\u5165\u7684\u6240\u6709\u63d2\u4ef6\u4e2d\r\n\r\n**\u73af\u5883\u4fe1\u606f\uff1a**\r\n\r\n - OS: [Windows]\r\n - Python Version: [3.10]\r\n - Nonebot Version: [2.0.0 b1]\r\n\r\n**\u534f\u8bae\u7aef\u4fe1\u606f\uff1a**\r\n\r\n - \u534f\u8bae\u7aef: [go-cqhttp]\r\n - \u534f\u8bae\u7aef\u7248\u672c: [1.0.0]\r\n\r\n**\u622a\u56fe\u6216\u65e5\u5fd7**\r\n\r\n```\r\n[ERROR] nonebot | Failed to import \"kirami.plugins.weather\"\r\nValueError: Unknown parameter state for function <function handle_first_receive at 0x000001924056AB90> with type typing.Dict[typing.Any, typing.Any]\r\n\r\n{Plugin(name='weather', module=<module 'kirami.plugins.weather' from 'D:\\\\Users\\\\Documents\\\\gitee\\\\KiramiBot\\\\kirami\\\\plugins\\\\weather\\\\__init__.py'>, module_name='kirami.plugins.weather', manager=<nonebot.plugin.manager.PluginManager object at 0x000002140ECEF130>, export={}, matcher=set(), parent_plugin=None, sub_plugins=set())}\r\n```\n", "before_files": [{"content": "from types import ModuleType\nfrom dataclasses import field, dataclass\nfrom typing import TYPE_CHECKING, Set, Dict, Type, Optional\n\nfrom .export import Export\nfrom nonebot.matcher import Matcher\n\nif TYPE_CHECKING:\n    from .manager import PluginManager\n\nplugins: Dict[str, \"Plugin\"] = {}\n\"\"\"\n:\u7c7b\u578b: ``Dict[str, Plugin]``\n:\u8bf4\u660e: \u5df2\u52a0\u8f7d\u7684\u63d2\u4ef6\n\"\"\"\n\n\n@dataclass(eq=False)\nclass Plugin(object):\n    \"\"\"\u5b58\u50a8\u63d2\u4ef6\u4fe1\u606f\"\"\"\n\n    name: str\n    \"\"\"\n    - **\u7c7b\u578b**: ``str``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u540d\u79f0\uff0c\u4f7f\u7528 \u6587\u4ef6/\u6587\u4ef6\u5939 \u540d\u79f0\u4f5c\u4e3a\u63d2\u4ef6\u540d\n    \"\"\"\n    module: ModuleType\n    \"\"\"\n    - **\u7c7b\u578b**: ``ModuleType``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u6a21\u5757\u5bf9\u8c61\n    \"\"\"\n    module_name: str\n    \"\"\"\n    - **\u7c7b\u578b**: ``str``\n    - **\u8bf4\u660e**: \u70b9\u5206\u5272\u6a21\u5757\u8def\u5f84\n    \"\"\"\n    manager: \"PluginManager\"\n    \"\"\"\n    - **\u7c7b\u578b**: ``PluginManager``\n    - **\u8bf4\u660e**: \u5bfc\u5165\u8be5\u63d2\u4ef6\u7684\u63d2\u4ef6\u7ba1\u7406\u5668\n    \"\"\"\n    export: Export = field(default_factory=Export)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Export``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u5185\u5b9a\u4e49\u7684\u5bfc\u51fa\u5185\u5bb9\n    \"\"\"\n    matcher: Set[Type[Matcher]] = field(default_factory=set)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Set[Type[Matcher]]``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u5185\u5b9a\u4e49\u7684 ``Matcher``\n    \"\"\"\n    parent_plugin: Optional[\"Plugin\"] = None\n    \"\"\"\n    - **\u7c7b\u578b**: ``Optional[Plugin]``\n    - **\u8bf4\u660e**: \u7236\u63d2\u4ef6\n    \"\"\"\n    sub_plugins: Set[\"Plugin\"] = field(default_factory=set)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Set[Plugin]``\n    - **\u8bf4\u660e**: \u5b50\u63d2\u4ef6\u96c6\u5408\n    \"\"\"\n\n\ndef get_plugin(name: str) -> Optional[Plugin]:\n    \"\"\"\n    :\u8bf4\u660e:\n\n      \u83b7\u53d6\u5f53\u524d\u5bfc\u5165\u7684\u67d0\u4e2a\u63d2\u4ef6\u3002\n\n    :\u53c2\u6570:\n\n      * ``name: str``: \u63d2\u4ef6\u540d\uff0c\u4e0e ``load_plugin`` \u53c2\u6570\u4e00\u81f4\u3002\u5982\u679c\u4e3a ``load_plugins`` \u5bfc\u5165\u7684\u63d2\u4ef6\uff0c\u5219\u4e3a\u6587\u4ef6(\u5939)\u540d\u3002\n\n    :\u8fd4\u56de:\n\n      - ``Optional[Plugin]``\n    \"\"\"\n    return plugins.get(name)\n\n\ndef get_loaded_plugins() -> Set[Plugin]:\n    \"\"\"\n    :\u8bf4\u660e:\n\n      \u83b7\u53d6\u5f53\u524d\u5df2\u5bfc\u5165\u7684\u6240\u6709\u63d2\u4ef6\u3002\n\n    :\u8fd4\u56de:\n\n      - ``Set[Plugin]``\n    \"\"\"\n    return set(plugins.values())\n\n\ndef _new_plugin(fullname: str, module: ModuleType, manager: \"PluginManager\") -> Plugin:\n    name = fullname.rsplit(\".\", 1)[-1] if \".\" in fullname else fullname\n    if name in plugins:\n        raise RuntimeError(\"Plugin already exists! Check your plugin name.\")\n    plugin = Plugin(name, module, fullname, manager)\n    plugins[name] = plugin\n    return plugin\n", "path": "nonebot/plugin/plugin.py"}, {"content": "import sys\nimport pkgutil\nimport importlib\nfrom pathlib import Path\nfrom itertools import chain\nfrom types import ModuleType\nfrom importlib.abc import MetaPathFinder\nfrom importlib.machinery import PathFinder, SourceFileLoader\nfrom typing import Set, Dict, List, Union, Iterable, Optional, Sequence\n\nfrom nonebot.log import logger\nfrom nonebot.utils import escape_tag\nfrom .plugin import Plugin, _new_plugin\nfrom . import _managers, _current_plugin\n\n\nclass PluginManager:\n    def __init__(\n        self,\n        plugins: Optional[Iterable[str]] = None,\n        search_path: Optional[Iterable[str]] = None,\n    ):\n\n        # simple plugin not in search path\n        self.plugins: Set[str] = set(plugins or [])\n        self.search_path: Set[str] = set(search_path or [])\n        # cache plugins\n        self.searched_plugins: Dict[str, Path] = {}\n        self.list_plugins()\n\n    def _path_to_module_name(self, path: Path) -> str:\n        rel_path = path.resolve().relative_to(Path(\".\").resolve())\n        if rel_path.stem == \"__init__\":\n            return \".\".join(rel_path.parts[:-1])\n        else:\n            return \".\".join(rel_path.parts[:-1] + (rel_path.stem,))\n\n    def _previous_plugins(self) -> List[str]:\n        _pre_managers: List[PluginManager]\n        if self in _managers:\n            _pre_managers = _managers[: _managers.index(self)]\n        else:\n            _pre_managers = _managers[:]\n\n        return [\n            *chain.from_iterable(\n                [*manager.plugins, *manager.searched_plugins.keys()]\n                for manager in _pre_managers\n            )\n        ]\n\n    def list_plugins(self) -> Set[str]:\n        # get all previous ready to load plugins\n        previous_plugins = self._previous_plugins()\n        searched_plugins: Dict[str, Path] = {}\n        third_party_plugins: Set[str] = set()\n\n        for plugin in self.plugins:\n            name = plugin.rsplit(\".\", 1)[-1] if \".\" in plugin else plugin\n            if name in third_party_plugins or name in previous_plugins:\n                raise RuntimeError(\n                    f\"Plugin already exists: {name}! Check your plugin name\"\n                )\n            third_party_plugins.add(plugin)\n\n        for module_info in pkgutil.iter_modules(self.search_path):\n            if module_info.name.startswith(\"_\"):\n                continue\n            if (\n                module_info.name in searched_plugins.keys()\n                or module_info.name in previous_plugins\n                or module_info.name in third_party_plugins\n            ):\n                raise RuntimeError(\n                    f\"Plugin already exists: {module_info.name}! Check your plugin name\"\n                )\n            module_spec = module_info.module_finder.find_spec(module_info.name, None)\n            if not module_spec:\n                continue\n            module_path = module_spec.origin\n            if not module_path:\n                continue\n            searched_plugins[module_info.name] = Path(module_path).resolve()\n\n        self.searched_plugins = searched_plugins\n\n        return third_party_plugins | set(self.searched_plugins.keys())\n\n    def load_plugin(self, name) -> Optional[Plugin]:\n        try:\n            if name in self.plugins:\n                module = importlib.import_module(name)\n            elif name not in self.searched_plugins:\n                raise RuntimeError(f\"Plugin not found: {name}! Check your plugin name\")\n            else:\n                module = importlib.import_module(\n                    self._path_to_module_name(self.searched_plugins[name])\n                )\n\n            logger.opt(colors=True).success(\n                f'Succeeded to import \"<y>{escape_tag(name)}</y>\"'\n            )\n            return getattr(module, \"__plugin__\", None)\n        except Exception as e:\n            logger.opt(colors=True, exception=e).error(\n                f'<r><bg #f8bbd0>Failed to import \"{escape_tag(name)}\"</bg #f8bbd0></r>'\n            )\n\n    def load_all_plugins(self) -> Set[Plugin]:\n        return set(\n            filter(None, (self.load_plugin(name) for name in self.list_plugins()))\n        )\n\n\nclass PluginFinder(MetaPathFinder):\n    def find_spec(\n        self,\n        fullname: str,\n        path: Optional[Sequence[Union[bytes, str]]],\n        target: Optional[ModuleType] = None,\n    ):\n        if _managers:\n            index = -1\n            module_spec = PathFinder.find_spec(fullname, path, target)\n            if not module_spec:\n                return\n            module_origin = module_spec.origin\n            if not module_origin:\n                return\n            module_path = Path(module_origin).resolve()\n\n            while -index <= len(_managers):\n                manager = _managers[index]\n\n                if (\n                    fullname in manager.plugins\n                    or module_path in manager.searched_plugins.values()\n                ):\n                    module_spec.loader = PluginLoader(manager, fullname, module_origin)\n                    return module_spec\n\n                index -= 1\n        return\n\n\nclass PluginLoader(SourceFileLoader):\n    def __init__(self, manager: PluginManager, fullname: str, path) -> None:\n        self.manager = manager\n        self.loaded = False\n        super().__init__(fullname, path)\n\n    def create_module(self, spec) -> Optional[ModuleType]:\n        if self.name in sys.modules:\n            self.loaded = True\n            return sys.modules[self.name]\n        # return None to use default module creation\n        return super().create_module(spec)\n\n    def exec_module(self, module: ModuleType) -> None:\n        if self.loaded:\n            return\n\n        plugin = _new_plugin(self.name, module, self.manager)\n        parent_plugin = _current_plugin.get()\n        if parent_plugin and _managers.index(parent_plugin.manager) < _managers.index(\n            self.manager\n        ):\n            plugin.parent_plugin = parent_plugin\n            parent_plugin.sub_plugins.add(plugin)\n\n        _plugin_token = _current_plugin.set(plugin)\n\n        setattr(module, \"__plugin__\", plugin)\n\n        # try:\n        #     super().exec_module(module)\n        # except Exception as e:\n        #     raise ImportError(\n        #         f\"Error when executing module {module_name} from {module.__file__}.\"\n        #     ) from e\n        super().exec_module(module)\n\n        _current_plugin.reset(_plugin_token)\n        return\n\n\nsys.meta_path.insert(0, PluginFinder())\n", "path": "nonebot/plugin/manager.py"}], "after_files": [{"content": "from types import ModuleType\nfrom dataclasses import field, dataclass\nfrom typing import TYPE_CHECKING, Set, Dict, Type, Optional\n\nfrom .export import Export\nfrom nonebot.matcher import Matcher\n\nif TYPE_CHECKING:\n    from .manager import PluginManager\n\nplugins: Dict[str, \"Plugin\"] = {}\n\"\"\"\n:\u7c7b\u578b: ``Dict[str, Plugin]``\n:\u8bf4\u660e: \u5df2\u52a0\u8f7d\u7684\u63d2\u4ef6\n\"\"\"\n\n\n@dataclass(eq=False)\nclass Plugin(object):\n    \"\"\"\u5b58\u50a8\u63d2\u4ef6\u4fe1\u606f\"\"\"\n\n    name: str\n    \"\"\"\n    - **\u7c7b\u578b**: ``str``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u540d\u79f0\uff0c\u4f7f\u7528 \u6587\u4ef6/\u6587\u4ef6\u5939 \u540d\u79f0\u4f5c\u4e3a\u63d2\u4ef6\u540d\n    \"\"\"\n    module: ModuleType\n    \"\"\"\n    - **\u7c7b\u578b**: ``ModuleType``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u6a21\u5757\u5bf9\u8c61\n    \"\"\"\n    module_name: str\n    \"\"\"\n    - **\u7c7b\u578b**: ``str``\n    - **\u8bf4\u660e**: \u70b9\u5206\u5272\u6a21\u5757\u8def\u5f84\n    \"\"\"\n    manager: \"PluginManager\"\n    \"\"\"\n    - **\u7c7b\u578b**: ``PluginManager``\n    - **\u8bf4\u660e**: \u5bfc\u5165\u8be5\u63d2\u4ef6\u7684\u63d2\u4ef6\u7ba1\u7406\u5668\n    \"\"\"\n    export: Export = field(default_factory=Export)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Export``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u5185\u5b9a\u4e49\u7684\u5bfc\u51fa\u5185\u5bb9\n    \"\"\"\n    matcher: Set[Type[Matcher]] = field(default_factory=set)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Set[Type[Matcher]]``\n    - **\u8bf4\u660e**: \u63d2\u4ef6\u5185\u5b9a\u4e49\u7684 ``Matcher``\n    \"\"\"\n    parent_plugin: Optional[\"Plugin\"] = None\n    \"\"\"\n    - **\u7c7b\u578b**: ``Optional[Plugin]``\n    - **\u8bf4\u660e**: \u7236\u63d2\u4ef6\n    \"\"\"\n    sub_plugins: Set[\"Plugin\"] = field(default_factory=set)\n    \"\"\"\n    - **\u7c7b\u578b**: ``Set[Plugin]``\n    - **\u8bf4\u660e**: \u5b50\u63d2\u4ef6\u96c6\u5408\n    \"\"\"\n\n\ndef get_plugin(name: str) -> Optional[Plugin]:\n    \"\"\"\n    :\u8bf4\u660e:\n\n      \u83b7\u53d6\u5f53\u524d\u5bfc\u5165\u7684\u67d0\u4e2a\u63d2\u4ef6\u3002\n\n    :\u53c2\u6570:\n\n      * ``name: str``: \u63d2\u4ef6\u540d\uff0c\u4e0e ``load_plugin`` \u53c2\u6570\u4e00\u81f4\u3002\u5982\u679c\u4e3a ``load_plugins`` \u5bfc\u5165\u7684\u63d2\u4ef6\uff0c\u5219\u4e3a\u6587\u4ef6(\u5939)\u540d\u3002\n\n    :\u8fd4\u56de:\n\n      - ``Optional[Plugin]``\n    \"\"\"\n    return plugins.get(name)\n\n\ndef get_loaded_plugins() -> Set[Plugin]:\n    \"\"\"\n    :\u8bf4\u660e:\n\n      \u83b7\u53d6\u5f53\u524d\u5df2\u5bfc\u5165\u7684\u6240\u6709\u63d2\u4ef6\u3002\n\n    :\u8fd4\u56de:\n\n      - ``Set[Plugin]``\n    \"\"\"\n    return set(plugins.values())\n\n\ndef _new_plugin(fullname: str, module: ModuleType, manager: \"PluginManager\") -> Plugin:\n    name = fullname.rsplit(\".\", 1)[-1] if \".\" in fullname else fullname\n    if name in plugins:\n        raise RuntimeError(\"Plugin already exists! Check your plugin name.\")\n    plugin = Plugin(name, module, fullname, manager)\n    return plugin\n\n\ndef _confirm_plugin(plugin: Plugin) -> None:\n    if plugin.name in plugins:\n        raise RuntimeError(\"Plugin already exists! Check your plugin name.\")\n    plugins[plugin.name] = plugin\n", "path": "nonebot/plugin/plugin.py"}, {"content": "import sys\nimport pkgutil\nimport importlib\nfrom pathlib import Path\nfrom itertools import chain\nfrom types import ModuleType\nfrom importlib.abc import MetaPathFinder\nfrom importlib.machinery import PathFinder, SourceFileLoader\nfrom typing import Set, Dict, List, Union, Iterable, Optional, Sequence\n\nfrom nonebot.log import logger\nfrom nonebot.utils import escape_tag\nfrom . import _managers, _current_plugin\nfrom .plugin import Plugin, _new_plugin, _confirm_plugin\n\n\nclass PluginManager:\n    def __init__(\n        self,\n        plugins: Optional[Iterable[str]] = None,\n        search_path: Optional[Iterable[str]] = None,\n    ):\n\n        # simple plugin not in search path\n        self.plugins: Set[str] = set(plugins or [])\n        self.search_path: Set[str] = set(search_path or [])\n        # cache plugins\n        self.searched_plugins: Dict[str, Path] = {}\n        self.list_plugins()\n\n    def _path_to_module_name(self, path: Path) -> str:\n        rel_path = path.resolve().relative_to(Path(\".\").resolve())\n        if rel_path.stem == \"__init__\":\n            return \".\".join(rel_path.parts[:-1])\n        else:\n            return \".\".join(rel_path.parts[:-1] + (rel_path.stem,))\n\n    def _previous_plugins(self) -> List[str]:\n        _pre_managers: List[PluginManager]\n        if self in _managers:\n            _pre_managers = _managers[: _managers.index(self)]\n        else:\n            _pre_managers = _managers[:]\n\n        return [\n            *chain.from_iterable(\n                [*manager.plugins, *manager.searched_plugins.keys()]\n                for manager in _pre_managers\n            )\n        ]\n\n    def list_plugins(self) -> Set[str]:\n        # get all previous ready to load plugins\n        previous_plugins = self._previous_plugins()\n        searched_plugins: Dict[str, Path] = {}\n        third_party_plugins: Set[str] = set()\n\n        for plugin in self.plugins:\n            name = plugin.rsplit(\".\", 1)[-1] if \".\" in plugin else plugin\n            if name in third_party_plugins or name in previous_plugins:\n                raise RuntimeError(\n                    f\"Plugin already exists: {name}! Check your plugin name\"\n                )\n            third_party_plugins.add(plugin)\n\n        for module_info in pkgutil.iter_modules(self.search_path):\n            if module_info.name.startswith(\"_\"):\n                continue\n            if (\n                module_info.name in searched_plugins.keys()\n                or module_info.name in previous_plugins\n                or module_info.name in third_party_plugins\n            ):\n                raise RuntimeError(\n                    f\"Plugin already exists: {module_info.name}! Check your plugin name\"\n                )\n            module_spec = module_info.module_finder.find_spec(module_info.name, None)\n            if not module_spec:\n                continue\n            module_path = module_spec.origin\n            if not module_path:\n                continue\n            searched_plugins[module_info.name] = Path(module_path).resolve()\n\n        self.searched_plugins = searched_plugins\n\n        return third_party_plugins | set(self.searched_plugins.keys())\n\n    def load_plugin(self, name) -> Optional[Plugin]:\n        try:\n            if name in self.plugins:\n                module = importlib.import_module(name)\n            elif name not in self.searched_plugins:\n                raise RuntimeError(f\"Plugin not found: {name}! Check your plugin name\")\n            else:\n                module = importlib.import_module(\n                    self._path_to_module_name(self.searched_plugins[name])\n                )\n\n            logger.opt(colors=True).success(\n                f'Succeeded to import \"<y>{escape_tag(name)}</y>\"'\n            )\n            return getattr(module, \"__plugin__\", None)\n        except Exception as e:\n            logger.opt(colors=True, exception=e).error(\n                f'<r><bg #f8bbd0>Failed to import \"{escape_tag(name)}\"</bg #f8bbd0></r>'\n            )\n\n    def load_all_plugins(self) -> Set[Plugin]:\n        return set(\n            filter(None, (self.load_plugin(name) for name in self.list_plugins()))\n        )\n\n\nclass PluginFinder(MetaPathFinder):\n    def find_spec(\n        self,\n        fullname: str,\n        path: Optional[Sequence[Union[bytes, str]]],\n        target: Optional[ModuleType] = None,\n    ):\n        if _managers:\n            index = -1\n            module_spec = PathFinder.find_spec(fullname, path, target)\n            if not module_spec:\n                return\n            module_origin = module_spec.origin\n            if not module_origin:\n                return\n            module_path = Path(module_origin).resolve()\n\n            while -index <= len(_managers):\n                manager = _managers[index]\n\n                if (\n                    fullname in manager.plugins\n                    or module_path in manager.searched_plugins.values()\n                ):\n                    module_spec.loader = PluginLoader(manager, fullname, module_origin)\n                    return module_spec\n\n                index -= 1\n        return\n\n\nclass PluginLoader(SourceFileLoader):\n    def __init__(self, manager: PluginManager, fullname: str, path) -> None:\n        self.manager = manager\n        self.loaded = False\n        super().__init__(fullname, path)\n\n    def create_module(self, spec) -> Optional[ModuleType]:\n        if self.name in sys.modules:\n            self.loaded = True\n            return sys.modules[self.name]\n        # return None to use default module creation\n        return super().create_module(spec)\n\n    def exec_module(self, module: ModuleType) -> None:\n        if self.loaded:\n            return\n\n        plugin = _new_plugin(self.name, module, self.manager)\n        parent_plugin = _current_plugin.get()\n        if parent_plugin and _managers.index(parent_plugin.manager) < _managers.index(\n            self.manager\n        ):\n            plugin.parent_plugin = parent_plugin\n            parent_plugin.sub_plugins.add(plugin)\n\n        _plugin_token = _current_plugin.set(plugin)\n\n        setattr(module, \"__plugin__\", plugin)\n\n        # try:\n        #     super().exec_module(module)\n        # except Exception as e:\n        #     raise ImportError(\n        #         f\"Error when executing module {module_name} from {module.__file__}.\"\n        #     ) from e\n        super().exec_module(module)\n\n        _confirm_plugin(plugin)\n\n        _current_plugin.reset(_plugin_token)\n        return\n\n\nsys.meta_path.insert(0, PluginFinder())\n", "path": "nonebot/plugin/manager.py"}]}