添加Bot管理插件 (#1758)

Co-authored-by: BalconyJH <73932916+BalconyJH@users.noreply.github.com>
This commit is contained in:
HibiKier
2024-12-10 20:16:14 +08:00
committed by GitHub
co-authored by BalconyJH
parent bc5a9c4fcc
commit 5590445679
11 changed files with 1068 additions and 33 deletions
@@ -1,17 +1,66 @@
from pathlib import Path
import nonebot
from nonebot.adapters import Bot
from nonebot.plugin import PluginMetadata
from zhenxun.configs.utils import PluginExtraData
from zhenxun.models.bot_console import BotConsole
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.models.task_info import TaskInfo
from zhenxun.services.log import logger
from zhenxun.utils.enum import PluginType
from zhenxun.utils.platform import PlatformUtils
driver = nonebot.get_driver()
_sub_plugins = set()
_sub_plugins |= nonebot.load_plugins(str(Path(__file__).parent.resolve()))
__plugin_meta__ = PluginMetadata(
name="Bot管理",
description="指定bot对象的功能/被动开关和状态",
usage="""
清理临时数据
""".strip(),
extra=PluginExtraData(
author="",
version="0.1",
plugin_type=PluginType.SUPERUSER,
plugin_type=PluginType.PARENT,
).dict(),
)
@driver.on_bot_connect
async def _(bot: Bot):
"""初始化Bot管理
参数:
bot: Bot
"""
plugin_list = await PluginInfo.get_plugins(
plugin_type__in=[PluginType.NORMAL, PluginType.DEPENDANT, PluginType.ADMIN]
)
available_tasks: list[str] = await TaskInfo.filter(status=True).values_list(
"module", flat=True
) # type: ignore
available_plugins = [p.module for p in plugin_list]
# for _, bot in nonebot.get_bots().items():
platform = PlatformUtils.get_platform(bot)
bot_data, is_create = await BotConsole.get_or_create(
bot_id=bot.self_id, platform=platform
)
if not is_create:
block_plugins = await bot_data.get_plugins(bot.self_id, False)
block_plugins = BotConsole._convert_module_format(block_plugins)
for module in available_plugins.copy():
if module in block_plugins:
available_plugins.remove(module)
block_tasks = await bot_data.get_tasks(bot.self_id, False)
block_tasks = BotConsole._convert_module_format(block_tasks)
for module in available_tasks.copy():
if module in block_plugins:
available_tasks.remove(module)
bot_data.available_plugins = BotConsole._convert_module_format(available_plugins)
bot_data.available_tasks = BotConsole._convert_module_format(available_tasks)
await bot_data.save(update_fields=["available_plugins", "available_tasks"])
logger.info("初始化Bot管理完成...")
@@ -0,0 +1,51 @@
from nonebot_plugin_alconna import AlconnaMatch, Match
from nonebot_plugin_uninfo import Uninfo
from zhenxun.builtin_plugins.superuser.bot_manage.command import bot_manage
from zhenxun.models.bot_console import BotConsole
from zhenxun.services.log import logger
from zhenxun.utils.message import MessageUtils
@bot_manage.assign("bot_switch.enable")
async def enable_bot_switch(
session: Uninfo,
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if not bot_id.available:
await MessageUtils.build_message("bot_id 不能为空").finish()
else:
logger.info(
f"开启 {bot_id.result} ",
"bot_manage.bot_switch.enable",
session=session,
)
try:
await BotConsole.set_bot_status(True, bot_id.result)
except ValueError:
await MessageUtils.build_message(f"bot_id {bot_id.result} 不存在").finish()
await MessageUtils.build_message(f"已开启 {bot_id.result} ").finish()
@bot_manage.assign("bot_switch.disable")
async def diasble_bot_switch(
session: Uninfo,
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if not bot_id.available:
await MessageUtils.build_message("bot_id 不能为空").finish()
else:
logger.info(
f"禁用 {bot_id.result} ",
"bot_manage.bot_switch.disable",
session=session,
)
try:
await BotConsole.set_bot_status(False, bot_id.result)
except ValueError:
await MessageUtils.build_message(f"bot_id {bot_id.result} 不存在").finish()
await MessageUtils.build_message(f"已禁用 {bot_id.result} ").finish()
@@ -0,0 +1,153 @@
from arclet.alconna import Alconna, Args, Option, Subcommand
from arclet.alconna.action import store_false
from nonebot.permission import SUPERUSER
from nonebot_plugin_alconna import on_alconna
bot_manage = on_alconna(
Alconna(
"bot_manage",
Subcommand(
"task",
Option(
"list",
action=store_false,
help_text="查看 bot_id 下的所有可用被动",
),
Option("-b|--bot", Args["bot_id", str], help_text="指定 bot_id"),
Subcommand(
"enable",
Args["feature_name?", str],
),
Subcommand(
"disable",
Args["feature_name?", str],
),
),
Subcommand(
"plugin",
Option(
"list",
action=store_false,
help_text="查看 bot_id 下的所有可用插件",
),
Option("-b|--bot", Args["bot_id", str], help_text="指定 bot_id"),
Subcommand(
"enable",
Args["plugin_name?", str],
),
Subcommand(
"disable",
Args["plugin_name?", str],
),
),
Subcommand(
"full_function",
Subcommand(
"enable",
Args["bot_id?", str],
),
Subcommand(
"disable",
Args["bot_id?", str],
),
),
Subcommand(
"bot_switch",
Subcommand(
"enable",
Args["bot_id?", str],
),
Subcommand(
"disable",
Args["bot_id?", str],
),
),
),
permission=SUPERUSER,
priority=5,
block=True,
)
bot_manage.shortcut(
r"bot被动状态",
command="bot_manage",
arguments=["task", "list"],
prefix=True,
)
bot_manage.shortcut(
r"bot开启被动\s*(?P<name>.+)",
command="bot_manage",
arguments=["task", "enable", "{name}"],
prefix=True,
)
bot_manage.shortcut(
r"bot关闭被动\s*(?P<name>.+)",
command="bot_manage",
arguments=["task", "disable", "{name}"],
prefix=True,
)
bot_manage.shortcut(
r"bot开启(全部|所有)被动",
command="bot_manage",
arguments=["task", "enable"],
prefix=True,
)
bot_manage.shortcut(
r"bot关闭(全部|所有)被动",
command="bot_manage",
arguments=["task", "disable"],
prefix=True,
)
bot_manage.shortcut(
r"bot插件列表",
command="bot_manage",
arguments=["plugin", "list"],
prefix=True,
)
bot_manage.shortcut(
r"bot开启(全部|所有)插件",
command="bot_manage",
arguments=["plugin", "enable"],
prefix=True,
)
bot_manage.shortcut(
r"bot关闭(全部|所有)插件",
command="bot_manage",
arguments=["plugin", "disable"],
prefix=True,
)
bot_manage.shortcut(
r"bot开启\s*(?P<name>.+)",
command="bot_manage",
arguments=["plugin", "enable", "{name}"],
prefix=True,
)
bot_manage.shortcut(
r"bot关闭\s*(?P<name>.+)",
command="bot_manage",
arguments=["plugin", "disable", "{name}"],
prefix=True,
)
bot_manage.shortcut(
r"bot休眠\s*(?P<bot_id>.+)?",
command="bot_manage",
arguments=["bot_switch", "disable", "{bot_id}"],
prefix=True,
)
bot_manage.shortcut(
r"bot醒来\s*(?P<bot_id>.+)?",
command="bot_manage",
arguments=["bot_switch", "enable", "{bot_id}"],
prefix=True,
)
@@ -0,0 +1,51 @@
from nonebot_plugin_alconna import AlconnaMatch, Match
from nonebot_plugin_uninfo import Uninfo
from zhenxun.builtin_plugins.superuser.bot_manage.command import bot_manage
from zhenxun.models.bot_console import BotConsole
from zhenxun.services.log import logger
from zhenxun.utils.message import MessageUtils
@bot_manage.assign("full_function.enable")
async def enable_full_function(
session: Uninfo,
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if not bot_id.available:
await MessageUtils.build_message("bot_id 不能为空").finish()
else:
logger.info(
f"开启 {bot_id.result} 的所有可用插件及被动",
"bot_manage.full_function.enable",
session=session,
)
await BotConsole.enable_all(bot_id.result, "tasks")
await BotConsole.enable_all(bot_id.result, "plugins")
await MessageUtils.build_message(
f"已开启 {bot_id.result} 的所有插件及被动"
).finish()
@bot_manage.assign("full_function.disable")
async def diasble_full_function(
session: Uninfo,
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if not bot_id.available:
await MessageUtils.build_message("bot_id 不能为空").finish()
else:
logger.info(
f"禁用 {bot_id.result} 的所有可用插件及被动",
"bot_manage.full_function.disable",
session=session,
)
await BotConsole.disable_all(bot_id.result, "tasks")
await BotConsole.disable_all(bot_id.result, "plugins")
await MessageUtils.build_message(
f"已禁用 {bot_id.result} 的所有插件及被动"
).finish()
@@ -0,0 +1,182 @@
from nonebot_plugin_alconna import AlconnaMatch, Match
from nonebot_plugin_uninfo import Uninfo
from zhenxun.builtin_plugins.superuser.bot_manage.command import bot_manage
from zhenxun.models.bot_console import BotConsole
from zhenxun.models.plugin_info import PluginInfo
from zhenxun.services.log import logger
from zhenxun.utils._build_image import BuildImage
from zhenxun.utils._image_template import ImageTemplate, RowStyle
from zhenxun.utils.enum import PluginType
from zhenxun.utils.message import MessageUtils
def task_row_style(column: str, text: str) -> RowStyle:
"""被动技能文本风格
参数:
column: 表头
text: 文本内容
返回:
RowStyle: RowStyle
"""
style = RowStyle()
if column in {"全局状态"}:
style.font_color = "#67C23A" if text == "开启" else "#F56C6C"
return style
@bot_manage.assign("plugin.list")
async def bot_plugin(session: Uninfo, bot_id: Match[str] = AlconnaMatch("bot_id")):
logger.info("获取全部 bot 的所有可用插件", "bot_manage.plugin", session=session)
column_name = [
"ID",
"模块",
"名称",
"全局状态",
"禁用类型",
"加载状态",
"菜单分类",
"作者",
"版本",
"金币花费",
]
if bot_id.available:
data_dict = {
bot_id.result: await BotConsole.get_plugins(
bot_id=bot_id.result, status=False
)
}
else:
data_dict = await BotConsole.get_plugins(status=False)
db_plugin_list = await PluginInfo.filter(
load_status=True, plugin_type__not=PluginType.HIDDEN
).all()
img_list = []
for __bot_id, tk in data_dict.items():
column_data = [
[
plugin.id,
plugin.module,
plugin.name,
"开启" if plugin.module not in tk else "关闭",
plugin.block_type,
"SUCCESS" if plugin.load_status else "ERROR",
plugin.menu_type,
plugin.author,
plugin.version,
plugin.cost_gold,
]
for plugin in db_plugin_list
]
img = await ImageTemplate.table_page(
f"{__bot_id}插件列表",
None,
column_name,
column_data,
text_style=task_row_style,
)
img_list.append(img)
result = await BuildImage.auto_paste(img_list, 3)
await MessageUtils.build_message(result).finish()
@bot_manage.assign("plugin.enable")
async def enable_plugin(
session: Uninfo,
plugin_name: Match[str] = AlconnaMatch("plugin_name"),
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if plugin_name.available:
plugin: PluginInfo | None = await PluginInfo.get_plugin(name=plugin_name.result)
if not plugin:
await MessageUtils.build_message("未找到该插件...").finish()
if bot_id.available:
logger.info(
f"开启 {bot_id.result} 的插件 {plugin_name.result}",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.enable_plugin(bot_id.result, plugin.module)
await MessageUtils.build_message(
f"已开启 {bot_id.result} 的插件 {plugin_name.result}"
).finish()
else:
logger.info(
f"开启全部 bot 的插件: {plugin_name.result}",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.enable_plugin(None, plugin.module)
await MessageUtils.build_message(
f"已禁用全部 bot 的插件: {plugin_name.result}"
).finish()
elif bot_id.available:
logger.info(
f"开启 {bot_id.result} 全部插件",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.enable_all(bot_id.result, "plugins")
await MessageUtils.build_message(f"已开启 {bot_id.result} 全部插件").finish()
else:
bot_id_list = await BotConsole.annotate().values_list("bot_id", flat=True)
for __bot_id in bot_id_list:
await BotConsole.enable_all(__bot_id, "plugins") # type: ignore
logger.info(
"开启全部 bot 全部插件",
"bot_manage.plugin.disable",
session=session,
)
await MessageUtils.build_message("开启全部 bot 全部插件").finish()
@bot_manage.assign("plugin.disable")
async def disable_plugin(
session: Uninfo,
plugin_name: Match[str] = AlconnaMatch("plugin_name"),
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if plugin_name.available:
plugin = await PluginInfo.get_plugin(name=plugin_name.result)
if not plugin:
await MessageUtils.build_message("未找到该插件...").finish()
if bot_id.available:
logger.info(
f"禁用 {bot_id.result} 的插件 {plugin_name.result}",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.disable_plugin(bot_id.result, plugin.module)
await MessageUtils.build_message(
f"已禁用 {bot_id.result} 的插件 {plugin_name.result}"
).finish()
else:
logger.info(
f"禁用全部 bot 的插件: {plugin_name.result}",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.disable_plugin(None, plugin.module)
await MessageUtils.build_message(
f"已禁用全部 bot 的插件: {plugin_name.result}"
).finish()
elif bot_id.available:
logger.info(
f"禁用 {bot_id.result} 全部插件",
"bot_manage.plugin.disable",
session=session,
)
await BotConsole.disable_all(bot_id.result, "plugins")
await MessageUtils.build_message(f"已禁用 {bot_id.result} 全部插件").finish()
else:
bot_id_list = await BotConsole.annotate().values_list("bot_id", flat=True)
for __bot_id in bot_id_list:
await BotConsole.disable_all(__bot_id, "plugins") # type: ignore
logger.info(
"禁用全部 bot 全部插件",
"bot_manage.plugin.disable",
session=session,
)
await MessageUtils.build_message("禁用全部 bot 全部插件").finish()
@@ -0,0 +1,164 @@
from nonebot_plugin_alconna import AlconnaMatch, Match
from nonebot_plugin_uninfo import Uninfo
from zhenxun.builtin_plugins.superuser.bot_manage.command import bot_manage
from zhenxun.models.bot_console import BotConsole
from zhenxun.models.task_info import TaskInfo
from zhenxun.services.log import logger
from zhenxun.utils._build_image import BuildImage
from zhenxun.utils._image_template import RowStyle
from zhenxun.utils.image_utils import ImageTemplate
from zhenxun.utils.message import MessageUtils
def task_row_style(column: str, text: str) -> RowStyle:
"""被动技能文本风格
参数:
column: 表头
text: 文本内容
返回:
RowStyle: RowStyle
"""
style = RowStyle()
if column in {"全局状态"}:
style.font_color = "#67C23A" if text == "开启" else "#F56C6C"
return style
@bot_manage.assign("task.list")
async def bot_task(session: Uninfo, bot_id: Match[str] = AlconnaMatch("bot_id")):
logger.info("获取全部 bot 的所有可用被动", "bot_manage.task", session=session)
if bot_id.available:
data_dict = {
bot_id.result: await BotConsole.get_tasks(
bot_id=bot_id.result, status=False
)
}
else:
data_dict = await BotConsole.get_tasks(status=False)
db_task_list = await TaskInfo.all()
column_name = ["ID", "模块", "名称", "全局状态", "运行时间"]
img_list = []
for __bot_id, tk in data_dict.items():
column_data = [
[
task.id,
task.module,
task.name,
"开启" if task.module not in tk else "关闭",
task.run_time or "-",
]
for task in db_task_list
]
img = await ImageTemplate.table_page(
f"{__bot_id}被动技能状态",
None,
column_name,
column_data,
text_style=task_row_style,
)
img_list.append(img)
result = await BuildImage.auto_paste(img_list, 3)
await MessageUtils.build_message(result).finish()
@bot_manage.assign("task.enable")
async def enable_task(
session: Uninfo,
task_name: Match[str] = AlconnaMatch("feature_name"),
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if task_name.available:
task: TaskInfo | None = await TaskInfo.get_or_none(name=task_name.result)
if not task:
await MessageUtils.build_message("未找到被动...").finish()
if bot_id.available:
logger.info(
f"开启 {bot_id.result} 被动的 {task_name.available}",
"bot_manage.task.disable",
session=session,
)
await BotConsole.enable_task(bot_id.result, task.module)
await MessageUtils.build_message(
f"已开启 {bot_id.result} 被动的 {task_name.available}"
).finish()
else:
logger.info(
f"开启全部 bot 的被动: {task_name.available}",
"bot_manage.task.disable",
session=session,
)
await BotConsole.enable_task(None, task.module)
await MessageUtils.build_message(
f"已禁用全部 bot 的被动: {task_name.available}"
).finish()
elif bot_id.available:
logger.info(
f"开启 {bot_id.result} 全部被动",
"bot_manage.task.disable",
session=session,
)
await BotConsole.enable_all(bot_id.result, "tasks")
await MessageUtils.build_message(f"已开启 {bot_id.result} 全部被动").finish()
else:
bot_id_list = await BotConsole.annotate().values_list("bot_id", flat=True)
for __bot_id in bot_id_list:
await BotConsole.enable_all(__bot_id, "tasks") # type: ignore
logger.info(
"开启全部 bot 全部被动",
"bot_manage.task.disable",
session=session,
)
await MessageUtils.build_message("开启全部 bot 全部被动").finish()
@bot_manage.assign("task.disable")
async def disable_task(
session: Uninfo,
task_name: Match[str] = AlconnaMatch("feature_name"),
bot_id: Match[str] = AlconnaMatch("bot_id"),
):
if task_name.available:
task: TaskInfo | None = await TaskInfo.get_or_none(name=task_name.result)
if not task:
await MessageUtils.build_message("未找到被动...").finish()
if bot_id.available:
logger.info(
f"禁用 {bot_id.result} 被动的 {task_name.available}",
"bot_manage.task.disable",
session=session,
)
await BotConsole.disable_task(bot_id.result, task.module)
await MessageUtils.build_message(
f"已禁用 {bot_id.result} 被动的 {task_name.available}"
).finish()
else:
logger.info(
f"禁用全部 bot 的被动: {task_name.available}",
"bot_manage.task.disable",
session=session,
)
await BotConsole.disable_task(None, task.module)
await MessageUtils.build_message(
f"已禁用全部 bot 的被动: {task_name.available}"
).finish()
elif bot_id.available:
logger.info(
f"禁用 {bot_id.result} 全部被动",
"bot_manage.task.disable",
session=session,
)
await BotConsole.disable_all(bot_id.result, "tasks")
await MessageUtils.build_message(f"已禁用 {bot_id.result} 全部被动").finish()
else:
bot_id_list = await BotConsole.annotate().values_list("bot_id", flat=True)
for __bot_id in bot_id_list:
await BotConsole.disable_all(__bot_id, "tasks") # type: ignore
logger.info(
"禁用全部 bot 全部被动",
"bot_manage.task.disable",
session=session,
)
await MessageUtils.build_message("禁用全部 bot 全部被动").finish()