加入限流策略,一个群一分钟只能获取5张图来

This commit is contained in:
liuwei
2025-06-25 16:31:36 +08:00
parent e2d0e57bbe
commit 11661906c4
2 changed files with 54 additions and 5 deletions

View File

@@ -0,0 +1,46 @@
import time
import functools
from typing import Callable, Any, Dict, Tuple, Optional
from loguru import logger
# 本地缓存,主键为 (group_id, feature_key)
_rate_limit_cache: Dict[Tuple[str, str], list] = {}
def group_feature_rate_limit(max_per_minute: int = 3, feature_key: str = None):
"""
用于插件异步消息处理的限流装饰器,按 group_id 和 FEATURE_KEY 作为主键,每分钟最多允许 N 次。
Args:
max_per_minute: 每分钟最大允许次数
feature_key: 功能权限键名(可选,优先使用参数,其次用 self.FEATURE_KEY
用法:
@group_feature_rate_limit(max_per_minute=3, feature_key="DAILY_NEWS")
async def process_message(self, plugin_msg):
...
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def async_wrapper(self, message: Dict[str, Any], *args, **kwargs) -> Tuple[bool, str]:
group_id = message.get("roomid")
# 优先用参数,其次用 self.FEATURE_KEY
_feature_key = feature_key or getattr(self, "FEATURE_KEY", None)
if not group_id or not _feature_key:
# 缺少主键信息,不限流
return await func(self, message, *args, **kwargs)
now = time.time()
key = (str(group_id), str(_feature_key))
times = _rate_limit_cache.get(key, [])
# 只保留最近60秒内的记录
times = [t for t in times if now - t < 60]
if len(times) >= max_per_minute:
logger.info(
f"限流: group_id={group_id}, feature_key={_feature_key}, {len(times)}/{max_per_minute} 次/分钟")
return False, f"触发频率过高,请稍后再试(限{max_per_minute}次/分钟)"
times.append(now)
_rate_limit_cache[key] = times
return await func(self, message, *args, **kwargs)
return async_wrapper
return decorator