nonebot2/nonebot/plugins/single_session.py

42 lines
1.2 KiB
Python
Raw Permalink Normal View History

from collections.abc import AsyncGenerator
from nonebot.adapters import Event
2022-01-20 02:05:57 +08:00
from nonebot.params import Depends
from nonebot.plugin import PluginMetadata
from nonebot.message import IgnoredException, event_preprocessor
2021-01-25 18:15:25 +08:00
__plugin_meta__ = PluginMetadata(
name="唯一会话",
description="限制同一会话内同时只能运行一个响应器",
usage="加载插件后自动生效",
type="application",
homepage="https://github.com/nonebot/nonebot2/blob/master/nonebot/plugins/single_session.py",
config=None,
supported_adapters=None,
)
_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)
if event_id := _running_matcher.get(session_id):
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:05:57 +08:00
@event_preprocessor
async def preprocess(mutex: bool = Depends(matcher_mutex)):
if mutex:
raise IgnoredException("Another matcher running")