Skip to content

Commit

Permalink
✨ 添加事件锁定依赖
Browse files Browse the repository at this point in the history
  • Loading branch information
A-kirami committed Aug 17, 2023
1 parent 8fbf524 commit fd97f88
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion kirami/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

from kirami.database import Group, User
from kirami.matcher import Matcher
from kirami.service.limiter import Cooldown, LimitScope, Quota, get_scope_key
from kirami.service.limiter import Cooldown, LimitScope, Lock, Quota, get_scope_key
from kirami.service.service import Ability
from kirami.service.subject import Subjects as Subjects
from kirami.typing import (
Expand Down Expand Up @@ -462,3 +462,43 @@ async def check_quota(
await quota.consume(key)

return check_quota


def useLock(
max_count: int = 1,
*,
prompt: str | None = None,
scope: LimitScope = LimitScope.LOCAL,
**kwargs: Any,
) -> None:
"""使用事件锁定限制"""

@depends
async def check_lock(matcher: Matcher, event: Event) -> AsyncGenerator[Lock, None]:
name = f"depends:{Ability.got(matcher).id}"
if not (lock := Lock.get(name)):
lock = Lock(
matcher=matcher.__class__,
scope=scope,
prompt=prompt,
max_count=max_count,
)
Lock.set(name, lock)

if not (key := get_scope_key(event, scope)):
return

if not lock.check(key):
await matcher.finish(
prompt.format(**lock.get_info(key)) if prompt else None,
**kwargs,
)

lock.claim(key)

try:
yield lock
finally:
lock.unclaim(key)

return check_lock

0 comments on commit fd97f88

Please sign in to comment.