🐛 fix single_session bug

This commit is contained in:
AkiraXie
2022-01-20 02:05:57 +08:00
parent ce0e230887
commit 67f5b87492
2 changed files with 48 additions and 21 deletions

View File

@ -1,34 +1,33 @@
from typing import Dict
from typing import Generator, Dict
from nonebot.adapters import Event
from nonebot.message import (
IgnoredException,
run_preprocessor,
run_postprocessor,
event_preprocessor
)
from nonebot.params import Depends
_running_matcher: Dict[str, int] = {}
@run_preprocessor
async def preprocess(event: Event):
async def matcher_mutex(event: Event) -> Generator[bool, None, None]:
result = False
try:
session_id = event.get_session_id()
except Exception:
return
current_event_id = id(event)
event_id = _running_matcher.get(session_id, None)
if event_id and event_id != current_event_id:
yield result
else:
current_event_id = id(event)
event_id = _running_matcher.get(session_id, None)
if event_id :
result = event_id != current_event_id
else:
_running_matcher[session_id] = current_event_id
yield result
if result:
del _running_matcher[session_id]
@event_preprocessor
async def preprocess(mutex: bool = Depends(matcher_mutex)):
if mutex:
raise IgnoredException("Another matcher running")
_running_matcher[session_id] = current_event_id
@run_postprocessor
async def postprocess(event: Event):
try:
session_id = event.get_session_id()
except Exception:
return
if session_id in _running_matcher:
del _running_matcher[session_id]