change plugin load

This commit is contained in:
yanyongyu 2020-08-15 17:22:10 +08:00
parent 1dcc43161a
commit c4a5cfb513
5 changed files with 36 additions and 32 deletions

View File

@ -6,8 +6,8 @@ from functools import wraps
from datetime import datetime from datetime import datetime
from collections import defaultdict from collections import defaultdict
from nonebot.rule import Rule, user from nonebot.rule import SyncRule, user
from nonebot.typing import Bot, Event, Handler from nonebot.typing import Bot, Rule, Event, Handler
from nonebot.typing import Type, List, Dict, Optional, NoReturn from nonebot.typing import Type, List, Dict, Optional, NoReturn
from nonebot.exception import PausedException, RejectedException, FinishedException from nonebot.exception import PausedException, RejectedException, FinishedException
@ -18,7 +18,7 @@ class Matcher:
"""`Matcher`类 """`Matcher`类
""" """
rule: Rule = Rule() rule: Rule = SyncRule()
handlers: List[Handler] = [] handlers: List[Handler] = []
temp: bool = False temp: bool = False
expire_time: Optional[datetime] = None expire_time: Optional[datetime] = None
@ -38,7 +38,7 @@ class Matcher:
@classmethod @classmethod
def new(cls, def new(cls,
rule: Rule = Rule(), rule: Rule = SyncRule(),
handlers: list = [], handlers: list = [],
temp: bool = False, temp: bool = False,
priority: int = 1, priority: int = 1,
@ -66,7 +66,7 @@ class Matcher:
return NewMatcher return NewMatcher
@classmethod @classmethod
def check_rule(cls, bot: Bot, event: Event) -> bool: async def check_rule(cls, bot: Bot, event: Event) -> bool:
"""检查 Matcher 的 Rule 是否成立 """检查 Matcher 的 Rule 是否成立
Args: Args:
@ -75,7 +75,7 @@ class Matcher:
Returns: Returns:
bool: 条件成立与否 bool: 条件成立与否
""" """
return cls.rule(bot, event) return await cls.rule(bot, event)
# @classmethod # @classmethod
# def args_parser(cls, func: Callable[[Event, dict], None]): # def args_parser(cls, func: Callable[[Event, dict], None]):

View File

@ -40,7 +40,7 @@ async def handle_event(bot: Bot, event: Event):
# Check rule # Check rule
try: try:
if not Matcher.check_rule(bot, event): if not await Matcher.check_rule(bot, event):
index += 1 index += 1
continue continue
except Exception as e: except Exception as e:

View File

@ -1,14 +1,14 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import pkgutil
import re
import importlib import importlib
from importlib.util import module_from_spec
from nonebot.log import logger from nonebot.log import logger
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.rule import Rule, metaevent, message, notice, request from nonebot.rule import SyncRule, metaevent, message, notice, request
from nonebot.typing import Set, Dict, Type, Union, Optional, ModuleType, RuleChecker from nonebot.typing import Set, Dict, Type, Rule, Union, Optional, ModuleType, RuleChecker
plugins: Dict[str, "Plugin"] = {} plugins: Dict[str, "Plugin"] = {}
@ -25,7 +25,7 @@ class Plugin(object):
self.matchers = matchers self.matchers = matchers
def on_metaevent(rule: Union[Rule, RuleChecker] = Rule(), def on_metaevent(rule: Union[Rule, RuleChecker] = SyncRule(),
*, *,
handlers=[], handlers=[],
temp=False, temp=False,
@ -40,7 +40,7 @@ def on_metaevent(rule: Union[Rule, RuleChecker] = Rule(),
return matcher return matcher
def on_message(rule: Union[Rule, RuleChecker] = Rule(), def on_message(rule: Union[Rule, RuleChecker] = SyncRule(),
*, *,
handlers=[], handlers=[],
temp=False, temp=False,
@ -55,7 +55,7 @@ def on_message(rule: Union[Rule, RuleChecker] = Rule(),
return matcher return matcher
def on_notice(rule: Union[Rule, RuleChecker] = Rule(), def on_notice(rule: Union[Rule, RuleChecker] = SyncRule(),
*, *,
handlers=[], handlers=[],
temp=False, temp=False,
@ -70,7 +70,7 @@ def on_notice(rule: Union[Rule, RuleChecker] = Rule(),
return matcher return matcher
def on_request(rule: Union[Rule, RuleChecker] = Rule(), def on_request(rule: Union[Rule, RuleChecker] = SyncRule(),
*, *,
handlers=[], handlers=[],
temp=False, temp=False,
@ -117,26 +117,26 @@ def load_plugin(module_path: str) -> Optional[Plugin]:
return None return None
def load_plugins(plugin_dir: str) -> Set[Plugin]: def load_plugins(*plugin_dir: str) -> Set[Plugin]:
plugins = set() loaded_plugins = set()
for name in os.listdir(plugin_dir): for module_info in pkgutil.iter_modules(plugin_dir):
path = os.path.join(plugin_dir, name) _tmp_matchers.clear()
if os.path.isfile(path) and \ name = module_info.name
(name.startswith("_") or not name.endswith(".py")): if name.startswith("_"):
continue
if os.path.isdir(path) and \
(name.startswith("_") or not os.path.exists(
os.path.join(path, "__init__.py"))):
continue continue
m = re.match(r"([_A-Z0-9a-z]+)(.py)?", name) try:
if not m: spec = module_info.module_finder.find_spec(name)
continue module = module_from_spec(spec)
result = load_plugin(f"{plugin_dir.replace(os.sep, '.')}.{m.group(1)}") plugin = Plugin(name, module, _tmp_matchers.copy())
if result: plugins[name] = plugin
plugins.add(result) loaded_plugins.add(plugin)
return plugins logger.info(f"Succeeded to import \"{name}\"")
except Exception as e:
logger.error(f"Failed to import \"{name}\", error: {e}")
logger.exception(e)
return loaded_plugins
def get_loaded_plugins() -> Set[Plugin]: def get_loaded_plugins() -> Set[Plugin]:

View File

@ -0,0 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from . import matchers