mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-10 22:30:02 +08:00
update v0.0.5.0
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
from typing import Optional
|
||||
from .group_manager import GroupManager
|
||||
from pathlib import Path
|
||||
from .withdraw_message_manager import WithdrawMessageManager
|
||||
from .plugins2cd_manager import Plugins2cdManager
|
||||
from .plugins2block_manager import Plugins2blockManager
|
||||
from .plugins2settings_manager import Plugins2settingsManager
|
||||
from configs.path_config import DATA_PATH
|
||||
from nonebot import Driver
|
||||
import nonebot
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
# 群功能开关 | 群被动技能 | 群权限 管理
|
||||
group_manager: Optional[GroupManager] = GroupManager(
|
||||
Path(DATA_PATH) / "manager" / "group_manager.json"
|
||||
)
|
||||
# 撤回消息管理
|
||||
withdraw_message_manager: Optional[WithdrawMessageManager] = WithdrawMessageManager()
|
||||
|
||||
# 插件基本设置管理
|
||||
plugins2settings_manager: Optional[Plugins2settingsManager] = Plugins2settingsManager(
|
||||
Path(DATA_PATH) / "configs" / "plugins2settings.yaml"
|
||||
)
|
||||
|
||||
# 插件命令 cd 管理
|
||||
plugins2cd_manager: Optional[Plugins2cdManager] = Plugins2cdManager(
|
||||
Path(DATA_PATH) / "configs" / "plugins2cd.yaml"
|
||||
)
|
||||
|
||||
# 插件命令 阻塞 管理
|
||||
plugins2block_manager: Optional[Plugins2blockManager] = Plugins2blockManager(
|
||||
Path(DATA_PATH) / "configs" / "plugins2block.yaml"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
from typing import Union, Optional
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
import ujson as json
|
||||
|
||||
yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
class StaticData:
|
||||
"""
|
||||
静态数据共享类
|
||||
"""
|
||||
|
||||
def __init__(self, file: Optional[Path]):
|
||||
self._data = {}
|
||||
if file:
|
||||
file.parent.mkdir(exist_ok=True, parents=True)
|
||||
self.file = file
|
||||
if file.exists():
|
||||
self._data: dict = json.load(open(file, "r", encoding="utf8"))
|
||||
|
||||
def set(self, key, value):
|
||||
self._data[key] = value
|
||||
|
||||
def get(self, key):
|
||||
return self._data.get(key)
|
||||
|
||||
def keys(self):
|
||||
return self._data.keys()
|
||||
|
||||
def delete(self, key):
|
||||
if self._data.get(key) is not None:
|
||||
del self._data[key]
|
||||
|
||||
def get_data(self):
|
||||
return self._data
|
||||
|
||||
def save(self, path: Union[str, Path] = None):
|
||||
path = path if path else self.file
|
||||
with open(path, "w", encoding="utf8") as f:
|
||||
json.dump(self._data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def reload(self):
|
||||
if self.file.exists():
|
||||
if self.file.name.endswith('json'):
|
||||
self._data: dict = json.load(open(self.file, "r", encoding="utf8"))
|
||||
elif self.file.name.endswith('yaml'):
|
||||
self._data: dict = yaml.load(open(self.file, "r", encoding="utf8"))
|
||||
|
||||
def is_exists(self):
|
||||
return self.file.exists()
|
||||
|
||||
def is_empty(self):
|
||||
return bool(len(self._data))
|
||||
|
||||
def __str__(self):
|
||||
return str(self._data)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self._data[key] = value
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self._data[key]
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
from configs.config import DEFAULT_GROUP_LEVEL
|
||||
from typing import Optional, List, Union, Dict
|
||||
from pathlib import Path
|
||||
from .data_class import StaticData
|
||||
from utils.utils import get_matchers, get_bot
|
||||
import nonebot
|
||||
|
||||
|
||||
class GroupManager(StaticData):
|
||||
"""
|
||||
群权限 | 功能 | 聊天时间 管理器
|
||||
"""
|
||||
|
||||
def __init__(self, file: Path):
|
||||
super().__init__(file)
|
||||
if not self._data:
|
||||
self._data = {
|
||||
"super": {"close_plugins": {}, "white_group_list": []},
|
||||
"group_manager": {},
|
||||
}
|
||||
self._task = {}
|
||||
|
||||
def block_plugin(
|
||||
self, plugin_cmd: str, group_id: Optional[int] = None, block_type: str = "all"
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
锁定插件
|
||||
参数:
|
||||
:param plugin_cmd: 功能模块名
|
||||
:param group_id: 群组,None时为超级用户禁用
|
||||
:param block_type: 限制类型
|
||||
"""
|
||||
self._set_plugin_status(plugin_cmd, "block", group_id, block_type)
|
||||
|
||||
def unblock_plugin(self, plugin_cmd: str, group_id: Optional[int] = None):
|
||||
"""
|
||||
说明:
|
||||
解锁插件
|
||||
参数:
|
||||
:param plugin_cmd: 功能模块名
|
||||
:param group_id: 群组
|
||||
"""
|
||||
self._set_plugin_status(plugin_cmd, "unblock", group_id)
|
||||
|
||||
def set_group_level(self, group_id: int, level: int):
|
||||
"""
|
||||
说明:
|
||||
设置群权限
|
||||
参数:
|
||||
:param group_id: 群组
|
||||
:param level: 权限等级
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
self._data["group_manager"][group_id]["level"] = level
|
||||
self.save()
|
||||
|
||||
def get_plugin_status(
|
||||
self, plugin_cmd: str, group_id: Optional[int] = None, block_type: str = "all"
|
||||
) -> bool:
|
||||
"""
|
||||
说明:
|
||||
获取插件状态
|
||||
参数:
|
||||
:param plugin_cmd: 功能模块名
|
||||
:param group_id: 群组
|
||||
:param block_type: 限制类型
|
||||
"""
|
||||
group_id = str(group_id) if group_id else group_id
|
||||
if group_id:
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
return True
|
||||
if plugin_cmd in self._data["group_manager"][group_id]["close_plugins"]:
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
if plugin_cmd in self._data["super"]["close_plugins"]:
|
||||
if (
|
||||
self._data["super"]["close_plugins"][plugin_cmd] == "all"
|
||||
and block_type == "all"
|
||||
):
|
||||
return False
|
||||
else:
|
||||
return (
|
||||
not self._data["super"]["close_plugins"][plugin_cmd]
|
||||
== block_type
|
||||
)
|
||||
return True
|
||||
|
||||
def get_plugin_block_type(self, plugin_cmd: str) -> str:
|
||||
"""
|
||||
说明:
|
||||
获取功能限制类型
|
||||
参数:
|
||||
:param plugin_cmd: 模块名称
|
||||
"""
|
||||
if plugin_cmd in self._data["super"]["close_plugins"]:
|
||||
return self._data["super"]["close_plugins"][plugin_cmd]
|
||||
return ""
|
||||
|
||||
def get_group_level(self, group_id: int) -> int:
|
||||
"""
|
||||
说明:
|
||||
获取群等级
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
return self._data["group_manager"][group_id]["level"]
|
||||
|
||||
def check_group_is_white(self, group_id: int) -> bool:
|
||||
"""
|
||||
说明:
|
||||
检测群聊是否在白名单
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
return group_id in self._data["super"]["white_group_list"]
|
||||
|
||||
def add_group_white_list(self, group_id: int):
|
||||
"""
|
||||
说明:
|
||||
将群聊加入白名单
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
if group_id not in self._data["super"]["white_group_list"]:
|
||||
self._data["super"]["white_group_list"].append(group_id)
|
||||
|
||||
def delete_group_white_list(self, group_id: int):
|
||||
"""
|
||||
说明:
|
||||
将群聊从白名单中删除
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
if group_id in self._data["super"]["white_group_list"]:
|
||||
self._data["super"]["white_group_list"].remove(group_id)
|
||||
|
||||
def get_group_white_list(self) -> List[str]:
|
||||
"""
|
||||
说明:
|
||||
获取所有群白名单
|
||||
"""
|
||||
return self._data["super"]["white_group_list"]
|
||||
|
||||
async def open_group_task(self, group_id: int, task: str):
|
||||
"""
|
||||
开启群被动技能
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
await self._set_group_task_status(group_id, task, True)
|
||||
|
||||
async def close_group_task(self, group_id: int, task: str):
|
||||
"""
|
||||
关闭群被动技能
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
await self._set_group_task_status(group_id, task, False)
|
||||
|
||||
async def check_group_task_status(self, group_id: int, task: str) -> bool:
|
||||
"""
|
||||
查看群被动技能状态
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能名称
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if (
|
||||
not self._data["group_manager"][group_id].get("group_task_status")
|
||||
or self._data["group_manager"][group_id]["group_task_status"].get(task)
|
||||
is None
|
||||
):
|
||||
await self.init_group_task(group_id)
|
||||
return self._data["group_manager"][group_id]["group_task_status"][task]
|
||||
|
||||
def get_task_data(self) -> Dict[str, str]:
|
||||
return self._task
|
||||
|
||||
async def group_task_status(self, group_id: int) -> str:
|
||||
"""
|
||||
查看群被全部动技能状态
|
||||
:param group_id: 群号
|
||||
"""
|
||||
x = '[群被动技能]:\n'
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"][group_id].get("group_task_status"):
|
||||
await self.init_group_task(group_id)
|
||||
for key in self._data["group_manager"][group_id]["group_task_status"].keys():
|
||||
x += f'{self._task[key]}:{"√" if await self.check_group_task_status(int(group_id), key) else "×"}\n'
|
||||
return x[:-1]
|
||||
|
||||
async def _set_group_task_status(self, group_id: int, task: str, status: bool):
|
||||
"""
|
||||
管理群被动技能状态
|
||||
:param group_id: 群号
|
||||
:param task: 被动技能
|
||||
:param status: 状态
|
||||
"""
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
if (
|
||||
not self._data["group_manager"][group_id].get("group_task_status")
|
||||
or self._data["group_manager"][group_id]["group_task_status"].get(task)
|
||||
is None
|
||||
):
|
||||
await self.init_group_task(group_id)
|
||||
self._data["group_manager"][group_id]["group_task_status"][task] = status
|
||||
self.save()
|
||||
|
||||
async def init_group_task(self, group_id: Optional[Union[int, str]] = None):
|
||||
"""
|
||||
初始化群聊 被动技能 状态
|
||||
"""
|
||||
if not self._task:
|
||||
for matcher in get_matchers():
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.module)
|
||||
_module = _plugin.module
|
||||
try:
|
||||
plugin_task = _module.__getattribute__("__plugin_task__")
|
||||
for key in plugin_task.keys():
|
||||
self._task[key] = plugin_task[key]
|
||||
except AttributeError:
|
||||
pass
|
||||
bot = get_bot()
|
||||
if bot or group_id:
|
||||
if group_id:
|
||||
_group_list = [group_id]
|
||||
else:
|
||||
_group_list = [x["group_id"] for x in await bot.get_group_list()]
|
||||
for group_id in _group_list:
|
||||
group_id = str(group_id)
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
if not self._data["group_manager"][group_id].get("group_task_status"):
|
||||
self._data["group_manager"][group_id]['group_task_status'] = {}
|
||||
for task in self._task:
|
||||
if (
|
||||
self._data["group_manager"][group_id][
|
||||
"group_task_status"
|
||||
].get(task)
|
||||
is None
|
||||
):
|
||||
self._data["group_manager"][group_id]["group_task_status"][
|
||||
task
|
||||
] = True
|
||||
for task in self._data["group_manager"][group_id]["group_task_status"]:
|
||||
if task not in self._task:
|
||||
del self._data["group_manager"][group_id]["group_task_status"][
|
||||
task
|
||||
]
|
||||
self.save()
|
||||
|
||||
def _set_plugin_status(
|
||||
self,
|
||||
plugin_cmd: str,
|
||||
status: str,
|
||||
group_id: Optional[str],
|
||||
block_type: str = "all",
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
设置功能开关状态
|
||||
参数:
|
||||
:param plugin_cmd: 功能模块名
|
||||
:param status: 功能状态
|
||||
:param group_id: 群组
|
||||
:param block_type: 限制类型
|
||||
"""
|
||||
group_id = str(group_id) if group_id else group_id
|
||||
if plugin_cmd:
|
||||
if group_id:
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._init_group(group_id)
|
||||
if status == "block":
|
||||
if (
|
||||
plugin_cmd
|
||||
not in self._data["group_manager"][group_id]["close_plugins"]
|
||||
):
|
||||
self._data["group_manager"][group_id]["close_plugins"].append(
|
||||
plugin_cmd
|
||||
)
|
||||
else:
|
||||
if plugin_cmd in self._data["group_manager"][group_id]["close_plugins"]:
|
||||
self._data["group_manager"][group_id]["close_plugins"].remove(
|
||||
plugin_cmd
|
||||
)
|
||||
else:
|
||||
if status == "block":
|
||||
if (
|
||||
plugin_cmd not in self._data["super"]["close_plugins"]
|
||||
or block_type != self._data["super"]["close_plugins"][plugin_cmd]
|
||||
):
|
||||
self._data["super"]["close_plugins"][plugin_cmd] = block_type
|
||||
else:
|
||||
if plugin_cmd in self._data["super"]["close_plugins"]:
|
||||
del self._data["super"]["close_plugins"][plugin_cmd]
|
||||
self.save()
|
||||
|
||||
def _init_group(self, group_id: str):
|
||||
"""
|
||||
说明:
|
||||
初始化群数据
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
if not self._data["group_manager"].get(group_id):
|
||||
self._data["group_manager"][group_id] = {
|
||||
"level": DEFAULT_GROUP_LEVEL,
|
||||
"close_plugins": [],
|
||||
"group_task_status": {},
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
from typing import Optional, Dict
|
||||
from .data_class import StaticData
|
||||
from services.log import logger
|
||||
from utils.utils import UserBlockLimiter
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
class Plugins2blockManager(StaticData):
|
||||
"""
|
||||
插件命令阻塞 管理器
|
||||
"""
|
||||
def __init__(self, file: Path):
|
||||
self.file = file
|
||||
super().__init__(None)
|
||||
self._block_limiter: Dict[str, UserBlockLimiter] = {}
|
||||
|
||||
def add_block_limit(
|
||||
self,
|
||||
plugin: str,
|
||||
status: Optional[bool] = True,
|
||||
check_type: Optional[str] = "all",
|
||||
limit_type: Optional[str] = "user",
|
||||
rst: Optional[str] = None,
|
||||
data_dict: Optional[dict] = None,
|
||||
):
|
||||
"""
|
||||
添加插件调用 block 限制
|
||||
:param plugin: 插件模块名称
|
||||
:param status: 默认开关状态
|
||||
:param check_type: 检查类型 'private'/'group'/'all',限制私聊/群聊/全部
|
||||
:param limit_type: 限制类型 监听对象,以user_id或group_id作为键来限制,'user':用户id,'group':群id
|
||||
:param rst: 回复的话,为空则不回复
|
||||
:param data_dict: 封装好的字典数据
|
||||
"""
|
||||
if data_dict:
|
||||
status = data_dict.get('status')
|
||||
check_type = data_dict.get('check_type')
|
||||
limit_type = data_dict.get('limit_type')
|
||||
rst = data_dict.get('rst')
|
||||
status = status if status is not None else True
|
||||
check_type = check_type if check_type else 'all'
|
||||
limit_type = limit_type if limit_type else 'user'
|
||||
if check_type not in ["all", "group", "private"]:
|
||||
raise ValueError(
|
||||
f"{plugin} 添加block限制错误,‘check_type‘ 必须为 'private'/'group'/'all'"
|
||||
)
|
||||
if limit_type not in ["user", "group"]:
|
||||
raise ValueError(f"{plugin} 添加block限制错误,‘limit_type‘ 必须为 'user'/'group'")
|
||||
self._data[plugin] = {
|
||||
"status": status,
|
||||
"check_type": check_type,
|
||||
"limit_type": limit_type,
|
||||
"rst": rst,
|
||||
}
|
||||
|
||||
def remove_block_limit(self, plugin: str):
|
||||
"""
|
||||
删除一个插件 block 限制
|
||||
:param plugin: 插件模块名称
|
||||
"""
|
||||
if self._data.get(plugin):
|
||||
del self._data[plugin]
|
||||
|
||||
def get_plugin_block_data(self, plugin: str) -> Optional[dict]:
|
||||
"""
|
||||
获取插件block数据
|
||||
:param plugin: 模块名
|
||||
"""
|
||||
if self.check_plugin_block_status(plugin):
|
||||
return self._data[plugin]
|
||||
return None
|
||||
|
||||
def check_plugin_block_status(self, plugin: str) -> bool:
|
||||
"""
|
||||
检测插件是否有 block
|
||||
:param plugin: 模块名
|
||||
"""
|
||||
return (
|
||||
plugin in self._data.keys()
|
||||
and self._data[plugin]["status"]
|
||||
)
|
||||
|
||||
def check(self, id_: int, plugin: str) -> bool:
|
||||
"""
|
||||
检查 block
|
||||
:param plugin: 模块名
|
||||
:param id_: 限制 id
|
||||
"""
|
||||
if self._block_limiter.get(plugin):
|
||||
return self._block_limiter[plugin].check(id_)
|
||||
return False
|
||||
|
||||
def set_true(self, id_: int, plugin: str):
|
||||
"""
|
||||
对插件 block
|
||||
:param plugin: 模块名
|
||||
:param id_: 限制 id
|
||||
"""
|
||||
if self._block_limiter.get(plugin):
|
||||
self._block_limiter[plugin].set_true(id_)
|
||||
|
||||
def set_false(self, id_: int, plugin: str):
|
||||
"""
|
||||
对插件 unblock
|
||||
:param plugin: 模块名
|
||||
:param id_: 限制 id
|
||||
"""
|
||||
if self._block_limiter.get(plugin):
|
||||
self._block_limiter[plugin].set_false(id_)
|
||||
|
||||
def reload_block_limit(self):
|
||||
"""
|
||||
加载 block 限制器
|
||||
:return:
|
||||
"""
|
||||
for plugin in self._data:
|
||||
if self.check_plugin_block_status(plugin):
|
||||
self._block_limiter[plugin] = UserBlockLimiter()
|
||||
logger.info(f'已成功加载 {len(self._block_limiter)} 个Block限制.')
|
||||
|
||||
def reload(self):
|
||||
"""
|
||||
重载本地数据
|
||||
"""
|
||||
if self.file.exists():
|
||||
with open(self.file, "r", encoding="utf8") as f:
|
||||
self._data: dict = yaml.load(f)
|
||||
self._data = self._data['PluginBlockLimit']
|
||||
self.reload_block_limit()
|
||||
@@ -0,0 +1,144 @@
|
||||
from typing import Optional, Dict
|
||||
from .data_class import StaticData
|
||||
from utils.utils import FreqLimiter
|
||||
from services.log import logger
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
class Plugins2cdManager(StaticData):
|
||||
"""
|
||||
插件命令 cd 管理器
|
||||
"""
|
||||
|
||||
def __init__(self, file: Path):
|
||||
self.file = file
|
||||
super().__init__(None)
|
||||
self._freq_limiter: Dict[str, FreqLimiter] = {}
|
||||
|
||||
def add_cd_limit(
|
||||
self,
|
||||
plugin: str,
|
||||
*,
|
||||
cd: Optional[int] = 5,
|
||||
status: Optional[bool] = True,
|
||||
check_type: Optional[str] = "all",
|
||||
limit_type: Optional[str] = "user",
|
||||
rst: Optional[str] = None,
|
||||
data_dict: Optional[dict] = None,
|
||||
):
|
||||
"""
|
||||
添加插件调用 cd 限制
|
||||
:param plugin: 插件模块名称
|
||||
:param cd: cd 时长
|
||||
:param status: 默认开关状态
|
||||
:param check_type: 检查类型 'private'/'group'/'all',限制私聊/群聊/全部
|
||||
:param limit_type: 限制类型 监听对象,以user_id或group_id作为键来限制,'user':用户id,'group':群id
|
||||
:param rst: 回复的话,为空则不回复
|
||||
:param data_dict: 封装好的字典数据
|
||||
"""
|
||||
if data_dict:
|
||||
cd = data_dict.get('cd')
|
||||
status = data_dict.get('status')
|
||||
check_type = data_dict.get('check_type')
|
||||
limit_type = data_dict.get('limit_type')
|
||||
rst = data_dict.get('rst')
|
||||
cd = cd if cd is not None else 5
|
||||
status = status if status is not None else True
|
||||
check_type = check_type if check_type else 'all'
|
||||
limit_type = limit_type if limit_type else 'user'
|
||||
if check_type not in ["all", "group", "private"]:
|
||||
raise ValueError(
|
||||
f"{plugin} 添加cd限制错误,‘check_type‘ 必须为 'private'/'group'/'all'"
|
||||
)
|
||||
if limit_type not in ["user", "group"]:
|
||||
raise ValueError(f"{plugin} 添加cd限制错误,‘limit_type‘ 必须为 'user'/'group'")
|
||||
self._data[plugin] = {
|
||||
"cd": cd,
|
||||
"status": status,
|
||||
"check_type": check_type,
|
||||
"limit_type": limit_type,
|
||||
"rst": rst,
|
||||
}
|
||||
|
||||
def remove_cd_limit(self, plugin: str):
|
||||
"""
|
||||
删除一个插件 cd 限制
|
||||
:param plugin: 插件模块名称
|
||||
"""
|
||||
if self._data.get(plugin):
|
||||
del self._data[plugin]
|
||||
|
||||
def get_plugin_cd_data(self, plugin: str) -> Optional[dict]:
|
||||
"""
|
||||
获取插件cd数据
|
||||
:param plugin: 模块名
|
||||
"""
|
||||
if self.check_plugin_cd_status(plugin):
|
||||
return self._data[plugin]
|
||||
return None
|
||||
|
||||
def check_plugin_cd_status(self, plugin: str) -> bool:
|
||||
"""
|
||||
检测插件是否有 cd
|
||||
:param plugin: 模块名
|
||||
"""
|
||||
return (
|
||||
plugin in self._data.keys()
|
||||
and self._data[plugin]["cd"] > 0
|
||||
and self._data[plugin]["status"]
|
||||
)
|
||||
|
||||
def check(self, plugin: str, id_: int) -> bool:
|
||||
"""
|
||||
检查 cd
|
||||
:param plugin: 模块名
|
||||
:param id_: 限制 id
|
||||
"""
|
||||
if self._freq_limiter.get(plugin):
|
||||
return self._freq_limiter[plugin].check(id_)
|
||||
return False
|
||||
|
||||
def start_cd(self, plugin: str, id_: int, cd: int = 0):
|
||||
"""
|
||||
开始cd
|
||||
:param plugin: 模块名
|
||||
:param id_: cd 限制类型
|
||||
:param cd: cd 时长
|
||||
:return:
|
||||
"""
|
||||
if self._freq_limiter.get(plugin):
|
||||
self._freq_limiter[plugin].start_cd(id_, cd)
|
||||
|
||||
def get_plugin_data(self, plugin: str) -> dict:
|
||||
"""
|
||||
获取单个模块限制数据
|
||||
:param plugin: 模块名
|
||||
"""
|
||||
if self._data.get(plugin) is not None:
|
||||
return self._data.get(plugin)
|
||||
return {}
|
||||
|
||||
def reload_cd_limit(self):
|
||||
"""
|
||||
加载 cd 限制器
|
||||
:return:
|
||||
"""
|
||||
for plugin in self._data:
|
||||
if self.check_plugin_cd_status(plugin):
|
||||
self._freq_limiter[plugin] = FreqLimiter(self.get_plugin_cd_data(plugin)['cd'])
|
||||
logger.info(f'已成功加载 {len(self._freq_limiter)} 个Cd限制.')
|
||||
|
||||
def reload(self):
|
||||
"""
|
||||
重载本地数据
|
||||
"""
|
||||
if self.file.exists():
|
||||
with open(self.file, "r", encoding="utf8") as f:
|
||||
self._data: dict = yaml.load(f)
|
||||
self._data = self._data['PluginCdLimit']
|
||||
self.reload_cd_limit()
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
from typing import List, Optional, Union, Tuple
|
||||
from .data_class import StaticData
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
class Plugins2settingsManager(StaticData):
|
||||
"""
|
||||
插件命令阻塞 管理器
|
||||
"""
|
||||
|
||||
def __init__(self, file: Path):
|
||||
self.file = file
|
||||
super().__init__(None)
|
||||
|
||||
def add_plugin_settings(
|
||||
self,
|
||||
plugin: str,
|
||||
cmd: Optional[List[str]] = None,
|
||||
default_status: Optional[bool] = True,
|
||||
level: Optional[int] = 5,
|
||||
limit_superuser: Optional[bool] = False,
|
||||
plugin_type: Tuple[Union[str, int]] = ("normal",),
|
||||
data_dict: Optional[dict] = None,
|
||||
):
|
||||
"""
|
||||
添加一个插件设置
|
||||
:param plugin: 插件模块名称
|
||||
:param cmd: 命令 或 命令别名
|
||||
:param default_status: 默认开关状态
|
||||
:param level: 功能权限等级
|
||||
:param limit_superuser: 功能状态是否限制超级用户
|
||||
:param plugin_type: 插件类型
|
||||
:param data_dict: 封装好的字典数据
|
||||
"""
|
||||
if data_dict:
|
||||
level = data_dict.get("level") if data_dict.get("level") is not None else 5
|
||||
default_status = (
|
||||
data_dict.get("default_status")
|
||||
if data_dict.get("default_status") is not None
|
||||
else True
|
||||
)
|
||||
limit_superuser = (
|
||||
data_dict.get("limit_superuser")
|
||||
if data_dict.get("limit_superuser") is not None
|
||||
else False
|
||||
)
|
||||
cmd = data_dict.get("cmd") if data_dict.get("cmd") is not None else []
|
||||
self._data[plugin] = {
|
||||
"level": level if level is not None else 5,
|
||||
"default_status": default_status if default_status is not None else True,
|
||||
"limit_superuser": limit_superuser
|
||||
if limit_superuser is not None
|
||||
else False,
|
||||
"cmd": cmd,
|
||||
"plugin_type": list(plugin_type if plugin_type is not None else ("normal",))
|
||||
}
|
||||
|
||||
def remove_plugin_settings(self, plugin: str):
|
||||
"""
|
||||
删除一个插件设置
|
||||
:param plugin: 插件模块名称
|
||||
"""
|
||||
if self._data.get(plugin):
|
||||
del self._data[plugin]
|
||||
|
||||
def get_plugin_data(self, module: str) -> dict:
|
||||
"""
|
||||
通过模块名获取数据
|
||||
:param module: 模块名称
|
||||
"""
|
||||
if self._data.get(module) is not None:
|
||||
return self._data.get(module)
|
||||
return {}
|
||||
|
||||
def get_plugin_module(
|
||||
self, cmd: str, is_all: bool = False
|
||||
) -> Union[str, List[str]]:
|
||||
"""
|
||||
根据 cmd 获取功能 module
|
||||
:param cmd: 命令
|
||||
:param is_all: 获取全部包含cmd的模块
|
||||
"""
|
||||
keys = []
|
||||
for key in self._data.keys():
|
||||
if cmd in self._data[key]["cmd"]:
|
||||
if is_all:
|
||||
keys.append(key)
|
||||
else:
|
||||
return key
|
||||
return keys
|
||||
|
||||
def reload(self):
|
||||
"""
|
||||
重载本地数据
|
||||
"""
|
||||
if self.file.exists():
|
||||
with open(self.file, "r", encoding="utf8") as f:
|
||||
self._data: dict = yaml.load(f)
|
||||
self._data = self._data['PluginSettings']
|
||||
@@ -0,0 +1,28 @@
|
||||
from typing import Tuple, Union, Dict
|
||||
|
||||
|
||||
class WithdrawMessageManager:
|
||||
|
||||
def __init__(self):
|
||||
self.data = []
|
||||
|
||||
def append(self, message_data: Tuple[Union[int, Dict[str, int]], int]):
|
||||
"""
|
||||
说明:
|
||||
添加一个撤回消息id和时间
|
||||
参数:
|
||||
:param message_data: 撤回消息id和时间
|
||||
"""
|
||||
if isinstance(message_data[0], dict):
|
||||
message_data = (message_data[0]['message_id'], message_data[1])
|
||||
self.data.append(message_data)
|
||||
|
||||
def remove(self, message_data: Tuple[int, int]):
|
||||
"""
|
||||
说明:
|
||||
删除一个数据
|
||||
参数:
|
||||
:param message_data: 消息id和时间
|
||||
"""
|
||||
self.data.remove(message_data)
|
||||
|
||||
Reference in New Issue
Block a user