diff options
| -rw-r--r-- | HydroRoll/bot.py | 34 | ||||
| -rw-r--r-- | HydroRoll/config.py | 97 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_base/__init__.py | 18 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_base/config.py | 2 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py | 12 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_echo/config.py | 2 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_send/config.py | 2 | ||||
| -rw-r--r-- | HydroRoll/plugins/HydroRoll_plugin_system/__init__.py | 4 | ||||
| -rw-r--r-- | HydroRoll/test.py | 0 | ||||
| -rw-r--r-- | pyproject.toml | 4 |
10 files changed, 155 insertions, 20 deletions
diff --git a/HydroRoll/bot.py b/HydroRoll/bot.py index 9dcc623..c2b99e6 100644 --- a/HydroRoll/bot.py +++ b/HydroRoll/bot.py @@ -1,7 +1,7 @@ from iamai import Bot as _Bot from typing import Optional, Dict, List, Type, Any, Union from pathlib import Path - +import os # 获取当前目录路径 current_dir = Path.cwd() @@ -26,9 +26,39 @@ class Bot: config_dict=config_dict ) self.bot.load_plugins_from_dirs(Path(f"{script_dir}/plugins")) + self.create_folders() + self.init_data() + self.init_conf() + self.init_webui() def run(self) -> None: self.bot.run() def restart(self) -> None: - self.bot.restart()
\ No newline at end of file + self.bot.restart() + + def create_folders(self): + folder_path = os.path.dirname(os.path.abspath('__file__')) # 获取main.py所在文件夹路径 + if not os.path.isdir(os.path.join(folder_path, 'user')): + os.mkdir(os.path.join(folder_path, 'user')) + if not os.path.isdir(os.path.join(folder_path, 'data')): + os.mkdir(os.path.join(folder_path, 'data')) + if not os.path.isdir(os.path.join(folder_path, 'models')): + os.mkdir(os.path.join(folder_path, 'models')) + if not os.path.isdir(os.path.join(folder_path, 'web')): + os.mkdir(os.path.join(folder_path, 'web')) + if not os.path.isdir(os.path.join(folder_path, 'config')): + os.mkdir(os.path.join(folder_path, 'config')) + if not os.path.isdir(os.path.join(folder_path, 'logs')): + os.mkdir(os.path.join(folder_path, 'logs')) + if not os.path.isdir(os.path.join(folder_path, 'rules')): + os.mkdir(os.path.join(folder_path, 'rules')) + + def init_data(self): + ... + + def init_webui(self): + ... + + def init_conf(self): + ...
\ No newline at end of file diff --git a/HydroRoll/config.py b/HydroRoll/config.py index 1e132e4..2029575 100644 --- a/HydroRoll/config.py +++ b/HydroRoll/config.py @@ -3,6 +3,11 @@ import sys import platform from importlib.metadata import version from iamai import Plugin +import os +import pickle +import threading + + # 创建全局 ArgumentParser 对象 global_parser = argparse.ArgumentParser(description='HydroRoll[水系] 全局命令参数') @@ -15,6 +20,8 @@ class GlobalConfig: _iamai_version = version('iamai') _python_ver = sys.version _python_ver_raw= '.'.join(map(str, platform.python_version_tuple()[:3])) + current_path = os.path.dirname(os.path.abspath('__file__')) + # 定义系统组件 class HydroSystem: def __init__(self): @@ -26,4 +33,92 @@ class GlobalConfig: self.help = '\n'.join(self.parser.format_help().replace('\r\n', '\n').replace('\r', '').split('\n')[2:-3]) class HydroBot: def __init__(self) -> None: - self.parser = argparse.ArgumentParser(description="Bot命令")
\ No newline at end of file + self.parser = argparse.ArgumentParser(description="Bot命令") + + +class ConfigManager: + def __init__(self, directory): + self.directory = directory + self.configs = {} + self.locks = {} + + def get(self, filename, section, key, default=None): + if not self._check_file_exists(filename): + return default + config = self._get_config(filename) + if section not in config: + return default + return config[section].get(key, default) + + def set(self, filename, section, key, value): + config = self._get_config(filename) + if section not in config: + config[section] = {} + config[section][key] = value + self._save_config(filename, config) + + def delete(self, filename, section, key): + config = self._get_config(filename) + if section not in config: + return + if key not in config[section]: + return + del config[section][key] + self._save_config(filename, config) + + def sections(self, filename): + if not self._check_file_exists(filename): + return [] + config = self._get_config(filename) + return list(config.keys()) + + def section_items(self, filename, section): + if not self._check_file_exists(filename): + return [] + config = self._get_config(filename) + if section not in config: + return [] + return list(config[section].items()) + + def files(self): + return [filename for filename in os.listdir(self.directory) if filename.endswith('.dat')] + + def _get_lock(self, filename): + if filename not in self.locks: + self.locks[filename] = threading.Lock() + return self.locks[filename] + + def _get_config(self, filename): + with self._get_lock(filename): + if filename not in self.configs: + filepath = os.path.join(self.directory, filename) + if os.path.exists(filepath): + try: + with open(filepath, 'rb') as f: + self.configs[filename] = pickle.load(f) + except: + pass + if filename not in self.configs: + self.configs[filename] = {} + return self.configs[filename] + + def _save_config(self, filename, config): + with self._get_lock(filename): + try: + filepath = os.path.join(self.directory, filename) + backuppath = os.path.join(self.directory, filename + '.bak') + lockpath = os.path.join(self.directory, filename + '.lock') + with open(lockpath, 'wb') as f: + pass + if os.path.exists(filepath): + os.replace(filepath, backuppath) + with open(filepath, 'wb') as f: + pickle.dump(config, f) + os.remove(backuppath) + os.remove(lockpath) + except: + pass + + def _check_file_exists(self, filename): + filepath = os.path.join(self.directory, filename) + return os.path.exists(filepath) and filename.endswith('.dat') diff --git a/HydroRoll/plugins/HydroRoll_plugin_base/__init__.py b/HydroRoll/plugins/HydroRoll_plugin_base/__init__.py index 8fe559b..a050ae1 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_base/__init__.py +++ b/HydroRoll/plugins/HydroRoll_plugin_base/__init__.py @@ -28,22 +28,30 @@ class BasePlugin( ) async def rule(self) -> bool: + is_bot_off = True + if self.event.adapter.name != "cqhttp": return False - if self.event.type != "message_sent": + if self.event.type != "message": return False + match_str = self.event.message.get_plain_text() + if is_bot_off: + if self.event.message.startswith(f'[CQ:at,qq={self.event.self_id}]'): + match_str = re.sub(fr'^\[CQ:at,qq={self.event.self_id}\]', '', match_str) + else: + return False if self.config.handle_all_message: - return self.str_match(self.event.message.get_plain_text()) + return self.str_match(match_str) elif self.config.handle_friend_message: if self.event.message_type == "private": - return self.str_match(self.event.message.get_plain_text()) + return self.str_match(match_str) 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 self.str_match(match_str) return False @abstractmethod @@ -82,4 +90,4 @@ class CommandPluginBase(RegexPluginBase[T_State, T_CommandPluginConfig], ABC): self.msg_match = self.re_pattern.fullmatch( self.command_match.group("command_args") ) - return bool(self.msg_match) + return bool(self.msg_match)
\ No newline at end of file diff --git a/HydroRoll/plugins/HydroRoll_plugin_base/config.py b/HydroRoll/plugins/HydroRoll_plugin_base/config.py index 04924e0..311874c 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_base/config.py +++ b/HydroRoll/plugins/HydroRoll_plugin_base/config.py @@ -13,7 +13,7 @@ class BasePluginConfig(ConfigModel): """是否处理群消息。""" accept_group: Optional[Set[int]] = None """处理消息的群号,仅当 handle_group_message 为 True 时生效,留空表示处理所有群。""" - message_str: str = "{user_name}: {message}" + message_str: str = "*{user_name} {message}" """最终发送消息的格式。""" diff --git a/HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py b/HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py index fb37d4c..d07aaf8 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py +++ b/HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py @@ -15,12 +15,12 @@ class HydroBot(CommandPluginBase[None, Config]): self.re_pattern = re.compile(r"(?P<bot_info_str>.*)", flags=re.I) def bot_info(self): - info_str = f'{self.CurrentConfig._name} ' - info_str += f'{self.CurrentConfig._version}({self.CurrentConfig._svn}) ' - info_str += f'by {self.CurrentConfig._author} ' - info_str += f'on Python {self.CurrentConfig._python_ver_raw}\n' - info_str += f'with {" & ".join([adapter + "("+version("iamai-adapter-"+adapter) +")" for adapter in dict(self.bot.config.adapter)])}\n' - info_str += f'for iamai({self.CurrentConfig._iamai_version})' + info_str = f'{self.CurrentConfig._name} '\ + f'{self.CurrentConfig._version}({self.CurrentConfig._svn}) '\ + f'by {self.CurrentConfig._author} '\ + f'on Python {self.CurrentConfig._python_ver_raw} '\ + f'with {" & ".join([adapter + "("+version("iamai-adapter-"+adapter) +")" for adapter in dict(self.bot.config.adapter)])} '\ + f'for iamai({self.CurrentConfig._iamai_version})' return info_str diff --git a/HydroRoll/plugins/HydroRoll_plugin_echo/config.py b/HydroRoll/plugins/HydroRoll_plugin_echo/config.py index b82b85d..976411f 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_echo/config.py +++ b/HydroRoll/plugins/HydroRoll_plugin_echo/config.py @@ -7,5 +7,5 @@ class Config(CommandPluginConfig): __config_name__ = "plugin_echo" command: Set[str] = {"echo"} """命令文本。""" - message_str: str = "复读{user_name}: {message}" + message_str: str = "*{user_name} {message}" """最终发送消息的格式。""" diff --git a/HydroRoll/plugins/HydroRoll_plugin_send/config.py b/HydroRoll/plugins/HydroRoll_plugin_send/config.py index f6559d6..1c554ab 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_send/config.py +++ b/HydroRoll/plugins/HydroRoll_plugin_send/config.py @@ -9,7 +9,7 @@ class Config(CommandPluginConfig): """命令文本。""" send_user_id: int = 2753364619 """发送消息的对象的 QQ 号码。""" - send_success_msg: Optional[str] = "本大魔王已将消息送出√" + send_success_msg: Optional[str] = "已将消息送出√" """发送成功时回复的消息,设置为 None 表示不发送任何消息。""" send_filed_msg: Optional[str] = "发送失败:{message}" """发送失败时回复的消息。""" diff --git a/HydroRoll/plugins/HydroRoll_plugin_system/__init__.py b/HydroRoll/plugins/HydroRoll_plugin_system/__init__.py index bbb7190..d7f8d21 100644 --- a/HydroRoll/plugins/HydroRoll_plugin_system/__init__.py +++ b/HydroRoll/plugins/HydroRoll_plugin_system/__init__.py @@ -4,10 +4,11 @@ from .config import Config import psutil import time from HydroRoll.config import GlobalConfig - +from iamai.adapter.cqhttp.message import CQHTTPMessageSegment class System(CommandPluginBase[None, Config]): priority: int = 0 + block: bool = True Config = Config CurrentConfig = GlobalConfig @@ -69,5 +70,6 @@ class System(CommandPluginBase[None, Config]): ) else: await self.event.reply( + CQHTTPMessageSegment.reply(self.event.message_id) + self.format_str(self.config.message_str, system.help) ) diff --git a/HydroRoll/test.py b/HydroRoll/test.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/HydroRoll/test.py diff --git a/pyproject.toml b/pyproject.toml index c0db4c6..a778812 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,11 +1,11 @@ [tool.poetry] name = "HydroRoll" version = "0.1.1" -description = "ChienDice" +description = "A new Dice" license = "MIT" authors = ["HsiangNianian <admin@jyunko.cn>"] readme = "README.md" -repository = "https://github.com/retrofor/ChienDice" +repository = "https://github.com/retrofor/HydroRoll" [tool.poetry.dependencies] python = "^3.8" |
