feat: 野兽先辈主题包
fix: 插件模块名问题 feat: `nps` -> `npm`
This commit is contained in:
22
liteyuki/plugins/liteyuki_pacman/__init__.py
Normal file
22
liteyuki/plugins/liteyuki_pacman/__init__.py
Normal file
@ -0,0 +1,22 @@
|
||||
from nonebot.plugin import PluginMetadata
|
||||
from .npm import *
|
||||
from .rpm import *
|
||||
|
||||
__author__ = "snowykami"
|
||||
__plugin_meta__ = PluginMetadata(
|
||||
name="轻雪插件管理",
|
||||
description="本地插件管理和插件商店支持,支持启用/停用,安装/卸载插件",
|
||||
usage=(
|
||||
"npm list\n"
|
||||
"npm enable/disable <plugin_name>\n"
|
||||
"npm search <keywords...>\n"
|
||||
"npm install/uninstall <plugin_name>\n"
|
||||
),
|
||||
type="application",
|
||||
homepage="https://github.com/snowykami/LiteyukiBot",
|
||||
extra={
|
||||
"liteyuki": True,
|
||||
"toggleable" : False,
|
||||
"default_enable" : True,
|
||||
}
|
||||
)
|
125
liteyuki/plugins/liteyuki_pacman/common.py
Normal file
125
liteyuki/plugins/liteyuki_pacman/common.py
Normal file
@ -0,0 +1,125 @@
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
import aiofiles
|
||||
import nonebot.plugin
|
||||
|
||||
from liteyuki.utils.data import LiteModel
|
||||
from liteyuki.utils.data_manager import GlobalPlugin, Group, User, group_db, plugin_db, user_db
|
||||
from liteyuki.utils.ly_typing import T_MessageEvent
|
||||
|
||||
|
||||
class PluginTag(LiteModel):
|
||||
label: str
|
||||
color: str = '#000000'
|
||||
|
||||
|
||||
class StorePlugin(LiteModel):
|
||||
name: str
|
||||
desc: str
|
||||
module_name: str # 插件商店中的模块名不等于本地的模块名,前者是文件夹名,后者是点分割模块名
|
||||
project_link: str = ""
|
||||
homepage: str = ""
|
||||
author: str = ""
|
||||
type: str | None = None
|
||||
version: str | None = ""
|
||||
time: str = ""
|
||||
tags: list[PluginTag] = []
|
||||
is_official: bool = False
|
||||
|
||||
|
||||
def get_plugin_exist(plugin_name: str) -> bool:
|
||||
"""
|
||||
获取插件是否存在
|
||||
Args:
|
||||
plugin_name:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
for plugin in nonebot.plugin.get_loaded_plugins():
|
||||
if plugin.name == plugin_name:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def get_store_plugin(plugin_name: str) -> Optional[StorePlugin]:
|
||||
"""
|
||||
获取插件信息
|
||||
|
||||
Args:
|
||||
plugin_name (str): 插件模块名
|
||||
|
||||
Returns:
|
||||
Optional[StorePlugin]: 插件信息
|
||||
"""
|
||||
async with aiofiles.open("data/liteyuki/plugins.json", "r", encoding="utf-8") as f:
|
||||
plugins: list[StorePlugin] = [StorePlugin(**pobj) for pobj in json.loads(await f.read())]
|
||||
for plugin in plugins:
|
||||
if plugin.name == plugin_name:
|
||||
return plugin
|
||||
return None
|
||||
|
||||
|
||||
def get_plugin_default_enable(plugin_name: str) -> bool:
|
||||
"""
|
||||
获取插件默认启用状态,由插件定义,不存在则默认为启用
|
||||
|
||||
Args:
|
||||
plugin_name (str): 插件模块名
|
||||
|
||||
Returns:
|
||||
bool: 插件默认状态
|
||||
"""
|
||||
plug = nonebot.plugin.get_plugin(plugin_name)
|
||||
return (plug.metadata.extra.get("default_enable", True)
|
||||
if plug.metadata else True) if plug else True
|
||||
|
||||
|
||||
def get_plugin_session_enable(event: T_MessageEvent, plugin_name: str) -> bool:
|
||||
"""
|
||||
获取插件当前会话启用状态
|
||||
|
||||
Args:
|
||||
event: 会话事件
|
||||
plugin_name (str): 插件模块名
|
||||
|
||||
Returns:
|
||||
bool: 插件当前状态
|
||||
"""
|
||||
if event.message_type == "group":
|
||||
session: Group = group_db.first(Group(), "group_id = ?", event.group_id, default=Group(group_id=str(event.group_id)))
|
||||
else:
|
||||
session: User = user_db.first(User(), "user_id = ?", event.user_id, default=User(user_id=str(event.user_id)))
|
||||
# 默认停用插件在启用列表内表示启用
|
||||
# 默认停用插件不在启用列表内表示停用
|
||||
# 默认启用插件在停用列表内表示停用
|
||||
# 默认启用插件不在停用列表内表示启用
|
||||
default_enable = get_plugin_default_enable(plugin_name)
|
||||
if default_enable:
|
||||
return plugin_name not in session.disabled_plugins
|
||||
else:
|
||||
return plugin_name in session.enabled_plugins
|
||||
|
||||
|
||||
def get_plugin_global_enable(plugin_name: str) -> bool:
|
||||
nonebot.plugin.get_plugin(plugin_name)
|
||||
return plugin_db.first(
|
||||
GlobalPlugin(),
|
||||
"module_name = ?",
|
||||
plugin_name,
|
||||
default=GlobalPlugin(module_name=plugin_name, enabled=True)).enabled
|
||||
|
||||
|
||||
def get_plugin_can_be_toggle(plugin_name: str) -> bool:
|
||||
"""
|
||||
获取插件是否可以被启用/停用
|
||||
|
||||
Args:
|
||||
plugin_name (str): 插件模块名
|
||||
|
||||
Returns:
|
||||
bool: 插件是否可以被启用/停用
|
||||
"""
|
||||
plug = nonebot.plugin.get_plugin(plugin_name)
|
||||
return plug.metadata.extra.get("toggleable", True) if plug and plug.metadata else True
|
460
liteyuki/plugins/liteyuki_pacman/npm.py
Normal file
460
liteyuki/plugins/liteyuki_pacman/npm.py
Normal file
@ -0,0 +1,460 @@
|
||||
import os
|
||||
import sys
|
||||
import aiohttp
|
||||
import nonebot.plugin
|
||||
import pip
|
||||
from io import StringIO
|
||||
from arclet.alconna import MultiVar
|
||||
from nonebot import require
|
||||
from nonebot.exception import FinishedException, IgnoredException
|
||||
from nonebot.internal.adapter import Event
|
||||
from nonebot.internal.matcher import Matcher
|
||||
from nonebot.message import run_preprocessor
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.plugin import Plugin
|
||||
from liteyuki.utils.data_manager import InstalledPlugin
|
||||
from liteyuki.utils.language import get_user_lang
|
||||
from liteyuki.utils.ly_typing import T_Bot
|
||||
from liteyuki.utils.message import Markdown as md
|
||||
from liteyuki.utils.permission import GROUP_ADMIN, GROUP_OWNER
|
||||
from liteyuki.utils.tools import clamp
|
||||
from .common import *
|
||||
|
||||
require("nonebot_plugin_alconna")
|
||||
from nonebot_plugin_alconna import on_alconna, Alconna, Args, Arparma, Subcommand
|
||||
|
||||
# const
|
||||
enable_global = "enable-global"
|
||||
disable_global = "disable-global"
|
||||
enable = "enable"
|
||||
disable = "disable"
|
||||
|
||||
|
||||
@on_alconna(
|
||||
aliases={"插件"},
|
||||
command=Alconna(
|
||||
"npm",
|
||||
Subcommand(
|
||||
"enable",
|
||||
Args["plugin_name", str],
|
||||
alias=["启用"],
|
||||
|
||||
),
|
||||
Subcommand(
|
||||
"disable",
|
||||
Args["plugin_name", str],
|
||||
alias=["停用"],
|
||||
),
|
||||
Subcommand(
|
||||
enable_global,
|
||||
Args["plugin_name", str],
|
||||
alias=["全局启用"],
|
||||
),
|
||||
Subcommand(
|
||||
disable_global,
|
||||
Args["plugin_name", str],
|
||||
alias=["全局停用"],
|
||||
),
|
||||
# 安装部分
|
||||
Subcommand(
|
||||
"update",
|
||||
alias=["u"],
|
||||
),
|
||||
Subcommand(
|
||||
"search",
|
||||
Args["keywords", MultiVar(str)]["show_num", int, 15],
|
||||
alias=["s", "搜索"],
|
||||
),
|
||||
Subcommand(
|
||||
"install",
|
||||
Args["plugin_name", str],
|
||||
alias=["i", "安装"],
|
||||
),
|
||||
Subcommand(
|
||||
"uninstall",
|
||||
Args["plugin_name", str],
|
||||
alias=["r", "rm", "卸载"],
|
||||
),
|
||||
Subcommand(
|
||||
"list",
|
||||
Args["num", int, 10]["page", int, 1],
|
||||
alias=["ls", "列表"],
|
||||
),
|
||||
Subcommand(
|
||||
"usage",
|
||||
Args["plugin_name", str],
|
||||
alias=["详情"],
|
||||
)
|
||||
)
|
||||
).handle()
|
||||
async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
|
||||
if not os.path.exists("data/liteyuki/plugins.json"):
|
||||
await npm_update()
|
||||
# 判断会话类型
|
||||
ulang = get_user_lang(str(event.user_id))
|
||||
plugin_name = result.args.get("plugin_name")
|
||||
sc = result.subcommands # 获取子命令
|
||||
perm_s = await SUPERUSER(bot, event) # 判断是否为超级用户
|
||||
# 支持对自定义command_start的判断
|
||||
if sc.get("enable") or result.subcommands.get("disable"):
|
||||
|
||||
toggle = result.subcommands.get("enable") is not None
|
||||
|
||||
plugin_exist = get_plugin_exist(plugin_name)
|
||||
|
||||
session_enable = get_plugin_session_enable(event, plugin_name) # 获取插件当前状态
|
||||
|
||||
default_enable = get_plugin_default_enable(plugin_name) # 获取插件默认状态
|
||||
|
||||
can_be_toggled = get_plugin_can_be_toggle(plugin_name) # 获取插件是否可以被启用/停用
|
||||
|
||||
if not plugin_exist:
|
||||
await npm.finish(ulang.get("npm.plugin_not_found", NAME=plugin_name))
|
||||
|
||||
if not can_be_toggled:
|
||||
await npm.finish(ulang.get("npm.plugin_cannot_be_toggled", NAME=plugin_name))
|
||||
|
||||
if session_enable == toggle:
|
||||
await npm.finish(
|
||||
ulang.get("npm.plugin_already", NAME=plugin_name, STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable")))
|
||||
|
||||
if event.message_type == "private":
|
||||
session = user_db.first(User(), "user_id = ?", event.user_id, default=User(user_id=event.user_id))
|
||||
else:
|
||||
if await GROUP_ADMIN(bot, event) or await GROUP_OWNER(bot, event) or await SUPERUSER(bot, event):
|
||||
session = group_db.first(Group(), "group_id = ?", event.group_id, default=Group(group_id=str(event.group_id)))
|
||||
else:
|
||||
raise FinishedException(ulang.get("Permission Denied"))
|
||||
try:
|
||||
if toggle:
|
||||
if default_enable:
|
||||
session.disabled_plugins.remove(plugin_name)
|
||||
else:
|
||||
session.enabled_plugins.append(plugin_name)
|
||||
else:
|
||||
if default_enable:
|
||||
session.disabled_plugins.append(plugin_name)
|
||||
else:
|
||||
session.enabled_plugins.remove(plugin_name)
|
||||
if event.message_type == "private":
|
||||
user_db.upsert(session)
|
||||
else:
|
||||
group_db.upsert(session)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await npm.finish(
|
||||
ulang.get(
|
||||
"npm.toggle_failed",
|
||||
NAME=plugin_name,
|
||||
STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable"),
|
||||
ERROR=str(e))
|
||||
)
|
||||
|
||||
await npm.finish(
|
||||
ulang.get(
|
||||
"npm.toggle_success",
|
||||
NAME=plugin_name,
|
||||
STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable"))
|
||||
)
|
||||
|
||||
elif sc.get(enable_global) or result.subcommands.get(disable_global) and await SUPERUSER(bot, event):
|
||||
plugin_exist = get_plugin_exist(plugin_name)
|
||||
|
||||
toggle = result.subcommands.get(enable_global) is not None
|
||||
|
||||
can_be_toggled = get_plugin_can_be_toggle(plugin_name)
|
||||
|
||||
if not plugin_exist:
|
||||
await npm.finish(ulang.get("npm.plugin_not_found", NAME=plugin_name))
|
||||
|
||||
if not can_be_toggled:
|
||||
await npm.finish(ulang.get("npm.plugin_cannot_be_toggled", NAME=plugin_name))
|
||||
|
||||
global_enable = get_plugin_global_enable(plugin_name)
|
||||
if global_enable == toggle:
|
||||
await npm.finish(
|
||||
ulang.get("npm.plugin_already", NAME=plugin_name, STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable")))
|
||||
|
||||
try:
|
||||
storePlugin = plugin_db.first(GlobalPlugin(), "module_name = ?", plugin_name, default=GlobalPlugin(module_name=plugin_name))
|
||||
if toggle:
|
||||
storePlugin.enabled = True
|
||||
else:
|
||||
storePlugin.enabled = False
|
||||
plugin_db.upsert(storePlugin)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await npm.finish(
|
||||
ulang.get(
|
||||
"npm.toggle_failed",
|
||||
NAME=plugin_name,
|
||||
STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable"),
|
||||
ERROR=str(e))
|
||||
)
|
||||
|
||||
await npm.finish(
|
||||
ulang.get(
|
||||
"npm.toggle_success",
|
||||
NAME=plugin_name,
|
||||
STATUS=ulang.get("npm.enable") if toggle else ulang.get("npm.disable"))
|
||||
)
|
||||
|
||||
elif sc.get("update") and perm_s:
|
||||
r = await npm_update()
|
||||
if r:
|
||||
await npm.finish(ulang.get("npm.store_update_success"))
|
||||
else:
|
||||
await npm.finish(ulang.get("npm.store_update_failed"))
|
||||
|
||||
elif sc.get("search"):
|
||||
keywords: list[str] = result.subcommands["search"].args.get("keywords")
|
||||
rs = await npm_search(keywords)
|
||||
max_show = result.subcommands.get("search").args.get("show_num")
|
||||
if len(rs):
|
||||
reply = f"{ulang.get('npm.search_result')} | {ulang.get('npm.total', TOTAL=len(rs))}\n***"
|
||||
for storePlugin in rs[:min(max_show, len(rs))]:
|
||||
btn_install = md.btn_cmd(ulang.get("npm.install"), "npm install %s" % storePlugin.module_name)
|
||||
link_page = md.btn_link(ulang.get("npm.homepage"), storePlugin.homepage)
|
||||
link_pypi = md.btn_link(ulang.get("npm.pypi"), storePlugin.homepage)
|
||||
|
||||
reply += (f"\n# **{storePlugin.name}**\n"
|
||||
f"\n> **{storePlugin.desc}**\n"
|
||||
f"\n> {ulang.get('npm.author')}: {storePlugin.author}"
|
||||
f"\n> *{md.escape(storePlugin.module_name)}*"
|
||||
f"\n> {btn_install} {link_page} {link_pypi}\n\n***\n")
|
||||
if len(rs) > max_show:
|
||||
reply += f"\n{ulang.get('npm.too_many_results', HIDE_NUM=len(rs) - max_show)}"
|
||||
else:
|
||||
reply = ulang.get("npm.search_no_result")
|
||||
await md.send_md(reply, bot, event=event)
|
||||
|
||||
elif sc.get("install") and perm_s:
|
||||
plugin_name: str = result.subcommands["install"].args.get("plugin_name")
|
||||
store_plugin = await get_store_plugin(plugin_name)
|
||||
await npm.send(ulang.get("npm.installing", NAME=plugin_name))
|
||||
r, log = npm_install(plugin_name)
|
||||
log = log.replace("\\", "/")
|
||||
|
||||
if not store_plugin:
|
||||
await npm.finish(ulang.get("npm.plugin_not_found", NAME=plugin_name))
|
||||
|
||||
homepage_btn = md.btn_cmd(ulang.get("npm.homepage"), store_plugin.homepage)
|
||||
if r:
|
||||
|
||||
r_load = nonebot.load_plugin(plugin_name) # 加载插件
|
||||
installed_plugin = InstalledPlugin(module_name=plugin_name) # 构造插件信息模型
|
||||
found_in_db_plugin = plugin_db.first(InstalledPlugin(), "module_name = ?", plugin_name) # 查询数据库中是否已经安装
|
||||
|
||||
if r_load:
|
||||
if found_in_db_plugin is None:
|
||||
plugin_db.upsert(installed_plugin)
|
||||
info = md.escape(ulang.get("npm.install_success", NAME=store_plugin.name)) # markdown转义
|
||||
await md.send_md(
|
||||
f"{info}\n\n"
|
||||
f"```\n{log}\n```",
|
||||
bot,
|
||||
event=event
|
||||
)
|
||||
else:
|
||||
await npm.finish(ulang.get("npm.plugin_already_installed", NAME=store_plugin.name))
|
||||
else:
|
||||
info = ulang.get("npm.load_failed", NAME=plugin_name, HOMEPAGE=homepage_btn).replace("_", r"\\_")
|
||||
await md.send_md(
|
||||
f"{info}\n\n"
|
||||
f"```\n{log}\n```\n",
|
||||
bot,
|
||||
event=event
|
||||
)
|
||||
else:
|
||||
info = ulang.get("npm.install_failed", NAME=plugin_name, HOMEPAGE=homepage_btn).replace("_", r"\\_")
|
||||
await md.send_md(
|
||||
f"{info}\n\n"
|
||||
f"```\n{log}\n```",
|
||||
bot,
|
||||
event=event
|
||||
)
|
||||
|
||||
elif sc.get("uninstall") and perm_s:
|
||||
plugin_name: str = result.subcommands["uninstall"].args.get("plugin_name")
|
||||
found_installed_plugin: InstalledPlugin = plugin_db.first(InstalledPlugin(), "module_name = ?", plugin_name)
|
||||
if found_installed_plugin:
|
||||
plugin_db.delete(InstalledPlugin(), "module_name = ?", plugin_name)
|
||||
reply = f"{ulang.get('npm.uninstall_success', NAME=found_installed_plugin.module_name)}"
|
||||
await npm.finish(reply)
|
||||
else:
|
||||
await npm.finish(ulang.get("npm.plugin_not_installed", NAME=plugin_name))
|
||||
|
||||
elif sc.get("list"):
|
||||
loaded_plugin_list = sorted(nonebot.get_loaded_plugins(), key=lambda x: x.name)
|
||||
num_per_page = result.subcommands.get("list").args.get("num")
|
||||
total = len(loaded_plugin_list) // num_per_page + (1 if len(loaded_plugin_list) % num_per_page else 0)
|
||||
|
||||
page = clamp(result.subcommands.get("list").args.get("page"), 1, total)
|
||||
|
||||
# 已加载插件 | 总计10 | 第1/3页
|
||||
reply = (f"# {ulang.get('npm.loaded_plugins')} | "
|
||||
f"{ulang.get('npm.total', TOTAL=len(nonebot.get_loaded_plugins()))} | "
|
||||
f"{ulang.get('npm.page', PAGE=page, TOTAL=total)} \n***\n")
|
||||
|
||||
permission_oas = await GROUP_ADMIN(bot, event) or await GROUP_OWNER(bot, event) or await SUPERUSER(bot, event)
|
||||
permission_s = await SUPERUSER(bot, event)
|
||||
|
||||
for storePlugin in loaded_plugin_list[(page - 1) * num_per_page: min(page * num_per_page, len(loaded_plugin_list))]:
|
||||
# 检查是否有 metadata 属性
|
||||
# 添加帮助按钮
|
||||
|
||||
btn_usage = md.btn_cmd(ulang.get("npm.usage"), f"npm usage {storePlugin.name}", False)
|
||||
store_plugin = await get_store_plugin(storePlugin.name)
|
||||
session_enable = get_plugin_session_enable(event, storePlugin.name)
|
||||
if store_plugin:
|
||||
btn_homepage = md.btn_link(ulang.get("npm.homepage"), store_plugin.homepage)
|
||||
show_name = store_plugin.name
|
||||
elif storePlugin.metadata:
|
||||
if storePlugin.metadata.extra.get("liteyuki"):
|
||||
btn_homepage = md.btn_link(ulang.get("npm.homepage"), "https://github.com/snowykami/LiteyukiBot")
|
||||
else:
|
||||
btn_homepage = ulang.get("npm.homepage")
|
||||
show_name = storePlugin.metadata.name
|
||||
else:
|
||||
btn_homepage = ulang.get("npm.homepage")
|
||||
show_name = storePlugin.name
|
||||
ulang.get("npm.no_description")
|
||||
|
||||
if storePlugin.metadata:
|
||||
reply += f"\n**{md.escape(show_name)}**\n"
|
||||
else:
|
||||
reply += f"**{md.escape(show_name)}**\n"
|
||||
|
||||
reply += f"\n > {btn_usage} {btn_homepage}"
|
||||
|
||||
if permission_oas:
|
||||
# 添加启用/停用插件按钮
|
||||
cmd_toggle = f"npm {'disable' if session_enable else 'enable'} {storePlugin.name}"
|
||||
text_toggle = ulang.get("npm.disable" if session_enable else "npm.enable")
|
||||
can_be_toggle = get_plugin_can_be_toggle(storePlugin.name)
|
||||
btn_toggle = text_toggle if not can_be_toggle else md.btn_cmd(text_toggle, cmd_toggle)
|
||||
reply += f" {btn_toggle}"
|
||||
|
||||
if permission_s:
|
||||
plugin_in_database = plugin_db.first(InstalledPlugin(), "module_name = ?", storePlugin.name)
|
||||
# 添加移除插件和全局切换按钮
|
||||
global_enable = get_plugin_global_enable(storePlugin.name)
|
||||
btn_uninstall = (
|
||||
md.btn_cmd(ulang.get("npm.uninstall"), f'npm uninstall {storePlugin.name}')) if plugin_in_database else ulang.get(
|
||||
'npm.uninstall')
|
||||
btn_toggle_global_text = ulang.get("npm.disable_global" if global_enable else "npm.enable_global")
|
||||
cmd_toggle_global = f"npm {'disable' if global_enable else 'enable'}-global {storePlugin.name}"
|
||||
btn_toggle_global = btn_toggle_global_text if not can_be_toggle else md.btn_cmd(btn_toggle_global_text, cmd_toggle_global)
|
||||
|
||||
reply += f" {btn_uninstall} {btn_toggle_global}"
|
||||
reply += "\n\n***\n"
|
||||
await md.send_md(reply, bot, event=event)
|
||||
|
||||
elif sc.get("usage"):
|
||||
# TODO
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
|
||||
|
||||
@run_preprocessor
|
||||
async def pre_handle(event: Event, matcher: Matcher):
|
||||
plugin: Plugin = matcher.plugin
|
||||
plugin_global_enable = get_plugin_global_enable(plugin.name)
|
||||
if not plugin_global_enable:
|
||||
raise IgnoredException("Plugin disabled globally")
|
||||
if event.get_type() == "message":
|
||||
plugin_session_enable = get_plugin_session_enable(event, plugin.name)
|
||||
if not plugin_session_enable:
|
||||
raise IgnoredException("Plugin disabled in session")
|
||||
|
||||
|
||||
async def npm_update() -> bool:
|
||||
"""
|
||||
更新本地插件json缓存
|
||||
|
||||
Returns:
|
||||
bool: 是否成功更新
|
||||
"""
|
||||
url_list = [
|
||||
"https://registry.nonebot.dev/plugins.json",
|
||||
]
|
||||
for url in url_list:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status == 200:
|
||||
async with aiofiles.open("data/liteyuki/plugins.json", "wb") as f:
|
||||
data = await resp.read()
|
||||
await f.write(data)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def npm_search(keywords: list[str]) -> list[StorePlugin]:
|
||||
"""
|
||||
搜索插件
|
||||
|
||||
Args:
|
||||
keywords (list[str]): 关键词列表
|
||||
|
||||
Returns:
|
||||
list[StorePlugin]: 插件列表
|
||||
"""
|
||||
results = []
|
||||
async with aiofiles.open("data/liteyuki/plugins.json", "r", encoding="utf-8") as f:
|
||||
plugins: list[StorePlugin] = [StorePlugin(**pobj) for pobj in json.loads(await f.read())]
|
||||
for plugin in plugins:
|
||||
plugin_text = ' '.join(
|
||||
[
|
||||
plugin.name,
|
||||
plugin.desc,
|
||||
plugin.author,
|
||||
plugin.module_name,
|
||||
' '.join([tag.label for tag in plugin.tags])
|
||||
]
|
||||
)
|
||||
if all([keyword in plugin_text for keyword in keywords]):
|
||||
results.append(plugin)
|
||||
return results
|
||||
|
||||
|
||||
def npm_install(plugin_package_name) -> tuple[bool, str]:
|
||||
"""
|
||||
Args:
|
||||
plugin_package_name:
|
||||
|
||||
Returns:
|
||||
tuple[bool, str]:
|
||||
|
||||
"""
|
||||
buffer = StringIO()
|
||||
sys.stdout = buffer
|
||||
sys.stderr = buffer
|
||||
|
||||
mirrors = [
|
||||
"https://pypi.tuna.tsinghua.edu.cn/simple", # 清华大学
|
||||
"https://pypi.mirrors.cqupt.edu.cn/simple", # 重庆邮电大学
|
||||
"https://pypi.liteyuki.icu/simple", # 轻雪代理镜像
|
||||
"https://pypi.org/simple", # 官方源
|
||||
]
|
||||
|
||||
# 使用pip安装包,对每个镜像尝试一次,成功后返回值
|
||||
success = False
|
||||
for mirror in mirrors:
|
||||
try:
|
||||
nonebot.logger.info(f"npm_install try mirror: {mirror}")
|
||||
result = pip.main(["install", plugin_package_name, "-i", mirror])
|
||||
success = result == 0
|
||||
if success:
|
||||
break
|
||||
else:
|
||||
nonebot.logger.warning(f"npm_install failed, try next mirror.")
|
||||
except Exception as e:
|
||||
|
||||
success = False
|
||||
continue
|
||||
|
||||
sys.stdout = sys.__stdout__
|
||||
sys.stderr = sys.__stderr__
|
||||
|
||||
return success, buffer.getvalue()
|
171
liteyuki/plugins/liteyuki_pacman/rpm.py
Normal file
171
liteyuki/plugins/liteyuki_pacman/rpm.py
Normal file
@ -0,0 +1,171 @@
|
||||
# 轻雪资源包管理器
|
||||
import os
|
||||
|
||||
import yaml
|
||||
from nonebot import require
|
||||
from nonebot.permission import SUPERUSER
|
||||
|
||||
from liteyuki.utils.language import get_user_lang
|
||||
from liteyuki.utils.ly_typing import T_Bot, T_MessageEvent
|
||||
from liteyuki.utils.message import Markdown as md
|
||||
from liteyuki.utils.resource import (ResourceMetadata, add_resource_pack, change_priority, check_exist, check_status, get_loaded_resource_packs, get_resource_metadata, load_resources, remove_resource_pack)
|
||||
|
||||
require("nonebot_plugin_alconna")
|
||||
from nonebot_plugin_alconna import Alconna, Args, on_alconna, Arparma, Subcommand
|
||||
|
||||
|
||||
@on_alconna(
|
||||
aliases={"资源包"},
|
||||
command=Alconna(
|
||||
"rpm",
|
||||
Subcommand(
|
||||
"list",
|
||||
Args["page", int, 1]["num", int, 10],
|
||||
alias=["ls", "列表", "列出"],
|
||||
),
|
||||
Subcommand(
|
||||
"load",
|
||||
Args["name", str],
|
||||
alias=["安装"],
|
||||
),
|
||||
Subcommand(
|
||||
"unload",
|
||||
Args["name", str],
|
||||
alias=["卸载"],
|
||||
),
|
||||
Subcommand(
|
||||
"up",
|
||||
Args["name", str],
|
||||
alias=["上移"],
|
||||
),
|
||||
Subcommand(
|
||||
"down",
|
||||
Args["name", str],
|
||||
alias=["下移"],
|
||||
),
|
||||
Subcommand(
|
||||
"top",
|
||||
Args["name", str],
|
||||
alias=["置顶"],
|
||||
),
|
||||
Subcommand(
|
||||
"reload",
|
||||
alias=["重载"],
|
||||
),
|
||||
),
|
||||
permission=SUPERUSER
|
||||
).handle()
|
||||
async def _(bot: T_Bot, event: T_MessageEvent, result: Arparma):
|
||||
ulang = get_user_lang(str(event.user_id))
|
||||
reply = ""
|
||||
if result.subcommands.get("list"):
|
||||
loaded_rps = get_loaded_resource_packs()
|
||||
reply += f"{ulang.get('liteyuki.loaded_resources', NUM=len(loaded_rps))}\n"
|
||||
for rp in loaded_rps:
|
||||
btn_unload = md.btn_cmd(
|
||||
ulang.get("npm.uninstall"),
|
||||
f"rpm unload {rp.folder}"
|
||||
)
|
||||
btn_move_up = md.btn_cmd(
|
||||
ulang.get("rpm.move_up"),
|
||||
f"rpm up {rp.folder}"
|
||||
)
|
||||
btn_move_down = md.btn_cmd(
|
||||
ulang.get("rpm.move_down"),
|
||||
f"rpm down {rp.folder}"
|
||||
)
|
||||
btn_move_top = md.btn_cmd(
|
||||
ulang.get("rpm.move_top"),
|
||||
f"rpm top {rp.folder}"
|
||||
)
|
||||
# 添加新行
|
||||
reply += (f"\n**{md.escape(rp.name)}**({md.escape(rp.folder)})\n\n"
|
||||
f"> {btn_move_up} {btn_move_down} {btn_move_top} {btn_unload}\n\n***")
|
||||
reply += f"\n\n{ulang.get('liteyuki.unloaded_resources')}\n"
|
||||
loaded_folders = [rp.folder for rp in get_loaded_resource_packs()]
|
||||
for folder in os.listdir("resources"):
|
||||
if folder not in loaded_folders and os.path.exists(os.path.join("resources", folder, "metadata.yml")):
|
||||
metadata = ResourceMetadata(
|
||||
**yaml.load(
|
||||
open(
|
||||
os.path.join("resources", folder, "metadata.yml"),
|
||||
encoding="utf-8"
|
||||
),
|
||||
Loader=yaml.FullLoader
|
||||
)
|
||||
)
|
||||
metadata.folder = folder
|
||||
metadata.path = os.path.join("resources", folder)
|
||||
btn_load = md.btn_cmd(
|
||||
ulang.get("npm.install"),
|
||||
f"rpm load {metadata.folder}"
|
||||
)
|
||||
# 添加新行
|
||||
reply += (f"\n**{md.escape(metadata.name)}**({md.escape(metadata.folder)})\n\n"
|
||||
f"> {btn_load}\n\n***")
|
||||
elif result.subcommands.get("load") or result.subcommands.get("unload"):
|
||||
load = result.subcommands.get("load") is not None
|
||||
rp_name = result.args.get("name")
|
||||
r = False # 操作结果
|
||||
if check_exist(rp_name):
|
||||
if load != check_status(rp_name):
|
||||
# 状态不同
|
||||
if load:
|
||||
r = add_resource_pack(rp_name)
|
||||
else:
|
||||
r = remove_resource_pack(rp_name)
|
||||
rp_meta = get_resource_metadata(rp_name)
|
||||
reply += ulang.get(
|
||||
f"liteyuki.{'load' if load else 'unload'}_resource_{'success' if r else 'failed'}",
|
||||
NAME=rp_meta.name
|
||||
)
|
||||
else:
|
||||
# 重复操作
|
||||
reply += ulang.get(f"liteyuki.resource_already_{'load' if load else 'unload'}ed", NAME=rp_name)
|
||||
else:
|
||||
reply += ulang.get("liteyuki.resource_not_found", NAME=rp_name)
|
||||
if r:
|
||||
btn_reload = md.btn_cmd(
|
||||
ulang.get("liteyuki.reload_resources"),
|
||||
f"rpm reload"
|
||||
)
|
||||
reply += "\n" + ulang.get("liteyuki.need_reload", BTN=btn_reload)
|
||||
elif result.subcommands.get("up") or result.subcommands.get("down") or result.subcommands.get("top"):
|
||||
rp_name = result.args.get("name")
|
||||
if result.subcommands.get("up"):
|
||||
delta = -1
|
||||
elif result.subcommands.get("down"):
|
||||
delta = 1
|
||||
else:
|
||||
delta = 0
|
||||
if check_exist(rp_name):
|
||||
if check_status(rp_name):
|
||||
r = change_priority(rp_name, delta)
|
||||
reply += ulang.get(f"liteyuki.change_priority_{'success' if r else 'failed'}", NAME=rp_name)
|
||||
if r:
|
||||
btn_reload = md.btn_cmd(
|
||||
ulang.get("liteyuki.reload_resources"),
|
||||
f"rpm reload"
|
||||
)
|
||||
reply += "\n" + ulang.get("liteyuki.need_reload", BTN=btn_reload)
|
||||
else:
|
||||
reply += ulang.get("liteyuki.resource_not_found", NAME=rp_name)
|
||||
else:
|
||||
reply += ulang.get("liteyuki.resource_not_found", NAME=rp_name)
|
||||
elif result.subcommands.get("reload"):
|
||||
load_resources()
|
||||
reply = ulang.get(
|
||||
"liteyuki.reload_resources_success",
|
||||
NUM=len(get_loaded_resource_packs())
|
||||
)
|
||||
else:
|
||||
btn_reload = md.btn_cmd(
|
||||
ulang.get("liteyuki.reload_resources"),
|
||||
f"rpm reload"
|
||||
)
|
||||
btn_list = md.btn_cmd(
|
||||
ulang.get("liteyuki.list_resources"),
|
||||
f"rpm list"
|
||||
)
|
||||
reply += f"{btn_list} {btn_reload}"
|
||||
await md.send_md(reply, bot, event=event)
|
Reference in New Issue
Block a user