加入用户级别限流注释器
This commit is contained in:
@@ -18,7 +18,7 @@ from base.plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from base.plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from utils.decorator.rate_limit_decorator import group_feature_rate_limit
|
||||
from utils.decorator.rate_limit_decorator import user_feature_rate_limit
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from wechat_ipad import WechatAPIClient
|
||||
from db.connection import DBConnectionManager
|
||||
@@ -459,7 +459,7 @@ class XiuxianPlugin(MessagePluginInterface):
|
||||
return False
|
||||
|
||||
@plugin_stats_decorator(plugin_name="群聊文字修仙")
|
||||
@group_feature_rate_limit(max_per_minute=6, feature_key=FEATURE_KEY)
|
||||
@user_feature_rate_limit(max_per_minute=6, feature_key=FEATURE_KEY)
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
content = str(message.get("content", "")).strip()
|
||||
sender = message.get("sender")
|
||||
|
||||
@@ -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