mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-09-29 08:39:59 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cb4099a2e | ||
|
|
e75a4966b2 | ||
|
|
d55cba49bd | ||
|
|
0215abac30 | ||
|
|
2dcac5f009 | ||
|
|
0d8c64f7d1 | ||
|
|
55626645fb | ||
|
|
f7925fa259 | ||
|
|
c814ae08b1 | ||
|
|
24666368f7 | ||
|
|
a77e85b62d | ||
|
|
6319c7fce1 | ||
|
|
a45b95d5d4 | ||
|
|
188f6f0f99 |
@@ -32,6 +32,12 @@
|
||||
## 普通帮助图片
|
||||

|
||||
|
||||
## Web UI
|
||||
[zhenxun_bot_webui](https://github.com/HibiKier/zhenxun_bot_webui)
|
||||
|
||||
## 一键安装脚本
|
||||
[zhenxun_bot-deploy](https://github.com/AkashiCoin/zhenxun_bot-deploy)
|
||||
|
||||
## 提供符合真寻标准的插件仓库
|
||||
|
||||
[AkashiCoin/nonebot_plugins_zhenxun_bot](https://github.com/AkashiCoin/nonebot_plugins_zhenxun_bot)
|
||||
@@ -236,6 +242,25 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
|
||||
## 更新
|
||||
|
||||
### 2022/4/10 \[v0.1.4.7]
|
||||
|
||||
* 新增消息记录模块
|
||||
* 丰富处理请求操作提示
|
||||
* web ui新增配置项修改
|
||||
* 修复chat_history阻断消息
|
||||
|
||||
### 2022/4/9
|
||||
|
||||
* fix: 更新问题,戳一戳图片路径问题 [@pull/144](https://github.com/HibiKier/zhenxun_bot/pull/144)
|
||||
|
||||
### 2022/4/8
|
||||
|
||||
* 修复原神玩家查询
|
||||
|
||||
### 2022/4/6
|
||||
|
||||
* update search_type [@pull/143](https://github.com/HibiKier/zhenxun_bot/pull/143)
|
||||
|
||||
### 2022/4/5 \[v0.1.4.6]
|
||||
|
||||
* 修复web修改插件后帮助图片生成错误
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__: v0.1.4.6
|
||||
__version__: v0.1.4.7
|
||||
@@ -0,0 +1,41 @@
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
|
||||
from models.chat_history import ChatHistory
|
||||
from ._rule import rule
|
||||
from configs.config import Config
|
||||
from nonebot import on_message
|
||||
|
||||
__zx_plugin_name__ = "消息存储 [Hidden]"
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
"chat_history",
|
||||
"FLAG",
|
||||
True,
|
||||
help_="是否开启消息自从存储",
|
||||
name="消息存储",
|
||||
default_value=True
|
||||
)
|
||||
|
||||
|
||||
chat_history = on_message(rule=rule, priority=1, block=False)
|
||||
|
||||
# test = on_command("aa")
|
||||
|
||||
|
||||
@chat_history.handle()
|
||||
async def _(event: MessageEvent):
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
await ChatHistory.add_chat_msg(event.user_id, event.group_id, str(event.get_message()))
|
||||
else:
|
||||
await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message()))
|
||||
|
||||
# @test.handle()
|
||||
# async def _(event: MessageEvent):
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_group_msg(event.group_id))
|
||||
# print(await ChatHistory.get_group_msg_count(event.group_id))
|
||||
@@ -0,0 +1,6 @@
|
||||
from nonebot.adapters.onebot.v11 import Event, MessageEvent
|
||||
from configs.config import Config
|
||||
|
||||
|
||||
def rule(event: Event) -> bool:
|
||||
return Config.get_config("chat_history", "FLAG") and isinstance(event, MessageEvent)
|
||||
@@ -82,15 +82,16 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
if is_number(id_):
|
||||
id_ = int(id_)
|
||||
if cmd[:2] == "同意":
|
||||
if await requests_manager.approve(bot, id_, "private"):
|
||||
await friend_handle.send("同意好友请求成功..")
|
||||
else:
|
||||
await friend_handle.send("同意好友请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.approve(bot, id_, "private")
|
||||
else:
|
||||
if await requests_manager.refused(bot, id_, "private"):
|
||||
await friend_handle.send("拒绝好友请求成功..")
|
||||
else:
|
||||
await friend_handle.send("拒绝好友请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.refused(bot, id_, "private")
|
||||
if flag == 1:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求失败,该请求已失效..")
|
||||
requests_manager.delete_request(id_, "private")
|
||||
elif flag == 2:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求失败,未找到此id的请求..")
|
||||
else:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求成功!")
|
||||
else:
|
||||
await friend_handle.send("id必须为纯数字!")
|
||||
|
||||
@@ -99,12 +100,12 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
cmd = cmd[0]
|
||||
id_ = arg.extract_plain_text().strip()
|
||||
flag = None
|
||||
if is_number(id_):
|
||||
id_ = int(id_)
|
||||
if cmd[:2] == "同意":
|
||||
rid = requests_manager.get_group_id(id_)
|
||||
if rid:
|
||||
await friend_handle.send("同意群聊请求成功..")
|
||||
if await GroupInfo.get_group_info(rid):
|
||||
await GroupInfo.set_group_flag(rid, 1)
|
||||
else:
|
||||
@@ -116,14 +117,18 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
group_info["member_count"],
|
||||
1
|
||||
)
|
||||
await requests_manager.approve(bot, id_, "group")
|
||||
flag = await requests_manager.approve(bot, id_, "group")
|
||||
else:
|
||||
await friend_handle.send("同意群聊请求失败,可能是未找到此id的请求..")
|
||||
await friend_handle.send("同意群聊请求失败,未找到此id的请求..")
|
||||
else:
|
||||
if await requests_manager.refused(bot, id_, "group"):
|
||||
await friend_handle.send("拒绝群聊请求成功..")
|
||||
else:
|
||||
await friend_handle.send("拒绝群聊请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.refused(bot, id_, "group")
|
||||
if flag == 1:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求失败,该请求已失效..")
|
||||
requests_manager.delete_request(id_, "group")
|
||||
elif flag == 2:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求失败,未找到此id的请求..")
|
||||
else:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求成功!")
|
||||
else:
|
||||
await friend_handle.send("id必须为纯数字!")
|
||||
|
||||
|
||||
@@ -11,14 +11,19 @@ class ConfigsManager:
|
||||
|
||||
def __init__(self, file: Path):
|
||||
self._data: dict = {}
|
||||
self._simple_data: dict = {}
|
||||
self._admin_level_data = []
|
||||
self._simple_file = Path() / "configs" / "config.yaml"
|
||||
if file:
|
||||
file.parent.mkdir(exist_ok=True, parents=True)
|
||||
self.file = file
|
||||
_yaml = YAML()
|
||||
if file.exists():
|
||||
_yaml = YAML()
|
||||
with open(file, "r", encoding="utf8") as f:
|
||||
self._data = _yaml.load(f)
|
||||
if self._simple_file.exists():
|
||||
with open(self._simple_file, "r", encoding="utf8") as f:
|
||||
self._simple_data = _yaml.load(f)
|
||||
|
||||
def add_plugin_config(
|
||||
self,
|
||||
@@ -71,6 +76,7 @@ class ConfigsManager:
|
||||
"""
|
||||
if module in self._data.keys():
|
||||
del self._data[module]
|
||||
self.save()
|
||||
|
||||
def set_config(self, module: str, key: str, value: str):
|
||||
"""
|
||||
@@ -80,8 +86,10 @@ class ConfigsManager:
|
||||
:param value: 值
|
||||
"""
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
if self._data[module].get(key) is not None and self._data[module][key] != value:
|
||||
self._data[module][key]["value"] = value
|
||||
self._simple_data[module][key] = value
|
||||
self.save()
|
||||
|
||||
def set_help(self, module: str, key: str, help_: str):
|
||||
"""
|
||||
@@ -93,6 +101,7 @@ class ConfigsManager:
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
self._data[module][key]["help"] = help_
|
||||
self.save()
|
||||
|
||||
def set_default_value(self, module: str, key: str, value: str):
|
||||
"""
|
||||
@@ -104,6 +113,7 @@ class ConfigsManager:
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
self._data[module][key]["default_value"] = value
|
||||
self.save()
|
||||
|
||||
def get_config(self, module: str, key: str, default: Optional[Any] = None) -> Optional[Any]:
|
||||
"""
|
||||
@@ -142,11 +152,17 @@ class ConfigsManager:
|
||||
if key in self._data.keys():
|
||||
return self._data[key]
|
||||
|
||||
def save(self, path: Union[str, Path] = None):
|
||||
def save(self, path: Union[str, Path] = None, save_simple_data: bool = False):
|
||||
"""
|
||||
保存数据
|
||||
:param path: 路径
|
||||
:param save_simple_data: 同时保存至config.yaml
|
||||
"""
|
||||
if save_simple_data:
|
||||
with open(self._simple_file, "w", encoding="utf8") as f:
|
||||
yaml.dump(
|
||||
self._simple_data, f, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True
|
||||
)
|
||||
path = path if path else self.file
|
||||
with open(path, "w", encoding="utf8") as f:
|
||||
yaml.dump(
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
from services.db_context import db
|
||||
|
||||
|
||||
class ChatHistory(db.Model):
|
||||
__tablename__ = "chat_history"
|
||||
|
||||
id = db.Column(db.Integer(), primary_key=True)
|
||||
user_qq = db.Column(db.BigInteger(), nullable=False)
|
||||
group_id = db.Column(db.BigInteger())
|
||||
text = db.Column(db.Text())
|
||||
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
|
||||
|
||||
@classmethod
|
||||
async def add_chat_msg(cls, user_qq: int, group_id: Optional[int], text: str):
|
||||
await cls.create(
|
||||
user_qq=user_qq, group_id=group_id, text=text, create_time=datetime.now()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def get_user_msg(
|
||||
cls,
|
||||
uid: int,
|
||||
msg_type: Optional[Literal["private", "group"]],
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取用户消息
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param msg_type: 消息类型,私聊或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return await cls._get_msg(uid, None, "user", msg_type, days).gino.all()
|
||||
|
||||
@classmethod
|
||||
async def get_user_msg_count(
|
||||
cls,
|
||||
uid: int,
|
||||
msg_type: Optional[Literal["private", "group"]],
|
||||
days: Optional[int] = None,
|
||||
) -> int:
|
||||
"""
|
||||
说明:
|
||||
获取用户消息数量
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param msg_type: 消息类型,私聊或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return (await cls._get_msg(uid, None, "user", msg_type, days, True).gino.first())[0]
|
||||
|
||||
@classmethod
|
||||
async def get_group_msg(
|
||||
cls,
|
||||
gid: int,
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取群聊消息
|
||||
参数:
|
||||
:param gid: 用户qq
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return await cls._get_msg(None, gid, "group", None, days).gino.all()
|
||||
|
||||
@classmethod
|
||||
async def get_group_msg_count(
|
||||
cls,
|
||||
gid: int,
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取群聊消息数量
|
||||
参数:
|
||||
:param gid: 用户qq
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return (await cls._get_msg(None, gid, "group", None, days, True).gino.first())[0]
|
||||
|
||||
@classmethod
|
||||
def _get_msg(
|
||||
cls,
|
||||
uid: Optional[int],
|
||||
gid: Optional[int],
|
||||
type_: Literal["user", "group"],
|
||||
msg_type: Optional[Literal["private", "group"]],
|
||||
days: Optional[int],
|
||||
is_select_count: bool = False
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
获取消息查询query
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param gid: 群号
|
||||
:param type_: 类型,私聊或群聊
|
||||
:param msg_type: 消息类型,用户或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
if is_select_count:
|
||||
setattr(ChatHistory, 'count', db.func.count(cls.id).label('count'))
|
||||
query = cls.select('count')
|
||||
else:
|
||||
query = cls.query
|
||||
if type_ == "user":
|
||||
query = query.where(cls.user_qq == uid)
|
||||
if msg_type == "private":
|
||||
query = query.where(cls.group_id == None)
|
||||
elif msg_type == "group":
|
||||
query = query.where(cls.group_id != None)
|
||||
else:
|
||||
query = query.where(cls.group_id == gid)
|
||||
if days:
|
||||
query = query.where(
|
||||
cls.create_time >= datetime.now() - timedelta(days=days)
|
||||
)
|
||||
return query
|
||||
@@ -76,6 +76,7 @@ async def _(bot: Bot, event: MessageEvent):
|
||||
f"问题:{msg} ---- 回答:{result}"
|
||||
)
|
||||
if result:
|
||||
result = str(result)
|
||||
for t in Config.get_config("ai", "TEXT_FILTER"):
|
||||
result = result.replace(t, "*")
|
||||
await ai.finish(Message(result))
|
||||
|
||||
@@ -73,6 +73,7 @@ async def check_update(bot: Bot) -> 'int, str':
|
||||
message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....",
|
||||
)
|
||||
logger.info(f"开始下载真寻最新版文件....")
|
||||
tar_gz_url = (await AsyncHttpx.get(tar_gz_url)).headers.get('Location')
|
||||
if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz):
|
||||
logger.info("下载真寻最新版文件完成....")
|
||||
error = await asyncio.get_event_loop().run_in_executor(
|
||||
|
||||
@@ -299,8 +299,8 @@ def get_country_data_image(world_data_dict: Dict) -> BuildImage:
|
||||
# 层岩巨渊 和 地下矿区 算一个
|
||||
region = BuildImage(790, 267 * (len(world_data_dict) - 1), color="#F9F6F2")
|
||||
height = 0
|
||||
|
||||
for country in ["蒙德", "龙脊雪山", "璃月", "璃月层岩巨渊", "稻妻", "渊下宫"]:
|
||||
print(world_data_dict)
|
||||
for country in ["蒙德", "龙脊雪山", "璃月", "层岩巨渊", "稻妻", "渊下宫"]:
|
||||
x = BuildImage(790, 250, color="#3A4467")
|
||||
logo = BuildImage(180, 180, background=image_path / "logo" / f"{country}.png")
|
||||
tmp_bk = BuildImage(770, 230, color="#606779")
|
||||
@@ -322,23 +322,23 @@ def get_country_data_image(world_data_dict: Dict) -> BuildImage:
|
||||
f"Lv.{world_data_dict[country]['level']}",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
elif country in ["璃月层岩巨渊"]:
|
||||
elif country in ["层岩巨渊"]:
|
||||
content_bk.text((300, 20), "层岩巨渊探索", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 20),
|
||||
f"{world_data_dict['璃月层岩巨渊']['exploration_percentage'] / 10}%",
|
||||
f"{world_data_dict['层岩巨渊']['exploration_percentage'] / 10}%",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
content_bk.text((300, 85), "地下矿区探索", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 85),
|
||||
f"{world_data_dict['璃月层岩巨渊·地下矿区']['exploration_percentage'] / 10}%",
|
||||
f"{world_data_dict['层岩巨渊·地下矿区']['exploration_percentage'] / 10}%",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
content_bk.text((300, 150), "流明石触媒", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 150),
|
||||
f"LV.{world_data_dict['璃月层岩巨渊·地下矿区']['offerings'][0]['level']}",
|
||||
f"LV.{world_data_dict['层岩巨渊·地下矿区']['offerings'][0]['level']}",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
elif country in ["龙脊雪山"]:
|
||||
|
||||
@@ -64,8 +64,8 @@ async def _poke_event(event: PokeNotifyEvent):
|
||||
rand = random.random()
|
||||
if rand <= 0.3:
|
||||
path = random.choice(["luoli", "meitu"])
|
||||
index = random.randint(0, len(os.listdir(IMAGE_PATH / path)))
|
||||
result = f"id:{index}" + image(f"{index}.jpg", path)
|
||||
index = random.randint(0, len(os.listdir(IMAGE_PATH / "image_management" / path)))
|
||||
result = f"id:{index}" + image(f"{index}.jpg", "image_management/" + path)
|
||||
await poke_.send(result)
|
||||
logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} \n {result}")
|
||||
elif 0.3 < rand < 0.6:
|
||||
|
||||
@@ -139,7 +139,7 @@ async def update_setu_img(flag: bool = False):
|
||||
f"--> /{path}/{image.local_id}.jpg"
|
||||
)
|
||||
os.rename(
|
||||
TEMP_PATH / f"/{image.local_id}.jpg",
|
||||
TEMP_PATH / f"{image.local_id}.jpg",
|
||||
path / f"{image.local_id}.jpg",
|
||||
)
|
||||
except FileNotFoundError:
|
||||
|
||||
@@ -1,206 +1,3 @@
|
||||
from utils.manager import (
|
||||
plugins_manager,
|
||||
group_manager,
|
||||
plugins2settings_manager,
|
||||
plugins2cd_manager,
|
||||
plugins2block_manager,
|
||||
plugins2count_manager,
|
||||
requests_manager,
|
||||
)
|
||||
from ..auth import token_to_user, Depends, User
|
||||
from utils.utils import get_matchers, get_bot
|
||||
from models.group_info import GroupInfo
|
||||
from pydantic.error_wrappers import ValidationError
|
||||
from services.log import logger
|
||||
from ..config import *
|
||||
import nonebot
|
||||
|
||||
app = nonebot.get_app()
|
||||
|
||||
|
||||
plugin_name_list = None
|
||||
|
||||
|
||||
@app.get("/webui/plugins")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取插件列表
|
||||
:param type_: 类型 normal, superuser, hidden, admin
|
||||
"""
|
||||
global plugin_name_list
|
||||
if not plugin_name_list:
|
||||
plugin_name_list = [x.plugin_name for x in get_matchers()]
|
||||
plugin_list = []
|
||||
plugin_data = plugins_manager.get_data()
|
||||
for model in plugin_data:
|
||||
if model in plugin_name_list:
|
||||
data = plugin_data.get(model)
|
||||
data["model"] = model
|
||||
plugin_name = data.get("plugin_name")
|
||||
if (
|
||||
(type_ == "hidden" and "[hidden]" not in plugin_name.lower())
|
||||
or (type_ == "admin" and "[admin]" not in plugin_name.lower())
|
||||
or (type_ == "superuser" and "[superuser]" not in plugin_name.lower())
|
||||
):
|
||||
continue
|
||||
if type_ == "normal" and (
|
||||
"[hidden]" in plugin_name.lower()
|
||||
or "[admin]" in plugin_name.lower()
|
||||
or "[superuser]" in plugin_name.lower()
|
||||
):
|
||||
continue
|
||||
data = {"model": model}
|
||||
if x := plugin_data.get(model):
|
||||
if not x.get("status") and x.get("block_type") in [
|
||||
"group",
|
||||
"private",
|
||||
"all",
|
||||
]:
|
||||
x["block_type"] = (
|
||||
"群聊"
|
||||
if x["block_type"] == "group"
|
||||
else "私聊"
|
||||
if x["block_type"] == "private"
|
||||
else "全部"
|
||||
)
|
||||
data["plugin_manager"] = PluginManager(**x)
|
||||
if x := plugins2settings_manager.get(model):
|
||||
if x.get("cmd") and isinstance(x.get("cmd"), list):
|
||||
x["cmd"] = ",".join(x["cmd"])
|
||||
# if isinstance(x["plugin_type"], list):
|
||||
# x["plugin_type"] = x["plugin_type"][0]
|
||||
data["plugin_settings"] = PluginSettings(**x)
|
||||
if x := plugins2cd_manager.get(model):
|
||||
data["cd_limit"] = CdLimit(**x)
|
||||
if x := plugins2block_manager.get(model):
|
||||
data["block_limit"] = BlockLimit(**x)
|
||||
if x := plugins2count_manager.get(model):
|
||||
data["count_limit"] = CountLimit(**x)
|
||||
# if x := resources_manager.get(model):
|
||||
# data = dict(data, **x)
|
||||
plugin_list.append(Plugin(**data))
|
||||
return Result(code=200, data=plugin_list)
|
||||
|
||||
|
||||
@app.post("/webui/plugins")
|
||||
def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改插件信息
|
||||
:param plugin: 插件内容
|
||||
"""
|
||||
if plugin.plugin_settings:
|
||||
for key, value in plugin.plugin_settings:
|
||||
plugins2settings_manager.set_module_data(plugin.model, key, value)
|
||||
if plugin.plugin_manager:
|
||||
for key, value in plugin.plugin_manager:
|
||||
plugins_manager.set_module_data(plugin.model, key, value)
|
||||
return Result(code=200)
|
||||
|
||||
|
||||
@app.get("/webui/group")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取群信息
|
||||
"""
|
||||
group_list_result = []
|
||||
group_info = {}
|
||||
if bot := get_bot():
|
||||
group_list = await bot.get_group_list()
|
||||
for g in group_list:
|
||||
group_info[g["group_id"]] = Group(**g)
|
||||
group_data = group_manager.get_data()
|
||||
for group_id in group_data["group_manager"]:
|
||||
try:
|
||||
task_list = []
|
||||
data = group_data["group_manager"][group_id]
|
||||
for tn, status in data["group_task_status"].items():
|
||||
task_list.append(
|
||||
Task(
|
||||
**{
|
||||
"name": tn,
|
||||
"nameZh": group_manager.get_task_data().get(tn) or tn,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
)
|
||||
data["task"] = task_list
|
||||
if x := group_info.get(int(group_id)):
|
||||
data["group"] = x
|
||||
else:
|
||||
continue
|
||||
try:
|
||||
group_list_result.append(GroupResult(**data))
|
||||
except ValidationError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"WEB_UI /webui/group 发生错误 {type(e)}:{e}")
|
||||
return Result(code=200, data=group_list_result)
|
||||
|
||||
|
||||
@app.post("/webui/group")
|
||||
async def _(group: GroupResult, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改群信息
|
||||
"""
|
||||
group_id = group.group.group_id
|
||||
group_manager.set_group_level(group_id, group.level)
|
||||
if group.status:
|
||||
group_manager.turn_on_group_bot_status(group_id)
|
||||
else:
|
||||
group_manager.shutdown_group_bot_status(group_id)
|
||||
return Result(code=200)
|
||||
|
||||
|
||||
@app.get("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
req_data = requests_manager.get_data()
|
||||
req_list = []
|
||||
if type_ in ["group", "private"]:
|
||||
req_data = req_data[type_]
|
||||
for x in req_data:
|
||||
req_data[x]["oid"] = x
|
||||
req_list.append(RequestResult(**req_data[x]))
|
||||
return Result(code=200, data=req_list)
|
||||
|
||||
|
||||
@app.delete("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
清空请求
|
||||
:param type_: 类型
|
||||
"""
|
||||
requests_manager.clear(type_)
|
||||
return Result(code=200)
|
||||
|
||||
|
||||
@app.post("/webui/request")
|
||||
async def _(parma: RequestParma, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
操作请求
|
||||
:param parma: 参数
|
||||
"""
|
||||
result = "error"
|
||||
if bot := get_bot():
|
||||
if parma.handle == "approve":
|
||||
if parma.type == "group":
|
||||
rid = requests_manager.get_group_id(parma.id)
|
||||
if await GroupInfo.get_group_info(rid):
|
||||
await GroupInfo.set_group_flag(rid, 1)
|
||||
else:
|
||||
group_info = await bot.get_group_info(group_id=rid)
|
||||
await GroupInfo.add_group_info(
|
||||
rid,
|
||||
group_info["group_name"],
|
||||
group_info["max_member_count"],
|
||||
group_info["member_count"],
|
||||
1,
|
||||
)
|
||||
if await requests_manager.approve(bot, parma.id, parma.type):
|
||||
result = "ok"
|
||||
elif parma.handle == "refuse":
|
||||
if await requests_manager.refused(bot, parma.id, parma.type):
|
||||
result = "ok"
|
||||
elif parma.handle == "delete":
|
||||
requests_manager.delete_request(parma.id, parma.type)
|
||||
result = "ok"
|
||||
return Result(code=200, data=result)
|
||||
from .group import *
|
||||
from .plugins import *
|
||||
from .request import *
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
from pydantic.error_wrappers import ValidationError
|
||||
from services.log import logger
|
||||
from utils.manager import group_manager
|
||||
from utils.utils import get_bot
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
|
||||
@app.get("/webui/group")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取群信息
|
||||
"""
|
||||
group_list_result = []
|
||||
group_info = {}
|
||||
if bot := get_bot():
|
||||
group_list = await bot.get_group_list()
|
||||
for g in group_list:
|
||||
group_info[g["group_id"]] = Group(**g)
|
||||
group_data = group_manager.get_data()
|
||||
for group_id in group_data["group_manager"]:
|
||||
try:
|
||||
task_list = []
|
||||
data = group_data["group_manager"][group_id]
|
||||
for tn, status in data["group_task_status"].items():
|
||||
task_list.append(
|
||||
Task(
|
||||
**{
|
||||
"name": tn,
|
||||
"nameZh": group_manager.get_task_data().get(tn) or tn,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
)
|
||||
data["task"] = task_list
|
||||
if x := group_info.get(int(group_id)):
|
||||
data["group"] = x
|
||||
else:
|
||||
continue
|
||||
try:
|
||||
group_list_result.append(GroupResult(**data))
|
||||
except ValidationError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"WEB_UI /webui/group 发生错误 {type(e)}:{e}")
|
||||
return Result(code=200, data=group_list_result)
|
||||
|
||||
|
||||
@app.post("/webui/group")
|
||||
async def _(group: GroupResult, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改群信息
|
||||
"""
|
||||
group_id = group.group.group_id
|
||||
group_manager.set_group_level(group_id, group.level)
|
||||
if group.status:
|
||||
group_manager.turn_on_group_bot_status(group_id)
|
||||
else:
|
||||
group_manager.shutdown_group_bot_status(group_id)
|
||||
return Result(code=200)
|
||||
@@ -0,0 +1,142 @@
|
||||
from configs.config import Config
|
||||
from services.log import logger
|
||||
from utils.manager import (plugins2block_manager, plugins2cd_manager,
|
||||
plugins2count_manager, plugins2settings_manager,
|
||||
plugins_manager)
|
||||
from utils.utils import get_matchers
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
plugin_name_list = None
|
||||
|
||||
|
||||
@app.get("/webui/plugins")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取插件列表
|
||||
:param type_: 类型 normal, superuser, hidden, admin
|
||||
"""
|
||||
global plugin_name_list
|
||||
if not plugin_name_list:
|
||||
plugin_name_list = [x.plugin_name for x in get_matchers()]
|
||||
plugin_list = []
|
||||
plugin_data = plugins_manager.get_data()
|
||||
for model in plugin_data:
|
||||
if model in plugin_name_list:
|
||||
try:
|
||||
data = plugin_data.get(model)
|
||||
data["model"] = model
|
||||
plugin_name = data.get("plugin_name")
|
||||
if (
|
||||
(type_ == "hidden" and "[hidden]" not in plugin_name.lower())
|
||||
or (type_ == "admin" and "[admin]" not in plugin_name.lower())
|
||||
or (
|
||||
type_ == "superuser"
|
||||
and "[superuser]" not in plugin_name.lower()
|
||||
)
|
||||
):
|
||||
continue
|
||||
if type_ == "normal" and (
|
||||
"[hidden]" in plugin_name.lower()
|
||||
or "[admin]" in plugin_name.lower()
|
||||
or "[superuser]" in plugin_name.lower()
|
||||
):
|
||||
continue
|
||||
data = {"model": model}
|
||||
if x := plugin_data.get(model):
|
||||
if not x.get("status") and x.get("block_type") in [
|
||||
"group",
|
||||
"private",
|
||||
"all",
|
||||
]:
|
||||
x["block_type"] = (
|
||||
"群聊"
|
||||
if x["block_type"] == "group"
|
||||
else "私聊"
|
||||
if x["block_type"] == "private"
|
||||
else "全部"
|
||||
)
|
||||
data["plugin_manager"] = PluginManager(**x)
|
||||
if x := plugins2settings_manager.get(model):
|
||||
if x.get("cmd") and isinstance(x.get("cmd"), list):
|
||||
x["cmd"] = ",".join(x["cmd"])
|
||||
data["plugin_settings"] = PluginSettings(**x)
|
||||
if x := plugins2cd_manager.get(model):
|
||||
data["cd_limit"] = CdLimit(**x)
|
||||
if x := plugins2block_manager.get(model):
|
||||
data["block_limit"] = BlockLimit(**x)
|
||||
if x := plugins2count_manager.get(model):
|
||||
data["count_limit"] = CountLimit(**x)
|
||||
if x := Config.get(model):
|
||||
id_ = 0
|
||||
tmp = []
|
||||
for key in x.keys():
|
||||
tmp.append(
|
||||
PluginConfig(
|
||||
**{
|
||||
"key": key,
|
||||
"help_": x[key].get("help"),
|
||||
"id": id_,
|
||||
**x[key],
|
||||
}
|
||||
)
|
||||
)
|
||||
id_ += 1
|
||||
data["plugin_config"] = tmp
|
||||
plugin_list.append(Plugin(**data))
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}"
|
||||
)
|
||||
return Result(
|
||||
code=500,
|
||||
data=f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}",
|
||||
)
|
||||
return Result(code=200, data=plugin_list)
|
||||
|
||||
|
||||
@app.post("/webui/plugins")
|
||||
def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改插件信息
|
||||
:param plugin: 插件内容
|
||||
"""
|
||||
try:
|
||||
if plugin.plugin_config:
|
||||
for c in plugin.plugin_config:
|
||||
if str(c.value).lower() in ["true", "false"] and (
|
||||
c.default_value is None or isinstance(c.default_value, bool)
|
||||
):
|
||||
c.value = True if str(c.value).lower() == "true" else False
|
||||
elif isinstance(
|
||||
Config.get_config(plugin.model, c.key, c.value), int
|
||||
) or isinstance(c.default_value, int):
|
||||
c.value = int(c.value)
|
||||
elif isinstance(
|
||||
Config.get_config(plugin.model, c.key, c.value), float
|
||||
) or isinstance(c.default_value, float):
|
||||
c.value = float(c.value)
|
||||
elif isinstance(c.value, str) and (
|
||||
isinstance(Config.get_config(plugin.model, c.key, c.value), list)
|
||||
or isinstance(c.default_value, list)
|
||||
):
|
||||
c.value = c.value.split(",")
|
||||
Config.set_config(plugin.model, c.key, c.value)
|
||||
Config.save(None, True)
|
||||
else:
|
||||
if plugin.plugin_settings:
|
||||
for key, value in plugin.plugin_settings:
|
||||
plugins2settings_manager.set_module_data(plugin.model, key, value)
|
||||
if plugin.plugin_manager:
|
||||
for key, value in plugin.plugin_manager:
|
||||
plugins_manager.set_module_data(plugin.model, key, value)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}"
|
||||
)
|
||||
return Result(
|
||||
code=500,
|
||||
data=f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}",
|
||||
)
|
||||
return Result(code=200)
|
||||
@@ -0,0 +1,65 @@
|
||||
from utils.manager import requests_manager
|
||||
from ..auth import token_to_user, Depends, User
|
||||
from utils.utils import get_bot
|
||||
from models.group_info import GroupInfo
|
||||
from ..config import *
|
||||
|
||||
|
||||
@app.get("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
req_data = requests_manager.get_data()
|
||||
req_list = []
|
||||
if type_ in ["group", "private"]:
|
||||
req_data = req_data[type_]
|
||||
for x in req_data:
|
||||
req_data[x]["oid"] = x
|
||||
req_list.append(RequestResult(**req_data[x]))
|
||||
req_list.reverse()
|
||||
return Result(code=200, data=req_list)
|
||||
|
||||
|
||||
@app.delete("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
清空请求
|
||||
:param type_: 类型
|
||||
"""
|
||||
requests_manager.clear(type_)
|
||||
return Result(code=200)
|
||||
|
||||
|
||||
@app.post("/webui/request")
|
||||
async def _(parma: RequestParma, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
操作请求
|
||||
:param parma: 参数
|
||||
"""
|
||||
result = "ok"
|
||||
flag = 3
|
||||
if bot := get_bot():
|
||||
if parma.handle == "approve":
|
||||
if parma.type == "group":
|
||||
rid = requests_manager.get_group_id(parma.id)
|
||||
if await GroupInfo.get_group_info(rid):
|
||||
await GroupInfo.set_group_flag(rid, 1)
|
||||
else:
|
||||
group_info = await bot.get_group_info(group_id=rid)
|
||||
await GroupInfo.add_group_info(
|
||||
rid,
|
||||
group_info["group_name"],
|
||||
group_info["max_member_count"],
|
||||
group_info["member_count"],
|
||||
1,
|
||||
)
|
||||
flag = await requests_manager.approve(bot, parma.id, parma.type)
|
||||
elif parma.handle == "refuse":
|
||||
flag = await requests_manager.refused(bot, parma.id, parma.type)
|
||||
elif parma.handle == "delete":
|
||||
requests_manager.delete_request(parma.id, parma.type)
|
||||
if parma.handle != "delete":
|
||||
if flag == 1:
|
||||
result = "该请求已失效"
|
||||
requests_manager.delete_request(parma.id, parma.type)
|
||||
elif flag == 2:
|
||||
result = "未找到此Id"
|
||||
return Result(code=200, data=result)
|
||||
@@ -57,10 +57,19 @@ class PluginSettings(BaseModel):
|
||||
plugin_type: Optional[List[Union[str, int]]] # 帮助类型
|
||||
|
||||
|
||||
class PluginConfig(BaseModel):
|
||||
id: int
|
||||
key: str
|
||||
value: Optional[Any]
|
||||
help_: Optional[str]
|
||||
default_value: Optional[Any]
|
||||
|
||||
|
||||
class Plugin(BaseModel):
|
||||
model: str # 模块
|
||||
plugin_settings: Optional[PluginSettings]
|
||||
plugin_manager: Optional[PluginManager]
|
||||
plugin_config: Optional[List[PluginConfig]]
|
||||
cd_limit: Optional[CdLimit]
|
||||
block_limit: Optional[BlockLimit]
|
||||
count_limit: Optional[CountLimit]
|
||||
|
||||
@@ -28,13 +28,13 @@ class WordBankBuilder:
|
||||
"""
|
||||
self._data["answer"] = answer
|
||||
|
||||
async def save(self):
|
||||
async def save(self,search_type):
|
||||
user_id = self._data["user_id"]
|
||||
group_id = self._data["group_id"]
|
||||
problem = self._data["problem"]
|
||||
answer = self._data["answer"]
|
||||
placeholder = self._data.get("placeholder")
|
||||
await WordBank.add_problem_answer(user_id, group_id, problem, answer, placeholder)
|
||||
return await WordBank.add_problem_answer(user_id, group_id, search_type,problem, answer, placeholder)
|
||||
|
||||
async def update(self, index):
|
||||
user_id = self._data["user_id"]
|
||||
|
||||
+33
-23
@@ -25,6 +25,7 @@ class WordBank(db.Model):
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
search_type: [int],
|
||||
problem: str,
|
||||
answer: str,
|
||||
format_: Optional[List[Tuple[int, Union[int, str]]]],
|
||||
@@ -33,6 +34,7 @@ class WordBank(db.Model):
|
||||
添加或新增一个问答
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:search_type: 问题类型,
|
||||
:param problem: 问题
|
||||
:param answer: 回答
|
||||
:param format_: 格式化数据
|
||||
@@ -43,7 +45,7 @@ class WordBank(db.Model):
|
||||
for x, y in format_:
|
||||
_str += f"{x}<_s>{y}<format>"
|
||||
return await cls._problem_answer_handle(
|
||||
user_id, group_id, problem, "add", answer=answer, format_=_str
|
||||
user_id, group_id, problem, "add", search_type=search_type, answer=answer, format_=_str
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -159,22 +161,25 @@ class WordBank(db.Model):
|
||||
if problem:
|
||||
FUZZY = Config.get_config("word_bank", "WORD_BANK_FUZZY")
|
||||
KEY = Config.get_config("word_bank", "WORD_BANK_KEY")
|
||||
q = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem == problem)
|
||||
).gino.all()
|
||||
if KEY and FUZZY:
|
||||
q_fuzzy = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem.contains(f'{problem}'))).gino.all()
|
||||
q_key = await cls.query.where(cls.group_id == group_id).gino.all()
|
||||
(cls.group_id == group_id) & (cls.search_type == 2) & (
|
||||
cls.problem.contains(f'{problem}'))).gino.all()
|
||||
q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
|
||||
q_key = [x for x in q_key if str(x.problem) in (problem)]
|
||||
q = q_fuzzy + q_key
|
||||
q += q_fuzzy + q_key
|
||||
elif FUZZY:
|
||||
q = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem.contains(f'{problem}'))).gino.all()
|
||||
q_fuzzy = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.search_type == 2) & (
|
||||
cls.problem.contains(f'{problem}'))).gino.all()
|
||||
q += q_fuzzy
|
||||
elif KEY:
|
||||
q = await cls.query.where(cls.group_id == group_id).gino.all()
|
||||
q = [x for x in q if str(x.problem) in (problem)]
|
||||
else:
|
||||
q = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem == problem)
|
||||
).gino.all()
|
||||
q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
|
||||
q_key = [x for x in q_key if str(x.problem) in (problem)]
|
||||
q += q_key
|
||||
else:
|
||||
return None
|
||||
|
||||
@@ -188,6 +193,7 @@ class WordBank(db.Model):
|
||||
problem: str,
|
||||
type_: str,
|
||||
*,
|
||||
search_type: [int] = 0,
|
||||
answer: Optional[str] = None,
|
||||
index: Optional[int] = None,
|
||||
format_: Optional[str] = None,
|
||||
@@ -213,17 +219,21 @@ class WordBank(db.Model):
|
||||
else:
|
||||
q = cls.query.where((cls.user_qq == user_id) & (cls.problem == problem))
|
||||
if type_ == "add":
|
||||
q = await q.where(cls.answer == answer).gino.all()
|
||||
if not q or ".jpg" in format_:
|
||||
await cls.create(
|
||||
user_qq=user_id,
|
||||
group_id=group_id,
|
||||
problem=problem,
|
||||
answer=answer,
|
||||
format=format_,
|
||||
create_time=datetime.now().replace(microsecond=0),
|
||||
update_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
q = await q.where((cls.answer == answer) & (cls.search_type == search_type)).gino.all()
|
||||
try:
|
||||
if not q or ".jpg" in format_:
|
||||
await cls.create(
|
||||
user_qq=user_id,
|
||||
group_id=group_id,
|
||||
search_type=search_type,
|
||||
problem=problem,
|
||||
answer=answer,
|
||||
format=format_,
|
||||
create_time=datetime.now().replace(microsecond=0),
|
||||
update_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
elif type_ == "delete":
|
||||
q = await q.with_for_update().gino.all()
|
||||
|
||||
@@ -4,7 +4,6 @@ from services.log import logger
|
||||
from configs.path_config import DATA_PATH
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from ._data_source import WordBankBuilder
|
||||
from configs.config import Config
|
||||
from utils.message_builder import image
|
||||
from utils.image_utils import text2image
|
||||
from .message_handle import get_one_answer
|
||||
@@ -27,7 +26,7 @@ usage:
|
||||
对指定问题的随机回答,对相同问题可以设置多个不同回答
|
||||
删除词条后每个词条的id可能会变化,请查看后再删除
|
||||
指令:
|
||||
添加词条问...答...:添加问答词条,可重复添加相同问题的不同回答
|
||||
添加词条 ?[模糊/关键字]...答...:添加问答词条,可重复添加相同问题的不同回答
|
||||
删除词条 [问题/下标] ?[下标]:删除指定词条指定或全部回答
|
||||
修改词条 [问题/下标] ?[下标/新回答] [新回答]:修改指定词条指定回答默认修改为第一条
|
||||
查看词条 ?[问题/下标]:查看全部词条或对应词条回答
|
||||
@@ -44,12 +43,12 @@ usage:
|
||||
""".strip()
|
||||
__plugin_des__ = "自定义词条内容随机回复"
|
||||
__plugin_cmd__ = [
|
||||
"添加词条问...答..",
|
||||
"添加词条 ?[模糊/关键字]问...答..",
|
||||
"删除词条 [问题/下标] ?[下标]",
|
||||
"修改词条 [问题/下标] ?[下标/新回答] [新回答]",
|
||||
"查看词条 ?[问题/下标]",
|
||||
]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_version__ = 0.2
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"admin_level": Config.get_config("word_bank", "WORD_BANK_LEVEL [LEVEL]"),
|
||||
@@ -71,7 +70,7 @@ show_word = on_command("显示词条", aliases={"查看词条"}, priority=5, blo
|
||||
@add_word.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = CommandArg()):
|
||||
msg = str(arg)
|
||||
r = re.search(r"^问(.+)\s?答([\s\S]*)", msg)
|
||||
r = re.search(r"问(.+)\s?答([\s\S]*)", msg)
|
||||
if not r:
|
||||
await add_word.finish("未检测到词条问题...")
|
||||
problem = r.group(1).strip()
|
||||
@@ -87,10 +86,17 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = C
|
||||
break
|
||||
else:
|
||||
_problem = problem
|
||||
search_type = 0
|
||||
if re.search("^关键字(.*)", msg):
|
||||
search_type = 1
|
||||
elif re.search("^模糊(.*)", msg):
|
||||
search_type = 2
|
||||
_builder = await get__builder(event, _problem, answer, idx)
|
||||
await _builder.save()
|
||||
logger.info(f"已保存词条 问:{problem} 答:{msg}")
|
||||
await add_word.send(f"已保存词条:{problem}")
|
||||
if await _builder.save(search_type):
|
||||
logger.info(f"已保存词条 问:{problem} 答:{msg}")
|
||||
await add_word.send(f"已保存词条:{problem}")
|
||||
else:
|
||||
await delete_word.send("保存失败,可能是回答重复")
|
||||
|
||||
|
||||
@delete_word.handle()
|
||||
|
||||
@@ -85,7 +85,7 @@ class RequestManager(StaticData):
|
||||
return data["invite_group"]
|
||||
return None
|
||||
|
||||
async def approve(self, bot: Bot, id_: int, type_: str) -> Optional[int]:
|
||||
async def approve(self, bot: Bot, id_: int, type_: str) -> int:
|
||||
"""
|
||||
同意请求
|
||||
:param bot: Bot
|
||||
@@ -232,7 +232,7 @@ class RequestManager(StaticData):
|
||||
|
||||
async def _set_add_request(
|
||||
self, bot: Bot, id_: int, type_: str, approve: bool
|
||||
) -> Optional[int]:
|
||||
) -> int:
|
||||
"""
|
||||
处理请求
|
||||
:param bot: Bot
|
||||
@@ -260,12 +260,13 @@ class RequestManager(StaticData):
|
||||
f"同意{self._data[type_][id_]['nickname']}({self._data[type_][id_]['id']})"
|
||||
f"的{'好友' if type_ == 'private' else '入群'}请求失败了..."
|
||||
)
|
||||
return None
|
||||
logger.info(
|
||||
f"{'同意' if approve else '拒绝'}{self._data[type_][id_]['nickname']}({self._data[type_][id_]['id']})"
|
||||
f"的{'好友' if type_ == 'private' else '入群'}请求..."
|
||||
)
|
||||
return 1 # flag失效
|
||||
else:
|
||||
logger.info(
|
||||
f"{'同意' if approve else '拒绝'}{self._data[type_][id_]['nickname']}({self._data[type_][id_]['id']})"
|
||||
f"的{'好友' if type_ == 'private' else '入群'}请求..."
|
||||
)
|
||||
del self._data[type_][id_]
|
||||
self.save()
|
||||
return rid
|
||||
return None
|
||||
return 2 # 未找到id
|
||||
|
||||
Reference in New Issue
Block a user