Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎨 notice响应期添加rule #1682

Merged
merged 2 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions zhenxun/builtin_plugins/admin/admin_watch.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
from nonebot import on_notice
from nonebot.adapters.onebot.v11 import GroupAdminNoticeEvent
from nonebot.plugin import PluginMetadata
from nonebot.adapters.onebot.v11 import GroupAdminNoticeEvent

from zhenxun.configs.config import Config
from zhenxun.configs.utils import PluginExtraData, RegisterConfig
from zhenxun.models.level_user import LevelUser
from zhenxun.services.log import logger
from zhenxun.configs.config import Config
from zhenxun.utils.enum import PluginType
from zhenxun.utils.rules import notice_rule
from zhenxun.models.level_user import LevelUser
from zhenxun.configs.utils import RegisterConfig, PluginExtraData

__plugin_meta__ = PluginMetadata(
name="群管理员变动监测",
description="检测群管理员变动, 添加与删除管理员默认权限, 当配置项 ADMIN_DEFAULT_AUTH 为空时, 不会添加管理员权限",
description="""检测群管理员变动, 添加与删除管理员默认权限,
当配置项 ADMIN_DEFAULT_AUTH 为空时, 不会添加管理员权限""",
usage="",
extra=PluginExtraData(
author="HibiKier",
Expand All @@ -29,7 +31,7 @@
)


admin_notice = on_notice(priority=5)
admin_notice = on_notice(priority=5, rule=notice_rule(GroupAdminNoticeEvent))

base_config = Config.get("admin_bot_manage")

Expand All @@ -52,7 +54,8 @@ async def _(event: GroupAdminNoticeEvent):
)
else:
logger.warning(
f"配置项 MODULE: [<u><y>admin_bot_manage</y></u>] | KEY: [<u><y>ADMIN_DEFAULT_AUTH</y></u>] 为空"
"配置项 MODULE: [<u><y>admin_bot_manage</y></u>] |"
" KEY: [<u><y>ADMIN_DEFAULT_AUTH</y></u>] 为空"
)
elif event.sub_type == "unset":
await LevelUser.delete_level(str(event.user_id), str(event.group_id))
Expand Down
14 changes: 7 additions & 7 deletions zhenxun/builtin_plugins/admin/group_member_update/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import nonebot
from nonebot import on_notice
from nonebot.adapters import Bot
from nonebot.adapters.onebot.v11 import GroupIncreaseNoticeEvent
from nonebot.plugin import PluginMetadata
from nonebot_plugin_alconna import Alconna, Arparma, on_alconna
from nonebot_plugin_apscheduler import scheduler
from nonebot_plugin_session import EventSession
from nonebot_plugin_apscheduler import scheduler
from nonebot_plugin_alconna import Alconna, Arparma, on_alconna
from nonebot.adapters.onebot.v11 import GroupIncreaseNoticeEvent

from zhenxun.configs.config import BotConfig
from zhenxun.configs.utils import PluginExtraData
from zhenxun.services.log import logger
from zhenxun.utils.enum import PluginType
from zhenxun.configs.config import BotConfig
from zhenxun.utils.message import MessageUtils
from zhenxun.utils.platform import PlatformUtils
from zhenxun.utils.rules import admin_check, ensure_group
from zhenxun.configs.utils import PluginExtraData
from zhenxun.utils.rules import admin_check, notice_rule, ensure_group

from ._data_source import MemberUpdateManage

Expand Down Expand Up @@ -42,7 +42,7 @@
)


_notice = on_notice(priority=1, block=False)
_notice = on_notice(priority=1, block=False, rule=notice_rule(GroupIncreaseNoticeEvent))


@_matcher.handle()
Expand Down
20 changes: 10 additions & 10 deletions zhenxun/builtin_plugins/hooks/ban_hook.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import logging

from nonebot.adapters import Bot, Event
from nonebot.exception import IgnoredException
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor
from nonebot.typing import T_State
from nonebot.matcher import Matcher
from nonebot_plugin_alconna import At
from nonebot.adapters import Bot, Event
from nonebot.message import run_preprocessor
from nonebot.exception import IgnoredException
from nonebot_plugin_session import EventSession

from zhenxun.configs.config import Config
from zhenxun.models.ban_console import BanConsole
from zhenxun.models.group_console import GroupConsole
from zhenxun.utils.enum import PluginType
from zhenxun.utils.message import MessageUtils
from zhenxun.utils.utils import FreqLimiter
from zhenxun.utils.message import MessageUtils
from zhenxun.models.ban_console import BanConsole
from zhenxun.models.group_console import GroupConsole

Config.add_plugin_config(
"hook",
Expand Down Expand Up @@ -58,12 +58,12 @@ async def _(
else:
time = abs(int(time))
if time < 60:
time_str = str(time) + " 秒"
time_str = f"{time!s} 秒"
else:
minute = int(time / 60)
if minute > 60:
hours = int(minute / 60)
minute = minute % 60
hours = minute // 60
minute %= 60
time_str = f"{hours} 小时 {minute}分钟"
else:
time_str = f"{minute} 分钟"
Expand Down
13 changes: 11 additions & 2 deletions zhenxun/builtin_plugins/platform/qq/group_handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
)

from zhenxun.services.log import logger
from zhenxun.utils.rules import notice_rule
from zhenxun.utils.utils import FreqLimiter
from zhenxun.utils.message import MessageUtils
from zhenxun.models.fg_request import FgRequest
Expand Down Expand Up @@ -95,9 +96,17 @@
_flmt = FreqLimiter(limit_cd)


group_increase_handle = on_notice(priority=1, block=False)
group_increase_handle = on_notice(
priority=1,
block=False,
rule=notice_rule([GroupIncreaseNoticeEvent, GroupMemberIncreaseEvent]),
)
"""群员增加处理"""
group_decrease_handle = on_notice(priority=1, block=False)
group_decrease_handle = on_notice(
priority=1,
block=False,
rule=notice_rule([GroupDecreaseNoticeEvent, GroupMemberDecreaseEvent]),
)
"""群员减少处理"""
add_group = on_request(priority=1, block=False)
"""加群同意请求"""
Expand Down
13 changes: 11 additions & 2 deletions zhenxun/builtin_plugins/platform/qq/group_handle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)

from zhenxun.utils.enum import PluginType
from zhenxun.utils.rules import notice_rule
from zhenxun.utils.platform import PlatformUtils
from zhenxun.utils.common_utils import CommonUtils
from zhenxun.configs.config import Config, BotConfig
Expand Down Expand Up @@ -82,9 +83,17 @@
limit_cd = base_config.get("welcome_msg_cd")


group_increase_handle = on_notice(priority=1, block=False)
group_increase_handle = on_notice(
priority=1,
block=False,
rule=notice_rule([GroupIncreaseNoticeEvent, GroupMemberIncreaseEvent]),
)
"""群员增加处理"""
group_decrease_handle = on_notice(priority=1, block=False)
group_decrease_handle = on_notice(
priority=1,
block=False,
rule=notice_rule([GroupMemberDecreaseEvent, GroupMemberIncreaseEvent]),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): 修正 group_decrease_handle 的事件类型

group_decrease_handle 使用的是 GroupMemberIncreaseEvent 而不是 GroupDecreaseNoticeEvent。这似乎是一个复制粘贴错误,可能导致意外行为。请验证并更正事件类型。

Original comment in English

issue (bug_risk): Correct event type for group_decrease_handle

The group_decrease_handle is using GroupMemberIncreaseEvent instead of GroupDecreaseNoticeEvent. This appears to be a copy-paste error and could lead to unexpected behavior. Please verify and correct the event types.

)
"""群员减少处理"""
add_group = on_request(priority=1, block=False)
"""加群同意请求"""
Expand Down
27 changes: 25 additions & 2 deletions zhenxun/utils/rules.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from nonebot.adapters import Bot, Event
from nonebot.internal.rule import Rule
from nonebot.adapters import Bot, Event
from nonebot.permission import SUPERUSER
from nonebot_plugin_session import EventSession, SessionLevel

Expand All @@ -24,7 +24,7 @@ async def _rule(bot: Bot, event: Event, session: EventSession) -> bool:
return True
if session.id1 and session.id2:
level = a
if type(a) == str and key:
if isinstance(a, str) and key:
level = Config.get_config(a, key)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): 考虑优化 notice_rule 函数以便提前返回

notice_rule 函数中,当 event_type 是一个列表时,你可以在找到匹配项后立即返回 True,而不是继续遍历整个列表。对于较长的事件类型列表,这将更高效。

Original comment in English

suggestion (performance): Consider optimizing the notice_rule function for early return

In the notice_rule function, when event_type is a list, you could return True immediately upon finding a match instead of continuing to iterate through the entire list. This would be more efficient for longer lists of event types.

if level is not None:
return bool(
Expand Down Expand Up @@ -59,3 +59,26 @@ def ensure_private(session: EventSession) -> bool:
bool: bool
"""
return not session.id3 and not session.id2


def notice_rule(event_type: type | list[type]) -> Rule:
"""
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): 考虑重构 notice_rule 函数以简化其实现并提高效率。

notice_rule 函数可以简化以减少复杂性,同时保持清晰。以下是一个建议的重构:

def notice_rule(event_types: type | tuple[type, ...]) -> Rule:
    if not isinstance(event_types, tuple):
        event_types = (event_types,)

    def _rule(event: Event) -> bool:
        return isinstance(event, event_types)

    return Rule(_rule)

此重构解决了几个问题:

  1. 它使用元组而不是列表来确保 event_types 的不变性。
  2. 它通过利用 isinstance 可以接受类型元组来简化类型检查。
  3. 它移除了嵌套的 if-else 结构,简化了逻辑。
  4. 它消除了显式迭代的需要,使代码更简洁。

此实现更简单、更高效且更易于理解,同时保持了原有功能。使用带有类型元组的 isinstance 是一种 Pythonic 的方式来检查多种类型,这既清晰又高效。

Original comment in English

issue (complexity): Consider refactoring the notice_rule function to simplify its implementation and improve efficiency.

The notice_rule function can be simplified to reduce complexity while maintaining clarity. Here's a suggested refactoring:

def notice_rule(event_types: type | tuple[type, ...]) -> Rule:
    if not isinstance(event_types, tuple):
        event_types = (event_types,)

    def _rule(event: Event) -> bool:
        return isinstance(event, event_types)

    return Rule(_rule)

This refactoring addresses several issues:

  1. It uses a tuple instead of a list for event_types, ensuring immutability.
  2. It simplifies the type checking by leveraging the fact that isinstance can accept a tuple of types.
  3. It removes the nested if-else structure, flattening the logic.
  4. It eliminates the need for explicit iteration, making the code more concise.

This implementation is simpler, more efficient, and easier to understand while maintaining the original functionality. The use of isinstance with a tuple of types is a Pythonic way to check against multiple types, which is both clear and performant.

Notice限制

参数:
event_type: Event类型

返回:
Rule: Rule
"""

async def _rule(event: Event) -> bool:
if isinstance(event_type, list):
for et in event_type:
if isinstance(event, et):
return True
else:
return isinstance(event, event_type)
return False

return Rule(_rule)
Loading