mirror of
https://github.com/nonebot/nonebot2.git
synced 2024-11-28 03:46:54 +08:00
⚗️ new stop propagation method
This commit is contained in:
parent
41663e1b08
commit
2ae76ff78b
@ -16,7 +16,7 @@ from nonebot.rule import Rule
|
|||||||
from nonebot.log import logger
|
from nonebot.log import logger
|
||||||
from nonebot.permission import Permission, USER
|
from nonebot.permission import Permission, USER
|
||||||
from nonebot.typing import T_State, T_StateFactory, T_Handler, T_ArgsParser
|
from nonebot.typing import T_State, T_StateFactory, T_Handler, T_ArgsParser
|
||||||
from nonebot.exception import PausedException, RejectedException, FinishedException
|
from nonebot.exception import PausedException, RejectedException, FinishedException, StopPropagation
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from nonebot.adapters import Bot, Event, Message, MessageSegment
|
from nonebot.adapters import Bot, Event, Message, MessageSegment
|
||||||
@ -248,12 +248,14 @@ class Matcher(metaclass=MatcherMeta):
|
|||||||
bot = signature.parameters.get("bot")
|
bot = signature.parameters.get("bot")
|
||||||
event = signature.parameters.get("event")
|
event = signature.parameters.get("event")
|
||||||
state = signature.parameters.get("state")
|
state = signature.parameters.get("state")
|
||||||
|
matcher = signature.parameters.get("matcher")
|
||||||
if not bot:
|
if not bot:
|
||||||
raise ValueError("Handler missing parameter 'bot'")
|
raise ValueError("Handler missing parameter 'bot'")
|
||||||
handler.__params__ = {
|
handler.__params__ = {
|
||||||
"bot": bot.annotation,
|
"bot": bot.annotation,
|
||||||
"event": event.annotation if event else None,
|
"event": event.annotation if event else None,
|
||||||
"state": T_State if state else None
|
"state": T_State if state else None,
|
||||||
|
"matcher": matcher.annotation if matcher else None
|
||||||
}
|
}
|
||||||
return handler
|
return handler
|
||||||
|
|
||||||
@ -357,9 +359,10 @@ class Matcher(metaclass=MatcherMeta):
|
|||||||
parser = cls.handlers.pop()
|
parser = cls.handlers.pop()
|
||||||
|
|
||||||
@wraps(func)
|
@wraps(func)
|
||||||
async def wrapper(bot: "Bot", event: "Event", state: T_State):
|
async def wrapper(bot: "Bot", event: "Event", state: T_State,
|
||||||
await cls.run_handler(parser, bot, event, state)
|
matcher: Matcher):
|
||||||
await cls.run_handler(func, bot, event, state)
|
await matcher.run_handler(parser, bot, event, state)
|
||||||
|
await matcher.run_handler(func, bot, event, state)
|
||||||
if "_current_key" in state:
|
if "_current_key" in state:
|
||||||
del state["_current_key"]
|
del state["_current_key"]
|
||||||
|
|
||||||
@ -449,11 +452,13 @@ class Matcher(metaclass=MatcherMeta):
|
|||||||
await bot.send(event=event, message=prompt, **kwargs)
|
await bot.send(event=event, message=prompt, **kwargs)
|
||||||
raise RejectedException
|
raise RejectedException
|
||||||
|
|
||||||
@classmethod
|
def stop_propagation(self):
|
||||||
async def run_handler(cls, handler: T_Handler, bot: "Bot", event: "Event",
|
self.block = True
|
||||||
|
|
||||||
|
async def run_handler(self, handler: T_Handler, bot: "Bot", event: "Event",
|
||||||
state: T_State):
|
state: T_State):
|
||||||
if not hasattr(handler, "__params__"):
|
if not hasattr(handler, "__params__"):
|
||||||
cls.process_handler(handler)
|
self.process_handler(handler)
|
||||||
params = getattr(handler, "__params__")
|
params = getattr(handler, "__params__")
|
||||||
BotType = ((params["bot"] is not inspect.Parameter.empty) and
|
BotType = ((params["bot"] is not inspect.Parameter.empty) and
|
||||||
inspect.isclass(params["bot"]) and params["bot"])
|
inspect.isclass(params["bot"]) and params["bot"])
|
||||||
@ -462,7 +467,7 @@ class Matcher(metaclass=MatcherMeta):
|
|||||||
if (BotType and not isinstance(bot, BotType)) or (
|
if (BotType and not isinstance(bot, BotType)) or (
|
||||||
EventType and not isinstance(event, EventType)):
|
EventType and not isinstance(event, EventType)):
|
||||||
return
|
return
|
||||||
args = {"bot": bot, "event": event, "state": state}
|
args = {"bot": bot, "event": event, "state": state, "matcher": self}
|
||||||
await handler(
|
await handler(
|
||||||
**{k: v for k, v in args.items() if params[k] is not None})
|
**{k: v for k, v in args.items() if params[k] is not None})
|
||||||
|
|
||||||
@ -509,6 +514,8 @@ class Matcher(metaclass=MatcherMeta):
|
|||||||
expire_time=datetime.now() + bot.config.session_expire_timeout)
|
expire_time=datetime.now() + bot.config.session_expire_timeout)
|
||||||
except FinishedException:
|
except FinishedException:
|
||||||
pass
|
pass
|
||||||
|
except StopPropagation:
|
||||||
|
self.block = True
|
||||||
finally:
|
finally:
|
||||||
logger.info(f"Matcher {self} running complete")
|
logger.info(f"Matcher {self} running complete")
|
||||||
current_bot.reset(b_t)
|
current_bot.reset(b_t)
|
||||||
|
@ -164,8 +164,6 @@ async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event",
|
|||||||
try:
|
try:
|
||||||
logger.debug(f"Running matcher {matcher}")
|
logger.debug(f"Running matcher {matcher}")
|
||||||
await matcher.run(bot, event, state)
|
await matcher.run(bot, event, state)
|
||||||
except StopPropagation as e:
|
|
||||||
exception = e
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.opt(colors=True, exception=e).error(
|
logger.opt(colors=True, exception=e).error(
|
||||||
f"<r><bg #f8bbd0>Running matcher {matcher} failed.</bg #f8bbd0></r>"
|
f"<r><bg #f8bbd0>Running matcher {matcher} failed.</bg #f8bbd0></r>"
|
||||||
@ -183,7 +181,7 @@ async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event",
|
|||||||
"<r><bg #f8bbd0>Error when running RunPostProcessors</bg #f8bbd0></r>"
|
"<r><bg #f8bbd0>Error when running RunPostProcessors</bg #f8bbd0></r>"
|
||||||
)
|
)
|
||||||
|
|
||||||
if matcher.block or isinstance(exception, StopPropagation):
|
if matcher.block:
|
||||||
raise StopPropagation
|
raise StopPropagation
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -107,7 +107,9 @@ T_PermissionChecker = Callable[["Bot", "Event"], Union[bool, Awaitable[bool]]]
|
|||||||
RuleChecker 即判断是否响应消息的处理函数。
|
RuleChecker 即判断是否响应消息的处理函数。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
T_Handler = Union[Callable[[Any, Any, Any], Union[Awaitable[None],
|
T_Handler = Union[Callable[[Any, Any, Any, Any], Union[Awaitable[None],
|
||||||
|
Awaitable[NoReturn]]],
|
||||||
|
Callable[[Any, Any, Any], Union[Awaitable[None],
|
||||||
Awaitable[NoReturn]]],
|
Awaitable[NoReturn]]],
|
||||||
Callable[[Any, Any], Union[Awaitable[None],
|
Callable[[Any, Any], Union[Awaitable[None],
|
||||||
Awaitable[NoReturn]]],
|
Awaitable[NoReturn]]],
|
||||||
|
Loading…
Reference in New Issue
Block a user