From 025020c503ef5b8dc0270197c5b1e6d4e0f8807d Mon Sep 17 00:00:00 2001 From: 简律纯 Date: Tue, 18 Apr 2023 18:03:02 +0800 Subject: ✨本体文件 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/alicebot_plugin_base/__init__.py | 85 +++++++++++++++++++++++++++++++ plugins/alicebot_plugin_base/config.py | 30 +++++++++++ plugins/alicebot_plugin_dice/__init__.py | 50 ++++++++++++++++++ plugins/alicebot_plugin_dice/config.py | 13 +++++ plugins/alicebot_plugin_echo/__init__.py | 17 +++++++ plugins/alicebot_plugin_echo/config.py | 11 ++++ plugins/alicebot_plugin_luck/__init__.py | 21 ++++++++ plugins/alicebot_plugin_luck/config.py | 15 ++++++ plugins/alicebot_plugin_reply/__init__.py | 43 ++++++++++++++++ plugins/alicebot_plugin_reply/config.py | 11 ++++ plugins/alicebot_plugin_send/__init__.py | 28 ++++++++++ plugins/alicebot_plugin_send/config.py | 15 ++++++ 12 files changed, 339 insertions(+) create mode 100644 plugins/alicebot_plugin_base/__init__.py create mode 100644 plugins/alicebot_plugin_base/config.py create mode 100644 plugins/alicebot_plugin_dice/__init__.py create mode 100644 plugins/alicebot_plugin_dice/config.py create mode 100644 plugins/alicebot_plugin_echo/__init__.py create mode 100644 plugins/alicebot_plugin_echo/config.py create mode 100644 plugins/alicebot_plugin_luck/__init__.py create mode 100644 plugins/alicebot_plugin_luck/config.py create mode 100644 plugins/alicebot_plugin_reply/__init__.py create mode 100644 plugins/alicebot_plugin_reply/config.py create mode 100644 plugins/alicebot_plugin_send/__init__.py create mode 100644 plugins/alicebot_plugin_send/config.py (limited to 'plugins') diff --git a/plugins/alicebot_plugin_base/__init__.py b/plugins/alicebot_plugin_base/__init__.py new file mode 100644 index 0000000..a36fb78 --- /dev/null +++ b/plugins/alicebot_plugin_base/__init__.py @@ -0,0 +1,85 @@ +import re +from abc import ABC, abstractmethod +from typing import Type, Union, Generic, TypeVar + +from alicebot import Plugin +from alicebot.typing import T_State +from alicebot.adapter.cqhttp.event import GroupMessageEvent, PrivateMessageEvent + +from .config import BasePluginConfig, RegexPluginConfig, CommandPluginConfig + +T_Config = TypeVar("T_Config", bound=BasePluginConfig) +T_RegexPluginConfig = TypeVar("T_RegexPluginConfig", bound=RegexPluginConfig) +T_CommandPluginConfig = TypeVar("T_CommandPluginConfig", bound=CommandPluginConfig) + + +class BasePlugin( + Plugin[Union[PrivateMessageEvent, GroupMessageEvent], T_State, T_Config], + ABC, + Generic[T_State, T_Config], +): + Config: Type[T_Config] = BasePluginConfig + + def format_str(self, format_str: str, message_str: str = "") -> str: + return format_str.format( + message=message_str, + user_name=self.event.sender.nickname, + user_id=self.event.sender.user_id, + ) + + async def rule(self) -> bool: + if self.event.adapter.name != "cqhttp": + return False + if self.event.type != "message": + return False + if self.config.handle_all_message: + return self.str_match(self.event.message.get_plain_text()) + elif self.config.handle_friend_message: + if self.event.message_type == "private": + return self.str_match(self.event.message.get_plain_text()) + elif self.config.handle_group_message: + if self.event.message_type == "group": + if ( + self.config.accept_group is None + or self.event.group_id in self.config.accept_group + ): + return self.str_match(self.event.message.get_plain_text()) + return False + + @abstractmethod + def str_match(self, msg_str: str) -> bool: + raise NotImplemented + + +class RegexPluginBase(BasePlugin[T_State, T_RegexPluginConfig], ABC): + msg_match: re.Match + re_pattern: re.Pattern + Config: Type[T_RegexPluginConfig] = RegexPluginConfig + + def str_match(self, msg_str: str) -> bool: + msg_str = msg_str.strip() + self.msg_match = self.re_pattern.fullmatch(msg_str) + return bool(self.msg_match) + + +class CommandPluginBase(RegexPluginBase[T_State, T_CommandPluginConfig], ABC): + command_match: re.Match + command_re_pattern: re.Pattern + Config: Type[T_CommandPluginConfig] = CommandPluginConfig + + def str_match(self, msg_str: str) -> bool: + if not hasattr(self, "command_re_pattern"): + self.command_re_pattern = re.compile( + f'({"|".join(self.config.command_prefix)})' + f'({"|".join(self.config.command)})' + r"\s*(?P.*)", + flags=re.I if self.config.ignore_case else 0, + ) + msg_str = msg_str.strip() + self.command_match = self.command_re_pattern.fullmatch(msg_str) + if not self.command_match: + return False + self.msg_match = self.re_pattern.fullmatch( + self.command_match.group("command_args") + ) + return bool(self.msg_match) diff --git a/plugins/alicebot_plugin_base/config.py b/plugins/alicebot_plugin_base/config.py new file mode 100644 index 0000000..24e5ecf --- /dev/null +++ b/plugins/alicebot_plugin_base/config.py @@ -0,0 +1,30 @@ +from typing import Set, Optional + +from alicebot import ConfigModel + + +class BasePluginConfig(ConfigModel): + __config_name__ = "" + handle_all_message: bool = False + """是否处理所有类型的消息,此配置为 True 时会覆盖 handle_friend_message 和 handle_group_message。""" + handle_friend_message: bool = True + """是否处理好友消息。""" + handle_group_message: bool = True + """是否处理群消息。""" + accept_group: Optional[Set[int]] = None + """处理消息的群号,仅当 handle_group_message 为 True 时生效,留空表示处理所有群。""" + message_str: str = "{user_name}: {message}" + """最终发送消息的格式。""" + + +class RegexPluginConfig(BasePluginConfig): + pass + + +class CommandPluginConfig(RegexPluginConfig): + command_prefix: Set[str] = {".", "。"} + """命令前缀。""" + command: Set[str] = {} + """命令文本。""" + ignore_case: bool = True + """忽略大小写。""" diff --git a/plugins/alicebot_plugin_dice/__init__.py b/plugins/alicebot_plugin_dice/__init__.py new file mode 100644 index 0000000..528ba2b --- /dev/null +++ b/plugins/alicebot_plugin_dice/__init__.py @@ -0,0 +1,50 @@ +import re +import random + +from alicebot.log import logger + +from plugins.alicebot_plugin_base import CommandPluginBase + +from .config import Config + + +class Dice(CommandPluginBase[None, Config]): + Config = Config + + def __post_init__(self): + self.re_pattern = re.compile( + r"\s*(?P\d+)d(?P\d+)([*x](?P\d+))?", + flags=re.I, + ) + + async def handle(self) -> None: + dice_times = int(self.msg_match.group("dice_times")) + dice_faces = int(self.msg_match.group("dice_faces")) + if self.msg_match.group("dice_multiply") is None: + dice_multiply = None + else: + dice_multiply = int(self.msg_match.group("dice_multiply")) + + if dice_times > self.config.max_dice_times: + await self.event.reply( + self.format_str(self.config.exceed_max_dice_times_str) + ) + return + + dice = [random.randint(1, dice_faces) for _ in range(dice_times)] + dice_sum = sum(dice) + if dice_multiply is None: + result_str = f"{dice_times}D{dice_faces}=" + if dice_times != 1: + result_str += f"{'+'.join(map(lambda x: str(x), dice))}=" + result_str += str(dice_sum) + else: + result_str = f"{dice_times}D{dice_faces}X{dice_multiply}=" + if dice_times != 1: + result_str += ( + f"({'+'.join(map(lambda x: str(x), dice))})X{dice_multiply}=" + ) + result_str += f"{dice_sum}X{dice_multiply}={dice_sum * dice_multiply}" + + logger.info(f"Dice Plugin: {result_str}") + await self.event.reply(self.format_str(self.config.message_str, result_str)) diff --git a/plugins/alicebot_plugin_dice/config.py b/plugins/alicebot_plugin_dice/config.py new file mode 100644 index 0000000..716e753 --- /dev/null +++ b/plugins/alicebot_plugin_dice/config.py @@ -0,0 +1,13 @@ +from typing import Set + +from plugins.alicebot_plugin_base import CommandPluginConfig + + +class Config(CommandPluginConfig): + __config_name__ = "plugin_dice" + command: Set[str] = {"r", "roll", "dice"} + """命令文本。""" + max_dice_times: int = 1000 + """最大单次投掷次数。""" + exceed_max_dice_times_str: str = "错误:超过最大投掷次数。" + """超过最大单次投掷次数时的提示语。""" diff --git a/plugins/alicebot_plugin_echo/__init__.py b/plugins/alicebot_plugin_echo/__init__.py new file mode 100644 index 0000000..e439319 --- /dev/null +++ b/plugins/alicebot_plugin_echo/__init__.py @@ -0,0 +1,17 @@ +import re + +from plugins.alicebot_plugin_base import CommandPluginBase + +from .config import Config + + +class Echo(CommandPluginBase[None, Config]): + Config = Config + + def __post_init__(self): + self.re_pattern = re.compile(r"(?P.*)", flags=re.I) + + async def handle(self) -> None: + await self.event.reply( + self.format_str(self.config.message_str, self.msg_match.group("echo_str")) + ) diff --git a/plugins/alicebot_plugin_echo/config.py b/plugins/alicebot_plugin_echo/config.py new file mode 100644 index 0000000..8908bf2 --- /dev/null +++ b/plugins/alicebot_plugin_echo/config.py @@ -0,0 +1,11 @@ +from typing import Set + +from plugins.alicebot_plugin_base import CommandPluginConfig + + +class Config(CommandPluginConfig): + __config_name__ = "plugin_echo" + command: Set[str] = {"echo"} + """命令文本。""" + message_str: str = "复读{user_name}: {message}" + """最终发送消息的格式。""" diff --git a/plugins/alicebot_plugin_luck/__init__.py b/plugins/alicebot_plugin_luck/__init__.py new file mode 100644 index 0000000..d033464 --- /dev/null +++ b/plugins/alicebot_plugin_luck/__init__.py @@ -0,0 +1,21 @@ +import re +import time +import random + +from plugins.alicebot_plugin_base import CommandPluginBase + +from .config import Config + + +class Luck(CommandPluginBase[None, Config]): + Config = Config + + def __post_init__(self): + self.re_pattern = re.compile(r".*", flags=re.I) + + async def handle(self) -> None: + random.seed( + time.strftime("%Y%j", time.localtime()) + self.format_str("{user_id}") + ) + lucy = random.randint(self.config.min_int, self.config.max_int) + await self.event.reply(self.format_str(self.config.message_str, str(lucy))) diff --git a/plugins/alicebot_plugin_luck/config.py b/plugins/alicebot_plugin_luck/config.py new file mode 100644 index 0000000..b8b3e70 --- /dev/null +++ b/plugins/alicebot_plugin_luck/config.py @@ -0,0 +1,15 @@ +from typing import Set + +from plugins.alicebot_plugin_base import CommandPluginConfig + + +class Config(CommandPluginConfig): + __config_name__ = "plugin_luck" + command: Set[str] = {"luck"} + """命令文本。""" + min_int: int = 0 + """最小随机整数。""" + max_int: int = 100 + """最大随机整数。""" + message_str: str = "{user_name}今天的运气是: {message}" + """最终发送消息的格式。""" diff --git a/plugins/alicebot_plugin_reply/__init__.py b/plugins/alicebot_plugin_reply/__init__.py new file mode 100644 index 0000000..396f276 --- /dev/null +++ b/plugins/alicebot_plugin_reply/__init__.py @@ -0,0 +1,43 @@ +import re +import json + +from plugins.alicebot_plugin_base import BasePlugin + +from .config import Config + + +class Reply(BasePlugin[None, Config]): + priority: int = 1 + Config = Config + + def __post_init__(self): + with open(self.config.data_file, "r") as fp: + if self.config.data_type == "json": + json_data = json.load(fp) + else: + raise ValueError(f"data_type must be json, not {self.config.data_type}") + self.rule_to_message = { + item["rule"]: item["message"] + for item in json_data + if isinstance(item, dict) + and "rule" in item.keys() + and "message" in item.keys() + } + + async def handle(self) -> None: + msg = self.rule_to_message[self.msg_match.re.pattern] + if isinstance(msg, str): + await self.event.reply(self.format_str(msg, self.msg_match.string)) + else: + await self.event.reply(msg) + + def str_match(self, msg_str: str) -> bool: + msg_str = msg_str.strip() + for rule in self.rule_to_message.keys(): + msg_match = re.fullmatch( + rule, msg_str, flags=re.I if self.config.ignore_case else 0 + ) + if msg_match: + self.msg_match = msg_match + return bool(self.msg_match) + return False diff --git a/plugins/alicebot_plugin_reply/config.py b/plugins/alicebot_plugin_reply/config.py new file mode 100644 index 0000000..f4f01f4 --- /dev/null +++ b/plugins/alicebot_plugin_reply/config.py @@ -0,0 +1,11 @@ +from plugins.alicebot_plugin_base import CommandPluginConfig + + +class Config(CommandPluginConfig): + __config_name__ = "plugin_reply" + data_type: str = "json" + """数据类型,目前只支持 json。""" + data_file: str = "data/reply_data.json" + """数据文件位置。""" + ignore_case: bool = True + """是否忽略大小写,默认为 True。""" diff --git a/plugins/alicebot_plugin_send/__init__.py b/plugins/alicebot_plugin_send/__init__.py new file mode 100644 index 0000000..46264ed --- /dev/null +++ b/plugins/alicebot_plugin_send/__init__.py @@ -0,0 +1,28 @@ +import re + +from plugins.alicebot_plugin_base import CommandPluginBase + +from .config import Config + + +class Send(CommandPluginBase[None, Config]): + Config = Config + + def __post_init__(self): + self.re_pattern = re.compile(r"\s*(?P.*)", flags=re.I) + + async def handle(self) -> None: + try: + await self.event.adapter.send( + self.msg_match.group("message"), + "private", + self.config.send_user_id, + ) + except Exception as e: + if self.config.send_filed_msg is not None: + await self.event.reply( + self.format_str(self.config.send_filed_msg, repr(e)) + ) + else: + if self.config.send_success_msg is not None: + await self.event.reply(self.format_str(self.config.send_success_msg)) diff --git a/plugins/alicebot_plugin_send/config.py b/plugins/alicebot_plugin_send/config.py new file mode 100644 index 0000000..85f794a --- /dev/null +++ b/plugins/alicebot_plugin_send/config.py @@ -0,0 +1,15 @@ +from typing import Set, Optional + +from plugins.alicebot_plugin_base import CommandPluginConfig + + +class Config(CommandPluginConfig): + __config_name__ = "plugin_send" + command: Set[str] = {"send"} + """命令文本。""" + send_user_id: int = 0 + """发送消息的对象的 QQ 号码。""" + send_success_msg: Optional[str] = None + """发送成功时回复的消息,设置为 None 表示不发送任何消息。""" + send_filed_msg: Optional[str] = "发送失败:{message}" + """发送失败时回复的消息。""" -- cgit v1.2.3-70-g09d2