feat: 对部分消息回复用markdown进行了重新排版

This commit is contained in:
snowy 2024-03-20 18:27:49 +08:00
parent fdefedf288
commit 8a1c981666
8 changed files with 152 additions and 118 deletions

View File

@ -1,91 +1,91 @@
# import nonebot
# import psutil
# from dash import Dash, Input, Output, dcc, html
# from starlette.middleware.wsgi import WSGIMiddleware
#
# from src.utils.language import Language
# from src.utils.tools import convert_size
#
# app = nonebot.get_app()
#
#
# def get_system_info():
# cpu_percent = psutil.cpu_percent()
# memory_info = psutil.virtual_memory()
# memory_percent = memory_info.percent
# return {
# "cpu_percent" : cpu_percent,
# "memory_percent": memory_percent
# }
#
#
# @app.get("/system_info")
# async def system_info():
# return get_system_info()
#
#
# lang = Language()
# dash_app = Dash(__name__)
# dash_app.layout = dash_app.layout = html.Div(children=[
# html.H1(children=lang.get("main.monitor.title"), style={
# 'textAlign': 'center'
# }),
#
# dcc.Graph(id='live-update-graph'),
# dcc.Interval(
# id='interval-component',
# interval=1 * 1000, # in milliseconds
# n_intervals=0
# )
# ])
#
#
# @dash_app.callback(Output('live-update-graph', 'figure'),
# [Input('interval-component', 'n_intervals')])
# def update_graph_live(n):
# lang = Language()
# system_inf = get_system_info()
# dash_app.layout = html.Div(children=[
# html.H1(children=lang.get("main.monitor.title"), style={
# 'textAlign': 'center'
# }),
#
# dcc.Graph(id='live-update-graph'),
# dcc.Interval(
# id='interval-component',
# interval=2 * 1000, # in milliseconds
# n_intervals=0
# )
# ])
# mem = psutil.virtual_memory()
# cpu_f = psutil.cpu_freq()
# figure = {
# 'data' : [
# {
# 'x' : [f"{cpu_f.current / 1000:.2f}GHz {psutil.cpu_count(logical=False)}c{psutil.cpu_count()}t"],
# 'y' : [system_inf['cpu_percent']],
# 'type': 'bar',
# 'name': f"{lang.get('main.monitor.cpu')} {lang.get('main.monitor.usage')}"
#
# },
# {
# 'x' : [f"{convert_size(mem.used, add_unit=False)}/{convert_size(mem.total)}({mem.used / mem.total * 100:.2f}%)"],
# 'y' : [system_inf['memory_percent']],
# 'type': 'bar',
# 'name': f"{lang.get('main.monitor.memory')} {lang.get('main.monitor.usage')}"
# },
# ],
# 'layout': {
# 'title': lang.get('main.monitor.description'),
# # 'xaxis': {
# # 'range': [0, 10]
# # }, # 设置x轴的范围
# 'yaxis': {
# 'range': [0, 100]
# }, # 设置y轴的范围
# }
# }
# return figure
#
#
# app.mount("/", WSGIMiddleware(dash_app.server))
import nonebot
import psutil
from dash import Dash, Input, Output, dcc, html
from starlette.middleware.wsgi import WSGIMiddleware
from src.utils.language import Language
from src.utils.tools import convert_size
app = nonebot.get_app()
def get_system_info():
cpu_percent = psutil.cpu_percent()
memory_info = psutil.virtual_memory()
memory_percent = memory_info.percent
return {
"cpu_percent" : cpu_percent,
"memory_percent": memory_percent
}
@app.get("/system_info")
async def system_info():
return get_system_info()
lang = Language()
dash_app = Dash(__name__)
dash_app.layout = dash_app.layout = html.Div(children=[
html.H1(children=lang.get("main.monitor.title"), style={
'textAlign': 'center'
}),
dcc.Graph(id='live-update-graph'),
dcc.Interval(
id='interval-component',
interval=1 * 1000, # in milliseconds
n_intervals=0
)
])
@dash_app.callback(Output('live-update-graph', 'figure'),
[Input('interval-component', 'n_intervals')])
def update_graph_live(n):
lang = Language()
system_inf = get_system_info()
dash_app.layout = html.Div(children=[
html.H1(children=lang.get("main.monitor.title"), style={
'textAlign': 'center'
}),
dcc.Graph(id='live-update-graph'),
dcc.Interval(
id='interval-component',
interval=2 * 1000, # in milliseconds
n_intervals=0
)
])
mem = psutil.virtual_memory()
cpu_f = psutil.cpu_freq()
figure = {
'data' : [
{
'x' : [f"{cpu_f.current / 1000:.2f}GHz {psutil.cpu_count(logical=False)}c{psutil.cpu_count()}t"],
'y' : [system_inf['cpu_percent']],
'type': 'bar',
'name': f"{lang.get('main.monitor.cpu')} {lang.get('main.monitor.usage')}"
},
{
'x' : [f"{convert_size(mem.used, add_unit=False)}/{convert_size(mem.total)}({mem.used / mem.total * 100:.2f}%)"],
'y' : [system_inf['memory_percent']],
'type': 'bar',
'name': f"{lang.get('main.monitor.memory')} {lang.get('main.monitor.usage')}"
},
],
'layout': {
'title': lang.get('main.monitor.description'),
# 'xaxis': {
# 'range': [0, 10]
# }, # 设置x轴的范围
'yaxis': {
'range': [0, 100]
}, # 设置y轴的范围
}
}
return figure
app.mount("/", WSGIMiddleware(dash_app.server))

View File

@ -4,6 +4,7 @@ from nonebot.adapters.onebot.v11 import MessageSegment
from nonebot.exception import FinishedException
from nonebot.params import CommandArg
from nonebot.permission import SUPERUSER
from nonebot.plugin import PluginMetadata
from src.utils.message import send_markdown
from src.utils.typing import T_Message, T_Bot, v11, T_MessageEvent
@ -12,7 +13,6 @@ md_test = on_command("mdts", aliases={"会话md"}, permission=SUPERUSER)
md_group = on_command("mdg", aliases={"群md"}, permission=SUPERUSER)
md_conv = on_command("md", block=False, permission=SUPERUSER)
placeholder = {
"[": "[",
"]": "]",
@ -31,16 +31,25 @@ async def _(bot: T_Bot, event: T_MessageEvent, arg: v11.Message = CommandArg()):
message_type=event.message_type,
session_id=event.user_id if event.message_type == "private" else event.group_id
)
ignore_msg_ids = []
last_sent = None
@md_conv.handle()
async def _(bot: v11.Bot, event: v11.MessageEvent, arg: v11.Message = CommandArg()):
if str(event.user_id) == str(bot.self_id) and str(bot.self_id) in ["2751454815"]:
nonebot.logger.info("开始处理:%s" % str(event.message_id))
data, fdata = await send_markdown(str(arg), bot, event.message_type,
event.group_id if event.message_type == "group" else event.user_id)
data = await send_markdown(str(arg), bot, event=event)
await bot.delete_msg(message_id=event.message_id)
nonebot.logger.info("已处理:%s, %s" % (str(data["message_id"]), str(fdata["message_id"])))
__author__ = "snowykami"
__plugin_meta__ = PluginMetadata(
name="轻雪Markdown测试",
description="用于测试Markdown的插件",
usage="",
homepage="https://github.com/snowykami/LiteyukiBot",
)

View File

@ -3,6 +3,7 @@ from typing import Optional
import nonebot
from nonebot import on_message
from arclet.alconna import Arparma, Alconna, Args, Option, Subcommand, Arg
from nonebot.plugin import PluginMetadata
from nonebot_plugin_alconna import on_alconna
from src.utils.data import LiteModel
from src.utils.message import send_markdown
@ -34,7 +35,7 @@ alc = Alconna(
"add",
Args["source", str],
Args["target", str],
Option("-b", Args["bidirectional", bool])
Option("bidirectional", Args["bidirectional", bool])
),
Subcommand(
"rm",
@ -105,5 +106,14 @@ async def _(event: T_MessageEvent, bot: T_Bot):
push_message = (
f"> From {event.sender.nickname}@{push.source.session_type}.{push.source.session_id}\n> Bot {bot.self_id}\n\n"
f"{msg_formatted}")
await send_markdown(push_message, bot2, push.target.session_type, push.target.session_id)
await send_markdown(push_message, bot2, event=event)
return
__author__ = "snowykami"
__plugin_meta__ = PluginMetadata(
name="轻雪事件推送",
description="事件推送插件支持单向和双向推送支持跨Bot推送",
usage="",
homepage="https://github.com/snowykami/LiteyukiBot",
)

View File

@ -2,21 +2,22 @@ import nonebot.plugin
from nonebot import on_command
from nonebot.permission import SUPERUSER
from src.utils.typing import T_MessageEvent
from src.utils.message import send_markdown
from src.utils.typing import T_Bot, T_MessageEvent
from src.utils.language import get_user_lang
list_plugins = on_command("list-plugin", aliases={"列出插件"}, priority=0)
toggle_plugin = on_command("enable-plugin", aliases={"启用插件", "禁用插件", "disable-plugin"}, priority=0)
list_plugins = on_command("list-plugin", aliases={"列出插件"}, priority=0, permission=SUPERUSER)
toggle_plugin = on_command("enable-plugin", aliases={"启用插件", "禁用插件", "disable-plugin"}, priority=0, permission=SUPERUSER)
@list_plugins.handle()
async def _(event: T_MessageEvent):
async def _(event: T_MessageEvent, bot: T_Bot):
lang = get_user_lang(str(event.user_id))
reply = lang.get("npm.loaded_plugins")
reply = f"# {lang.get('npm.loaded_plugins')} | {lang.get('npm.total', TOTAL=len(nonebot.get_loaded_plugins()))} \n***"
for plugin in nonebot.get_loaded_plugins():
# 检查是否有 metadata 属性
if plugin.metadata:
reply += f"\n- {plugin.metadata.name}"
reply += f"\n- **{plugin.metadata.name}**".replace('_', r'\_')
else:
reply += f"\n- {plugin.name}"
await list_plugins.finish(reply)
reply += f"\n- **{plugin.name}**".replace('_', r'\_')
await send_markdown(reply, bot, event=event)

View File

@ -1 +1,11 @@
from nonebot.plugin import PluginMetadata
from .profile_manager import *
__author__ = "snowykami"
__plugin_meta__ = PluginMetadata(
name="轻雪用户管理",
description="用户管理插件",
usage="",
homepage="https://github.com/snowykami/LiteyukiBot",
)

View File

@ -11,6 +11,7 @@ main.monitor.disk=Disk
main.monitor.usage=Usage
npm.loaded_plugins=Loaded plugins
npm.total=Total {TOTAL}
user.profile_manager.query=Your {ATTR} is {VALUE}
user.profile_manager.set=Your {ATTR} has been set to {VALUE}

View File

@ -11,7 +11,7 @@ main.monitor.disk=磁盘
main.monitor.usage=使用率
npm.loaded_plugins=已加载插件
npm.loaded_plugins.description=已加载的插件列表
npm.total=总计 {TOTAL}
user.profile_manager.query=你的个人信息 {ATTR} 为 {VALUE}
user.profile_manager.set=你的个人信息 {ATTR} 已设置为 {VALUE}

View File

@ -3,11 +3,14 @@ from nonebot.adapters.onebot import v11, v12
from typing_extensions import Any
from .tools import de_escape
from .typing import T_Bot
from .typing import T_Bot, T_MessageEvent
async def send_markdown(markdown: str, bot: T_Bot, message_type: str, session_id: str | int) -> tuple[dict[str, Any], dict[str, Any]]:
async def send_markdown(markdown: str, bot: T_Bot, *, message_type: str=None, session_id: str | int=None, event: T_MessageEvent=None) -> dict[str, Any]:
formatted_md = de_escape(markdown).replace("\n", r"\n").replace("\"", r'\\\"')
if event is not None and message_type is None:
message_type = event.message_type
session_id = event.user_id if event.message_type == "private" else event.group_id
try:
forward_data = await bot.call_api(
api="send_private_forward_msg",
@ -67,4 +70,4 @@ async def send_markdown(markdown: str, bot: T_Bot, message_type: str, session_id
else:
nonebot.logger.error("send_markdown: bot type not supported")
data = {}
return data, forward_data
return data