From f9c8334a36b6989ba561fbd42c3a54b9560513d8 Mon Sep 17 00:00:00 2001 From: student_2333 Date: Mon, 28 Oct 2024 16:32:39 +0800 Subject: [PATCH] up --- nonebot_plugin_nailongremove/config.py | 1 + nonebot_plugin_nailongremove/handler.py | 44 +++--- .../uniapi/__init__.py | 2 + nonebot_plugin_nailongremove/uniapi/mute.py | 135 ++++++++++++++++++ .../{ => uniapi}/recall.py | 3 +- pdm.lock | 10 +- pyproject.toml | 2 +- 7 files changed, 172 insertions(+), 25 deletions(-) create mode 100644 nonebot_plugin_nailongremove/uniapi/__init__.py create mode 100644 nonebot_plugin_nailongremove/uniapi/mute.py rename nonebot_plugin_nailongremove/{ => uniapi}/recall.py (99%) diff --git a/nonebot_plugin_nailongremove/config.py b/nonebot_plugin_nailongremove/config.py index d76d96b..8cb57b7 100644 --- a/nonebot_plugin_nailongremove/config.py +++ b/nonebot_plugin_nailongremove/config.py @@ -15,6 +15,7 @@ class Config(BaseModel): nailong_list_scenes: List[str] = Field(default_factory=list) nailong_blacklist: bool = True nailong_recall: bool = True + nailong_mute_seconds: int = 0 nailong_tip: str = "本群禁止发送奶龙!" nailong_failed_tip: str = "{:Reply($message_id)}呜,不要发奶龙了嘛 🥺 👉👈" diff --git a/nonebot_plugin_nailongremove/handler.py b/nonebot_plugin_nailongremove/handler.py index 9461195..fb9cb2f 100644 --- a/nonebot_plugin_nailongremove/handler.py +++ b/nonebot_plugin_nailongremove/handler.py @@ -1,5 +1,5 @@ import io -from typing import Iterable, TypeVar, cast +from typing import Any, Awaitable, Callable, Iterable, List, TypeVar, cast import cv2 import numpy as np @@ -17,7 +17,7 @@ from PIL import Image as PilImage from .config import config from .model import check_image -from .recall import recall +from .uniapi import mute, recall T = TypeVar("T") @@ -47,6 +47,21 @@ def judge_list(lst: Iterable[T], val: T, blacklist: bool) -> bool: return (val not in lst) if blacklist else (val in lst) +async def execute_functions_any_ok( + func: Iterable[Callable[[], Awaitable[Any]]], +) -> bool: + ok = False + for f in func: + try: + await f() + except Exception as e: + logger.warning(f"{type(e).__name__}: {e}") + logger.opt(exception=e).debug("Stacktrace:") + else: + ok = True + return ok + + async def nailong_rule( bot: BaseBot, event: BaseEvent, @@ -125,32 +140,25 @@ async def handle_function( continue try: - ok = await run_sync(check_image)( + check_ok = await run_sync(check_image)( await run_sync(transform_image)(image), ) except Exception: logger.exception(f"Failed to process image: {seg!r}") continue - - if not ok: + if not check_ok: continue - # logger.debug(f"尝试撤回包含奶龙的图片并发送警告:{seg!r}") - recall_ok = False + functions: List[Callable[[], Awaitable[Any]]] = [] if config.nailong_recall: - try: - await recall(bot, ev) - except NotImplementedError: - pass - except Exception as e: - logger.warning(f"{type(e).__name__}: {e}") - else: - recall_ok = True + functions.append(lambda: recall(bot, ev)) + if config.nailong_mute_seconds > 0: + functions.append(lambda: mute(bot, ev, config.nailong_mute_seconds)) + punish_ok = (not functions) or (await execute_functions_any_ok(functions)) + template_str = config.nailong_tip if punish_ok else config.nailong_failed_tip await ( - UniMessage.template( - config.nailong_tip if recall_ok else config.nailong_failed_tip, - ) + UniMessage.template(template_str) .format_map( { "$event": ev, diff --git a/nonebot_plugin_nailongremove/uniapi/__init__.py b/nonebot_plugin_nailongremove/uniapi/__init__.py new file mode 100644 index 0000000..b19d43c --- /dev/null +++ b/nonebot_plugin_nailongremove/uniapi/__init__.py @@ -0,0 +1,2 @@ +from .mute import mute as mute +from .recall import recall as recall diff --git a/nonebot_plugin_nailongremove/uniapi/mute.py b/nonebot_plugin_nailongremove/uniapi/mute.py new file mode 100644 index 0000000..8e78b20 --- /dev/null +++ b/nonebot_plugin_nailongremove/uniapi/mute.py @@ -0,0 +1,135 @@ +from time import time +from typing import Awaitable, Callable, Dict, TypeVar +from typing_extensions import TypeAlias + +from nonebot.adapters import Bot as BaseBot, Event as BaseEvent + +Muter: TypeAlias = Callable[[BaseBot, BaseEvent, int], Awaitable[None]] +MT = TypeVar("MT", bound=Muter) + +muter_map: Dict[str, Muter] = {} + + +def muter(adapter_name: str): + def deco(func: MT) -> MT: + muter_map[adapter_name] = func + return func + + return deco + + +@muter("DoDo") +async def dodo(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.dodo import Bot, MessageEvent + + if not ( + isinstance(bot, Bot) + and isinstance(ev, MessageEvent) + and ev.island_source_id + and ev.dodo_source_id + ): + raise TypeError("Unsupported bot or event type") + + if seconds > 0: + await bot.set_member_mute_add( + island_source_id=ev.island_source_id, + dodo_source_id=ev.dodo_source_id, + duration=seconds, + ) + else: + await bot.set_member_mute_remove( + island_source_id=ev.island_source_id, + dodo_source_id=ev.dodo_source_id, + ) + + +@muter("Kritor") +async def kritor(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.kritor import Bot + from nonebot.adapters.kritor.event import GroupMessage + + if not (isinstance(bot, Bot) and isinstance(ev, GroupMessage)): + raise TypeError("Unsupported bot or event type") + + await bot.ban_member( + group=ev.sender.group_id, + target=ev.sender.uin, + duration=seconds, + ) + + +@muter("Mirai") +async def mirai(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.mirai import Bot + from nonebot.adapters.mirai.event import GroupMessage + + if not (isinstance(bot, Bot) and isinstance(ev, GroupMessage)): + raise TypeError("Unsupported bot or event type") + + await bot.mute_member(group=ev.sender.group.id, member=ev.sender.id, time=seconds) + + +@muter("OneBot V11") +async def onebot_v11(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent + + if not (isinstance(bot, Bot) and isinstance(ev, GroupMessageEvent)): + raise TypeError("Unsupported bot or event type") + + await bot.set_group_ban(group_id=ev.group_id, user_id=ev.user_id, duration=seconds) + + +@muter("RedProtocol") +async def red(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.red import Bot, GroupMessageEvent + + if not (isinstance(bot, Bot) and isinstance(ev, GroupMessageEvent)): + raise TypeError("Unsupported bot or event type") + + if seconds > 0: + await bot.mute_member(int(ev.peerUin), int(ev.senderUin), duration=seconds) + else: + await bot.unmute_member(int(ev.peerUin), int(ev.senderUin)) + + +@muter("Telegram") +async def telegram(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot.adapters.telegram import Bot + from nonebot.adapters.telegram.event import GroupMessageEvent + from nonebot.adapters.telegram.model import ChatPermissions + + if not (isinstance(bot, Bot) and isinstance(ev, GroupMessageEvent)): + raise TypeError("Unsupported bot or event type") + + await bot.restrict_chat_member( + chat_id=ev.chat.id, + user_id=ev.from_.id, + permissions=ChatPermissions(can_send_messages=seconds < 30), + until_date=int(time()) + seconds, + ) + + +@muter("Tailchat") +async def tailchat(bot: BaseBot, ev: BaseEvent, seconds: int): + from nonebot_adapter_tailchat import Bot + from nonebot_adapter_tailchat.event import MessageEvent + + if not ( + isinstance(bot, Bot) + and isinstance(ev, MessageEvent) + and ev.is_group() + and (group_id := ev.get_group_id()) + ): + raise TypeError("Unsupported bot or event type") + + await bot.muteGroupMember( + muteMs=seconds * 1000, + groupId=group_id, + memberId=ev.get_user_id(), + ) + + +async def mute(bot: BaseBot, ev: BaseEvent, seconds: int): + if f := muter_map.get(bot.adapter.get_name()): + return await f(bot, ev, seconds) + raise NotImplementedError diff --git a/nonebot_plugin_nailongremove/recall.py b/nonebot_plugin_nailongremove/uniapi/recall.py similarity index 99% rename from nonebot_plugin_nailongremove/recall.py rename to nonebot_plugin_nailongremove/uniapi/recall.py index fe05c06..9259bb0 100644 --- a/nonebot_plugin_nailongremove/recall.py +++ b/nonebot_plugin_nailongremove/uniapi/recall.py @@ -175,7 +175,6 @@ async def tailchat(bot: BaseBot, ev: BaseEvent): async def recall(bot: BaseBot, ev: BaseEvent): - f = recall_map.get(bot.adapter.get_name()) - if f: + if f := recall_map.get(bot.adapter.get_name()): return await f(bot, ev) raise NotImplementedError diff --git a/pdm.lock b/pdm.lock index fad688d..afd19c6 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "dev"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:b94ec67695f625d80df63fcbabe93a5208440011755c4a1c6fef461bc47334a6" +content_hash = "sha256:eda6f151d9722ddbc986c73c5debb21599fcc15c819af9d4e75497c1d78673ee" [[metadata.targets]] requires_python = "~=3.9" @@ -714,6 +714,7 @@ name = "mpmath" version = "1.3.0" summary = "Python library for arbitrary-precision floating-point arithmetic" groups = ["default"] +marker = "python_version >= \"3.9\"" files = [ {file = "mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}, {file = "mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f"}, @@ -1079,7 +1080,7 @@ files = [ [[package]] name = "nonebot-adapter-telegram" -version = "0.1.0b18" +version = "0.1.0b19" requires_python = "<4.0,>=3.9" summary = "Telegram Adapter for NoneBot2" groups = ["dev"] @@ -1089,8 +1090,8 @@ dependencies = [ "pydantic!=2.5.0,!=2.5.1,<3.0.0,>=2.0.3", ] files = [ - {file = "nonebot-adapter-telegram-0.1.0b18.tar.gz", hash = "sha256:233225f4d2fed8d720e10b631a761598dc23e6f51c2d2c4b1181b5f786f9d9db"}, - {file = "nonebot_adapter_telegram-0.1.0b18-py3-none-any.whl", hash = "sha256:1d0291c677ab8c90a83636955d51d376904fa59e8f6afbb709492443d6e70ba1"}, + {file = "nonebot-adapter-telegram-0.1.0b19.tar.gz", hash = "sha256:b741027a1b4828d69d2191e880b6e7919a342071e9bac0dcf5db58b44884b33f"}, + {file = "nonebot_adapter_telegram-0.1.0b19-py3-none-any.whl", hash = "sha256:59d0f63a49487c9558c99709958c9392243c2fb27b8032b830afb63b775f0a54"}, ] [[package]] @@ -1975,6 +1976,7 @@ version = "1.13.1" requires_python = ">=3.8" summary = "Computer algebra system (CAS) in Python" groups = ["default"] +marker = "python_version >= \"3.9\"" dependencies = [ "mpmath<1.4,>=1.1.0", ] diff --git a/pyproject.toml b/pyproject.toml index 8a4b1e2..0a9d535 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ dependencies = [ "opencv-python>=4.5", "numpy>=1.19", "keras>=2.4", - "pillow>=10", + "pillow>=9", "torch>=2.4", "torchvision>=0.19", "nonebot-plugin-alconna>=0.53.1",