🐛 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,9 +685,8 @@ 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) with self.ensure_context(bot, event):
m_t = current_matcher.set(self)
try: try:
# Refresh preprocess state # Refresh preprocess state
self.state.update(state) self.state.update(state)
@ -699,9 +710,6 @@ class Matcher(metaclass=MatcherMeta):
self.block = True self.block = True
finally: finally:
logger.info(f"{self} running complete") logger.info(f"{self} running complete")
current_bot.reset(b_t)
current_event.reset(e_t)
current_matcher.reset(m_t)
# 运行handlers # 运行handlers
async def run( async def run(

View File

@ -167,6 +167,8 @@ async def _run_matcher(
) )
for proc in _run_preprocessors for proc in _run_preprocessors
]: ]:
# ensure matcher function can be correctly called
with matcher.ensure_context(bot, event):
try: try:
await asyncio.gather(*coros) await asyncio.gather(*coros)
except IgnoredException: except IgnoredException:
@ -205,6 +207,8 @@ async def _run_matcher(
) )
for proc in _run_postprocessors for proc in _run_postprocessors
]: ]:
# ensure matcher function can be correctly called
with matcher.ensure_context(bot, event):
try: try:
await asyncio.gather(*coros) await asyncio.gather(*coros)
except Exception as e: except Exception as e: