From 45c6dbd2ce4d72b70081fd61390ee44f7cd1f7e7 Mon Sep 17 00:00:00 2001 From: HibiKier <775757368@qq.com> Date: Sat, 24 Aug 2024 19:32:52 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20=E4=BB=A3=E7=A0=81=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.dev | 13 ++-- bot.py | 5 +- zhenxun/builtin_plugins/__init__.py | 15 ---- .../admin/group_member_update/__init__.py | 2 +- zhenxun/builtin_plugins/nickname.py | 16 ++--- .../platform/qq/group_handle.py | 5 +- .../builtin_plugins/plugin_store/__init__.py | 3 +- .../builtin_plugins/plugin_store/config.py | 6 +- .../plugin_store/data_source.py | 35 +++++++--- zhenxun/builtin_plugins/record_request.py | 6 +- zhenxun/builtin_plugins/restart/__init__.py | 6 +- zhenxun/builtin_plugins/scheduler/morning.py | 2 +- zhenxun/builtin_plugins/sign_in/utils.py | 10 +-- .../builtin_plugins/superuser/group_manage.py | 4 +- .../web_ui/api/tabs/manage/__init__.py | 4 +- .../builtin_plugins/web_ui/public/__init__.py | 4 +- .../web_ui/public/data_source.py | 23 ++----- zhenxun/configs/config.py | 69 +++++++------------ zhenxun/plugins/ai/__init__.py | 2 +- zhenxun/plugins/ai/data_source.py | 8 +-- zhenxun/plugins/ai/utils.py | 8 +-- zhenxun/plugins/black_word/black_word.py | 4 +- zhenxun/plugins/dialogue/__init__.py | 11 ++- zhenxun/plugins/fudu.py | 2 +- zhenxun/plugins/gold_redbag/__init__.py | 8 +-- zhenxun/plugins/gold_redbag/data_source.py | 4 +- zhenxun/plugins/mute/mute_message.py | 2 +- zhenxun/plugins/mute/mute_setting.py | 2 +- zhenxun/plugins/roll.py | 2 +- zhenxun/plugins/russian/data_source.py | 4 +- .../search_buff_skin_price/__init__.py | 2 +- .../plugins/send_setu_/send_setu/__init__.py | 2 +- .../send_setu_/send_setu/_data_source.py | 2 +- zhenxun/services/db_context.py | 48 ++----------- zhenxun/utils/_image_template.py | 17 +++-- zhenxun/utils/message.py | 2 +- 36 files changed, 149 insertions(+), 209 deletions(-) diff --git a/.env.dev b/.env.dev index 5b5ffd35..44f19fe2 100644 --- a/.env.dev +++ b/.env.dev @@ -11,10 +11,14 @@ SESSION_EXPIRE_TIMEOUT=30 # 全局图片统一使用bytes发送,当真寻与协议端不在同一服务器上时为True IMAGE_TO_BYTES = False -# 作为原config.py文件中的NICKNAME -CONFIG_NICKNAME="小真寻" +# 回复消息时自称 +SELF_NICKNAME="小真寻" -# 作为原config.py文件中的SYSTEM_PROXY +# 数据库配置 +# 示例: "postgres://user:password@127.0.0.1:5432/database" +DB_URL = "" + +# 系统代理 # SYSTEM_PROXY = "http://127.0.0.1:7890" PLATFORM_SUPERUSERS = ' @@ -61,5 +65,4 @@ PORT = 8080 # ' # application_commands的{"*": ["*"]}代表将全部应用命令注册为全局应用命令 -# {"admin": ["123", "456"]}则代表将admin命令注册为id是123、456服务器的局部命令,其余命令不注册 - +# {"admin": ["123", "456"]}则代表将admin命令注册为id是123、456服务器的局部命令,其余命令不注册 \ No newline at end of file diff --git a/bot.py b/bot.py index b3009b5c..915b7778 100644 --- a/bot.py +++ b/bot.py @@ -5,9 +5,10 @@ from nonebot.adapters.dodo import Adapter as DoDoAdapter from nonebot.adapters.kaiheila import Adapter as KaiheilaAdapter from nonebot.adapters.onebot.v11 import Adapter as OneBotV11Adapter +nonebot.init() + from zhenxun.services.db_context import disconnect, init -nonebot.init() driver = nonebot.get_driver() driver.register_adapter(OneBotV11Adapter) driver.register_adapter(KaiheilaAdapter) @@ -18,7 +19,7 @@ driver.register_adapter(DoDoAdapter) driver.on_startup(init) driver.on_shutdown(disconnect) -nonebot.load_builtin_plugins("echo") # 内置插件 +# nonebot.load_builtin_plugins("echo") nonebot.load_plugins("zhenxun/builtin_plugins") nonebot.load_plugins("zhenxun/plugins") diff --git a/zhenxun/builtin_plugins/__init__.py b/zhenxun/builtin_plugins/__init__.py index 7eb01d6e..9bce3c1c 100644 --- a/zhenxun/builtin_plugins/__init__.py +++ b/zhenxun/builtin_plugins/__init__.py @@ -5,7 +5,6 @@ from nonebot.drivers import Driver from tortoise import Tortoise from tortoise.exceptions import OperationalError -from zhenxun.configs.config import BotConfig from zhenxun.models.goods_info import GoodsInfo from zhenxun.models.group_member_info import GroupInfoUser from zhenxun.models.sign_user import SignUser @@ -47,20 +46,6 @@ from public.bag_users t1 """ -@driver.on_startup -async def _(): - try: - if driver.config.config_nickname: - BotConfig.nickname = driver.config.config_nickname - except: - pass - try: - if driver.config.system_proxy: - BotConfig.system_proxy = driver.config.config_nickname - except: - pass - - @driver.on_startup async def _(): """签到与用户的数据迁移""" diff --git a/zhenxun/builtin_plugins/admin/group_member_update/__init__.py b/zhenxun/builtin_plugins/admin/group_member_update/__init__.py index 3b355bb1..2c9fbd21 100644 --- a/zhenxun/builtin_plugins/admin/group_member_update/__init__.py +++ b/zhenxun/builtin_plugins/admin/group_member_update/__init__.py @@ -62,7 +62,7 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent): if str(event.user_id) == bot.self_id: await MemberUpdateManage.update(bot, str(event.group_id)) logger.info( - f"{BotConfig.nickname}加入群聊更新群组信息", + f"{BotConfig.self_nickname}加入群聊更新群组信息", "更新群组成员列表", session=event.user_id, group_id=event.group_id, diff --git a/zhenxun/builtin_plugins/nickname.py b/zhenxun/builtin_plugins/nickname.py index 2e7ce521..60779e8b 100644 --- a/zhenxun/builtin_plugins/nickname.py +++ b/zhenxun/builtin_plugins/nickname.py @@ -24,11 +24,11 @@ __plugin_meta__ = PluginMetadata( name="昵称系统", description="区区昵称,才不想叫呢!", usage=f""" - 个人昵称,将替换{BotConfig.nickname}称呼你的名称,群聊 与 私聊 昵称相互独立,全局昵称设置将更改您目前所有群聊中及私聊的昵称 + 个人昵称,将替换{BotConfig.self_nickname}称呼你的名称,群聊 与 私聊 昵称相互独立,全局昵称设置将更改您目前所有群聊中及私聊的昵称 指令: 以后叫我 [昵称]: 设置当前群聊/私聊的昵称 全局昵称设置 [昵称]: 设置当前所有群聊和私聊的昵称 - {BotConfig.nickname}我是谁 + {BotConfig.self_nickname}我是谁 """.strip(), extra=PluginExtraData( author="HibiKier", @@ -86,25 +86,25 @@ _matcher.shortcut( CALL_NAME = [ "好啦好啦,我知道啦,{},以后就这么叫你吧", - f"嗯嗯,{BotConfig.nickname}" + "记住你的昵称了哦,{}", + f"嗯嗯,{BotConfig.self_nickname}" + "记住你的昵称了哦,{}", "好突然,突然要叫你昵称什么的...{}..", - f"{BotConfig.nickname}" + "会好好记住{}的,放心吧", + f"{BotConfig.self_nickname}" + "会好好记住{}的,放心吧", "好..好.,那窝以后就叫你{}了.", ] REMIND = [ "我肯定记得你啊,你是{}啊", "我不会忘记你的,你也不要忘记我!{}", - f"哼哼,{BotConfig.nickname}" + "记忆力可是很好的,{}", + f"哼哼,{BotConfig.self_nickname}" + "记忆力可是很好的,{}", "嗯?你是失忆了嘛...{}..", - f"不要小看{BotConfig.nickname}" + "的记忆力啊!笨蛋{}!QAQ", + f"不要小看{BotConfig.self_nickname}" + "的记忆力啊!笨蛋{}!QAQ", "哎?{}..怎么了吗..突然这样问..", ] CANCEL = [ - f"呜..{BotConfig.nickname}" + "睡一觉就会忘记的..和梦一样..{}", + f"呜..{BotConfig.self_nickname}" + "睡一觉就会忘记的..和梦一样..{}", "窝知道了..{}..", - f"是{BotConfig.nickname}" + "哪里做的不好嘛..好吧..晚安{}", + f"是{BotConfig.self_nickname}" + "哪里做的不好嘛..好吧..晚安{}", "呃,{},下次我绝对绝对绝对不会再忘记你!", "可..可恶!{}!太可恶了!呜", ] diff --git a/zhenxun/builtin_plugins/platform/qq/group_handle.py b/zhenxun/builtin_plugins/platform/qq/group_handle.py index d97d9013..d2f851e2 100644 --- a/zhenxun/builtin_plugins/platform/qq/group_handle.py +++ b/zhenxun/builtin_plugins/platform/qq/group_handle.py @@ -44,7 +44,7 @@ __plugin_meta__ = PluginMetadata( RegisterConfig( module="invite_manager", key="message", - value=f"请不要未经同意就拉{BotConfig.nickname}入群!告辞!", + value=f"请不要未经同意就拉{BotConfig.self_nickname}入群!告辞!", help="强制拉群后进群回复的内容", ), RegisterConfig( @@ -88,8 +88,6 @@ __plugin_meta__ = PluginMetadata( ) -superuser = nonebot.get_driver().config.platform_superusers["qq"][0] - base_config = Config.get("invite_manager") @@ -108,6 +106,7 @@ add_group = on_request(priority=1, block=False) @group_increase_handle.handle() async def _(bot: Bot, event: GroupIncreaseNoticeEvent | GroupMemberIncreaseEvent): + superuser = BotConfig.get_superuser("qq") user_id = str(event.user_id) group_id = str(event.group_id) if user_id == bot.self_id: diff --git a/zhenxun/builtin_plugins/plugin_store/__init__.py b/zhenxun/builtin_plugins/plugin_store/__init__.py index abf3049a..41185afc 100644 --- a/zhenxun/builtin_plugins/plugin_store/__init__.py +++ b/zhenxun/builtin_plugins/plugin_store/__init__.py @@ -57,9 +57,10 @@ async def _(session: EventSession): try: result = await ShopManage.get_plugins_info() logger.info("查看插件列表", "插件商店", session=session) - await MessageUtils.build_message(result).finish() + await MessageUtils.build_message(result).send() except Exception as e: logger.error(f"查看插件列表失败 e: {e}", "插件商店", session=session, e=e) + await MessageUtils.build_message("获取插件列表失败...").send() @_matcher.assign("add") diff --git a/zhenxun/builtin_plugins/plugin_store/config.py b/zhenxun/builtin_plugins/plugin_store/config.py index 056c1e83..867b383c 100644 --- a/zhenxun/builtin_plugins/plugin_store/config.py +++ b/zhenxun/builtin_plugins/plugin_store/config.py @@ -4,12 +4,10 @@ BASE_PATH = Path() / "zhenxun" BASE_PATH.mkdir(parents=True, exist_ok=True) -CONFIG_URL = ( - "https://cdn.jsdelivr.net/gh/HibiKier/zhenxun_bot_plugins/plugins.json" -) +CONFIG_URL = "https://cdn.jsdelivr.net/gh/zhenxun-org/zhenxun_bot_plugins/plugins.json" """插件信息文件""" DOWNLOAD_URL = ( - "https://api.github.com/repos/HibiKier/zhenxun_bot_plugins/contents/{}?ref=main" + "https://api.github.com/repos/zhenxun-org/zhenxun_bot_plugins/contents/{}?ref=main" ) """插件下载地址""" diff --git a/zhenxun/builtin_plugins/plugin_store/data_source.py b/zhenxun/builtin_plugins/plugin_store/data_source.py index c868998f..79104adf 100644 --- a/zhenxun/builtin_plugins/plugin_store/data_source.py +++ b/zhenxun/builtin_plugins/plugin_store/data_source.py @@ -1,7 +1,7 @@ -import shutil -from pathlib import Path -import subprocess import os +import shutil +import subprocess +from pathlib import Path import nonebot import ujson as json @@ -87,16 +87,29 @@ async def download_file(url: str): def install_requirement(plugin_path: Path): requirement_path = plugin_path / "requirement.txt" - + if not requirement_path.exists(): - logger.debug(f"No requirement.txt found for plugin: {plugin_path.name}", "插件管理") + logger.debug( + f"No requirement.txt found for plugin: {plugin_path.name}", "插件管理" + ) return - + try: - result = subprocess.run(["pip", "install", "-r", str(requirement_path)], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) - logger.debug(f"Successfully installed dependencies for plugin: {plugin_path.name}. Output:\n{result.stdout}", "插件管理") + result = subprocess.run( + ["pip", "install", "-r", str(requirement_path)], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + logger.debug( + f"Successfully installed dependencies for plugin: {plugin_path.name}. Output:\n{result.stdout}", + "插件管理", + ) except subprocess.CalledProcessError as e: - logger.error(f"Failed to install dependencies for plugin: {plugin_path.name}. Error:\n{e.stderr}") + logger.error( + f"Failed to install dependencies for plugin: {plugin_path.name}. Error:\n{e.stderr}" + ) class ShopManage: @@ -187,11 +200,11 @@ class ShopManage: return "插件下载地址构建失败..." logger.debug(f"尝试下载插件 URL: {url_path}", "插件管理") await download_file(DOWNLOAD_URL.format(url_path)) - + # 安装依赖 plugin_path = BASE_PATH / "/".join(module_path_split) install_requirement(plugin_path) - + return f"插件 {plugin_key} 安装成功!" @classmethod diff --git a/zhenxun/builtin_plugins/record_request.py b/zhenxun/builtin_plugins/record_request.py index 3833dbf6..8a837e7a 100644 --- a/zhenxun/builtin_plugins/record_request.py +++ b/zhenxun/builtin_plugins/record_request.py @@ -69,7 +69,7 @@ _t = on_message(priority=999, block=False, rule=lambda: False) @friend_req.handle() async def _(bot: v12Bot | v11Bot, event: FriendRequestEvent, session: EventSession): - superuser = nonebot.get_driver().config.platform_superusers["qq"][0] + superuser = BotConfig.get_superuser("qq") if event.user_id and Timer.check(event.user_id): logger.debug(f"收录好友请求...", "好友请求", target=event.user_id) user = await bot.get_stranger_info(user_id=event.user_id) @@ -117,7 +117,7 @@ async def _(bot: v12Bot | v11Bot, event: FriendRequestEvent, session: EventSessi @group_req.handle() async def _(bot: v12Bot | v11Bot, event: GroupRequestEvent, session: EventSession): - superuser = nonebot.get_driver().config.platform_superusers["qq"][0] + superuser = BotConfig.get_superuser("qq") # 邀请 if event.sub_type == "invite": if str(event.user_id) in bot.config.superusers: @@ -171,7 +171,7 @@ async def _(bot: v12Bot | v11Bot, event: GroupRequestEvent, session: EventSessio ) await bot.send_private_msg( user_id=event.user_id, - message=f"想要邀请我偷偷入群嘛~已经提醒{BotConfig.nickname}的管理员大人了\n" + message=f"想要邀请我偷偷入群嘛~已经提醒{BotConfig.self_nickname}的管理员大人了\n" "请确保已经群主或群管理沟通过!\n" "等待管理员处理吧!", ) diff --git a/zhenxun/builtin_plugins/restart/__init__.py b/zhenxun/builtin_plugins/restart/__init__.py index 95c21173..3c16091f 100644 --- a/zhenxun/builtin_plugins/restart/__init__.py +++ b/zhenxun/builtin_plugins/restart/__init__.py @@ -48,12 +48,12 @@ RESTART_FILE = Path() / "restart.sh" @_matcher.got( "flag", - prompt=f"确定是否重启{BotConfig.nickname}?确定请回复[是|好|确定](重启失败咱们将失去联系,请谨慎!)", + prompt=f"确定是否重启{BotConfig.self_nickname}?确定请回复[是|好|确定](重启失败咱们将失去联系,请谨慎!)", ) async def _(bot: Bot, session: EventSession, flag: str = ArgStr("flag")): if flag.lower() in ["true", "是", "好", "确定", "确定是"]: await MessageUtils.build_message( - f"开始重启{BotConfig.nickname}..请稍等..." + f"开始重启{BotConfig.self_nickname}..请稍等..." ).send() with open(RESTART_MARK, "w", encoding="utf8") as f: f.write(f"{bot.self_id} {session.id1}") @@ -93,6 +93,6 @@ async def _(bot: Bot): if bot := nonebot.get_bot(bot_id): if target := PlatformUtils.get_target(bot, session_id): await MessageUtils.build_message( - f"{BotConfig.nickname}已成功重启!" + f"{BotConfig.self_nickname}已成功重启!" ).send(target, bot=bot) RESTART_MARK.unlink() diff --git a/zhenxun/builtin_plugins/scheduler/morning.py b/zhenxun/builtin_plugins/scheduler/morning.py index 8c9d70ac..dbb3536a 100644 --- a/zhenxun/builtin_plugins/scheduler/morning.py +++ b/zhenxun/builtin_plugins/scheduler/morning.py @@ -61,7 +61,7 @@ async def _(): async def _(): message = MessageUtils.build_message( [ - f"{BotConfig.nickname}要睡觉了,你们也要早点睡呀", + f"{BotConfig.self_nickname}要睡觉了,你们也要早点睡呀", IMAGE_PATH / "zhenxun" / "sleep.jpg", ] ) diff --git a/zhenxun/builtin_plugins/sign_in/utils.py b/zhenxun/builtin_plugins/sign_in/utils.py index d822f1a7..b08a09d5 100644 --- a/zhenxun/builtin_plugins/sign_in/utils.py +++ b/zhenxun/builtin_plugins/sign_in/utils.py @@ -151,7 +151,7 @@ async def _generate_card( interpolation = 0 await info_img.text((0, 0), f"· 好感度等级:{level} [{lik2relation[level]}]") await info_img.text( - (0, 20), f"· {BotConfig.nickname}对你的态度:{level2attitude[level]}" + (0, 20), f"· {BotConfig.self_nickname}对你的态度:{level2attitude[level]}" ) await info_img.text((0, 40), f"· 距离升级还差 {interpolation:.2f} 好感度") @@ -216,7 +216,7 @@ async def _generate_card( f"好感度:{user.impression:.2f}", size=30 ) watermark = await BuildImage.build_text_image( - f"{BotConfig.nickname}@{datetime.now().year}", + f"{BotConfig.self_nickname}@{datetime.now().year}", size=15, font_color=(155, 155, 155), ) @@ -400,7 +400,7 @@ async def _generate_html_card( if level == "9": level = "8" interpolation = 0 - message = f"{BotConfig.nickname}希望你开心!" + message = f"{BotConfig.self_nickname}希望你开心!" hour = datetime.now().hour if hour > 6 and hour < 10: message = random.choice(MORNING_MESSAGE) @@ -420,13 +420,13 @@ async def _generate_html_card( "name": nickname, "uid": uid, "sign_count": f"{user.sign_count}", - "message": f"{BotConfig.nickname}说: {message}", + "message": f"{BotConfig.self_nickname}说: {message}", "cur_impression": f"{user.impression:.2f}", "impression": f"好感度+{_impression}", "gold": f"金币+{gold}", "gift": gift, "level": f"{level} [{lik2relation[level]}]", - "attitude": f"{BotConfig.nickname}对你的态度: {level2attitude[level]}", + "attitude": f"{BotConfig.self_nickname}对你的态度: {level2attitude[level]}", "interpolation": f"{interpolation:.2f}", "heart2": [1 for _ in range(int(level))], "heart1": [1 for _ in range(9 - int(level))], diff --git a/zhenxun/builtin_plugins/superuser/group_manage.py b/zhenxun/builtin_plugins/superuser/group_manage.py index 4bd01cc2..f8e282dd 100644 --- a/zhenxun/builtin_plugins/superuser/group_manage.py +++ b/zhenxun/builtin_plugins/superuser/group_manage.py @@ -192,12 +192,12 @@ async def _(bot: Bot, session: EventSession, arparma: Arparma, group_id: int): if group_id not in group_list: logger.debug("群组不存在", "退群", session=session, target=group_id) await MessageUtils.build_message( - f"{BotConfig.nickname}未在该群组中..." + f"{BotConfig.self_nickname}未在该群组中..." ).finish() try: await bot.set_group_leave(group_id=group_id) logger.info( - f"{BotConfig.nickname}退出群组成功", + f"{BotConfig.self_nickname}退出群组成功", "退群", session=session, target=group_id, diff --git a/zhenxun/builtin_plugins/web_ui/api/tabs/manage/__init__.py b/zhenxun/builtin_plugins/web_ui/api/tabs/manage/__init__.py index ea010d88..902b189b 100644 --- a/zhenxun/builtin_plugins/web_ui/api/tabs/manage/__init__.py +++ b/zhenxun/builtin_plugins/web_ui/api/tabs/manage/__init__.py @@ -133,7 +133,7 @@ async def _() -> Result: "friend_count": f_count, "group_count": g_count, } - return Result.ok(data, f"{BotConfig.nickname}带来了最新的数据!") + return Result.ok(data, f"{BotConfig.self_nickname}带来了最新的数据!") @router.get( @@ -177,7 +177,7 @@ async def _() -> Result: except Exception as e: logger.error("调用API错误", "/get_request", e=e) return Result.fail(f"{type(e)}: {e}") - return Result.ok(req_result, f"{BotConfig.nickname}带来了最新的数据!") + return Result.ok(req_result, f"{BotConfig.self_nickname}带来了最新的数据!") @router.post( diff --git a/zhenxun/builtin_plugins/web_ui/public/__init__.py b/zhenxun/builtin_plugins/web_ui/public/__init__.py index 144dcda8..b194ffe7 100644 --- a/zhenxun/builtin_plugins/web_ui/public/__init__.py +++ b/zhenxun/builtin_plugins/web_ui/public/__init__.py @@ -1,6 +1,6 @@ +from fastapi import APIRouter, FastAPI from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles -from fastapi import APIRouter, FastAPI from zhenxun.services.log import logger @@ -32,4 +32,4 @@ async def init_public(app: FastAPI): name=f"public_{pathname}", ) except Exception as e: - logger.error(f"初始化 web ui assets 失败 e: {e}", "Web UI assets") \ No newline at end of file + logger.error(f"初始化 web ui assets 失败", "Web UI assets", e=e) diff --git a/zhenxun/builtin_plugins/web_ui/public/data_source.py b/zhenxun/builtin_plugins/web_ui/public/data_source.py index 65fe5d3c..eb04d297 100644 --- a/zhenxun/builtin_plugins/web_ui/public/data_source.py +++ b/zhenxun/builtin_plugins/web_ui/public/data_source.py @@ -1,19 +1,14 @@ import os import shutil import zipfile - from pathlib import Path + from nonebot.utils import run_sync + from zhenxun.services.log import logger from zhenxun.utils.http_utils import AsyncHttpx -from .config import ( - WEBUI_ASSETS_DOWNLOAD_URL, - WEBUI_DATA_PATH, - TMP_PATH, - COMMAND_NAME, - PUBLIC_PATH, -) +from .config import COMMAND_NAME, PUBLIC_PATH, TMP_PATH, WEBUI_ASSETS_DOWNLOAD_URL async def update_webui_assets(): @@ -22,13 +17,8 @@ async def update_webui_assets(): WEBUI_ASSETS_DOWNLOAD_URL, webui_assets_path, follow_redirects=True ): logger.info("下载 webui_assets 成功...", COMMAND_NAME) - else: - logger.error("下载 webui_assets 失败...", COMMAND_NAME) - - await _file_handle(webui_assets_path) - - logger.info("更新 webui_assets 成功...", COMMAND_NAME) - return True + return await _file_handle(webui_assets_path) + raise Exception("下载 webui_assets 失败", COMMAND_NAME) @run_sync @@ -39,8 +29,7 @@ def _file_handle(webui_assets_path: Path): tf.extractall(TMP_PATH) logger.debug("解压 webui_assets 成功...", COMMAND_NAME) else: - logger.error("解压 webui_assets 失败...", COMMAND_NAME) - return + raise Exception("解压 webui_assets 失败,文件不存在...", COMMAND_NAME) download_file_path = ( TMP_PATH / [x for x in os.listdir(TMP_PATH) if (TMP_PATH / x).is_dir()][0] ) diff --git a/zhenxun/configs/config.py b/zhenxun/configs/config.py index 078f131c..56f0fdb9 100644 --- a/zhenxun/configs/config.py +++ b/zhenxun/configs/config.py @@ -1,57 +1,38 @@ -import platform +import random from pathlib import Path +import nonebot +from pydantic import BaseModel + from .utils import ConfigsManager -if platform.system() == "Linux": - import os - hostip = ( - os.popen("cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }'") - .read() - .replace("\n", "") - ) +class BotSetting(BaseModel): + self_nickname: str = "" + """回复时NICKNAME""" + system_proxy: str | None = None + """系统代理""" + db_url: str = "" + """数据库链接""" + platform_superusers: dict[str, list[str]] = {} + """平台超级用户""" -class BotConfigSetting: + def get_superuser(self, platform: str) -> str: + """获取超级用户 - def __init__(self) -> None: - self.__nickname: str = "" - self.__system_proxy: str | None = None + 参数: + platform: 对应平台 - @property - def nickname(self) -> str: - return self.__nickname + 返回: + str | None: 超级用户id + """ + if self.platform_superusers: + if platform_superuser := self.platform_superusers.get(platform): + return random.choice(platform_superuser) + return "" - @nickname.setter - def nickname(self, v: str): - self.__nickname = v - - @property - def system_proxy(self) -> str | None: - return self.__system_proxy - - @system_proxy.setter - def system_proxy(self, v: str): - self.__system_proxy = v - - -# 回复消息名称 -NICKNAME: str = "" - -# 代理,例如 "http://127.0.0.1:7890" -# 如果是WLS 可以 f"http://{hostip}:7890" 使用寄主机的代理 -SYSTEM_PROXY: str | None = None # 全局代理 - -# 示例:"bind": "postgres://user:password@127.0.0.1:5432/database" -bind: str = "" # 数据库连接链接 -sql_name: str = "postgres" -user: str = "" # 数据用户名 -password: str = "" # 数据库密码 -address: str = "" # 数据库地址 -port: str = "" # 数据库端口 -database: str = "" # 数据库名称 Config = ConfigsManager(Path() / "data" / "configs" / "plugins2config.yaml") -BotConfig = BotConfigSetting() +BotConfig = nonebot.get_plugin_config(BotSetting) diff --git a/zhenxun/plugins/ai/__init__.py b/zhenxun/plugins/ai/__init__.py index aecc17c0..bc5fd540 100644 --- a/zhenxun/plugins/ai/__init__.py +++ b/zhenxun/plugins/ai/__init__.py @@ -20,7 +20,7 @@ __plugin_meta__ = PluginMetadata( name="AI", description="屑Ai", usage=f""" - 与{BotConfig.nickname}普普通通的对话吧! + 与{BotConfig.self_nickname}普普通通的对话吧! """.strip(), extra=PluginExtraData( author="HibiKier", diff --git a/zhenxun/plugins/ai/data_source.py b/zhenxun/plugins/ai/data_source.py index 9a7c42f2..8c813c7d 100644 --- a/zhenxun/plugins/ai/data_source.py +++ b/zhenxun/plugins/ai/data_source.py @@ -154,9 +154,9 @@ async def xie_ai(text: str) -> str: if data["result"] == 0: content = data["content"] if "菲菲" in content: - content = content.replace("菲菲", BotConfig.nickname) + content = content.replace("菲菲", BotConfig.self_nickname) if "艳儿" in content: - content = content.replace("艳儿", BotConfig.nickname) + content = content.replace("艳儿", BotConfig.self_nickname) if "公众号" in content: content = "" if "{br}" in content: @@ -188,7 +188,7 @@ def hello() -> UniMessage: ( "哦豁?!", "你好!Ov<", - f"库库库,呼唤{BotConfig.nickname}做什么呢", + f"库库库,呼唤{BotConfig.self_nickname}做什么呢", "我在呢!", "呼呼,叫俺干嘛", ) @@ -206,7 +206,7 @@ def no_result() -> UniMessage: random.choice( [ "你在说啥子?", - f"纯洁的{BotConfig.nickname}没听懂", + f"纯洁的{BotConfig.self_nickname}没听懂", "下次再告诉你(下次一定)", "你觉得我听懂了吗?嗯?", "我!不!知!道!", diff --git a/zhenxun/plugins/ai/utils.py b/zhenxun/plugins/ai/utils.py index 1f8406d7..e22d1fde 100644 --- a/zhenxun/plugins/ai/utils.py +++ b/zhenxun/plugins/ai/utils.py @@ -15,14 +15,14 @@ class AiMessageManager: "你是只会说这一句话吗?", "[*],你发我也发!", "[uname],[*]", - f"救命!有笨蛋一直给{BotConfig.nickname}发一样的话!", + f"救命!有笨蛋一直给{BotConfig.self_nickname}发一样的话!", "这句话你已经给我发了{}次了,再发就生气!", ] self._repeat_message = [ - f"请不要学{BotConfig.nickname}说话", - f"为什么要一直学{BotConfig.nickname}说话?", + f"请不要学{BotConfig.self_nickname}说话", + f"为什么要一直学{BotConfig.self_nickname}说话?", "你再学!你再学我就生气了!", - f"呜呜,你是想欺负{BotConfig.nickname}嘛..", + f"呜呜,你是想欺负{BotConfig.self_nickname}嘛..", "[uname]不要再学我说话了!", "再学我说话,我就把你拉进黑名单(生气", "你再学![uname]是个笨蛋!", diff --git a/zhenxun/plugins/black_word/black_word.py b/zhenxun/plugins/black_word/black_word.py index ba0ede01..8164851f 100644 --- a/zhenxun/plugins/black_word/black_word.py +++ b/zhenxun/plugins/black_word/black_word.py @@ -79,7 +79,7 @@ __plugin_meta__ = PluginMetadata( ), RegisterConfig( key="WARNING_RESULT", - value=f"请注意对{BotConfig.nickname}的发言内容", + value=f"请注意对{BotConfig.self_nickname}的发言内容", help="口头警告内容", default_value=None, ), @@ -202,7 +202,7 @@ async def _(): 关于敏感词: - 记住不要骂{BotConfig.nickname}就对了! + 记住不要骂{BotConfig.self_nickname}就对了! """.strip() max_width = 0 for m in text.split("\n"): diff --git a/zhenxun/plugins/dialogue/__init__.py b/zhenxun/plugins/dialogue/__init__.py index 5524cf9a..a99bc055 100644 --- a/zhenxun/plugins/dialogue/__init__.py +++ b/zhenxun/plugins/dialogue/__init__.py @@ -8,6 +8,7 @@ from nonebot_plugin_alconna import Target, Text, UniMsg from nonebot_plugin_session import EventSession from nonebot_plugin_userinfo import EventUserInfo, UserInfo +from zhenxun.configs.config import BotConfig from zhenxun.configs.utils import PluginExtraData from zhenxun.models.group_console import GroupConsole from zhenxun.services.log import logger @@ -58,14 +59,10 @@ async def _( if session.id1: message[0] = Text(str(message[0]).replace("滴滴滴-", "", 1)) platform = PlatformUtils.get_platform(bot) + superuser_id = None try: - superuser_id = config.platform_superusers["qq"][0] - if platform == "dodo": - superuser_id = config.platform_superusers["dodo"][0] - if platform == "kaiheila": - superuser_id = config.platform_superusers["kaiheila"][0] - if platform == "discord": - superuser_id = config.platform_superusers["discord"][0] + if platform: + superuser_id = BotConfig.get_superuser(platform) except IndexError: await MessageUtils.build_message("管理员失联啦...").finish() if not superuser_id: diff --git a/zhenxun/plugins/fudu.py b/zhenxun/plugins/fudu.py index 141f951a..bf4555f4 100644 --- a/zhenxun/plugins/fudu.py +++ b/zhenxun/plugins/fudu.py @@ -112,7 +112,7 @@ async def _(message: UniMsg, event: Event, session: EventSession): image_list.append(m.url) if not plain_text and not image_list: return - if plain_text and plain_text.startswith(f"@可爱的{BotConfig.nickname}"): + if plain_text and plain_text.startswith(f"@可爱的{BotConfig.self_nickname}"): await MessageUtils.build_message("复制粘贴的虚空艾特?").send(reply_to=True) if image_list: img_hash = await get_download_image_hash(image_list[0], group_id) diff --git a/zhenxun/plugins/gold_redbag/__init__.py b/zhenxun/plugins/gold_redbag/__init__.py index 283dd9e3..7e6a1c28 100644 --- a/zhenxun/plugins/gold_redbag/__init__.py +++ b/zhenxun/plugins/gold_redbag/__init__.py @@ -298,7 +298,7 @@ async def _( try: await MessageUtils.build_message( [ - f"{BotConfig.nickname}的节日红包过时了,一共开启了 " + f"{BotConfig.self_nickname}的节日红包过时了,一共开启了 " f"{len(festive_red_bag.open_user)}" f" 个红包,共 {sum(festive_red_bag.open_user.values())} 金币\n", rank_image, @@ -314,10 +314,10 @@ async def _( except JobLookupError: pass await group_red_bag.add_red_bag( - f"{BotConfig.nickname}的红包", + f"{BotConfig.self_nickname}的红包", amount, num, - BotConfig.nickname, + BotConfig.self_nickname, FESTIVE_KEY, _uuid, platform=session.platform, @@ -335,7 +335,7 @@ async def _( ) await MessageUtils.build_message( [ - f"{BotConfig.nickname}发起了节日金币红包\n金额: {amount}\n数量: {num}\n", + f"{BotConfig.self_nickname}发起了节日金币红包\n金额: {amount}\n数量: {num}\n", image_result, ] ).send(target=target, bot=bot) diff --git a/zhenxun/plugins/gold_redbag/data_source.py b/zhenxun/plugins/gold_redbag/data_source.py index 63096914..ecc7dd38 100644 --- a/zhenxun/plugins/gold_redbag/data_source.py +++ b/zhenxun/plugins/gold_redbag/data_source.py @@ -58,7 +58,7 @@ class RedBagManager: try: await MessageUtils.build_message( [ - f"{BotConfig.nickname}的节日红包过时了,一共开启了 " + f"{BotConfig.self_nickname}的节日红包过时了,一共开启了 " f"{len(red_bag.open_user)}" f" 个红包,共 {sum(red_bag.open_user.values())} 金币\n", rank_image, @@ -92,7 +92,7 @@ class RedBagManager: rank_image = await festive_red_bag.build_amount_rank(rank_num, platform) return MessageUtils.build_message( [ - f"{BotConfig.nickname}的节日红包过时了,一共开启了 " + f"{BotConfig.self_nickname}的节日红包过时了,一共开启了 " f"{len(festive_red_bag.open_user)}" f" 个红包,共 {sum(festive_red_bag.open_user.values())} 金币\n", rank_image, diff --git a/zhenxun/plugins/mute/mute_message.py b/zhenxun/plugins/mute/mute_message.py index 64d58999..19e9326a 100644 --- a/zhenxun/plugins/mute/mute_message.py +++ b/zhenxun/plugins/mute/mute_message.py @@ -48,7 +48,7 @@ async def _(bot: Bot, session: EventSession, message: UniMsg): try: await PlatformUtils.ban_user(bot, session.id1, group_id, duration) await MessageUtils.build_message( - f"检测到恶意刷屏,{BotConfig.nickname}要把你关进小黑屋!" + f"检测到恶意刷屏,{BotConfig.self_nickname}要把你关进小黑屋!" ).send(at_sender=True) mute_manage.reset(session.id1, group_id) logger.info(f"检测刷屏 被禁言 {duration} 分钟", "禁言检查", session=session) diff --git a/zhenxun/plugins/mute/mute_setting.py b/zhenxun/plugins/mute/mute_setting.py index 63038e16..b7947ed6 100644 --- a/zhenxun/plugins/mute/mute_setting.py +++ b/zhenxun/plugins/mute/mute_setting.py @@ -15,7 +15,7 @@ __plugin_meta__ = PluginMetadata( name="刷屏禁言", description="刷屏禁言相关操作", usage=""" - 刷屏禁言相关操作,需要 {BotConfig.nickname} 有群管理员权限 + 刷屏禁言相关操作,需要 {BotConfig.self_nickname} 有群管理员权限 指令: 设置刷屏: 查看当前设置 -c [count]: 检测最大次数 diff --git a/zhenxun/plugins/roll.py b/zhenxun/plugins/roll.py index f8b242b9..1c21421b 100644 --- a/zhenxun/plugins/roll.py +++ b/zhenxun/plugins/roll.py @@ -56,7 +56,7 @@ async def _( await MessageUtils.build_message( random.choice( [ - f"让{BotConfig.nickname}看看是什么结果!答案是:‘{random_text}’", + f"让{BotConfig.self_nickname}看看是什么结果!答案是:‘{random_text}’", f"根据命运的指引,接下来{user_name} ‘{random_text}’ 会比较好", f"祈愿被回应了!是 ‘{random_text}’!", f"结束了,{user_name},命运之轮停在了 ‘{random_text}’!", diff --git a/zhenxun/plugins/russian/data_source.py b/zhenxun/plugins/russian/data_source.py index 239dafc5..73cdb078 100644 --- a/zhenxun/plugins/russian/data_source.py +++ b/zhenxun/plugins/russian/data_source.py @@ -278,7 +278,7 @@ class RussianManage: random.choice( [ f"不要打扰 {russian.player1[1]} 和 {russian.player2[1]} 的决斗啊!", - f"给我好好做好一个观众!不然{BotConfig.nickname}就要生气了", + f"给我好好做好一个观众!不然{BotConfig.self_nickname}就要生气了", f"不要捣乱啊baka{uname}!", ] ) @@ -429,7 +429,7 @@ class RussianManage: f"\t累计败场:{loser.fail_count}\n" f"\t累计输掉金币:{loser.lose_money}\n" f"-------------------\n" - f"哼哼,{BotConfig.nickname}从中收取了 {float(rand)}%({fee}金币) 作为手续费!\n" + f"哼哼,{BotConfig.self_nickname}从中收取了 {float(rand)}%({fee}金币) 作为手续费!\n" f"子弹排列:{russian.bullet_arr}", padding=10, color="#f9f6f2", diff --git a/zhenxun/plugins/search_buff_skin_price/__init__.py b/zhenxun/plugins/search_buff_skin_price/__init__.py index 14130a80..ca2a320f 100644 --- a/zhenxun/plugins/search_buff_skin_price/__init__.py +++ b/zhenxun/plugins/search_buff_skin_price/__init__.py @@ -83,7 +83,7 @@ async def arg_handle( result, status_code = await get_price(name) except FileNotFoundError: await MessageUtils.build_message( - f'请先对{BotConfig.nickname}说"设置cookie"来设置cookie!' + f'请先对{BotConfig.self_nickname}说"设置cookie"来设置cookie!' ).send(at_sender=True) if status_code in [996, 997, 998]: await MessageUtils.build_message(result).finish() diff --git a/zhenxun/plugins/send_setu_/send_setu/__init__.py b/zhenxun/plugins/send_setu_/send_setu/__init__.py index 9638727d..fea1ad41 100644 --- a/zhenxun/plugins/send_setu_/send_setu/__init__.py +++ b/zhenxun/plugins/send_setu_/send_setu/__init__.py @@ -173,7 +173,7 @@ async def _( local_id: Match[int], ): _tags = tags.result.split("#") if tags.available else None - if _tags and BotConfig.nickname in _tags: + if _tags and BotConfig.self_nickname in _tags: await MessageUtils.build_message( "咳咳咳,虽然我很可爱,但是我木有自己的色图~~~有的话记得发我一份呀" ).finish() diff --git a/zhenxun/plugins/send_setu_/send_setu/_data_source.py b/zhenxun/plugins/send_setu_/send_setu/_data_source.py index c7556bd6..f7a15d32 100644 --- a/zhenxun/plugins/send_setu_/send_setu/_data_source.py +++ b/zhenxun/plugins/send_setu_/send_setu/_data_source.py @@ -186,7 +186,7 @@ class SetuManage: IMAGE_PATH / "luoxiang" / random.choice(os.listdir(IMAGE_PATH / "luoxiang")), - f"\n(快向{BotConfig.nickname}签到提升好感度吧!)", + f"\n(快向{BotConfig.self_nickname}签到提升好感度吧!)", ] ) return None diff --git a/zhenxun/services/db_context.py b/zhenxun/services/db_context.py index de8bfdcb..a39e7175 100644 --- a/zhenxun/services/db_context.py +++ b/zhenxun/services/db_context.py @@ -1,18 +1,9 @@ -import ujson as json from nonebot.utils import is_coroutine_callable from tortoise import Tortoise from tortoise.connection import connections from tortoise.models import Model as Model_ -from zhenxun.configs.config import ( - address, - bind, - database, - password, - port, - sql_name, - user, -) +from zhenxun.configs.config import BotConfig from zhenxun.configs.path_config import DATA_PATH from .log import logger @@ -27,7 +18,7 @@ class Model(Model_): 自动添加模块 Args: - Model_ (_type_): Model + Model_: Model """ def __init_subclass__(cls, **kwargs): @@ -38,38 +29,13 @@ class Model(Model_): async def init(): - if DATABASE_SETTING_FILE.exists(): - with open(DATABASE_SETTING_FILE, "r", encoding="utf-8") as f: - setting_data = json.load(f) - else: - i_bind = bind - if not i_bind and any([user, password, address, port, database]): - i_bind = f"{sql_name}://{user}:{password}@{address}:{port}/{database}" - setting_data = { - "bind": i_bind, - "sql_name": sql_name, - "user": user, - "password": password, - "address": address, - "port": port, - "database": database, - } - with open(DATABASE_SETTING_FILE, "w", encoding="utf-8") as f: - json.dump(setting_data, f, ensure_ascii=False, indent=4) - i_bind = setting_data.get("bind") - _sql_name = setting_data.get("sql_name") - _user = setting_data.get("user") - _password = setting_data.get("password") - _address = setting_data.get("address") - _port = setting_data.get("port") - _database = setting_data.get("database") - if not i_bind and not any([_user, _password, _address, _port, _database]): - raise ValueError("\n数据库配置未填写...") - if not i_bind: - i_bind = f"{_sql_name}://{_user}:{_password}@{_address}:{_port}/{_database}" + if not BotConfig.db_url: + raise Exception(f"数据库配置为空,请在.env.dev中配置DB_URL...") try: await Tortoise.init( - db_url=i_bind, modules={"models": MODELS}, timezone="Asia/Shanghai" + db_url=BotConfig.db_url, + modules={"models": MODELS}, + timezone="Asia/Shanghai", ) if SCRIPT_METHOD: db = Tortoise.get_connection("default") diff --git a/zhenxun/utils/_image_template.py b/zhenxun/utils/_image_template.py index 399c054c..e989accc 100644 --- a/zhenxun/utils/_image_template.py +++ b/zhenxun/utils/_image_template.py @@ -182,15 +182,20 @@ class ImageTemplate: _temp["width"] = w build_data_list.append(_temp) column_image_list = [] + column_name_image_list: list[BuildImage] = [] + for i, data in enumerate(build_data_list): + column_name_image = await BuildImage.build_text_image( + column_name[i], font, 12, "#C8CCCF" + ) + column_name_image_list.append(column_name_image) + max_h = max([c.height for c in column_name_image_list]) for i, data in enumerate(build_data_list): width = data["width"] + padding * 2 height = (base_h + row_space) * (len(data["data"]) + 1) + padding * 2 background = BuildImage(width, height, (255, 255, 255)) - column_name_image = await BuildImage.build_text_image( - column_name[i], font, 12, "#C8CCCF" - ) + column_name_image = column_name_image_list[i] await background.paste(column_name_image, (0, 20), center_type="width") - cur_h = column_name_image.height + row_space + 20 + cur_h = max_h + row_space + 20 for item in data["data"]: style = RowStyle(font=font) if text_style: @@ -198,13 +203,15 @@ class ImageTemplate: if isinstance(item, tuple): """图片""" data, width, height = item + image_ = None if isinstance(data, Path): image_ = BuildImage(width, height, background=data) elif isinstance(data, bytes): image_ = BuildImage(width, height, background=BytesIO(data)) elif isinstance(data, BuildImage): image_ = data - await background.paste(image_, (padding, cur_h)) + if image_: + await background.paste(image_, (padding, cur_h)) else: await background.text( (padding, cur_h), diff --git a/zhenxun/utils/message.py b/zhenxun/utils/message.py index 7668984e..eb6549f2 100644 --- a/zhenxun/utils/message.py +++ b/zhenxun/utils/message.py @@ -81,7 +81,7 @@ class MessageUtils: cls, msg_list: list[str | Message], uin: str, - name: str = f"这里是{BotConfig.nickname}", + name: str = f"这里是{BotConfig.self_nickname}", ) -> list[dict]: """生成自定义合并消息