mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-03 10:40:02 +08:00
🎨 代码优化
This commit is contained in:
@@ -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 _():
|
||||
"""签到与用户的数据迁移"""
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}" + "哪里做的不好嘛..好吧..晚安{}",
|
||||
"呃,{},下次我绝对绝对绝对不会再忘记你!",
|
||||
"可..可恶!{}!太可恶了!呜",
|
||||
]
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
"""插件下载地址"""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
"等待管理员处理吧!",
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -61,7 +61,7 @@ async def _():
|
||||
async def _():
|
||||
message = MessageUtils.build_message(
|
||||
[
|
||||
f"{BotConfig.nickname}要睡觉了,你们也要早点睡呀",
|
||||
f"{BotConfig.self_nickname}要睡觉了,你们也要早点睡呀",
|
||||
IMAGE_PATH / "zhenxun" / "sleep.jpg",
|
||||
]
|
||||
)
|
||||
|
||||
@@ -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))],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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")
|
||||
logger.error(f"初始化 web ui assets 失败", "Web UI assets", e=e)
|
||||
|
||||
@@ -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]
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user