mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-09-28 16:20:56 +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>
220 lines
6.8 KiB
Python
220 lines
6.8 KiB
Python
import asyncio
|
|
from typing import ClassVar
|
|
|
|
from tortoise import fields
|
|
from tortoise.exceptions import IntegrityError
|
|
|
|
from zhenxun.models.goods_info import GoodsInfo
|
|
from zhenxun.services.db_context import Model
|
|
from zhenxun.utils.enum import CacheType, GoldHandle
|
|
from zhenxun.utils.exception import GoodsNotFound, InsufficientGold
|
|
|
|
from .user_gold_log import UserGoldLog
|
|
|
|
|
|
class UserConsole(Model):
|
|
id = fields.IntField(pk=True, generated=True, auto_increment=True)
|
|
"""自增id"""
|
|
user_id = fields.CharField(255, unique=True, description="用户id")
|
|
"""用户id"""
|
|
uid = fields.IntField(description="UID", unique=True)
|
|
"""UID"""
|
|
gold = fields.IntField(default=100, description="金币数量")
|
|
"""金币数量"""
|
|
sign = fields.ReverseRelation["SignUser"] # type: ignore
|
|
"""好感度"""
|
|
props: dict[str, int] = fields.JSONField(default={}) # type: ignore
|
|
"""道具"""
|
|
platform = fields.CharField(255, null=True, description="平台")
|
|
"""平台"""
|
|
create_time = fields.DatetimeField(auto_now_add=True, description="创建时间")
|
|
"""创建时间"""
|
|
|
|
class Meta: # pyright: ignore [reportIncompatibleVariableOverride]
|
|
table = "user_console"
|
|
table_description = "用户数据表"
|
|
indexes = [("user_id",), ("uid",)] # noqa: RUF012
|
|
|
|
cache_type = CacheType.USERS
|
|
"""缓存类型"""
|
|
cache_key_field = "user_id"
|
|
"""缓存键字段"""
|
|
|
|
_uid_counter: ClassVar[int | None] = None
|
|
_uid_lock: ClassVar[asyncio.Lock] = asyncio.Lock()
|
|
|
|
@classmethod
|
|
async def get_or_create_user(
|
|
cls, user_id: str, platform: str | None = None
|
|
) -> tuple["UserConsole", bool]:
|
|
for attempt in range(2):
|
|
try:
|
|
return await cls.get_or_create(
|
|
user_id=user_id,
|
|
defaults={"platform": platform, "uid": await cls.get_new_uid()},
|
|
)
|
|
except IntegrityError:
|
|
async with cls._uid_lock:
|
|
cls._uid_counter = None
|
|
if attempt >= 1:
|
|
raise
|
|
return await cls.get_or_create(
|
|
user_id=user_id,
|
|
defaults={"platform": platform, "uid": await cls.get_new_uid()},
|
|
)
|
|
|
|
@classmethod
|
|
async def get_user(cls, user_id: str, platform: str | None = None) -> "UserConsole":
|
|
"""获取用户
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
platform: 平台.
|
|
|
|
返回:
|
|
UserConsole: UserConsole
|
|
"""
|
|
user, _ = await cls.get_or_create_user(user_id=user_id, platform=platform)
|
|
return user
|
|
|
|
@classmethod
|
|
async def get_new_uid(cls) -> int:
|
|
"""获取最新uid
|
|
|
|
返回:
|
|
int: 最新uid
|
|
"""
|
|
async with cls._uid_lock:
|
|
if cls._uid_counter is None:
|
|
user = await cls.annotate().order_by("-uid").first()
|
|
cls._uid_counter = user.uid if user else 0
|
|
cls._uid_counter += 1
|
|
return cls._uid_counter
|
|
|
|
@classmethod
|
|
async def add_gold(
|
|
cls, user_id: str, gold: int, source: str, platform: str | None = None
|
|
):
|
|
"""添加金币
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
gold: 金币
|
|
source: 来源
|
|
platform: 平台.
|
|
"""
|
|
user, _ = await cls.get_or_create_user(user_id=user_id, platform=platform)
|
|
user.gold += gold
|
|
await user.save(update_fields=["gold"])
|
|
await UserGoldLog.create(
|
|
user_id=user_id, gold=gold, handle=GoldHandle.GET, source=source
|
|
)
|
|
|
|
@classmethod
|
|
async def reduce_gold(
|
|
cls,
|
|
user_id: str,
|
|
gold: int,
|
|
handle: GoldHandle,
|
|
plugin_module: str,
|
|
platform: str | None = None,
|
|
):
|
|
"""消耗金币
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
gold: 金币
|
|
handle: 金币处理
|
|
plugin_name: 插件模块
|
|
platform: 平台.
|
|
|
|
异常:
|
|
InsufficientGold: 金币不足
|
|
"""
|
|
user, _ = await cls.get_or_create_user(user_id=user_id, platform=platform)
|
|
if user.gold < gold:
|
|
raise InsufficientGold()
|
|
user.gold -= gold
|
|
await user.save(update_fields=["gold"])
|
|
await UserGoldLog.create(
|
|
user_id=user_id, gold=gold, handle=handle, source=plugin_module
|
|
)
|
|
|
|
@classmethod
|
|
async def add_props(
|
|
cls, user_id: str, goods_uuid: str, num: int = 1, platform: str | None = None
|
|
):
|
|
"""添加道具
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
goods_uuid: 道具uuid
|
|
num: 道具数量.
|
|
platform: 平台.
|
|
"""
|
|
user, _ = await cls.get_or_create_user(user_id=user_id, platform=platform)
|
|
if goods_uuid not in user.props:
|
|
user.props[goods_uuid] = 0
|
|
user.props[goods_uuid] += num
|
|
await user.save(update_fields=["props"])
|
|
|
|
@classmethod
|
|
async def add_props_by_name(
|
|
cls, user_id: str, name: str, num: int = 1, platform: str | None = None
|
|
):
|
|
"""根据名称添加道具
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
name: 道具名称
|
|
num: 道具数量.
|
|
platform: 平台.
|
|
"""
|
|
if goods := await GoodsInfo.get_or_none(goods_name=name):
|
|
return await cls.add_props(user_id, goods.uuid, num, platform)
|
|
raise GoodsNotFound("未找到商品...")
|
|
|
|
@classmethod
|
|
async def use_props(
|
|
cls, user_id: str, goods_uuid: str, num: int = 1, platform: str | None = None
|
|
):
|
|
"""添加道具
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
goods_uuid: 道具uuid
|
|
num: 道具数量.
|
|
platform: 平台.
|
|
"""
|
|
user, _ = await cls.get_or_create_user(user_id=user_id, platform=platform)
|
|
|
|
if goods_uuid not in user.props or user.props[goods_uuid] < num:
|
|
raise GoodsNotFound("未找到商品或道具数量不足...")
|
|
user.props[goods_uuid] -= num
|
|
if user.props[goods_uuid] <= 0:
|
|
del user.props[goods_uuid]
|
|
await user.save(update_fields=["props"])
|
|
|
|
@classmethod
|
|
async def use_props_by_name(
|
|
cls, user_id: str, name: str, num: int = 1, platform: str | None = None
|
|
):
|
|
"""根据名称添加道具
|
|
|
|
参数:
|
|
user_id: 用户id
|
|
name: 道具名称
|
|
num: 道具数量.
|
|
platform: 平台.
|
|
"""
|
|
if goods := await GoodsInfo.get_or_none(goods_name=name):
|
|
return await cls.use_props(user_id, goods.uuid, num, platform)
|
|
raise GoodsNotFound("未找到商品...")
|
|
|
|
@classmethod
|
|
async def _run_script(cls):
|
|
return [
|
|
"CREATE INDEX idx_user_console_user_id ON user_console(user_id);",
|
|
"CREATE INDEX idx_user_console_uid ON user_console(uid);",
|
|
]
|