2022-01-22 15:26:22 +08:00
|
|
|
from typing import Dict, AsyncGenerator
|
2022-01-20 02:10:30 +08:00
|
|
|
|
2021-11-21 16:12:36 +08:00
|
|
|
from nonebot.adapters import Event
|
2022-01-20 02:05:57 +08:00
|
|
|
from nonebot.params import Depends
|
2022-01-20 02:10:30 +08:00
|
|
|
from nonebot.message import IgnoredException, event_preprocessor
|
2021-01-25 18:15:25 +08:00
|
|
|
|
2021-01-26 15:03:37 +08:00
|
|
|
_running_matcher: Dict[str, int] = {}
|
2021-01-25 18:15:25 +08:00
|
|
|
|
|
|
|
|
2022-01-22 15:26:22 +08:00
|
|
|
async def matcher_mutex(event: Event) -> AsyncGenerator[bool, None]:
|
2022-01-20 02:05:57 +08:00
|
|
|
result = False
|
2021-02-24 22:21:47 +08:00
|
|
|
try:
|
|
|
|
session_id = event.get_session_id()
|
2021-02-24 23:56:52 +08:00
|
|
|
except Exception:
|
2022-01-20 02:05:57 +08:00
|
|
|
yield result
|
|
|
|
else:
|
|
|
|
current_event_id = id(event)
|
2022-09-09 11:52:57 +08:00
|
|
|
if event_id := _running_matcher.get(session_id, None):
|
2022-01-20 02:05:57 +08:00
|
|
|
result = event_id != current_event_id
|
|
|
|
else:
|
|
|
|
_running_matcher[session_id] = current_event_id
|
|
|
|
yield result
|
2022-01-20 03:16:04 +08:00
|
|
|
if not result:
|
2022-01-20 02:05:57 +08:00
|
|
|
del _running_matcher[session_id]
|
2021-01-25 18:15:25 +08:00
|
|
|
|
2022-01-20 02:10:30 +08:00
|
|
|
|
2022-01-20 02:05:57 +08:00
|
|
|
@event_preprocessor
|
|
|
|
async def preprocess(mutex: bool = Depends(matcher_mutex)):
|
|
|
|
if mutex:
|
|
|
|
raise IgnoredException("Another matcher running")
|