Skip to content

Commit

Permalink
No commit message
Browse files Browse the repository at this point in the history
  • Loading branch information
HsiangNianian committed Apr 27, 2023
1 parent b30315c commit 3fe9671
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 20 deletions.
34 changes: 32 additions & 2 deletions HydroRoll/bot.py
Original file line number Diff line number Diff line change
@@ -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()

Expand All @@ -26,9 +26,39 @@ def __init__(
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()
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):
...
97 changes: 96 additions & 1 deletion HydroRoll/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import platform
from importlib.metadata import version
from iamai import Plugin
import os
import pickle
import threading


# 创建全局 ArgumentParser 对象
global_parser = argparse.ArgumentParser(description='HydroRoll[水系] 全局命令参数')

Expand All @@ -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):
Expand All @@ -26,4 +33,92 @@ def __init__(self):
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命令")
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')
18 changes: 13 additions & 5 deletions HydroRoll/plugins/HydroRoll_plugin_base/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,30 @@ def format_str(self, format_str: str, message_str: str = "") -> str:
)

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
Expand Down Expand Up @@ -82,4 +90,4 @@ def str_match(self, msg_str: str) -> bool:
self.msg_match = self.re_pattern.fullmatch(
self.command_match.group("command_args")
)
return bool(self.msg_match)
return bool(self.msg_match)
2 changes: 1 addition & 1 deletion HydroRoll/plugins/HydroRoll_plugin_base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
"""最终发送消息的格式。"""


Expand Down
12 changes: 6 additions & 6 deletions HydroRoll/plugins/HydroRoll_plugin_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ def __post_init__(self):
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

Expand Down
2 changes: 1 addition & 1 deletion HydroRoll/plugins/HydroRoll_plugin_echo/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
"""最终发送消息的格式。"""
2 changes: 1 addition & 1 deletion HydroRoll/plugins/HydroRoll_plugin_send/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
"""发送失败时回复的消息。"""
4 changes: 3 additions & 1 deletion HydroRoll/plugins/HydroRoll_plugin_system/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
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

Expand Down Expand Up @@ -69,5 +70,6 @@ async def handle(self) -> None:
)
else:
await self.event.reply(
CQHTTPMessageSegment.reply(self.event.message_id) +
self.format_str(self.config.message_str, system.help)
)
Empty file added HydroRoll/test.py
Empty file.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down

1 comment on commit 3fe9671

@vercel
Copy link

@vercel vercel bot commented on 3fe9671 Apr 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.