aboutsummaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
-rw-r--r--hydroroll/bot.py22
-rw-r--r--hydroroll/config.py97
-rw-r--r--hydroroll/plugins/HydroRoll_plugin_dice/__init__.py51
-rw-r--r--hydroroll/plugins/HydroRoll_plugin_dice/config.py13
-rw-r--r--hydroroll/plugins/plugin_base/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_base/__init__.py)0
-rw-r--r--hydroroll/plugins/plugin_base/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_base/config.py)0
-rw-r--r--hydroroll/plugins/plugin_bot/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_bot/__init__.py)2
-rw-r--r--hydroroll/plugins/plugin_bot/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_bot/config.py)2
-rw-r--r--hydroroll/plugins/plugin_echo/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_echo/__init__.py)2
-rw-r--r--hydroroll/plugins/plugin_echo/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_echo/config.py)2
-rw-r--r--hydroroll/plugins/plugin_luck/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_luck/__init__.py)2
-rw-r--r--hydroroll/plugins/plugin_luck/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_luck/config.py)2
-rw-r--r--hydroroll/plugins/plugin_send/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_send/__init__.py)2
-rw-r--r--hydroroll/plugins/plugin_send/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_send/config.py)2
-rw-r--r--hydroroll/plugins/plugin_system/__init__.py (renamed from hydroroll/plugins/HydroRoll_plugin_system/__init__.py)2
-rw-r--r--hydroroll/plugins/plugin_system/config.py (renamed from hydroroll/plugins/HydroRoll_plugin_system/config.py)2
-rw-r--r--hydroroll/plugins/test.py8
-rw-r--r--tests/config.toml10
-rw-r--r--tests/config/userConf.datbin0 -> 140 bytes
-rw-r--r--tests/data/bot_info.json3
-rw-r--r--tests/data/reply_data.json17
-rw-r--r--tests/plugins/exc.py16
-rw-r--r--tests/plugins/iamai_plugin_base/__init__.py85
-rw-r--r--tests/plugins/iamai_plugin_base/config.py30
-rw-r--r--tests/plugins/iamai_plugin_reply/__init__.py43
-rw-r--r--tests/plugins/iamai_plugin_reply/config.py11
-rw-r--r--tests/plugins/test.py35
-rw-r--r--tests/rules/rules_default/wiki/config.toml (renamed from hydroroll/test.py)0
-rw-r--r--tests/rules/rules_default/wiki/default.json0
-rw-r--r--tests/test.py77
-rw-r--r--turbow.js19
31 files changed, 154 insertions, 403 deletions
diff --git a/hydroroll/bot.py b/hydroroll/bot.py
index c2b99e6..cbfc07f 100644
--- a/hydroroll/bot.py
+++ b/hydroroll/bot.py
@@ -2,13 +2,10 @@ 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()
+from hydroroll.config import GlobalConfig
-# 获取当前脚本文件路径
+current_dir = Path.cwd()
script_file = current_dir.resolve() / __file__
-
-# 获取当前脚本文件所在目录路径
script_dir = script_file.parent
__all__ = ["Bot"]
@@ -26,10 +23,7 @@ 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()
+ self.create_folder_structure(GlobalConfig._folder_dict)
def run(self) -> None:
self.bot.run()
@@ -53,12 +47,4 @@ class Bot:
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 6739249..4258606 100644
--- a/hydroroll/config.py
+++ b/hydroroll/config.py
@@ -4,9 +4,6 @@ import platform
from importlib.metadata import version
from iamai import Plugin
import os
-import pickle
-import threading
-
# 创建全局 ArgumentParser 对象
global_parser = argparse.ArgumentParser(description='hydroroll[水系] 全局命令参数')
@@ -20,8 +17,9 @@ 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__'))
-
+ _current_path = os.path.dirname(os.path.abspath('__file__'))
+ _folders = {'config':{},'data':{},'logs':{},'models':{},'rules':{'rules_default'},'users':{},'web':{'frontend':{'static','js','css','public'},'backend':{'app','template'}}}
+
# 定义系统组件
class HydroSystem:
def __init__(self):
@@ -34,91 +32,4 @@ class GlobalConfig:
class HydroBot:
def __init__(self) -> None:
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')
+ \ No newline at end of file
diff --git a/hydroroll/plugins/HydroRoll_plugin_dice/__init__.py b/hydroroll/plugins/HydroRoll_plugin_dice/__init__.py
deleted file mode 100644
index 2c9d2b4..0000000
--- a/hydroroll/plugins/HydroRoll_plugin_dice/__init__.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import re
-import random
-
-from iamai.log import logger
-
-from plugins.hydroroll_plugin_base import CommandPluginBase
-
-from .config import Config
-
-__all__ = ["Dice"]
-
-class Dice(CommandPluginBase[None, Config]):
- Config = Config
-
- def __post_init__(self):
- self.re_pattern = re.compile(
- r"\s*(?P<dice_times>\d+)d(?P<dice_faces>\d+)([*x](?P<dice_multiply>\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/hydroroll/plugins/HydroRoll_plugin_dice/config.py b/hydroroll/plugins/HydroRoll_plugin_dice/config.py
deleted file mode 100644
index 4846409..0000000
--- a/hydroroll/plugins/HydroRoll_plugin_dice/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Set
-
-from plugins.hydroroll_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/hydroroll/plugins/HydroRoll_plugin_base/__init__.py b/hydroroll/plugins/plugin_base/__init__.py
index a050ae1..a050ae1 100644
--- a/hydroroll/plugins/HydroRoll_plugin_base/__init__.py
+++ b/hydroroll/plugins/plugin_base/__init__.py
diff --git a/hydroroll/plugins/HydroRoll_plugin_base/config.py b/hydroroll/plugins/plugin_base/config.py
index 311874c..311874c 100644
--- a/hydroroll/plugins/HydroRoll_plugin_base/config.py
+++ b/hydroroll/plugins/plugin_base/config.py
diff --git a/hydroroll/plugins/HydroRoll_plugin_bot/__init__.py b/hydroroll/plugins/plugin_bot/__init__.py
index 2b3eec8..89ba17b 100644
--- a/hydroroll/plugins/HydroRoll_plugin_bot/__init__.py
+++ b/hydroroll/plugins/plugin_bot/__init__.py
@@ -1,6 +1,6 @@
import re
from importlib.metadata import version
-from plugins.hydroroll_plugin_base import CommandPluginBase
+from plugins.plugin_base import CommandPluginBase
from hydroroll.config import GlobalConfig
from .config import Config
diff --git a/hydroroll/plugins/HydroRoll_plugin_bot/config.py b/hydroroll/plugins/plugin_bot/config.py
index 717b7b2..640f23a 100644
--- a/hydroroll/plugins/HydroRoll_plugin_bot/config.py
+++ b/hydroroll/plugins/plugin_bot/config.py
@@ -1,6 +1,6 @@
from typing import Set
-from plugins.hydroroll_plugin_base import CommandPluginConfig
+from plugins.plugin_base import CommandPluginConfig
class Config(CommandPluginConfig):
diff --git a/hydroroll/plugins/HydroRoll_plugin_echo/__init__.py b/hydroroll/plugins/plugin_echo/__init__.py
index e800384..faa47df 100644
--- a/hydroroll/plugins/HydroRoll_plugin_echo/__init__.py
+++ b/hydroroll/plugins/plugin_echo/__init__.py
@@ -1,6 +1,6 @@
import re
-from plugins.hydroroll_plugin_base import CommandPluginBase
+from plugins.plugin_base import CommandPluginBase
from .config import Config
diff --git a/hydroroll/plugins/HydroRoll_plugin_echo/config.py b/hydroroll/plugins/plugin_echo/config.py
index 030bbec..c047134 100644
--- a/hydroroll/plugins/HydroRoll_plugin_echo/config.py
+++ b/hydroroll/plugins/plugin_echo/config.py
@@ -1,6 +1,6 @@
from typing import Set
-from plugins.hydroroll_plugin_base import CommandPluginConfig
+from plugins.plugin_base import CommandPluginConfig
class Config(CommandPluginConfig):
diff --git a/hydroroll/plugins/HydroRoll_plugin_luck/__init__.py b/hydroroll/plugins/plugin_luck/__init__.py
index a30c964..7967a0b 100644
--- a/hydroroll/plugins/HydroRoll_plugin_luck/__init__.py
+++ b/hydroroll/plugins/plugin_luck/__init__.py
@@ -2,7 +2,7 @@ import re
import time
import random
-from plugins.hydroroll_plugin_base import CommandPluginBase
+from plugins.plugin_base import CommandPluginBase
from .config import Config
diff --git a/hydroroll/plugins/HydroRoll_plugin_luck/config.py b/hydroroll/plugins/plugin_luck/config.py
index eeef14b..6190531 100644
--- a/hydroroll/plugins/HydroRoll_plugin_luck/config.py
+++ b/hydroroll/plugins/plugin_luck/config.py
@@ -1,6 +1,6 @@
from typing import Set
-from plugins.hydroroll_plugin_base import CommandPluginConfig
+from plugins.plugin_base import CommandPluginConfig
class Config(CommandPluginConfig):
diff --git a/hydroroll/plugins/HydroRoll_plugin_send/__init__.py b/hydroroll/plugins/plugin_send/__init__.py
index 234e5b3..2468189 100644
--- a/hydroroll/plugins/HydroRoll_plugin_send/__init__.py
+++ b/hydroroll/plugins/plugin_send/__init__.py
@@ -1,6 +1,6 @@
import re
-from plugins.hydroroll_plugin_base import CommandPluginBase
+from plugins.plugin_base import CommandPluginBase
from .config import Config
diff --git a/hydroroll/plugins/HydroRoll_plugin_send/config.py b/hydroroll/plugins/plugin_send/config.py
index 6903c0f..5b7fe7b 100644
--- a/hydroroll/plugins/HydroRoll_plugin_send/config.py
+++ b/hydroroll/plugins/plugin_send/config.py
@@ -1,6 +1,6 @@
from typing import Set, Optional
-from plugins.hydroroll_plugin_base import CommandPluginConfig
+from plugins.plugin_base import CommandPluginConfig
class Config(CommandPluginConfig):
diff --git a/hydroroll/plugins/HydroRoll_plugin_system/__init__.py b/hydroroll/plugins/plugin_system/__init__.py
index 6e4f232..ea797d3 100644
--- a/hydroroll/plugins/HydroRoll_plugin_system/__init__.py
+++ b/hydroroll/plugins/plugin_system/__init__.py
@@ -1,5 +1,5 @@
import re
-from plugins.hydroroll_plugin_base import CommandPluginBase
+from plugins.plugin_base import CommandPluginBase
from .config import Config
import psutil
import time
diff --git a/hydroroll/plugins/HydroRoll_plugin_system/config.py b/hydroroll/plugins/plugin_system/config.py
index 416fcbe..aa5f51b 100644
--- a/hydroroll/plugins/HydroRoll_plugin_system/config.py
+++ b/hydroroll/plugins/plugin_system/config.py
@@ -1,6 +1,6 @@
from typing import Set
-from plugins.hydroroll_plugin_base import CommandPluginConfig
+from plugins.plugin_base import CommandPluginConfig
class Config(CommandPluginConfig):
diff --git a/hydroroll/plugins/test.py b/hydroroll/plugins/test.py
new file mode 100644
index 0000000..01d0615
--- /dev/null
+++ b/hydroroll/plugins/test.py
@@ -0,0 +1,8 @@
+from iamai import Plugin
+
+class Test(Plugin):
+ async def handle(self) -> None:
+ ...
+
+ async def rule(self) -> None:
+ ... \ No newline at end of file
diff --git a/tests/config.toml b/tests/config.toml
index c3799b3..9088a86 100644
--- a/tests/config.toml
+++ b/tests/config.toml
@@ -1,13 +1,3 @@
-[hydroroll]
-version = "v0.1.0"
-svn = "1"
-author = "简律纯"
-
-[hydroroll.self]
-header = "Hydro系[1]号"
-# info = "一只水系骰子..."
-
-
[bot]
plugins = []
plugin_dirs = ["plugins"]
diff --git a/tests/config/userConf.dat b/tests/config/userConf.dat
new file mode 100644
index 0000000..ea150d9
--- /dev/null
+++ b/tests/config/userConf.dat
Binary files differ
diff --git a/tests/data/bot_info.json b/tests/data/bot_info.json
deleted file mode 100644
index 7890022..0000000
--- a/tests/data/bot_info.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- nick : "本大魔王"
-} \ No newline at end of file
diff --git a/tests/data/reply_data.json b/tests/data/reply_data.json
deleted file mode 100644
index e4977ee..0000000
--- a/tests/data/reply_data.json
+++ /dev/null
@@ -1,17 +0,0 @@
-[
- {
- "rule": "hello",
- "message": "你好!"
- },
- {
- "rule": "test",
- "message": [
- {
- "type": "text",
- "data": {
- "text": "测试"
- }
- }
- ]
- }
-] \ No newline at end of file
diff --git a/tests/plugins/exc.py b/tests/plugins/exc.py
new file mode 100644
index 0000000..7e453ed
--- /dev/null
+++ b/tests/plugins/exc.py
@@ -0,0 +1,16 @@
+from iamai import Plugin
+import os
+class Exec(Plugin):
+ async def handle(self) -> None:
+ from hydroroll.config import ConfigManager, GlobalConfig
+ tmpConf = ConfigManager(os.path.join(GlobalConfig._current_path, "config", "userConf.dat"))
+ tmpConf.load()
+ await self.event.reply(str(tmpConf.properties))
+
+
+ async def rule(self) -> bool:
+ if self.event.adapter.name != "cqhttp":
+ return False
+ if self.event.type != "message":
+ return False
+ return self.event.message.startswith("t") \ No newline at end of file
diff --git a/tests/plugins/iamai_plugin_base/__init__.py b/tests/plugins/iamai_plugin_base/__init__.py
deleted file mode 100644
index 8fe559b..0000000
--- a/tests/plugins/iamai_plugin_base/__init__.py
+++ /dev/null
@@ -1,85 +0,0 @@
-import re
-from abc import ABC, abstractmethod
-from typing import Type, Union, Generic, TypeVar
-
-from iamai import Plugin
-from iamai.typing import T_State
-from iamai.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_sent":
- 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<command_args>.*)",
- 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/tests/plugins/iamai_plugin_base/config.py b/tests/plugins/iamai_plugin_base/config.py
deleted file mode 100644
index 04924e0..0000000
--- a/tests/plugins/iamai_plugin_base/config.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Set, Optional
-
-from iamai import ConfigModel
-
-
-class BasePluginConfig(ConfigModel):
- __config_name__ = ""
- handle_all_message: bool = True
- """是否处理所有类型的消息,此配置为 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/tests/plugins/iamai_plugin_reply/__init__.py b/tests/plugins/iamai_plugin_reply/__init__.py
deleted file mode 100644
index 6835ca8..0000000
--- a/tests/plugins/iamai_plugin_reply/__init__.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import re
-import json
-
-from plugins.iamai_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",encoding="utf-8") 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/tests/plugins/iamai_plugin_reply/config.py b/tests/plugins/iamai_plugin_reply/config.py
deleted file mode 100644
index e024fb6..0000000
--- a/tests/plugins/iamai_plugin_reply/config.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from plugins.iamai_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/tests/plugins/test.py b/tests/plugins/test.py
new file mode 100644
index 0000000..6f3bc3b
--- /dev/null
+++ b/tests/plugins/test.py
@@ -0,0 +1,35 @@
+from iamai import Plugin
+from iamai.exceptions import GetEventTimeout
+
+
+class Weather(Plugin):
+ async def handle(self) -> None:
+ args = self.event.get_plain_text().split(" ")
+ if len(args) >= 2:
+ await self.event.reply(await self.get_weather(args[1]))
+ else:
+ await self.event.reply("请输入想要查询天气的城市:")
+ try:
+ city_event = await self.event.adapter.get(
+ lambda x: x.type == "message", timeout=10
+ )
+ except GetEventTimeout:
+ return
+ else:
+ await self.event.reply(
+ await self.get_weather(city_event.get_plain_text())
+ )
+
+ async def rule(self) -> bool:
+ if self.event.adapter.name != "cqhttp":
+ return False
+ if self.event.type != "message":
+ return False
+ return self.event.message.startswith("天气")
+
+ @staticmethod
+ async def get_weather(city):
+ if city not in ["北京", "上海"]:
+ return "你想查询的城市暂不支持!"
+ return f"{city}的天气是..."
+
diff --git a/hydroroll/test.py b/tests/rules/rules_default/wiki/config.toml
index e69de29..e69de29 100644
--- a/hydroroll/test.py
+++ b/tests/rules/rules_default/wiki/config.toml
diff --git a/tests/rules/rules_default/wiki/default.json b/tests/rules/rules_default/wiki/default.json
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/rules/rules_default/wiki/default.json
diff --git a/tests/test.py b/tests/test.py
new file mode 100644
index 0000000..8c3807b
--- /dev/null
+++ b/tests/test.py
@@ -0,0 +1,77 @@
+import threading
+import pickle
+import os
+
+
+class ConfigManager:
+ def __init__(self, filename):
+ self.lock = threading.RLock()
+ self.filename = filename
+ try:
+ with open(filename, 'rb') as f:
+ self.data = pickle.load(f)
+ except FileNotFoundError:
+ self.data = {}
+
+ self.properties = {}
+ self.apis = {}
+
+ def load(self):
+ with self.lock:
+ try:
+ with open(self.filename, 'rb') as f:
+ self.data = pickle.load(f)
+ self.properties.update(self.data)
+ except FileNotFoundError:
+ self.data = {}
+
+ def save(self):
+ with self.lock:
+ try:
+ with open(self.filename, 'wb') as f:
+ # 将self.properties字典中的内容合并至self.data字典中
+ for k, v in self.properties.items():
+ self.data[k] = v
+ # 将self.apis字典中的函数状态保存至self.data字典中
+ for k, v in self.apis.items():
+ if v is not None:
+ self.data[k] = v
+ pickle.dump(self.data, f)
+ except Exception as e:
+ print('Error saving config data:', repr(e))
+ raise
+
+ def register_property(self, name, default_value):
+ self.properties[name] = default_value
+
+ def getter(self, default_value=default_value):
+ with self.lock:
+ return self.data.get(name, default_value)
+
+ def setter(self, value):
+ with self.lock:
+ self.data[name] = value
+
+ setattr(ConfigManager, name, property(getter, setter))
+
+ def register_api(self, name, func, default_value=None):
+ self.apis[name] = default_value
+
+ def wrapper(*args, **kwargs):
+ with self.lock:
+ return func(*args, **kwargs)
+
+ setattr(ConfigManager, name, wrapper)
+
+
+c = ConfigManager("test.dat")
+
+# c.register_property("bot_off_list", [999, 777])
+# def send_message(self, message):
+# print("Sending message:", message)
+
+# c.register_api("send_message", send_message, default_value="Hello, world!")
+
+# c.save()
+c.load()
+print(c.properties,c.properties['bot_off_list'],c.apis)
diff --git a/turbow.js b/turbow.js
deleted file mode 100644
index e133ae3..0000000
--- a/turbow.js
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env node
-
-const path = require("path");
-
-let binPath;
-if (path.sep === "\\") {
- binPath = ".\\target\\debug\\turbo.exe";
-} else {
- binPath = "./target/debug/turbo";
-}
-
-try {
- require("child_process").execFileSync(binPath, process.argv.slice(2), {
- stdio: "inherit",
- });
-} catch (e) {
- if (e && e.status) process.exit(e.status);
- throw e;
-}