From 968fb7b157aaba74961b46d324b2fd7e24603954 Mon Sep 17 00:00:00 2001 From: HibiKier <775757368@qq.com> Date: Wed, 7 Aug 2024 18:59:43 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E6=94=B9bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/plugin_switch/__init__.py | 3 +- .../builtin_plugins/hooks/_auth_checker.py | 19 +- zhenxun/builtin_plugins/init/init_plugin.py | 6 +- zhenxun/plugins/black_word/__init__.py | 282 +----------------- zhenxun/plugins/black_word/black_watch.py | 61 ++++ zhenxun/plugins/black_word/black_word.py | 235 +++++++++++++++ zhenxun/plugins/mute/mute_message.py | 15 + 7 files changed, 326 insertions(+), 295 deletions(-) create mode 100644 zhenxun/plugins/black_word/black_watch.py create mode 100644 zhenxun/plugins/black_word/black_word.py diff --git a/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py b/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py index 7d383046..63c7484f 100644 --- a/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py +++ b/zhenxun/builtin_plugins/admin/plugin_switch/__init__.py @@ -337,7 +337,6 @@ async def _( @_group_status_matcher.handle() async def _( - bot: Bot, session: EventSession, arparma: Arparma, status: str, @@ -348,7 +347,7 @@ async def _( logger.info("进行休眠", arparma.header_result, session=session) await Text("那我先睡觉了...").finish() else: - if PluginManage.is_wake(gid): + if await PluginManage.is_wake(gid): await Text("我还醒着呢!").finish() await PluginManage.wake(gid) logger.info("醒来", arparma.header_result, session=session) diff --git a/zhenxun/builtin_plugins/hooks/_auth_checker.py b/zhenxun/builtin_plugins/hooks/_auth_checker.py index 4c92dfb3..773867c8 100644 --- a/zhenxun/builtin_plugins/hooks/_auth_checker.py +++ b/zhenxun/builtin_plugins/hooks/_auth_checker.py @@ -1,7 +1,4 @@ -from typing import Dict -from unittest import result - -from nonebot.adapters import Bot, Event +from nonebot.adapters import Bot from nonebot.exception import IgnoredException from nonebot.matcher import Matcher from nonebot_plugin_alconna import UniMsg @@ -10,7 +7,6 @@ from nonebot_plugin_session import EventSession from pydantic import BaseModel from zhenxun.configs.config import Config -from zhenxun.models.ban_console import BanConsole from zhenxun.models.group_console import GroupConsole from zhenxun.models.level_user import LevelUser from zhenxun.models.plugin_info import PluginInfo @@ -41,9 +37,9 @@ class LimitManage: add_module = [] - cd_limit: Dict[str, Limit] = {} - block_limit: Dict[str, Limit] = {} - count_limit: Dict[str, Limit] = {} + cd_limit: dict[str, Limit] = {} + block_limit: dict[str, Limit] = {} + count_limit: dict[str, Limit] = {} @classmethod def add_limit(cls, limit: PluginLimit): @@ -209,7 +205,8 @@ class AuthChecker: if user_id and matcher.plugin and (module_path := matcher.plugin.module_name): user = await UserConsole.get_user(user_id, session.platform) if plugin := await PluginInfo.get_or_none(module_path=module_path): - if plugin.plugin_type == PluginType.HIDDEN: + if plugin.plugin_type == PluginType.HIDDEN and plugin.name != "帮助": + logger.debug("插件为HIDDEN且不是帮助功能,已跳过...") return try: cost_gold = await self.auth_cost(user, plugin, session) @@ -433,7 +430,7 @@ class AuthChecker: if group.level < 0: """群权限小于0""" logger.debug( - f"{plugin.name}({plugin.module}) 群黑名单, 群权限-1...", + f"群黑名单, 群权限-1...", "HOOK", session=session, ) @@ -442,7 +439,7 @@ class AuthChecker: """群休眠""" if text.strip() != "醒来": logger.debug( - f"{plugin.name}({plugin.module}) 功能总开关关闭状态...", + f"功能总开关关闭状态...", "HOOK", session=session, ) diff --git a/zhenxun/builtin_plugins/init/init_plugin.py b/zhenxun/builtin_plugins/init/init_plugin.py index a2380d5c..49ec8dfb 100644 --- a/zhenxun/builtin_plugins/init/init_plugin.py +++ b/zhenxun/builtin_plugins/init/init_plugin.py @@ -105,7 +105,7 @@ async def _(): if module_list := await PluginInfo.all().values("id", "module_path"): module2id = {m["module_path"]: m["id"] for m in module_list} for plugin in get_loaded_plugins(): - load_plugin.append(plugin.name) + load_plugin.append(plugin.module_name) if plugin.metadata: await _handle_setting(plugin, plugin_list, limit_list, task_list) create_list = [] @@ -162,8 +162,8 @@ async def _(): 10, ) await data_migration() - await PluginInfo.filter(module__in=load_plugin).update(load_status=True) - await PluginInfo.filter(module__not_in=load_plugin).update(load_status=False) + await PluginInfo.filter(module_path__in=load_plugin).update(load_status=True) + await PluginInfo.filter(module_path__not_in=load_plugin).update(load_status=False) async def data_migration(): diff --git a/zhenxun/plugins/black_word/__init__.py b/zhenxun/plugins/black_word/__init__.py index 79cf4747..eb35e275 100644 --- a/zhenxun/plugins/black_word/__init__.py +++ b/zhenxun/plugins/black_word/__init__.py @@ -1,281 +1,5 @@ -from datetime import datetime -from typing import Any, List +from pathlib import Path -from nonebot import on_message -from nonebot.adapters import Bot, Event -from nonebot.matcher import Matcher -from nonebot.message import run_preprocessor -from nonebot.permission import SUPERUSER -from nonebot.plugin import PluginMetadata -from nonebot_plugin_alconna import ( - Alconna, - Args, - Arparma, - Match, - Option, - UniMsg, - on_alconna, -) -from nonebot_plugin_saa import Image, Text -from nonebot_plugin_session import EventSession +import nonebot -from zhenxun.configs.config import NICKNAME, Config -from zhenxun.configs.utils import PluginExtraData, RegisterConfig -from zhenxun.models.ban_console import BanConsole -from zhenxun.models.group_console import GroupConsole -from zhenxun.services.log import logger -from zhenxun.utils.enum import PluginType -from zhenxun.utils.image_utils import BuildImage - -from .data_source import set_user_punish, show_black_text_image -from .utils import black_word_manager - -__plugin_meta__ = PluginMetadata( - name="敏感词检测", - description="请注意你的发言!", - usage=""" - 惩罚机制: 检测内容提示 - 设置惩罚 [uid] [id] [level]: 设置惩罚内容, 此id需要通过`记录名单 -u:uid`来获取 - 记录名单: 查看检测记录名单 - 记录名单: - -u [uid] 指定用户记录名单 - -g [gid] 指定群组记录名单 - -d [date] 指定日期 - -dt ['=', '>', '<'] 大于小于等于指定日期 - - 示例: - 设置惩罚 123123123 0 1 - 记录名单 -u 123123123 - 记录名单 -g 333333 - 记录名单 -d 2022-11-11 - 记录名单 -d 2022-11-11 -dt > - """.strip(), - extra=PluginExtraData( - author="HibiKier", - version="0.1", - plugin_type=PluginType.SUPERUSER, - menu_type="其他", - configs=[ - RegisterConfig( - key="CYCLE_DAYS", - value=30, - help="黑名单词汇记录周期", - default_value=30, - type=int, - ), - RegisterConfig( - key="TOLERATE_COUNT", - value=[5, 1, 1, 1, 1], - help="各个级别惩罚的容忍次数, 依次为: 1, 2, 3, 4, 5", - default_value=[5, 1, 1, 1, 1], - type=List[int], - ), - RegisterConfig( - key="AUTO_PUNISH", - value=True, - help="是否启动自动惩罚机制", - default_value=True, - type=bool, - ), - RegisterConfig( - key="BAN_4_DURATION", - value=360, - help="Ban时长(分钟),四级惩罚,可以为指定数字或指定列表区间(随机),例如 [30, 360]", - default_value=360, - type=int, - ), - RegisterConfig( - key="BAN_3_DURATION", - value=7, - help="Ban时长(天),三级惩罚,可以为指定数字或指定列表区间(随机),例如 [7, 30]", - default_value=7, - type=int, - ), - RegisterConfig( - key="WARNING_RESULT", - value=f"请注意对{NICKNAME}的发言内容", - help="口头警告内容", - default_value=None, - ), - RegisterConfig( - key="AUTO_ADD_PUNISH_LEVEL", - value=360, - help="自动提级机制,当周期内处罚次数大于某一特定值就提升惩罚等级", - default_value=360, - type=int, - ), - RegisterConfig( - key="ADD_PUNISH_LEVEL_TO_COUNT", - value=3, - help="在CYCLE_DAYS周期内触发指定惩罚次数后提升惩罚等级", - default_value=3, - type=int, - ), - RegisterConfig( - key="ALAPI_CHECK_FLAG", - value=False, - help="当未检测到已收录的敏感词时,开启ALAPI文本检测并将疑似文本发送给超级用户", - default_value=False, - type=bool, - ), - RegisterConfig( - key="CONTAIN_BLACK_STOP_PROPAGATION", - value=True, - help="当文本包含任意敏感词时,停止向下级插件传递,即不触发ai", - default_value=True, - type=bool, - ), - ], - ).dict(), -) - - -_message_matcher = on_message(priority=1, block=False) - -_punish_matcher = on_alconna( - Alconna("设置惩罚", Args["uid", str]["id", int]["punish_level", int]), - priority=1, - permission=SUPERUSER, - block=True, -) - - -_show_matcher = on_alconna( - Alconna( - "记录名单", - Option("-u|--uid", Args["uid", str]), - Option("-g|--group", Args["gid", str]), - Option("-d|--date", Args["date", str]), - Option("-dt|--type", Args["date_type", ["=", ">", "<"]], default="="), - ), - priority=1, - permission=SUPERUSER, - block=True, -) - -_show_punish_matcher = on_alconna( - Alconna("惩罚机制"), aliases={"敏感词检测"}, priority=1, block=True -) - - -# 黑名单词汇检测 -@run_preprocessor -async def _( - bot: Bot, message: UniMsg, matcher: Matcher, event: Event, session: EventSession -): - gid = session.id3 or session.id2 - if session.id1: - if ( - event.is_tome() - and matcher.plugin_name == "black_word" - and not await BanConsole.is_ban(session.id1, gid) - ): - msg = message.extract_plain_text() - if session.id1 in bot.config.superusers: - return logger.debug( - f"超级用户跳过黑名单词汇检查 Message: {msg}", target=session.id1 - ) - if gid: - """屏蔽群权限-1的群""" - group, _ = await GroupConsole.get_or_create( - group_id=gid, channel_id__isnull=True - ) - if group.level < 0: - return - if await black_word_manager.check(bot, session, msg) and Config.get_config( - "black_word", "CONTAIN_BLACK_STOP_PROPAGATION" - ): - matcher.stop_propagation() - - -@_show_matcher.handle() -async def _( - bot: Bot, uid: Match[str], gid: Match[str], date: Match[str], date_type: Match[str] -): - user_id = None - group_id = None - date_ = None - date_str = None - date_type_ = "=" - if uid.available: - user_id = uid.result - if gid.available: - group_id = gid.result - if date.available: - date_str = date.result - if date_type.available: - date_type_ = date_type.result - if date_str: - try: - date_ = datetime.strptime(date_str, "%Y-%m-%d") - except ValueError: - await Text("日期格式错误,需要:年-月-日").finish() - result = await show_black_text_image( - user_id, - group_id, - date_, - date_type_, - ) - await Image(result.pic2bytes()).send() - - -@_show_punish_matcher.handle() -async def _(): - text = f""" - ** 惩罚机制 ** - - 惩罚前包含容忍机制,在指定周期内会容忍偶尔少次数的敏感词只会进行警告提醒 - - 多次触发同级惩罚会使惩罚等级提高,即惩罚自动提级机制 - - 目前公开的惩罚等级: - - 1级:永久ban - - 2级:删除好友 - - 3级:ban指定/随机天数 - - 4级:ban指定/随机时长 - - 5级:警告 - - 备注: - - 该功能为测试阶段,如果你有被误封情况,请联系管理员,会从数据库中提取出你的数据进行审核后判断 - - 目前该功能暂不完善,部分情况会由管理员鉴定,请注意对真寻的发言 - - 关于敏感词: - - 记住不要骂{NICKNAME}就对了! - """.strip() - max_width = 0 - for m in text.split("\n"): - max_width = len(m) * 20 if len(m) * 20 > max_width else max_width - max_height = len(text.split("\n")) * 24 - A = BuildImage( - max_width, max_height, font="CJGaoDeGuo.otf", font_size=24, color="#E3DBD1" - ) - await A.text((10, 10), text) - await Image(A.pic2bytes()).send() - - -@_punish_matcher.handle() -async def _( - bot: Bot, - session: EventSession, - arparma: Arparma, - uid: str, - id: int, - punish_level: int, -): - result = await set_user_punish( - bot, uid, session.id2 or session.id3, id, punish_level - ) - await Text(result).send(reply=True) - logger.info( - f"设置惩罚 uid:{uid} id_:{id} punish_level:{punish_level} --> {result}", - arparma.header_result, - session=session, - ) +nonebot.load_plugins(str(Path(__file__).parent.resolve())) diff --git a/zhenxun/plugins/black_word/black_watch.py b/zhenxun/plugins/black_word/black_watch.py new file mode 100644 index 00000000..be081a12 --- /dev/null +++ b/zhenxun/plugins/black_word/black_watch.py @@ -0,0 +1,61 @@ +from nonebot.adapters import Bot, Event +from nonebot.matcher import Matcher +from nonebot.message import run_preprocessor +from nonebot.plugin import PluginMetadata +from nonebot_plugin_alconna import UniMsg +from nonebot_plugin_session import EventSession + +from zhenxun.configs.config import Config +from zhenxun.configs.utils import PluginExtraData +from zhenxun.models.ban_console import BanConsole +from zhenxun.models.group_console import GroupConsole +from zhenxun.services.log import logger +from zhenxun.utils.enum import PluginType + +from .utils import black_word_manager + +__plugin_meta__ = PluginMetadata( + name="敏感词文本监听", + description="敏感词文本监听", + usage="".strip(), + extra=PluginExtraData( + author="HibiKier", + version="0.1", + plugin_type=PluginType.HIDDEN, + ).dict(), +) + +base_config = Config.get("black_word") + + +# 黑名单词汇检测 +@run_preprocessor +async def _( + bot: Bot, message: UniMsg, matcher: Matcher, event: Event, session: EventSession +): + gid = session.id3 or session.id2 + if session.id1: + if ( + event.is_tome() + and matcher.plugin_name == "black_word" + and not await BanConsole.is_ban(session.id1, gid) + ): + msg = message.extract_plain_text() + if session.id1 in bot.config.superusers: + return logger.debug( + f"超级用户跳过黑名单词汇检查 Message: {msg}", target=session.id1 + ) + if gid: + """屏蔽群权限-1的群""" + group, _ = await GroupConsole.get_or_create( + group_id=gid, channel_id__isnull=True + ) + if group.level < 0: + return + if await BanConsole.is_ban(None, gid): + """屏蔽群被ban的群""" + return + if await black_word_manager.check(bot, session, msg) and base_config.get( + "CONTAIN_BLACK_STOP_PROPAGATION" + ): + matcher.stop_propagation() diff --git a/zhenxun/plugins/black_word/black_word.py b/zhenxun/plugins/black_word/black_word.py new file mode 100644 index 00000000..1cad209f --- /dev/null +++ b/zhenxun/plugins/black_word/black_word.py @@ -0,0 +1,235 @@ +from datetime import datetime +from typing import List + +from nonebot.adapters import Bot +from nonebot.permission import SUPERUSER +from nonebot.plugin import PluginMetadata +from nonebot_plugin_alconna import Alconna, Args, Arparma, Match, Option, on_alconna +from nonebot_plugin_saa import Image, Text +from nonebot_plugin_session import EventSession + +from zhenxun.configs.config import NICKNAME +from zhenxun.configs.utils import PluginExtraData, RegisterConfig +from zhenxun.services.log import logger +from zhenxun.utils.enum import PluginType +from zhenxun.utils.image_utils import BuildImage + +from .data_source import set_user_punish, show_black_text_image + +__plugin_meta__ = PluginMetadata( + name="敏感词检测", + description="请注意你的发言!", + usage=""" + 惩罚机制: 检测内容提示 + 设置惩罚 [uid] [id] [level]: 设置惩罚内容, 此id需要通过`记录名单 -u:uid`来获取 + 记录名单: 查看检测记录名单 + 记录名单: + -u [uid] 指定用户记录名单 + -g [gid] 指定群组记录名单 + -d [date] 指定日期 + -dt ['=', '>', '<'] 大于小于等于指定日期 + + 示例: + 设置惩罚 123123123 0 1 + 记录名单 -u 123123123 + 记录名单 -g 333333 + 记录名单 -d 2022-11-11 + 记录名单 -d 2022-11-11 -dt > + """.strip(), + extra=PluginExtraData( + author="HibiKier", + version="0.1", + plugin_type=PluginType.SUPERUSER, + menu_type="其他", + configs=[ + RegisterConfig( + key="CYCLE_DAYS", + value=30, + help="黑名单词汇记录周期", + default_value=30, + type=int, + ), + RegisterConfig( + key="TOLERATE_COUNT", + value=[5, 1, 1, 1, 1], + help="各个级别惩罚的容忍次数, 依次为: 1, 2, 3, 4, 5", + default_value=[5, 1, 1, 1, 1], + type=List[int], + ), + RegisterConfig( + key="AUTO_PUNISH", + value=True, + help="是否启动自动惩罚机制", + default_value=True, + type=bool, + ), + RegisterConfig( + key="BAN_4_DURATION", + value=360, + help="Ban时长(分钟),四级惩罚,可以为指定数字或指定列表区间(随机),例如 [30, 360]", + default_value=360, + type=int, + ), + RegisterConfig( + key="BAN_3_DURATION", + value=7, + help="Ban时长(天),三级惩罚,可以为指定数字或指定列表区间(随机),例如 [7, 30]", + default_value=7, + type=int, + ), + RegisterConfig( + key="WARNING_RESULT", + value=f"请注意对{NICKNAME}的发言内容", + help="口头警告内容", + default_value=None, + ), + RegisterConfig( + key="AUTO_ADD_PUNISH_LEVEL", + value=360, + help="自动提级机制,当周期内处罚次数大于某一特定值就提升惩罚等级", + default_value=360, + type=int, + ), + RegisterConfig( + key="ADD_PUNISH_LEVEL_TO_COUNT", + value=3, + help="在CYCLE_DAYS周期内触发指定惩罚次数后提升惩罚等级", + default_value=3, + type=int, + ), + RegisterConfig( + key="ALAPI_CHECK_FLAG", + value=False, + help="当未检测到已收录的敏感词时,开启ALAPI文本检测并将疑似文本发送给超级用户", + default_value=False, + type=bool, + ), + RegisterConfig( + key="CONTAIN_BLACK_STOP_PROPAGATION", + value=True, + help="当文本包含任意敏感词时,停止向下级插件传递,即不触发ai", + default_value=True, + type=bool, + ), + ], + ).dict(), +) + + +_punish_matcher = on_alconna( + Alconna("设置惩罚", Args["uid", str]["id", int]["punish_level", int]), + priority=1, + permission=SUPERUSER, + block=True, +) + + +_show_matcher = on_alconna( + Alconna( + "记录名单", + Option("-u|--uid", Args["uid", str]), + Option("-g|--group", Args["gid", str]), + Option("-d|--date", Args["date", str]), + Option("-dt|--type", Args["date_type", ["=", ">", "<"]], default="="), + ), + priority=1, + permission=SUPERUSER, + block=True, +) + +_show_punish_matcher = on_alconna( + Alconna("惩罚机制"), aliases={"敏感词检测"}, priority=1, block=True +) + + +@_show_matcher.handle() +async def _( + bot: Bot, uid: Match[str], gid: Match[str], date: Match[str], date_type: Match[str] +): + user_id = None + group_id = None + date_ = None + date_str = None + date_type_ = "=" + if uid.available: + user_id = uid.result + if gid.available: + group_id = gid.result + if date.available: + date_str = date.result + if date_type.available: + date_type_ = date_type.result + if date_str: + try: + date_ = datetime.strptime(date_str, "%Y-%m-%d") + except ValueError: + await Text("日期格式错误,需要:年-月-日").finish() + result = await show_black_text_image( + user_id, + group_id, + date_, + date_type_, + ) + await Image(result.pic2bytes()).send() + + +@_show_punish_matcher.handle() +async def _(): + text = f""" + ** 惩罚机制 ** + + 惩罚前包含容忍机制,在指定周期内会容忍偶尔少次数的敏感词只会进行警告提醒 + + 多次触发同级惩罚会使惩罚等级提高,即惩罚自动提级机制 + + 目前公开的惩罚等级: + + 1级:永久ban + + 2级:删除好友 + + 3级:ban指定/随机天数 + + 4级:ban指定/随机时长 + + 5级:警告 + + 备注: + + 该功能为测试阶段,如果你有被误封情况,请联系管理员,会从数据库中提取出你的数据进行审核后判断 + + 目前该功能暂不完善,部分情况会由管理员鉴定,请注意对真寻的发言 + + 关于敏感词: + + 记住不要骂{NICKNAME}就对了! + """.strip() + max_width = 0 + for m in text.split("\n"): + max_width = len(m) * 20 if len(m) * 20 > max_width else max_width + max_height = len(text.split("\n")) * 24 + A = BuildImage( + max_width, max_height, font="CJGaoDeGuo.otf", font_size=24, color="#E3DBD1" + ) + await A.text((10, 10), text) + await Image(A.pic2bytes()).send() + + +@_punish_matcher.handle() +async def _( + bot: Bot, + session: EventSession, + arparma: Arparma, + uid: str, + id: int, + punish_level: int, +): + result = await set_user_punish( + bot, uid, session.id2 or session.id3, id, punish_level + ) + await Text(result).send(reply=True) + logger.info( + f"设置惩罚 uid:{uid} id_:{id} punish_level:{punish_level} --> {result}", + arparma.header_result, + session=session, + ) diff --git a/zhenxun/plugins/mute/mute_message.py b/zhenxun/plugins/mute/mute_message.py index 401b2fc5..a9e6d42a 100644 --- a/zhenxun/plugins/mute/mute_message.py +++ b/zhenxun/plugins/mute/mute_message.py @@ -1,17 +1,32 @@ from nonebot import on_message from nonebot.adapters import Bot +from nonebot.plugin import PluginMetadata from nonebot_plugin_alconna import Image as alcImage from nonebot_plugin_alconna import UniMsg from nonebot_plugin_saa import Text from nonebot_plugin_session import EventSession from zhenxun.configs.config import NICKNAME +from zhenxun.configs.utils import PluginExtraData from zhenxun.services.log import logger +from zhenxun.utils.enum import PluginType from zhenxun.utils.image_utils import get_download_image_hash from zhenxun.utils.platform import PlatformUtils from ._data_source import mute_manage +__plugin_meta__ = PluginMetadata( + name="刷屏监听", + description="", + usage="", + extra=PluginExtraData( + author="HibiKier", + version="0.1", + menu_type="其他", + plugin_type=PluginType.HIDDEN, + ).dict(), +) + _matcher = on_message(priority=1, block=False)