加入用户级别限流注释器
This commit is contained in:
@@ -5,6 +5,7 @@ from loguru import logger
|
||||
|
||||
# 本地缓存,主键为 (group_id, feature_key)
|
||||
_rate_limit_cache: Dict[Tuple[str, str], list] = {}
|
||||
_user_rate_limit_cache: Dict[Tuple[str, str], list] = {}
|
||||
|
||||
|
||||
def group_feature_rate_limit(max_per_minute: int = 3, feature_key: str = None):
|
||||
@@ -44,3 +45,29 @@ def group_feature_rate_limit(max_per_minute: int = 3, feature_key: str = None):
|
||||
return async_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def user_feature_rate_limit(max_per_minute: int = 6, feature_key: str = None):
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(self, message: Dict[str, Any], *args, **kwargs) -> Tuple[bool, str]:
|
||||
user_id = message.get("sender")
|
||||
_feature_key = feature_key or getattr(self, "FEATURE_KEY", None)
|
||||
if not user_id or not _feature_key:
|
||||
return await func(self, message, *args, **kwargs)
|
||||
now = time.time()
|
||||
key = (str(user_id), str(_feature_key))
|
||||
times = _user_rate_limit_cache.get(key, [])
|
||||
times = [t for t in times if now - t < 60]
|
||||
if len(times) >= max_per_minute:
|
||||
logger.info(
|
||||
f"限流: user_id={user_id}, feature_key={_feature_key}, {len(times)}/{max_per_minute} 次/分钟")
|
||||
return False, f"触发频率过高,请稍后再试(限{max_per_minute}次/分钟)"
|
||||
times.append(now)
|
||||
_user_rate_limit_cache[key] = times
|
||||
return await func(self, message, *args, **kwargs)
|
||||
|
||||
return async_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
Reference in New Issue
Block a user