数据库中所有user_qq改名以及user_id和group_id改为字符串

This commit is contained in:
HibiKier
2023-05-22 20:56:42 +08:00
parent 0d3c6d8684
commit 848de7f4fe
68 changed files with 1103 additions and 645 deletions
+38 -33
View File
@@ -17,14 +17,16 @@ from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage
from utils.manager import group_manager, plugins2settings_manager, plugins_manager
from utils.message_builder import image
from utils.typing import BLOCK_TYPE
from utils.utils import get_matchers
custom_welcome_msg_json = (
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
)
CUSTOM_WELCOME_FILE = Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
CUSTOM_WELCOME_FILE.parent.mkdir(parents=True, exist_ok=True)
ICON_PATH = IMAGE_PATH / "other"
GROUP_HELP_PATH = DATA_PATH / "group_help"
async def group_current_status(group_id: int) -> str:
"""
@@ -66,14 +68,14 @@ async def group_current_status(group_id: int) -> str:
async def custom_group_welcome(
msg: str, img_list: List[str], user_id: int, group_id: int
msg: str, img_list: List[str], user_id: str, group_id: str
) -> Union[str, Message]:
"""
说明:
替换群欢迎消息
参数:
:param msg: 欢迎消息文本
:param img_list: 欢迎消息图片,只取第一张
:param img_list: 欢迎消息图片
:param user_id: 用户id,用于log记录
:param group_id: 群号
"""
@@ -84,18 +86,16 @@ async def custom_group_welcome(
if msg_image.exists():
msg_image.unlink()
data = {}
if not custom_welcome_msg_json.exists():
custom_welcome_msg_json.parent.mkdir(parents=True, exist_ok=True)
else:
try:
data = json.load(open(custom_welcome_msg_json, "r"))
except FileNotFoundError:
pass
if CUSTOM_WELCOME_FILE.exists():
data = json.load(CUSTOM_WELCOME_FILE.open("r", encoding="utf8"))
try:
if msg:
data[str(group_id)] = str(msg)
data[group_id] = msg
json.dump(
data, open(custom_welcome_msg_json, "w"), indent=4, ensure_ascii=False
data,
CUSTOM_WELCOME_FILE.open("w", encoding="utf8"),
indent=4,
ensure_ascii=False,
)
logger.info(f"更换群欢迎消息 {msg}", "更换群欢迎信息", user_id, group_id)
result += msg
@@ -151,12 +151,12 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False) -
参数:
:param cmd: 功能名称
:param group_id: 群号
:param is_super: 是否位超级用户,超级用户用于私聊开关功能状态
:param is_super: 是否为超级用户,超级用户用于私聊开关功能状态
"""
global task_data
if not task_data:
task_data = group_manager.get_task_data()
group_help_file = DATA_PATH / "group_help" / f"{group_id}.png"
help_path = GROUP_HELP_PATH / f"{group_id}.png"
status = cmd[:2]
cmd = cmd[2:]
type_ = "plugin"
@@ -169,8 +169,8 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False) -
else:
if group_manager.check_group_task_status(group_id, task):
group_manager.close_group_task(group_id, task)
if group_help_file.exists():
group_help_file.unlink()
if help_path.exists():
help_path.unlink()
return f"已 {status} 全部被动技能!"
if cmd == "全部功能":
for f in plugins2settings_manager.get_data():
@@ -179,8 +179,8 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False) -
else:
group_manager.block_plugin(f, group_id, False)
group_manager.save()
if group_help_file.exists():
group_help_file.unlink()
if help_path.exists():
help_path.unlink()
return f"已 {status} 全部功能!"
if cmd.lower() in [task_data[x].lower() for x in task_data.keys()]:
type_ = "task"
@@ -206,27 +206,28 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False) -
if not group_manager.get_plugin_status(module, group_id):
return f"功能 {cmd} 正处于关闭状态!不要重复关闭."
group_manager.block_plugin(module, group_id)
if group_help_file.exists():
group_help_file.unlink()
if help_path.exists():
help_path.unlink()
if is_super:
for file in os.listdir(DATA_PATH / "group_help"):
file = DATA_PATH / "group_help" / file
for file in os.listdir(GROUP_HELP_PATH):
file = GROUP_HELP_PATH / file
file.unlink()
else:
_help_image = DATA_PATH / "group_help" / f"{group_id}.png"
if _help_image.exists():
_help_image.unlink()
if help_path.exists():
help_path.unlink()
return f"{status} {cmd} 功能!"
def set_plugin_status(cmd: str, block_type: str = "all"):
def set_plugin_status(cmd: str, block_type: BLOCK_TYPE = "all"):
"""
说明:
设置插件功能状态(超级用户使用)
参数:
:param cmd: 功能名称
:param block_type: 限制类型, 'all': 私聊+群里, 'private': 私聊, 'group': 群聊
:param block_type: 限制类型, 'all': 全局, 'private': 私聊, 'group': 群聊
"""
if block_type not in ["all", "private", "group"]:
raise TypeError("block_type类型错误, 可选值: ['all', 'private', 'group']")
status = cmd[:2]
cmd = cmd[2:]
module = plugins2settings_manager.get_plugin_module(cmd)
@@ -234,8 +235,8 @@ def set_plugin_status(cmd: str, block_type: str = "all"):
plugins_manager.unblock_plugin(module)
else:
plugins_manager.block_plugin(module, block_type=block_type)
for file in os.listdir(DATA_PATH / "group_help"):
file = DATA_PATH / "group_help" / file
for file in os.listdir(GROUP_HELP_PATH):
file = GROUP_HELP_PATH / file
file.unlink()
@@ -306,7 +307,9 @@ async def update_member_info(
if user_info["role"] in [
"owner",
"admin",
] and not await LevelUser.is_group_flag(user_info["user_id"], str(group_id)):
] and not await LevelUser.is_group_flag(
user_info["user_id"], str(group_id)
):
await LevelUser.set_level(
user_info["user_id"],
user_info["group_id"],
@@ -356,7 +359,9 @@ async def update_member_info(
)
if _del_member_list:
for del_user in _del_member_list:
await GroupInfoUser.filter(user_id=str(del_user), group_id=str(group_id)).delete()
await GroupInfoUser.filter(
user_id=str(del_user), group_id=str(group_id)
).delete()
logger.info(f"删除已退群用户", "更新群组成员信息", del_user, group_id)
if _error_member_list and remind_superuser:
result = ""
@@ -16,10 +16,10 @@ admin_notice = on_notice(priority=5)
@admin_notice.handle()
async def _(event: GroupAdminNoticeEvent):
if user := await GroupInfoUser.filter(
if user := await GroupInfoUser.get_or_none(
user_id=str(event.user_id), group_id=str(event.group_id)
).first():
nickname = user.nickname
):
nickname = user.user_name
else:
nickname = event.user_id
if event.sub_type == "set":
@@ -31,7 +31,10 @@ async def _(event: GroupAdminNoticeEvent):
admin_default_auth,
)
logger.info(
f"为新晋管理员 {nickname}({event.user_id}) " f"添加权限等级:{admin_default_auth}"
f"成为管理员,添加权限: {admin_default_auth}",
"群管理员变动监测",
event.user_id,
event.group_id,
)
else:
logger.warning(
@@ -39,4 +42,4 @@ async def _(event: GroupAdminNoticeEvent):
)
elif event.sub_type == "unset":
await LevelUser.delete_level(event.user_id, event.group_id)
logger.info(f"将非管理员 {nickname}({event.user_id}) 取消权限等级")
logger.info("撤销管理员,,取消权限等级", "群管理员变动监测", event.user_id, event.group_id)
@@ -16,8 +16,8 @@ __plugin_usage__ = """
usage:
指令:
自定义进群欢迎消息 ?[文本] ?[图片]
示例:自定义进群欢迎消息 欢迎新人![图片]
Note:可以通过[at]来确认是否艾特新成员
示例:自定义进群欢迎消息 欢迎新人![图片]
示例:自定义进群欢迎消息 欢迎你[at]
""".strip()
__plugin_des__ = "简易的自定义群欢迎消息"
@@ -51,10 +51,12 @@ async def _(
await custom_welcome.finish(__plugin_usage__)
try:
await custom_welcome.send(
await custom_group_welcome(msg, img, event.user_id, event.group_id),
await custom_group_welcome(
msg, img, str(event.user_id), str(event.group_id)
),
at_sender=True,
)
logger.info(f"USER {event.user_id} GROUP {event.group_id} 自定义群欢迎消息:{msg}")
logger.info(f"自定义群欢迎消息:{msg}", cmd, event.user_id, event.group_id)
except Exception as e:
logger.error(
f"自定义进群欢迎消息发生错误", cmd, event.user_id, getattr(event, "group_id", None), e=e
@@ -9,7 +9,7 @@ from nonebot.adapters.onebot.v11 import (
MessageEvent,
PrivateMessageEvent,
)
from nonebot.params import RegexGroup
from nonebot.params import CommandArg, RegexGroup
from nonebot.permission import SUPERUSER
from configs.config import NICKNAME, Config
@@ -111,7 +111,7 @@ async def _(
block_type = "all" if block_type == "a" else block_type
block_type = "private" if block_type == "p" else block_type
block_type = "group" if block_type == "g" else block_type
set_plugin_status(_cmd, block_type)
set_plugin_status(_cmd, block_type) # type: ignore
if block_type == "all":
await switch_rule_matcher.send(f"已{_cmd[:2]}功能:{_cmd[2:]}")
elif block_type == "private":
@@ -6,6 +6,8 @@ from nonebot.adapters.onebot.v11 import (
GroupMessageEvent,
)
from services.log import logger
from ._data_source import update_member_info
__zx_plugin_name__ = "更新群组成员列表 [Admin]"
@@ -32,9 +34,11 @@ refresh_member_group = on_command(
@refresh_member_group.handle()
async def _(bot: Bot, event: GroupMessageEvent):
if await update_member_info(bot, event.group_id):
await refresh_member_group.finish("更新群员信息成功!", at_sender=True)
await refresh_member_group.send("更新群员信息成功!", at_sender=True)
logger.info("更新群员信息成功!", "更新群组成员列表", event.user_id, event.group_id)
else:
await refresh_member_group.finish("更新群员信息失败!", at_sender=True)
await refresh_member_group.send("更新群员信息失败!", at_sender=True)
logger.info("更新群员信息失败!", "更新群组成员列表", event.user_id, event.group_id)
group_increase_handle = on_notice(priority=1, block=False)
@@ -42,5 +46,6 @@ group_increase_handle = on_notice(priority=1, block=False)
@group_increase_handle.handle()
async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
if event.user_id == int(bot.self_id):
if str(event.user_id) == bot.self_id:
await update_member_info(bot, event.group_id)
logger.info("{NICKNAME}加入群聊更新群组信息", "更新群组成员列表", event.user_id, event.group_id)
-1
View File
@@ -10,7 +10,6 @@ from utils.manager.models import PluginType
driver: Driver = nonebot.get_driver()
background = IMAGE_PATH / "background" / "0.png"
ADMIN_HELP_IMAGE = IMAGE_PATH / "admin_help_img.png"
+8 -3
View File
@@ -118,10 +118,15 @@ async def _():
bot = bots[key]
fl = await bot.get_friend_list()
for f in fl:
await FriendUser.create(user_id=str(f["user_id"]), user_name=f["nickname"])
logger.debug(f"更新好友信息成功", "自动更新好友", f["user_id"])
if FriendUser.exists(user_id=str(f["user_id"])):
await FriendUser.create(
user_id=str(f["user_id"]), user_name=f["nickname"]
)
logger.debug(f"更新好友信息成功", "自动更新好友", f["user_id"])
else:
logger.debug(f"好友信息已存在", "自动更新好友", f["user_id"])
except Exception as e:
logger.error(f"自动更新群组信息错误", e=e)
logger.error(f"自动更新好友信息错误", "自动更新好友", e=e)
logger.info("自动更新好友信息成功...")
+1 -1
View File
@@ -56,7 +56,7 @@ __plugin_configs__ = {
"value": 5,
"help": "ban/unban所需要的管理员权限等级",
"default_value": 5,
"type": int
"type": int,
}
}
+2 -2
View File
@@ -30,7 +30,7 @@ def parse_ban_time(msg: str) -> Union[int, str]:
return int(msg_split[0]) * 60 * 60 + int(msg_split[1]) * 60
except ValueError as e:
logger.error("解析ban时长错误", ".ban", e=e)
return "时长不可以带小数点!"
return "时间解析错误!"
async def a_ban(
@@ -56,7 +56,7 @@ async def a_ban(
return "未查询到ban级用户权限"
if await BanUser.ban(qq, ban_level, time):
logger.info(
f"将 [Target]({qq})封禁 时长 {time / 60} 分钟", ".ban", event.user_id, group_id
f"封禁 时长 {time / 60} 分钟", ".ban", event.user_id, group_id, qq
)
result = f"已经将 {user_name} 加入{NICKNAME}的黑名单了!"
if time != -1:
+7 -8
View File
@@ -37,12 +37,12 @@ async def _(event: MessageEvent, msg: str = PlaintText()):
if isinstance(event, GroupMessageEvent):
group_id = str(event.group_id)
TEMP_LIST.append(
{
"user_id": str(event.user_id),
"group_id": group_id,
"text": str(event.get_message()),
"plain_text": msg,
}
ChatHistory(
user_id=str(event.user_id),
group_id=group_id,
text=str(event.get_message()),
plain_text=msg,
)
)
@@ -55,8 +55,7 @@ async def _():
message_list = TEMP_LIST.copy()
TEMP_LIST.clear()
if message_list:
model_list = [ChatHistory(**x) for x in message_list]
await ChatHistory.bulk_create(model_list)
await ChatHistory.bulk_create(message_list)
logger.debug(f"批量添加聊天记录 {len(message_list)} 条", "定时任务")
except Exception as e:
logger.error(f"定时批量添加聊天记录", "定时任务", e=e)
@@ -69,7 +69,7 @@ async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup())
num_str = "发言次数:\n\n"
idx = 1
for uid, num in rank_data:
if user := await GroupInfoUser.filter(user_id=str(uid), group_id=str(gid)).first():
if user := await GroupInfoUser.filter(user_id=uid, group_id=gid).first():
user_name = user.user_name
else:
user_name = uid
+6 -4
View File
@@ -139,7 +139,7 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
group_id=event.group_id, user_id=event.user_id
)
await GroupInfoUser.update_or_create(
user_qq=str(user_info["user_id"]),
user_id=str(user_info["user_id"]),
group_id=str(user_info["group_id"]),
defaults={"user_name": user_info["nickname"], "user_join_time": join_time},
)
@@ -187,7 +187,7 @@ async def _(bot: Bot, event: GroupDecreaseNoticeEvent):
group_id = event.group_id
operator_id = event.operator_id
if user := await GroupInfoUser.get_or_none(
user_qq=str(event.operator_id), group_id=str(event.group_id)
user_id=str(event.operator_id), group_id=str(event.group_id)
):
operator_name = user.user_name
else:
@@ -207,12 +207,14 @@ async def _(bot: Bot, event: GroupDecreaseNoticeEvent):
group_manager.delete_group(event.group_id)
return
if user := await GroupInfoUser.get_or_none(
user_qq=str(event.user_id), group_id=str(event.group_id)
user_id=str(event.user_id), group_id=str(event.group_id)
):
user_name = user.user_name
else:
user_name = f"{event.user_id}"
await GroupInfoUser.filter(user_id=str(event.user_id), group_id=str(event.group_id)).delete()
await GroupInfoUser.filter(
user_id=str(event.user_id), group_id=str(event.group_id)
).delete()
logger.info(
f"名称: {user_name} 退出群聊",
"group_decrease_handle",
@@ -19,25 +19,25 @@ def init_plugins_settings():
for matcher in get_matchers(True):
try:
if matcher.plugin_name not in plugins2settings_manager.keys():
_plugin = matcher.plugin
try:
_module = _plugin.module
except AttributeError:
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,插件控制未加载.")
else:
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
if plugin_settings := plugin_data.plugin_setting:
if (name := _module.__getattribute__("__zx_plugin_name__")) not in plugin_settings.cmd:
plugin_settings.cmd.append(name)
# 管理员命令
if plugin_data.plugin_type == PluginType.ADMIN:
admin_manager.add_admin_plugin_settings(
matcher.plugin_name, plugin_settings.cmd, plugin_settings.level
)
else:
plugins2settings_manager.add_plugin_settings(
matcher.plugin_name, plugin_settings
)
if _plugin := matcher.plugin:
try:
_module = _plugin.module
except AttributeError:
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,插件控制未加载.")
else:
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
if plugin_settings := plugin_data.plugin_setting:
if (name := _module.__getattribute__("__zx_plugin_name__")) not in plugin_settings.cmd:
plugin_settings.cmd.append(name)
# 管理员命令
if plugin_data.plugin_type == PluginType.ADMIN:
admin_manager.add_admin_plugin_settings(
matcher.plugin_name, plugin_settings.cmd, plugin_settings.level
)
else:
plugins2settings_manager.add_plugin_settings(
matcher.plugin_name, plugin_settings
)
except Exception as e:
logger.error(f'{matcher.plugin_name} 初始化 plugin_settings 发生错误 {type(e)}:{e}')
plugins2settings_manager.save()
-20
View File
@@ -98,26 +98,6 @@ async def _(bot: Bot):
logger.info(f"移除不存在的群聊信息", group_id=group_id)
# async def __database_script(_flag: List[str]):
# # bag_user 将文本转为字典格式
# if "bag_users" in _flag:
# for x in await BagUser.get_all_users():
# props = {}
# if x.props:
# for prop in [p for p in x.props.split(",") if p]:
# if props.get(prop):
# props[prop] += 1
# else:
# props[prop] = 1
# logger.info(
# f"__database_script USER {x.user_qq} GROUP {x.group_id} 更新数据 {props}"
# )
# await x.update(
# property=props,
# props="",
# ).apply()
# 自动更新城市列表
@scheduler.scheduled_job(
"cron",