Skip to content

Commit

Permalink
🎨 代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
HibiKier committed Sep 2, 2024
1 parent 8d071f8 commit 02aba68
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from datetime import datetime, timedelta, timezone
from datetime import datetime, timezone, timedelta

from nonebot.adapters import Bot

# from nonebot.adapters.kaiheila import Bot as KaiheilaBot
from nonebot.adapters.onebot.v11 import Bot as v11Bot
from nonebot.adapters.onebot.v12 import Bot as v12Bot

from zhenxun.services.log import logger
from zhenxun.configs.config import Config
from zhenxun.models.group_member_info import GroupInfoUser
from zhenxun.models.level_user import LevelUser
from zhenxun.services.log import logger
from zhenxun.models.group_member_info import GroupInfoUser

# from nonebot.adapters.discord import Bot as DiscordBot
# from nonebot.adapters.dodo import Bot as DodoBot
Expand All @@ -19,6 +19,10 @@ class MemberUpdateManage:

@classmethod
async def update(cls, bot: Bot, group_id: str):
if not group_id:
return logger.warning(
f"bot: {bot.self_id},group_id为空,无法更新群成员信息..."
)
if isinstance(bot, v11Bot):
await cls.v11(bot, group_id)
elif isinstance(bot, v12Bot):
Expand Down
23 changes: 13 additions & 10 deletions zhenxun/builtin_plugins/help_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,30 @@
import random

from nonebot import on_message
from nonebot.rule import to_me
from nonebot.matcher import Matcher
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me
from nonebot_plugin_alconna import UniMsg
from nonebot_plugin_session import EventSession

from zhenxun.configs.path_config import IMAGE_PATH
from zhenxun.configs.utils import PluginExtraData
from zhenxun.models.ban_console import BanConsole
from zhenxun.models.group_console import GroupConsole
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.services.log import logger
from zhenxun.utils.enum import PluginType
from zhenxun.utils.message import MessageUtils
from zhenxun.configs.utils import PluginExtraData
from zhenxun.models.ban_console import BanConsole
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.configs.path_config import IMAGE_PATH
from zhenxun.models.group_console import GroupConsole

__plugin_meta__ = PluginMetadata(
name="功能名称当命令检测",
name="笨蛋检测",
description="功能名称当命令检测",
usage=f"""被动""".strip(),
usage="""被动""".strip(),
extra=PluginExtraData(
author="HibiKier",
version="0.1",
plugin_type=PluginType.DEPENDANT,
menu_type="其他",
).dict(),
)

Expand Down Expand Up @@ -57,10 +58,12 @@ async def _(matcher: Matcher, message: UniMsg, session: EventSession):
if image:
message_list.append(image)
message_list.append(
f"桀桀桀,预判到会有 '笨蛋' 把功能名称当命令用,特地前来嘲笑!但还是好心来帮帮你啦!\n请at我发送 '帮助{plugin.name}' 或者 '帮助{plugin.id}' 来获取该功能帮助!"
"桀桀桀,预判到会有 '笨蛋' 把功能名称当命令用,特地前来嘲笑!"
f"但还是好心来帮帮你啦!\n请at我发送 '帮助{plugin.name}' 或者"
f" '帮助{plugin.id}' 来获取该功能帮助!"
)
logger.info(
f"检测到功能名称当命令使用,已发送帮助信息", "功能帮助", session=session
"检测到功能名称当命令使用,已发送帮助信息", "功能帮助", session=session
)
await MessageUtils.build_message(message_list).send(reply_to=True)
matcher.stop_propagation()
2 changes: 1 addition & 1 deletion zhenxun/builtin_plugins/init/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ async def _(bot: Bot):
await GroupConsole.filter(group_id__in=update_id).update(group_flag=1)
logger.debug(
f"更新Bot: {bot.self_id} 的群认证完成,共创建 {len(create_list)} 条数据,"
"共修改 {len(update_id)} 条数据..."
f"共修改 {len(update_id)} 条数据..."
)
62 changes: 40 additions & 22 deletions zhenxun/builtin_plugins/superuser/set_admin.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
from nonebot.permission import SUPERUSER
from nonebot.plugin import PluginMetadata
from nonebot_plugin_session import EventSession, SessionLevel
from nonebot_plugin_alconna import (
Alconna,
Args,
Arparma,
At,
Args,
Match,
Option,
Alconna,
Arparma,
Subcommand,
on_alconna,
)
from nonebot_plugin_session import EventSession, SessionLevel

from zhenxun.configs.utils import PluginExtraData
from zhenxun.models.level_user import LevelUser
from zhenxun.services.log import logger
from zhenxun.utils.enum import PluginType
from zhenxun.utils.message import MessageUtils
from zhenxun.models.level_user import LevelUser
from zhenxun.configs.utils import PluginExtraData

__plugin_meta__ = PluginMetadata(
name="用户权限管理",
description="设置用户权限",
usage="""
权限设置 add [level: 权限等级] [at: at对象或用户id] [gid: 群组]
权限设置 delete [at: at对象或用户id]
权限设置 add 5 @user
权限设置 add 5 422 352352
权限设置 add [level: 权限等级] [at: at对象或用户id] ?[-g gid: 群组]
权限设置 delete [at: at对象或用户id] ?[-g gid: 群组]
添加权限 5 @user
权限设置 add 5 422 -g 352352
删除权限 @user
删除权限 1234123 -g 123123
权限设置 delete @user
权限设置 delete 123456
""".strip(),
extra=PluginExtraData(
author="HibiKier",
Expand All @@ -44,16 +45,31 @@
"权限设置",
Subcommand(
"add",
Args["level", int]["uid", [str, At]]["gid?", str],
Args["level", int]["uid", [str, At]],
help_text="添加权限",
),
Subcommand("delete", Args["uid", [str, At]]["gid?", str], help_text="删除权限"),
Subcommand("delete", Args["uid", [str, At]], help_text="删除权限"),
Option("-g|--group", Args["gid", str], help_text="指定群组"),
),
permission=SUPERUSER,
priority=5,
block=True,
)

_matcher.shortcut(
"添加权限",
command="权限设置",
arguments=["add", "{%0}"],
prefix=True,
)

_matcher.shortcut(
"删除权限",
command="权限设置",
arguments=["delete", "{%0}"],
prefix=True,
)


@_matcher.assign("add")
async def _(
Expand Down Expand Up @@ -82,9 +98,10 @@ async def _(
]
).finish(reply_to=True)
await MessageUtils.build_message(
f"成功为 \n群组:{group_id}\n用户:{uid} \n设置权限!\n权限:{old_level} -> {level}"
f"成功为 \n群组:{group_id}\n用户:{uid} \n"
f"设置权限!\n权限:{old_level} -> {level}"
).finish()
await MessageUtils.build_message(f"设置权限时群组不能为空...").finish()
await MessageUtils.build_message("设置权限时群组不能为空...").finish()


@_matcher.assign("delete")
Expand All @@ -107,15 +124,16 @@ async def _(
session=session,
)
await MessageUtils.build_message(
["成功删除 ", At(flag="user", target=uid), f" 的权限等级!"]
["成功删除 ", At(flag="user", target=uid), " 的权限等级!"]
).finish(reply_to=True)
logger.info(
f"删除群组用户权限: {user.user_level} -> 0",
arparma.header_result,
session=session,
)
await MessageUtils.build_message(
f"成功删除 \n群组:{group_id}\n用户:{uid} \n的权限等级!\n权限:{user.user_level} -> 0"
f"成功删除 \n群组:{group_id}\n用户:{uid} \n"
f"的权限等级!\n权限:{user.user_level} -> 0"
).finish()
await MessageUtils.build_message(f"对方目前暂无权限喔...").finish()
await MessageUtils.build_message(f"设置权限时群组不能为空...").finish()
await MessageUtils.build_message("对方目前暂无权限喔...").finish()
await MessageUtils.build_message("设置权限时群组不能为空...").finish()
32 changes: 23 additions & 9 deletions zhenxun/services/db_context.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from nonebot.utils import is_coroutine_callable
from tortoise import Tortoise
from tortoise.connection import connections
from tortoise.models import Model as Model_
from nonebot.utils import is_coroutine_callable

from zhenxun.configs.config import BotConfig
from zhenxun.configs.path_config import DATA_PATH
Expand All @@ -28,9 +28,25 @@ def __init_subclass__(cls, **kwargs):
SCRIPT_METHOD.append((cls.__module__, func))


class DbUrlIsNode(Exception):
"""
数据库链接地址为空
"""

pass


class DbConnectError(Exception):
"""
数据库连接错误
"""

pass


async def init():
if not BotConfig.db_url:
raise Exception(f"数据库配置为空,请在.env.dev中配置DB_URL...")
raise DbUrlIsNode("数据库配置为空,请在.env.dev中配置DB_URL...")
try:
await Tortoise.init(
db_url=BotConfig.db_url,
Expand All @@ -40,15 +56,13 @@ async def init():
if SCRIPT_METHOD:
db = Tortoise.get_connection("default")
logger.debug(
f"即将运行SCRIPT_METHOD方法, 合计 <u><y>{len(SCRIPT_METHOD)}</y></u> 个..."
"即将运行SCRIPT_METHOD方法, 合计 "
f"<u><y>{len(SCRIPT_METHOD)}</y></u> 个..."
)
sql_list = []
for module, func in SCRIPT_METHOD:
try:
if is_coroutine_callable(func):
sql = await func()
else:
sql = func()
sql = await func() if is_coroutine_callable(func) else func()
if sql:
sql_list += sql
except Exception as e:
Expand All @@ -63,9 +77,9 @@ async def init():
if sql_list:
logger.debug("SCRIPT_METHOD方法执行完毕!")
await Tortoise.generate_schemas()
logger.info(f"Database loaded successfully!")
logger.info("Database loaded successfully!")
except Exception as e:
raise Exception(f"数据库连接错误... e:{e}")
raise DbConnectError(f"数据库连接错误... e:{e}") from e


async def disconnect():
Expand Down

0 comments on commit 02aba68

Please sign in to comment.