🐛 fix run pre/post hook not in context (#1391)

This commit is contained in:
Ju4tCode 2022-11-15 10:50:52 +08:00 committed by GitHub
parent f1525c1ecd
commit a50990bef2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 45 deletions

View File

@ -1,8 +1,8 @@
from types import ModuleType from types import ModuleType
from contextvars import ContextVar from contextvars import ContextVar
from collections import defaultdict from collections import defaultdict
from contextlib import AsyncExitStack
from datetime import datetime, timedelta from datetime import datetime, timedelta
from contextlib import AsyncExitStack, contextmanager
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
@ -661,6 +661,18 @@ class Matcher(metaclass=MatcherMeta):
if REJECT_CACHE_TARGET in self.state: if REJECT_CACHE_TARGET in self.state:
self.state[REJECT_TARGET] = self.state[REJECT_CACHE_TARGET] self.state[REJECT_TARGET] = self.state[REJECT_CACHE_TARGET]
@contextmanager
def ensure_context(self, bot: Bot, event: Event):
b_t = current_bot.set(bot)
e_t = current_event.set(event)
m_t = current_matcher.set(self)
try:
yield
finally:
current_bot.reset(b_t)
current_event.reset(e_t)
current_matcher.reset(m_t)
async def simple_run( async def simple_run(
self, self,
bot: Bot, bot: Bot,
@ -673,35 +685,31 @@ class Matcher(metaclass=MatcherMeta):
f"{self} run with incoming args: " f"{self} run with incoming args: "
f"bot={bot}, event={event!r}, state={state!r}" f"bot={bot}, event={event!r}, state={state!r}"
) )
b_t = current_bot.set(bot)
e_t = current_event.set(event)
m_t = current_matcher.set(self)
try:
# Refresh preprocess state
self.state.update(state)
while self.handlers: with self.ensure_context(bot, event):
handler = self.handlers.pop(0) try:
current_handler.set(handler) # Refresh preprocess state
logger.debug(f"Running handler {handler}") self.state.update(state)
try:
await handler( while self.handlers:
matcher=self, handler = self.handlers.pop(0)
bot=bot, current_handler.set(handler)
event=event, logger.debug(f"Running handler {handler}")
state=self.state, try:
stack=stack, await handler(
dependency_cache=dependency_cache, matcher=self,
) bot=bot,
except SkippedException: event=event,
logger.debug(f"Handler {handler} skipped") state=self.state,
except StopPropagation: stack=stack,
self.block = True dependency_cache=dependency_cache,
finally: )
logger.info(f"{self} running complete") except SkippedException:
current_bot.reset(b_t) logger.debug(f"Handler {handler} skipped")
current_event.reset(e_t) except StopPropagation:
current_matcher.reset(m_t) self.block = True
finally:
logger.info(f"{self} running complete")
# 运行handlers # 运行handlers
async def run( async def run(

View File

@ -167,17 +167,19 @@ async def _run_matcher(
) )
for proc in _run_preprocessors for proc in _run_preprocessors
]: ]:
try: # ensure matcher function can be correctly called
await asyncio.gather(*coros) with matcher.ensure_context(bot, event):
except IgnoredException: try:
logger.opt(colors=True).info(f"{matcher} running is <b>cancelled</b>") await asyncio.gather(*coros)
return except IgnoredException:
except Exception as e: logger.opt(colors=True).info(f"{matcher} running is <b>cancelled</b>")
logger.opt(colors=True, exception=e).error( return
"<r><bg #f8bbd0>Error when running RunPreProcessors. Running cancelled!</bg #f8bbd0></r>" except Exception as e:
) logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running RunPreProcessors. Running cancelled!</bg #f8bbd0></r>"
)
return return
exception = None exception = None
@ -205,12 +207,14 @@ async def _run_matcher(
) )
for proc in _run_postprocessors for proc in _run_postprocessors
]: ]:
try: # ensure matcher function can be correctly called
await asyncio.gather(*coros) with matcher.ensure_context(bot, event):
except Exception as e: try:
logger.opt(colors=True, exception=e).error( await asyncio.gather(*coros)
"<r><bg #f8bbd0>Error when running RunPostProcessors</bg #f8bbd0></r>" except Exception as e:
) logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running RunPostProcessors</bg #f8bbd0></r>"
)
if matcher.block: if matcher.block:
raise StopPropagation raise StopPropagation