改进 bmclapi

This commit is contained in:
shenjack 2024-02-20 15:16:43 +08:00
parent 1da32a4401
commit 774b5b1d1c
Signed by: shenjack
GPG Key ID: 7B1134A979775551

View File

@ -1,3 +1,4 @@
import time
import json import json
import aiohttp import aiohttp
@ -7,10 +8,47 @@ from data_struct import NewMessage, SendMessage
logger = config.get_logger("bmcl") logger = config.get_logger("bmcl")
_version_ = "1.0.0" _version_ = "1.1.0"
def format_data_size(data_bytes: float) -> str:
data_lens = ["B", "KB", "MB", "GB", "TB"]
data_len = "0B"
for i in range(5):
if data_bytes < 1024:
data_bytes = round(data_bytes, 5)
data_len = f"{data_bytes}{data_lens[i]}"
break
else:
data_bytes /= 1024
return data_len
def format_hit_count(count: int) -> str:
"""数据分段, 四位一个下划线
Args:
count (int): 数据
Returns:
str: 格式化后的数据
1 -> 1
1000 -> 1000
10000 -> 1_0000
100000 -> 10_0000
1000000 -> 100_0000
"""
count_str = str(count)
count_len = len(count_str)
if count_len <= 4:
return count_str
else:
return "_".join(count_str[i:i + 4] for i in range(0, count_len, 4))
async def bmcl(sio, reply_msg: SendMessage, msg: NewMessage): async def bmcl(sio, reply_msg: SendMessage, msg: NewMessage):
req_time = time.time()
# 记录请求时间
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get( async with session.get(
"https://bd.bangbang93.com/openbmclapi/metric/dashboard" "https://bd.bangbang93.com/openbmclapi/metric/dashboard"
@ -36,21 +74,16 @@ async def bmcl(sio, reply_msg: SendMessage, msg: NewMessage):
load_str: float = data["load"] * 100 load_str: float = data["load"] * 100
online_node: int = data["currentNodes"] online_node: int = data["currentNodes"]
online_bandwidth: int = data["bandwidth"] online_bandwidth: int = data["bandwidth"]
data_lens = ["B", "KB", "MB", "GB", "TB"] data_len = format_data_size(data_bytes)
data_len = "0B" hits_count = format_hit_count(data_hits)
for i in range(5):
if data_bytes < 1024:
data_bytes = round(data_bytes, 5)
data_len = f"{data_bytes}{data_lens[i]}"
break
else:
data_bytes /= 1024
report_msg = ( report_msg = (
f"OpenBMCLAPI 状态面板v{_version_} :\n" f"OpenBMCLAPI 状态面板v{_version_} :\n"
f"在线节点: {online_node} 带宽: {online_bandwidth}Mbps\n" f"在线节点: {online_node} 带宽: {online_bandwidth}Mbps\n"
f"实时负载: {load_str:.3f}% 带宽: {data_bandwidth:.5f}Mbps\n" f"实时负载: {load_str:.3f}% 带宽: {data_bandwidth:.5f}Mbps\n"
f"当日请求: {data_hits} 总数据量: {data_len}" f"当日请求: {hits_count} 总数据量: {data_len}\n"
f"请求时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(req_time))}\n"
"数据源: https://bd.bangbang93.com/pages/dashboard"
) )
await sio.emit( await sio.emit(
"sendMessage", "sendMessage",