Skip to content

Commit

Permalink
🐛 修复群权限与插件等级匹配 (#1627)
Browse files Browse the repository at this point in the history
  • Loading branch information
HibiKier authored Sep 14, 2024
1 parent 029a731 commit f1354c6
Showing 1 changed file with 96 additions and 97 deletions.
193 changes: 96 additions & 97 deletions zhenxun/builtin_plugins/hooks/_auth_checker.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
from nonebot.adapters import Bot, Event
from nonebot.adapters.onebot.v11 import PokeNotifyEvent
from nonebot.exception import IgnoredException
from pydantic import BaseModel
from nonebot.matcher import Matcher
from nonebot.adapters import Bot, Event
from nonebot_plugin_alconna import At, UniMsg
from nonebot_plugin_session import EventSession
from pydantic import BaseModel
from nonebot.exception import IgnoredException
from tortoise.exceptions import IntegrityError
from nonebot_plugin_session import EventSession
from nonebot.adapters.onebot.v11 import PokeNotifyEvent

from zhenxun.services.log import logger
from zhenxun.configs.config import Config
from zhenxun.models.group_console import GroupConsole
from zhenxun.utils.message import MessageUtils
from zhenxun.models.level_user import LevelUser
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.models.plugin_limit import PluginLimit
from zhenxun.models.user_console import UserConsole
from zhenxun.services.log import logger
from zhenxun.utils.exception import InsufficientGold
from zhenxun.models.group_console import GroupConsole
from zhenxun.utils.utils import FreqLimiter, CountLimiter, UserBlockLimiter
from zhenxun.utils.enum import (
BlockType,
GoldHandle,
PluginType,
LimitWatchType,
PluginLimitType,
PluginType,
)
from zhenxun.utils.exception import InsufficientGold
from zhenxun.utils.message import MessageUtils
from zhenxun.utils.utils import CountLimiter, FreqLimiter, UserBlockLimiter

base_config = Config.get("hook")


class Limit(BaseModel):

limit: PluginLimit
limiter: FreqLimiter | UserBlockLimiter | CountLimiter

Expand All @@ -38,12 +37,11 @@ class Config:


class LimitManage:
add_module = [] # noqa: RUF012

add_module = []

cd_limit: dict[str, Limit] = {}
block_limit: dict[str, Limit] = {}
count_limit: dict[str, Limit] = {}
cd_limit: dict[str, Limit] = {} # noqa: RUF012
block_limit: dict[str, Limit] = {} # noqa: RUF012
count_limit: dict[str, Limit] = {} # noqa: RUF012

@classmethod
def add_limit(cls, limit: PluginLimit):
Expand Down Expand Up @@ -136,33 +134,34 @@ async def __check(
异常:
IgnoredException: IgnoredException
"""
if limit_model:
limit = limit_model.limit
limiter = limit_model.limiter
is_limit = (
LimitWatchType.ALL
or (group_id and limit.watch_type == LimitWatchType.GROUP)
or (not group_id and limit.watch_type == LimitWatchType.USER)
if not limit_model:
return
limit = limit_model.limit
limiter = limit_model.limiter
is_limit = (
LimitWatchType.ALL
or (group_id and limit.watch_type == LimitWatchType.GROUP)
or (not group_id and limit.watch_type == LimitWatchType.USER)
)
key_type = user_id
if group_id and limit.watch_type == LimitWatchType.GROUP:
key_type = channel_id or group_id
if is_limit and not limiter.check(key_type):
if limit.result:
await MessageUtils.build_message(limit.result).send()
logger.debug(
f"{limit.module}({limit.limit_type}) 正在限制中...",
"HOOK",
session=session,
)
key_type = user_id
if group_id and limit.watch_type == LimitWatchType.GROUP:
key_type = channel_id or group_id
if is_limit and not limiter.check(key_type):
if limit.result:
await MessageUtils.build_message(limit.result).send()
logger.debug(
f"{limit.module}({limit.limit_type}) 正在限制中...",
"HOOK",
session=session,
)
raise IgnoredException(f"{limit.module} 正在限制中...")
else:
if isinstance(limiter, FreqLimiter):
limiter.start_cd(key_type)
if isinstance(limiter, UserBlockLimiter):
limiter.set_true(key_type)
if isinstance(limiter, CountLimiter):
limiter.increase(key_type)
raise IgnoredException(f"{limit.module} 正在限制中...")
else:
if isinstance(limiter, FreqLimiter):
limiter.start_cd(key_type)
if isinstance(limiter, UserBlockLimiter):
limiter.set_true(key_type)
if isinstance(limiter, CountLimiter):
limiter.increase(key_type)


class IsSuperuserException(Exception):
Expand Down Expand Up @@ -196,11 +195,7 @@ def is_send_limit_message(self, plugin: PluginInfo, sid: str) -> bool:
return False
if plugin.plugin_type == PluginType.DEPENDANT:
return False
if not self._flmt_s.check(sid):
return False
if plugin.module == "ai":
return False
return True
return plugin.module != "ai" if self._flmt_s.check(sid) else False

async def auth(
self,
Expand Down Expand Up @@ -255,7 +250,7 @@ async def auth(
await self.auth_limit(plugin, session)
except IsSuperuserException:
logger.debug(
f"超级用户或被ban跳过权限检测...", "HOOK", session=session
"超级用户或被ban跳过权限检测...", "HOOK", session=session
)
except IgnoredException:
is_ignore = True
Expand Down Expand Up @@ -313,14 +308,13 @@ async def auth_plugin(
plugin: PluginInfo
session: EventSession
"""
user_id = session.id1
group_id = session.id3
channel_id = session.id2
is_poke = isinstance(event, PokeNotifyEvent)
if not group_id:
group_id = channel_id
channel_id = None
if user_id:
if user_id := session.id1:
is_poke = isinstance(event, PokeNotifyEvent)
if group_id:
sid = group_id or user_id
if await GroupConsole.is_super_block_plugin(
Expand Down Expand Up @@ -393,9 +387,8 @@ async def auth_plugin(
raise IgnoredException("该插件在私聊中已被禁用...")
if not plugin.status and plugin.block_type == BlockType.ALL:
"""全局状态"""
if group_id:
if await GroupConsole.is_super_group(group_id):
raise IsSuperuserException()
if group_id and await GroupConsole.is_super_group(group_id):
raise IsSuperuserException()
logger.debug(
f"{plugin.name}({plugin.module}) 全局未开启此功能...",
"HOOK",
Expand All @@ -414,9 +407,8 @@ async def auth_admin(self, plugin: PluginInfo, session: EventSession):
session: EventSession
"""
user_id = session.id1
group_id = session.id3 or session.id2
if user_id and plugin.admin_level:
if group_id:
if group_id := session.id3 or session.id2:
if not await LevelUser.check_level(
user_id, group_id, plugin.admin_level
):
Expand All @@ -426,7 +418,8 @@ async def auth_admin(self, plugin: PluginInfo, session: EventSession):
await MessageUtils.build_message(
[
At(flag="user", target=user_id),
f"你的权限不足喔,该功能需要的权限等级: {plugin.admin_level}",
f"你的权限不足喔,"
f"该功能需要的权限等级: {plugin.admin_level}",
]
).send(reply_to=True)
except Exception as e:
Expand All @@ -439,22 +432,21 @@ async def auth_admin(self, plugin: PluginInfo, session: EventSession):
session=session,
)
raise IgnoredException("管理员权限不足...")
else:
if not await LevelUser.check_level(user_id, None, plugin.admin_level):
try:
await MessageUtils.build_message(
f"你的权限不足喔,该功能需要的权限等级: {plugin.admin_level}"
).send()
except Exception as e:
logger.error(
"auth_admin 发送消息失败", "HOOK", session=session, e=e
)
logger.debug(
f"{plugin.name}({plugin.module}) 管理员权限不足...",
"HOOK",
session=session,
elif not await LevelUser.check_level(user_id, None, plugin.admin_level):
try:
await MessageUtils.build_message(
f"你的权限不足喔,该功能需要的权限等级: {plugin.admin_level}"
).send()
except Exception as e:
logger.error(
"auth_admin 发送消息失败", "HOOK", session=session, e=e
)
raise IgnoredException("权限不足")
logger.debug(
f"{plugin.name}({plugin.module}) 管理员权限不足...",
"HOOK",
session=session,
)
raise IgnoredException("权限不足")

async def auth_group(
self, plugin: PluginInfo, session: EventSession, message: UniMsg
Expand All @@ -466,29 +458,35 @@ async def auth_group(
session: EventSession
message: UniMsg
"""
if group_id := session.id3 or session.id2:
text = message.extract_plain_text()
group = await GroupConsole.get_group(group_id)
if not group:
"""群不存在"""
raise IgnoredException("群不存在")
if group.level < 0:
"""群权限小于0"""
logger.debug(
f"群黑名单, 群权限-1...",
"HOOK",
session=session,
)
raise IgnoredException("群黑名单")
if not group.status:
"""群休眠"""
if text.strip() != "醒来":
logger.debug(
f"群休眠状态...",
"HOOK",
session=session,
)
raise IgnoredException("群休眠状态")
if not (group_id := session.id3 or session.id2):
return
text = message.extract_plain_text()
group = await GroupConsole.get_group(group_id)
if not group:
"""群不存在"""
raise IgnoredException("群不存在")
if group.level < 0:
"""群权限小于0"""
logger.debug(
"群黑名单, 群权限-1...",
"HOOK",
session=session,
)
raise IgnoredException("群黑名单")
if not group.status:
"""群休眠"""
if text.strip() != "醒来":
logger.debug("群休眠状态...", "HOOK", session=session)
raise IgnoredException("群休眠状态")
if plugin.level > group.level:
"""插件等级大于群等级"""
logger.debug(
f"{plugin.name}({plugin.module}) 群等级限制.."
f"该功能需要的群等级: {plugin.level}..",
"HOOK",
session=session,
)
raise IgnoredException(f"{plugin.name}({plugin.module}) 群等级限制...")

async def auth_cost(
self, user: UserConsole, plugin: PluginInfo, session: EventSession
Expand All @@ -512,7 +510,8 @@ async def auth_cost(
except Exception as e:
logger.error("auth_cost 发送消息失败", "HOOK", session=session, e=e)
logger.debug(
f"{plugin.name}({plugin.module}) 金币限制..该功能需要{plugin.cost_gold}金币..",
f"{plugin.name}({plugin.module}) 金币限制.."
f"该功能需要{plugin.cost_gold}金币..",
"HOOK",
session=session,
)
Expand Down

0 comments on commit f1354c6

Please sign in to comment.