mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-09-29 08:39:59 +08:00
* 添加测试插件 * ✨ feat(auth): 添加缓存机制以优化用户和插件数据查询性能 * 🗑️ chore(help): 删除笨蛋检测插件代码 * ✨ feat(bot): 添加对扩展插件的加载支持 * ✨ feat(auth): 优化权限检查和缓存机制,增加用户和插件数据的并行查询 * ✨ feat(cache): 引入运行时缓存机制,优化用户和插件的ban记录管理 * ✨ feat(auth): 更新is_ban函数文档,添加参数和返回值说明 * ``` feat(auth): 使用内存缓存优化权限验证性能 - 移除数据库查询超时控制,改用 LevelUserMemoryCache、BotMemoryCache 和 PluginLimitMemoryCache 进行缓存查询 - 优化 auth_admin、auth_bot、auth_limit 权限验证逻辑,提升响应速度 - 添加 background 参数支持异步发送权限不足提示消息 - 移除 asyncio 依赖,简化代码结构 fix(auth): 修复限制通知频率控制问题 - 实现限制通知冷却机制,避免重复发送相同限制消息 - 添加 AUTH_LIMIT_NOTICE_CD 配置项,默认值为 2 秒 - 使用 FreqLimiter 控制限制通知发送频率 refactor(models): 增强模型数据变更时的缓存同步 - 在 BotConsole、GroupConsole、LevelUser、PluginLimit 模型的 create、update_or_create、save、delete 方法中自动更新对应缓存 - 确保数据库和内存缓存数据一致性 docs(ban_console): 修正文档注释并优化日志信息 - 修正 BanConsole 类中方法的文档字符串,使用标准参数和返回值格式 - 优化调试日志信息,使描述更加清晰准确 ``` * ✨ feat(auth): 更新Limit类以支持PluginLimitSnapshot,优化限制信息处理 * ✨ feat(bot_manage): 优化Bot控制台初始化逻辑,处理IntegrityError异常 * ✨ feat(mmm1): 新增消息推送功能,支持私聊和群聊事件处理 * ✨ feat(group_member_update): 优化群组成员更新逻辑,增加活动跟踪和消息记录功能 * ✨ feat(mmm1): 删除冗余的消息推送功能代码 * ✨ feat(auth): 优化权限检查逻辑,增加模块阻止功能和缓存处理 * ✨ feat(auth): 优化权限检查逻辑,增加快速ban检测和前置检查功能 * ✨ feat(chat_history): 增强消息处理规则,添加时间间隔限制以防止重复消息 ✨ feat(data_source): 引入异步获取群成员信息的功能,优化用户信息更新逻辑 * ✨ feat(send_queue): 添加异步发送队列以优化API调用和速率限制 * ✨ feat(auth): 添加缓存就绪检查以优化权限处理逻辑 * ✨ feat(plugins): 移除不必要的插件加载以简化插件管理 * ✨ feat(group_console): 优化群组获取逻辑,添加缓存检查以提升性能 ✨ 只接收缓存完成之后时间的消息 * ✨ feat(auth): 添加异步任务管理和超载检测,优化权限处理逻辑 ✨ feat(chat_history): 修改规则函数为异步,提升消息处理效率 ✨ feat(group_handle): 增加安全获取群组信息的异步方法,添加超时处理 ✨ feat(record_request): 引入安全获取群组信息的异步方法,优化群邀请处理 ✨ feat(ban_memory_cache): 增强禁言内存缓存,添加负缓存机制 ✨ feat(message_load): 新增消息负载检测功能,优化任务调度 ✨ feat(scheduler): 在调度器中集成消息压力检测,优化任务执行 ✨ feat(send_queue): 引入异步任务管理,优化发送队列处理 * ✨ feat(auth): 添加对 LevelUserSnapshot 和 BotSnapshot 的支持,优化权限检查逻辑 ✨ 格式化 * ✨ feat(db_context): 增强 get_or_create 方法,处理并发创建冲突并回退查询已存在记录 * ✨ feat(bot_manage): 增强 init_bot_console 方法,处理并发创建冲突并回退查询已存在的 bot 数据 * 🚨 auto fix by pre-commit hooks * ✨ feat(runtime_cache): 优化消息处理逻辑,支持 bytes 和 bytearray 类型的联合判断 * ✨ style(runtime_cache): 格式化代码,优化多行表达式的可读性 * 🚨 auto fix by pre-commit hooks * ✨ refactor: 优化类型注解,改进群组成员更新逻辑和平台处理 ✨ 格式化 * 🚨 auto fix by pre-commit hooks * ✨ refactor: 优化代码格式,增强可读性并修复类型注解 * 🚨 auto fix by pre-commit hooks * ✨ refactor: 更新文档注释,增强is_ban函数的可读性 * ✨ refactor: 优化代码结构,移除冗余函数,增强可读性并改进任务调度逻辑 * ✨ refactor: 调整定时任务时间,优化渲染服务的初始化逻辑,增强代码可读性 --------- Co-authored-by: ATTomatoo <1126160939@qq.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
303 lines
8.3 KiB
Python
303 lines
8.3 KiB
Python
import asyncio
|
||
import time
|
||
|
||
from nonebot.adapters import Bot
|
||
from nonebot.matcher import Matcher
|
||
from nonebot_plugin_alconna import At
|
||
from nonebot_plugin_uninfo import Uninfo
|
||
|
||
from zhenxun.configs.config import Config
|
||
from zhenxun.models.ban_console import BanConsole
|
||
from zhenxun.models.plugin_info import PluginInfo
|
||
from zhenxun.services.cache.cache_containers import CacheDict
|
||
from zhenxun.services.cache.runtime_cache import BanMemoryCache
|
||
from zhenxun.services.db_context import DB_TIMEOUT_SECONDS
|
||
from zhenxun.services.log import logger
|
||
from zhenxun.utils.enum import PluginType
|
||
from zhenxun.utils.utils import EntityIDs, get_entity_ids
|
||
|
||
from .config import LOGGER_COMMAND, WARNING_THRESHOLD
|
||
from .exception import SkipPluginException
|
||
from .utils import freq, send_message
|
||
|
||
Config.add_plugin_config(
|
||
"hook",
|
||
"BAN_RESULT",
|
||
"才不会给你发消息.",
|
||
help="对被ban用户发送的消息",
|
||
)
|
||
Config.add_plugin_config(
|
||
"hook",
|
||
"BAN_CACHE_TTL",
|
||
2,
|
||
help="ban cache ttl seconds",
|
||
)
|
||
Config.add_plugin_config(
|
||
"hook",
|
||
"BAN_CACHE_TTL_POSITIVE",
|
||
30,
|
||
help="ban cache ttl seconds for banned users",
|
||
)
|
||
Config.add_plugin_config(
|
||
"hook",
|
||
"BAN_CACHE_TTL_NEGATIVE",
|
||
5,
|
||
help="ban cache ttl seconds for non-banned users",
|
||
)
|
||
|
||
|
||
def _coerce_ttl(value, default):
|
||
try:
|
||
value_int = int(value)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
return value_int if value_int >= 0 else default
|
||
|
||
|
||
_ban_cache_ttl_value = Config.get_config("hook", "BAN_CACHE_TTL", 2)
|
||
try:
|
||
_ban_cache_ttl_value = int(_ban_cache_ttl_value)
|
||
except (TypeError, ValueError):
|
||
_ban_cache_ttl_value = 2
|
||
|
||
_ban_cache_ttl_positive = _coerce_ttl(
|
||
Config.get_config("hook", "BAN_CACHE_TTL_POSITIVE", _ban_cache_ttl_value),
|
||
_ban_cache_ttl_value,
|
||
)
|
||
_ban_cache_ttl_negative = _coerce_ttl(
|
||
Config.get_config("hook", "BAN_CACHE_TTL_NEGATIVE", _ban_cache_ttl_value),
|
||
_ban_cache_ttl_value,
|
||
)
|
||
|
||
BAN_CACHE = (
|
||
CacheDict("AUTH_BAN_CACHE", expire=0)
|
||
if max(_ban_cache_ttl_positive, _ban_cache_ttl_negative) > 0
|
||
else None
|
||
)
|
||
|
||
|
||
def _ban_cache_key(user_id: str | None, group_id: str | None) -> str:
|
||
return f"{user_id or ''}:{group_id or ''}"
|
||
|
||
|
||
def _ban_cache_get(key: str) -> int | None:
|
||
if not BAN_CACHE:
|
||
return None
|
||
try:
|
||
return BAN_CACHE[key]
|
||
except KeyError:
|
||
return None
|
||
|
||
|
||
def _ban_cache_set(key: str, value: int) -> None:
|
||
if not BAN_CACHE:
|
||
return
|
||
ttl = _ban_cache_ttl_positive if value else _ban_cache_ttl_negative
|
||
if ttl <= 0:
|
||
return
|
||
BAN_CACHE.set(key, value, expire=ttl)
|
||
|
||
|
||
async def calculate_ban_time(ban_record: BanConsole | None) -> int:
|
||
"""根据ban记录计算剩余ban时间
|
||
|
||
参数:
|
||
ban_record: BanConsole记录
|
||
|
||
返回:
|
||
int: ban剩余时长,-1时为永久ban,0表示未被ban
|
||
"""
|
||
if not ban_record:
|
||
return 0
|
||
|
||
if ban_record.duration == -1:
|
||
return -1
|
||
|
||
_time = time.time() - (ban_record.ban_time + ban_record.duration)
|
||
if _time < 0:
|
||
return int(abs(_time))
|
||
await ban_record.delete()
|
||
return 0
|
||
|
||
|
||
async def is_ban(user_id: str | None, group_id: str | None) -> int:
|
||
"""检查用户或群组是否被ban
|
||
|
||
参数:
|
||
user_id: 用户ID
|
||
group_id: 群组ID
|
||
|
||
返回:
|
||
int: ban剩余时长,-1时为永久ban,0表示未被ban
|
||
"""
|
||
if not user_id and not group_id:
|
||
return 0
|
||
if not BanMemoryCache.is_loaded():
|
||
return 0
|
||
return BanMemoryCache.remaining_time(user_id, group_id)
|
||
|
||
|
||
def check_plugin_type(matcher: Matcher) -> bool:
|
||
"""判断插件类型是否是隐藏插件
|
||
|
||
参数:
|
||
matcher: Matcher
|
||
|
||
返回:
|
||
bool: 是否为隐藏插件
|
||
"""
|
||
if plugin := matcher.plugin:
|
||
if metadata := plugin.metadata:
|
||
extra = metadata.extra
|
||
if extra.get("plugin_type") in [PluginType.HIDDEN]:
|
||
return False
|
||
return True
|
||
|
||
|
||
def format_time(time_val: float) -> str:
|
||
"""格式化时间
|
||
|
||
参数:
|
||
time_val: ban时长
|
||
|
||
返回:
|
||
str: 格式化时间文本
|
||
"""
|
||
if time_val == -1:
|
||
return "∞"
|
||
time_val = abs(int(time_val))
|
||
if time_val < 60:
|
||
time_str = f"{time_val!s} 秒"
|
||
else:
|
||
minute = int(time_val / 60)
|
||
if minute > 60:
|
||
hours = minute // 60
|
||
minute %= 60
|
||
time_str = f"{hours} 小时 {minute}分钟"
|
||
else:
|
||
time_str = f"{minute} 分钟"
|
||
return time_str
|
||
|
||
|
||
async def group_handle(group_id: str) -> None:
|
||
"""群组ban检查
|
||
|
||
参数:
|
||
group_id: 群组id
|
||
|
||
异常:
|
||
SkipPluginException: 群组处于黑名单
|
||
"""
|
||
start_time = time.time()
|
||
try:
|
||
if await is_ban(None, group_id):
|
||
raise SkipPluginException("群组处于黑名单中...")
|
||
finally:
|
||
# 记录执行时间
|
||
elapsed = time.time() - start_time
|
||
if elapsed > WARNING_THRESHOLD: # 记录耗时超过500ms的检查
|
||
logger.warning(
|
||
f"group_handle 耗时: {elapsed:.3f}s",
|
||
LOGGER_COMMAND,
|
||
group_id=group_id,
|
||
)
|
||
|
||
|
||
async def user_handle(plugin: PluginInfo, entity: EntityIDs, session: Uninfo) -> None:
|
||
"""用户ban检查
|
||
|
||
参数:
|
||
module: 插件模块名
|
||
entity: 实体ID信息
|
||
session: Uninfo
|
||
|
||
异常:
|
||
SkipPluginException: 用户处于黑名单
|
||
"""
|
||
start_time = time.time()
|
||
try:
|
||
ban_result = Config.get_config("hook", "BAN_RESULT")
|
||
time_val = await is_ban(entity.user_id, entity.group_id)
|
||
if not time_val:
|
||
return
|
||
time_str = format_time(time_val)
|
||
|
||
if (
|
||
plugin
|
||
and time_val != -1
|
||
and ban_result
|
||
and freq.is_send_limit_message(plugin, entity.user_id, False)
|
||
):
|
||
try:
|
||
await asyncio.wait_for(
|
||
send_message(
|
||
session,
|
||
[
|
||
At(flag="user", target=entity.user_id),
|
||
f"{ban_result}\n在..在 {time_str} 后才会理你喔",
|
||
],
|
||
entity.user_id,
|
||
),
|
||
timeout=DB_TIMEOUT_SECONDS,
|
||
)
|
||
except asyncio.TimeoutError:
|
||
logger.error(f"发送消息超时: {entity.user_id}", LOGGER_COMMAND)
|
||
raise SkipPluginException("用户处于黑名单中...")
|
||
finally:
|
||
# 记录执行时间
|
||
elapsed = time.time() - start_time
|
||
if elapsed > WARNING_THRESHOLD: # 记录耗时超过500ms的检查
|
||
logger.warning(
|
||
f"user_handle 耗时: {elapsed:.3f}s",
|
||
LOGGER_COMMAND,
|
||
session=session,
|
||
)
|
||
|
||
|
||
async def auth_ban(
|
||
matcher: Matcher, bot: Bot, session: Uninfo, plugin: PluginInfo
|
||
) -> None:
|
||
"""权限检查 - ban 检查
|
||
|
||
参数:
|
||
matcher: Matcher
|
||
bot: Bot
|
||
session: Uninfo
|
||
"""
|
||
start_time = time.time()
|
||
try:
|
||
if not check_plugin_type(matcher):
|
||
return
|
||
if not matcher.plugin_name:
|
||
return
|
||
entity = get_entity_ids(session)
|
||
if entity.user_id in bot.config.superusers:
|
||
return
|
||
if entity.group_id:
|
||
try:
|
||
await asyncio.wait_for(
|
||
group_handle(entity.group_id), timeout=DB_TIMEOUT_SECONDS
|
||
)
|
||
except asyncio.TimeoutError:
|
||
logger.error(f"群组ban检查超时: {entity.group_id}", LOGGER_COMMAND)
|
||
# 超时时不阻塞,继续执行
|
||
|
||
if entity.user_id:
|
||
try:
|
||
await asyncio.wait_for(
|
||
user_handle(plugin, entity, session),
|
||
timeout=DB_TIMEOUT_SECONDS,
|
||
)
|
||
except asyncio.TimeoutError:
|
||
logger.error(f"用户ban检查超时: {entity.user_id}", LOGGER_COMMAND)
|
||
# 超时时不阻塞,继续执行
|
||
finally:
|
||
# 记录总执行时间
|
||
elapsed = time.time() - start_time
|
||
if elapsed > WARNING_THRESHOLD: # 记录耗时超过500ms的检查
|
||
logger.warning(
|
||
f"auth_ban 总耗时: {elapsed:.3f}s, plugin={matcher.plugin_name}",
|
||
LOGGER_COMMAND,
|
||
session=session,
|
||
)
|