zhenxun_bot/zhenxun/builtin_plugins/hooks/auth/auth_bot.py

56 lines
1.8 KiB
Python
Raw Normal View History

:sparkles: 引入缓存机制 (#1889) * 添加全局cache * ✨ 构建缓存,hook使用缓存 * :sparkles: 新增数据库Model方法监控 * :sparkles: 数据库添加semaphore锁 * :adhesive_bandage: 优化webapi返回数据 * :sparkles: 添加增量缓存与缓存过期 * :art: 优化检测代码结构 * :zap: 优化hook权限检测性能 * :bug: 添加新异常判断跳过权限检测 * :sparkles: 添加插件limit缓存 * :art: 代码格式优化 * :bug: 修复代码导入 * :bug: 修复刷新时检查 * :alien: Rename exception for missing database URL in initialization * :wheelchair: Update default database URL to SQLite in configuration * :wrench: Update tortoise-orm and aiocache dependencies restrictions; add optional redis and asyncpg support * :bug: 修复ban检测 * :bug: 修复所有插件关闭时缓存更新 * :bug: 尝试迁移至aiocache * :bug: 完善aiocache缓存 * :zap: 代码性能优化 * :bug: 移除获取封禁缓存时的日志记录 * :bug: 修复缓存类型声明,优化封禁用户处理逻辑 * :bug: 优化LevelUser权限更新逻辑及数据库迁移 * :sparkles: cache支持redis连接 * :rotating_light: auto fix by pre-commit hooks * :zap: :增强获取群组的安全性和准确性。同时,优化了缓存管理中的相关逻辑,确保缓存操作的一致性。 * ✨ feat(auth_limit): 将插件初始化逻辑的启动装饰器更改为优先级管理器 * 🔧 修复日志记录级别 * 🔧 更新数据库连接字符串 * 🔧 更新数据库连接字符串为内存数据库,并优化权限检查逻辑 * ✨ feat(cache): 增加缓存功能配置项,并新增数据访问层以支持缓存逻辑 * :recycle: 重构cache * ✨ feat(cache): 增强缓存管理,新增缓存字典和缓存列表功能,支持过期时间管理 * 🔧 修复Notebook类中的viewport高度设置,将其从1000调整为10 * ✨ 更新插件管理逻辑,替换缓存服务为CacheRoot并优化缓存失效处理 * ✨ 更新RegisterConfig类中的type字段 * ✨ 修复清理重复记录逻辑,确保检查记录的id属性有效性 * :zap: 超级无敌大优化,解决延迟与卡死问题 * ✨ 更新封禁功能,增加封禁时长参数和描述,优化插件信息返回结构 * ✨ 更新zhenxun_help.py中的viewport高度,将其从453调整为10,以优化页面显示效果 * ✨ 优化插件分类逻辑,增加插件ID排序,并更新插件信息返回结构 --------- Co-authored-by: BalconyJH <balconyjh@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2025-07-14 22:35:29 +08:00
import asyncio
import time
from zhenxun.models.bot_console import BotConsole
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.services.data_access import DataAccess
from zhenxun.services.db_context import DB_TIMEOUT_SECONDS
from zhenxun.services.log import logger
from zhenxun.utils.common_utils import CommonUtils
from .config import LOGGER_COMMAND, WARNING_THRESHOLD
from .exception import SkipPluginException
async def auth_bot(plugin: PluginInfo, bot_id: str):
"""bot层面的权限检查
参数:
plugin: PluginInfo
bot_id: bot id
异常:
SkipPluginException: 忽略插件
SkipPluginException: 忽略插件
"""
start_time = time.time()
try:
# 从数据库或缓存中获取 bot 信息
bot_dao = DataAccess(BotConsole)
try:
bot: BotConsole | None = await asyncio.wait_for(
bot_dao.safe_get_or_none(bot_id=bot_id), timeout=DB_TIMEOUT_SECONDS
)
except asyncio.TimeoutError:
logger.error(f"查询Bot信息超时: bot_id={bot_id}", LOGGER_COMMAND)
# 超时时不阻塞,继续执行
return
if not bot or not bot.status:
raise SkipPluginException("Bot不存在或休眠中阻断权限检测...")
if CommonUtils.format(plugin.module) in bot.block_plugins:
raise SkipPluginException(
f"Bot插件 {plugin.name}({plugin.module}) 权限检查结果为关闭..."
)
finally:
# 记录执行时间
elapsed = time.time() - start_time
if elapsed > WARNING_THRESHOLD: # 记录耗时超过500ms的检查
logger.warning(
f"auth_bot 耗时: {elapsed:.3f}s, "
f"bot_id={bot_id}, plugin={plugin.module}",
LOGGER_COMMAND,
)