Release xiaohuicat MOTD plugin with 24-hour player history
This commit is contained in:
commit
2144e218ec
23 files changed
+1904
No files matched your search
@@ -0,0 +1 @@
|
||||
"""MOTD 查询、存储和图片服务。"""
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Validate Minecraft addresses without changing implicit SRV semantics."""
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
LABEL = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$")
|
||||
|
||||
|
||||
def normalize_address(value: str) -> str:
|
||||
value = value.strip().lower()
|
||||
if not value or len(value) > 259 or "/" in value:
|
||||
raise ValueError("服务器地址格式不正确。请输入域名或 IP,可附带 :端口。")
|
||||
# Brackets make IPv6 + port unambiguous.
|
||||
if value.startswith("["):
|
||||
match = re.fullmatch(r"\[([^]]+)\](?::([0-9]{1,5}))?", value)
|
||||
if not match:
|
||||
raise ValueError("IPv6 地址请使用 [IPv6]:端口 格式。")
|
||||
try:
|
||||
ipaddress.IPv6Address(match[1])
|
||||
except ValueError as exc:
|
||||
raise ValueError("IPv6 地址格式不正确。") from exc
|
||||
port = match[2]
|
||||
else:
|
||||
host, separator, port = value.partition(":")
|
||||
if len(host) > 253 or not all(LABEL.fullmatch(p) for p in host.split(".")):
|
||||
raise ValueError("服务器地址格式不正确。")
|
||||
if separator and (not port.isascii() or not port.isdigit()):
|
||||
raise ValueError("端口必须是 1 到 65535 的整数。")
|
||||
if port and not 1 <= int(port) <= 65535:
|
||||
raise ValueError("端口必须是 1 到 65535 的整数。")
|
||||
return value
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Minecraft Java 直连查询、真实 Ping 和原项目公开 API 备用服务。"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import struct
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from mcstatus import JavaServer
|
||||
|
||||
logger = logging.getLogger("qqbot.mc_api")
|
||||
|
||||
|
||||
class MinecraftServerAPI:
|
||||
"""Minecraft 服务器状态查询客户端"""
|
||||
|
||||
def __init__(self, config: dict):
|
||||
mc_cfg = config.get("mc_status", config)
|
||||
self.api_url: str = mc_cfg.get("api_url", "https://api.mcsrvstat.us/2/{address}")
|
||||
self.timeout: float = mc_cfg.get("request_timeout", 10)
|
||||
self.ping_timeout: float = mc_cfg.get("ping_timeout", 4)
|
||||
self.default_port: int = mc_cfg.get("default_port", 25565)
|
||||
self._metadata = OrderedDict()
|
||||
|
||||
async def query(self, address: str) -> dict | None:
|
||||
"""Prefer uncached Java status for player history; retain the original public API fallback."""
|
||||
|
||||
async def direct():
|
||||
server = await JavaServer.async_lookup(address, timeout=self.ping_timeout)
|
||||
status = await server.async_status(tries=1)
|
||||
raw = status.raw
|
||||
sample = raw.get("players", {}).get("sample", []) or []
|
||||
return {
|
||||
"online": True,
|
||||
"address": address,
|
||||
"hostname": "",
|
||||
"ip": server.address.host,
|
||||
"port": server.address.port,
|
||||
"version": status.version.name,
|
||||
"motd": status.motd.to_plain(),
|
||||
"players_online": status.players.online,
|
||||
"players_max": status.players.max,
|
||||
"player_list": [
|
||||
str(p.get("name", "")) for p in sample if isinstance(p, dict) and p.get("name")
|
||||
],
|
||||
"latency_ms": round(status.latency, 1),
|
||||
"software": raw.get("software", ""),
|
||||
"plugins": raw.get("plugins", {}),
|
||||
"icon": raw.get("favicon", ""),
|
||||
"source": "direct",
|
||||
}
|
||||
|
||||
try:
|
||||
data = await asyncio.wait_for(direct(), timeout=self.ping_timeout + 2)
|
||||
except Exception as exc:
|
||||
logger.debug("MC 直连失败,使用原公开 API %s: %s", address, exc)
|
||||
data = await self._query_api(address)
|
||||
if data is not None:
|
||||
data["source"] = "api"
|
||||
return data
|
||||
# Java status does not normally expose software/plugin names. Preserve the
|
||||
# old API's extra fields while NEVER replacing direct player counts or RTT.
|
||||
cached = self._metadata.get(address)
|
||||
if not cached or time.monotonic() - cached[0] >= 3600:
|
||||
extra = await self._query_api(address, measure_latency=False)
|
||||
self._metadata[address] = (time.monotonic(), extra)
|
||||
self._metadata.move_to_end(address)
|
||||
while len(self._metadata) > 128:
|
||||
self._metadata.popitem(last=False)
|
||||
else:
|
||||
extra = cached[1]
|
||||
if extra and extra.get("online"):
|
||||
for key in ("hostname", "software", "plugins", "icon", "player_list"):
|
||||
if not data.get(key) and extra.get(key):
|
||||
data[key] = extra[key]
|
||||
if key == "player_list":
|
||||
data["player_list_cached"] = True
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def _encode_varint(value: int) -> bytes:
|
||||
value &= 0xFFFFFFFF
|
||||
encoded = bytearray()
|
||||
while True:
|
||||
byte = value & 0x7F
|
||||
value >>= 7
|
||||
encoded.append(byte | (0x80 if value else 0))
|
||||
if not value:
|
||||
return bytes(encoded)
|
||||
|
||||
@classmethod
|
||||
def _encode_string(cls, value: str) -> bytes:
|
||||
raw = value.encode("utf-8")
|
||||
return cls._encode_varint(len(raw)) + raw
|
||||
|
||||
@staticmethod
|
||||
async def _read_varint(reader: asyncio.StreamReader) -> int:
|
||||
value = 0
|
||||
for position in range(5):
|
||||
byte = (await reader.readexactly(1))[0]
|
||||
value |= (byte & 0x7F) << (7 * position)
|
||||
if not byte & 0x80:
|
||||
return value
|
||||
raise ValueError("Minecraft VarInt 过长")
|
||||
|
||||
async def _measure_minecraft_latency(
|
||||
self, connect_host: str, port: int, handshake_host: str, protocol: int
|
||||
) -> float | None:
|
||||
"""执行 Minecraft Java 状态握手与 ping/pong,返回真实 RTT。"""
|
||||
|
||||
async def probe() -> float:
|
||||
reader, writer = await asyncio.open_connection(connect_host, port)
|
||||
try:
|
||||
handshake = (
|
||||
self._encode_varint(0)
|
||||
+ self._encode_varint(protocol)
|
||||
+ self._encode_string(handshake_host)
|
||||
+ struct.pack(">H", port)
|
||||
+ self._encode_varint(1)
|
||||
)
|
||||
writer.write(self._encode_varint(len(handshake)) + handshake)
|
||||
writer.write(b"\x01\x00") # status request: length=1, packet id=0
|
||||
await writer.drain()
|
||||
|
||||
packet_length = await self._read_varint(reader)
|
||||
if not 1 <= packet_length <= 2_097_152:
|
||||
raise ValueError("Minecraft 状态响应大小超出限制")
|
||||
if await self._read_varint(reader) != 0:
|
||||
raise ValueError("非法的 Minecraft 状态响应")
|
||||
json_length = await self._read_varint(reader)
|
||||
if not 0 <= json_length <= packet_length:
|
||||
raise ValueError("非法的 Minecraft JSON 长度")
|
||||
await reader.readexactly(json_length)
|
||||
|
||||
payload = int(time.time_ns() // 1_000_000)
|
||||
ping_packet = self._encode_varint(1) + struct.pack(">q", payload)
|
||||
started = time.perf_counter()
|
||||
writer.write(self._encode_varint(len(ping_packet)) + ping_packet)
|
||||
await writer.drain()
|
||||
if await self._read_varint(reader) != 9:
|
||||
raise ValueError("非法的 Minecraft pong 长度")
|
||||
if await self._read_varint(reader) != 1:
|
||||
raise ValueError("非法的 Minecraft pong 响应")
|
||||
if await reader.readexactly(8) != struct.pack(">q", payload):
|
||||
raise ValueError("Minecraft pong 校验失败")
|
||||
return round((time.perf_counter() - started) * 1000, 1)
|
||||
finally:
|
||||
writer.close()
|
||||
try:
|
||||
await writer.wait_closed()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(probe(), timeout=self.ping_timeout)
|
||||
except Exception as exc:
|
||||
logger.warning("Minecraft Ping 测量失败 %s:%s: %s", connect_host, port, exc)
|
||||
return None
|
||||
|
||||
async def _query_api(self, address: str, measure_latency: bool = True) -> dict | None:
|
||||
"""
|
||||
查询 Minecraft 服务器状态
|
||||
|
||||
Args:
|
||||
address: 服务器地址,如 "mc.hypixel.net" 或 "mc.example.com:25565"
|
||||
|
||||
Returns:
|
||||
服务器信息字典,失败返回 None
|
||||
"""
|
||||
# 不要给纯域名强制补 :25565。查询服务会先解析
|
||||
# _minecraft._tcp SRV 记录;只有用户显式填写端口时才固定端口。
|
||||
url = self.api_url.format(address=quote(address, safe=""))
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(url)
|
||||
|
||||
if response.status_code != 200:
|
||||
logger.warning(f"MC服务器查询失败: {address} HTTP {response.status_code}")
|
||||
return None
|
||||
|
||||
data = response.json()
|
||||
|
||||
if not data.get("online", False):
|
||||
return {
|
||||
"online": False,
|
||||
"address": address,
|
||||
"latency_ms": None,
|
||||
}
|
||||
|
||||
# 提取 MOTD 纯文本
|
||||
motd_text = ""
|
||||
motd = data.get("motd", {})
|
||||
if isinstance(motd, dict):
|
||||
motd_text = " | ".join(motd.get("clean", []))
|
||||
elif isinstance(motd, str):
|
||||
motd_text = motd
|
||||
|
||||
players = data.get("players", {})
|
||||
player_list = []
|
||||
for player in players.get("list", []) or []:
|
||||
if isinstance(player, dict):
|
||||
name = player.get("name") or player.get("username") or ""
|
||||
else:
|
||||
name = str(player)
|
||||
name = name.strip()
|
||||
if name:
|
||||
player_list.append(name)
|
||||
resolved_ip = str(data.get("ip") or "")
|
||||
resolved_port = int(data.get("port") or self.default_port)
|
||||
protocol = int(data.get("protocol") or 47)
|
||||
handshake_host = address.rsplit(":", 1)[0] if ":" in address else address
|
||||
latency_ms = None
|
||||
if resolved_ip and measure_latency:
|
||||
latency_ms = await self._measure_minecraft_latency(
|
||||
resolved_ip, resolved_port, handshake_host, protocol
|
||||
)
|
||||
return {
|
||||
"online": True,
|
||||
"address": address,
|
||||
"hostname": data.get("hostname", ""),
|
||||
"ip": data.get("ip", ""),
|
||||
"port": resolved_port,
|
||||
"version": data.get("version", "未知"),
|
||||
"motd": motd_text,
|
||||
"players_online": players.get("online", 0),
|
||||
"players_max": players.get("max", 0),
|
||||
"player_list": player_list,
|
||||
"latency_ms": latency_ms,
|
||||
"software": data.get("software", ""),
|
||||
"plugins": data.get("plugins", {}),
|
||||
"icon": data.get("icon", ""),
|
||||
}
|
||||
|
||||
except httpx.TimeoutException:
|
||||
logger.error(f"MC服务器查询超时: {address}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"MC服务器查询失败 ({address}): {e}")
|
||||
return None
|
||||
|
||||
def format_server_info(self, data: dict | None) -> str:
|
||||
"""格式化服务器信息为文本"""
|
||||
if not data:
|
||||
return "❌ 无法查询该服务器,请检查地址是否正确。"
|
||||
|
||||
if not data.get("online", False):
|
||||
addr = data.get("address", "未知服务器")
|
||||
return f"⚠️ 服务器离线\n🖥️ 地址: {addr}"
|
||||
|
||||
# 在线服务器
|
||||
lines = [
|
||||
"🟢 服务器在线",
|
||||
]
|
||||
|
||||
if data.get("hostname"):
|
||||
lines.append(f"🏷️ 名称: {data['hostname']}")
|
||||
|
||||
addr = data.get("address", "")
|
||||
if addr:
|
||||
lines.append(f"🖥️ 地址: {addr}")
|
||||
|
||||
lines.append(f"📦 版本: {data.get('version', '未知')}")
|
||||
|
||||
if data.get("software"):
|
||||
lines.append(f"🔧 服务端: {data['software']}")
|
||||
|
||||
motd = data.get("motd", "")
|
||||
if motd:
|
||||
# 限制标语长度
|
||||
if len(motd) > 200:
|
||||
motd = motd[:200] + "..."
|
||||
lines.append(f"📝 标语: {motd}")
|
||||
|
||||
players_online = data.get("players_online", 0)
|
||||
players_max = data.get("players_max", 0)
|
||||
# 玩家数进度条
|
||||
if players_max > 0:
|
||||
bar_len = 10
|
||||
ratio = min(players_online / players_max, 1.0)
|
||||
filled = int(bar_len * ratio)
|
||||
bar = "█" * filled + "░" * (bar_len - filled)
|
||||
lines.append(f"👥 在线: {players_online}/{players_max} [{bar}]")
|
||||
else:
|
||||
lines.append(f"👥 在线: {players_online}")
|
||||
|
||||
latency = data.get("latency_ms")
|
||||
lines.append(f"📡 MC Ping: {latency}ms" if latency is not None else "📡 MC Ping: 未提供")
|
||||
|
||||
# 如果安装了插件,显示数量
|
||||
plugins = data.get("plugins", {})
|
||||
if isinstance(plugins, dict) and plugins.get("names"):
|
||||
plug_count = len(plugins["names"])
|
||||
lines.append(f"🔌 插件: {plug_count} 个")
|
||||
|
||||
player_list = data.get("player_list") or []
|
||||
if player_list:
|
||||
lines.append(
|
||||
f"👤 已公开玩家({len(player_list)}/{players_online}): "
|
||||
+ "、".join(player_list)[:400]
|
||||
)
|
||||
elif players_online:
|
||||
lines.append("👤 服务器未公开玩家名单")
|
||||
else:
|
||||
lines.append("👤 暂无玩家在线")
|
||||
if data.get("source") == "api":
|
||||
lines.append("数据来源: 公开 API(可能有缓存)")
|
||||
if data.get("player_list_cached"):
|
||||
lines.append("玩家名单来源: API 缓存样本")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Shared query cache and bounded background sampling, with clean cancellation."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PlayerMonitor:
|
||||
def __init__(self, api, store, interval=300, retention_hours=48, enabled=True, addresses=()):
|
||||
self.api, self.store = api, store
|
||||
self.interval, self.retention_hours, self.enabled = interval, retention_hours, enabled
|
||||
self.addresses = set(addresses)
|
||||
self._semaphore = asyncio.Semaphore(4)
|
||||
self._cache = OrderedDict()
|
||||
self._pending = {}
|
||||
self._task = None
|
||||
|
||||
async def query(self, address: str):
|
||||
cached = self._cache.get(address)
|
||||
if cached and time.monotonic() - cached[0] < 15:
|
||||
return cached[1]
|
||||
# Concurrent requests for the same server share one query and one sample.
|
||||
if address not in self._pending:
|
||||
self._pending[address] = asyncio.create_task(self._fetch(address))
|
||||
task = self._pending[address]
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
finally:
|
||||
if task.done() and self._pending.get(address) is task:
|
||||
self._pending.pop(address, None)
|
||||
|
||||
async def _fetch(self, address):
|
||||
async with self._semaphore:
|
||||
try:
|
||||
data = await self.api.query(address)
|
||||
except Exception:
|
||||
logger.exception("MOTD 查询异常: %s", address)
|
||||
data = None
|
||||
await self.store.record(address, data)
|
||||
self._cache[address] = (time.monotonic(), data)
|
||||
self._cache.move_to_end(address)
|
||||
while len(self._cache) > 128:
|
||||
self._cache.popitem(last=False)
|
||||
return data
|
||||
|
||||
def start(self):
|
||||
if self.enabled and self._task is None:
|
||||
self._task = asyncio.create_task(self._loop(), name="motd-player-monitor")
|
||||
|
||||
async def sample_once(self):
|
||||
addresses = set(await self.store.monitored_addresses()) | self.addresses
|
||||
results = await asyncio.gather(*(self.query(a) for a in addresses), return_exceptions=True)
|
||||
for address, result in zip(addresses, results):
|
||||
if isinstance(result, Exception):
|
||||
logger.error("MOTD 采样失败 %s: %s", address, result)
|
||||
await self.store.prune(self.retention_hours)
|
||||
|
||||
async def _loop(self):
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
await self.sample_once()
|
||||
except Exception:
|
||||
logger.exception("MOTD 后台采样异常")
|
||||
await asyncio.sleep(max(1, self.interval - (time.monotonic() - started)))
|
||||
|
||||
async def close(self):
|
||||
tasks = list(self._pending.values())
|
||||
if self._task:
|
||||
tasks.append(self._task)
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
self._pending.clear()
|
||||
self._task = None
|
||||
@@ -0,0 +1,422 @@
|
||||
"""Minecraft MOTD 图片卡片渲染器。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import html
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
CARD_WIDTH = 1200
|
||||
CARD_HEIGHT = 1080
|
||||
CHINA_TIME = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
@lru_cache(maxsize=64)
|
||||
def _load_font(
|
||||
size: int, bold: bool = False, font_path: str = ""
|
||||
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
||||
"""优先使用服务器上的中文字体,兼容 Windows 本地预览。"""
|
||||
names = (
|
||||
[
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
|
||||
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
|
||||
"C:/Windows/Fonts/msyhbd.ttc",
|
||||
"C:/Windows/Fonts/simhei.ttf",
|
||||
]
|
||||
if bold
|
||||
else [
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
|
||||
"C:/Windows/Fonts/msyh.ttc",
|
||||
"C:/Windows/Fonts/simsun.ttc",
|
||||
]
|
||||
)
|
||||
for name in ([font_path] if font_path else []) + names:
|
||||
if Path(name).exists():
|
||||
return ImageFont.truetype(name, size=size)
|
||||
try:
|
||||
return ImageFont.truetype("DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf", size=size)
|
||||
except OSError:
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _rounded_panel(
|
||||
draw: ImageDraw.ImageDraw,
|
||||
box: tuple[int, int, int, int],
|
||||
fill: tuple[int, int, int, int],
|
||||
outline: tuple[int, int, int, int] | None = None,
|
||||
radius: int = 22,
|
||||
) -> None:
|
||||
draw.rounded_rectangle(box, radius=radius, fill=fill, outline=outline, width=2)
|
||||
|
||||
|
||||
def _draw_pixel_background(image: Image.Image, seed_text: str) -> None:
|
||||
draw = ImageDraw.Draw(image, "RGBA")
|
||||
top = (12, 23, 18)
|
||||
bottom = (22, 49, 34)
|
||||
for y in range(CARD_HEIGHT):
|
||||
ratio = y / max(CARD_HEIGHT - 1, 1)
|
||||
color = tuple(int(top[i] + (bottom[i] - top[i]) * ratio) for i in range(3))
|
||||
draw.line((0, y, CARD_WIDTH, y), fill=(*color, 255))
|
||||
|
||||
digest = hashlib.sha256(seed_text.encode("utf-8")).digest()
|
||||
palette = [(17, 39, 26, 255), (20, 46, 29, 255), (15, 34, 24, 255)]
|
||||
for index in range(34):
|
||||
x = (digest[index % len(digest)] * 47 + index * 113) % CARD_WIDTH
|
||||
y = (digest[(index + 9) % len(digest)] * 31 + index * 71) % CARD_HEIGHT
|
||||
size = 24 + digest[(index + 17) % len(digest)] % 64
|
||||
draw.rectangle((x, y, x + size, y + size), fill=palette[index % len(palette)])
|
||||
|
||||
|
||||
def _decode_server_icon(icon_value: str) -> Image.Image | None:
|
||||
if not icon_value:
|
||||
return None
|
||||
if len(icon_value) > 1_000_000:
|
||||
return None
|
||||
try:
|
||||
encoded = icon_value.split(",", 1)[1] if "," in icon_value else icon_value
|
||||
source = Image.open(io.BytesIO(base64.b64decode(encoded)))
|
||||
if source.width > 512 or source.height > 512:
|
||||
return None
|
||||
icon = source.convert("RGBA")
|
||||
return icon.resize((128, 128), Image.Resampling.NEAREST)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _draw_creeper_icon(image: Image.Image, box: tuple[int, int, int, int], seed_text: str) -> None:
|
||||
"""服务器没有图标时,绘制像素风苦力怕头像。"""
|
||||
x1, y1, x2, y2 = box
|
||||
size = x2 - x1
|
||||
cell = max(size // 8, 1)
|
||||
draw = ImageDraw.Draw(image, "RGBA")
|
||||
digest = hashlib.md5(seed_text.encode("utf-8")).digest()
|
||||
greens = [(72, 160, 72, 255), (83, 177, 79, 255), (55, 139, 65, 255), (101, 188, 88, 255)]
|
||||
for row in range(8):
|
||||
for col in range(8):
|
||||
color = greens[digest[(row * 8 + col) % len(digest)] % len(greens)]
|
||||
draw.rectangle(
|
||||
(x1 + col * cell, y1 + row * cell, x1 + (col + 1) * cell, y1 + (row + 1) * cell),
|
||||
fill=color,
|
||||
)
|
||||
dark = (15, 31, 22, 255)
|
||||
for col, row, width, height in (
|
||||
(1, 2, 2, 2),
|
||||
(5, 2, 2, 2),
|
||||
(3, 4, 2, 2),
|
||||
(2, 5, 4, 2),
|
||||
(2, 7, 1, 1),
|
||||
(5, 7, 1, 1),
|
||||
):
|
||||
draw.rectangle(
|
||||
(
|
||||
x1 + col * cell,
|
||||
y1 + row * cell,
|
||||
x1 + (col + width) * cell,
|
||||
y1 + (row + height) * cell,
|
||||
),
|
||||
fill=dark,
|
||||
)
|
||||
|
||||
|
||||
def _ellipsize(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> str:
|
||||
text = str(text)
|
||||
if draw.textlength(text, font=font) <= max_width:
|
||||
return text
|
||||
suffix = "..."
|
||||
while text and draw.textlength(text + suffix, font=font) > max_width:
|
||||
text = text[:-1]
|
||||
return text + suffix
|
||||
|
||||
|
||||
def _wrap_text(
|
||||
draw: ImageDraw.ImageDraw, text: str, font, max_width: int, max_lines: int = 2
|
||||
) -> list[str]:
|
||||
clean = (
|
||||
html.unescape(re.sub(r"§.", "", str(text))).replace("\r", " ").replace("\n", " ").strip()
|
||||
)
|
||||
if not clean:
|
||||
return []
|
||||
lines: list[str] = []
|
||||
current = ""
|
||||
for char in clean:
|
||||
candidate = current + char
|
||||
if current and draw.textlength(candidate, font=font) > max_width:
|
||||
lines.append(current)
|
||||
current = char
|
||||
if len(lines) == max_lines:
|
||||
break
|
||||
else:
|
||||
current = candidate
|
||||
if len(lines) < max_lines and current:
|
||||
lines.append(current)
|
||||
consumed = "".join(lines)
|
||||
if len(consumed) < len(clean) and lines:
|
||||
lines[-1] = _ellipsize(draw, lines[-1] + "...", font, max_width)
|
||||
return lines[:max_lines]
|
||||
|
||||
|
||||
def render_motd_card(
|
||||
data: dict,
|
||||
bot_name: str = "xiaohuicat",
|
||||
history: list[dict] | None = None,
|
||||
now: int | None = None,
|
||||
sample_interval: int = 300,
|
||||
history_enabled: bool = True,
|
||||
font_path: str = "",
|
||||
) -> bytes:
|
||||
"""把 MOTD 查询结果渲染为 PNG 字节。"""
|
||||
address = str(data.get("address") or "未知服务器")
|
||||
online = bool(data.get("online"))
|
||||
accent = (91, 214, 111, 255) if online else (241, 96, 89, 255)
|
||||
accent_soft = (27, 67, 37, 255) if online else (76, 31, 29, 255)
|
||||
|
||||
image = Image.new("RGBA", (CARD_WIDTH, CARD_HEIGHT), (12, 23, 18, 255))
|
||||
_draw_pixel_background(image, address)
|
||||
draw = ImageDraw.Draw(image, "RGBA")
|
||||
|
||||
# 主面板和左侧像素饰条
|
||||
_rounded_panel(draw, (44, 42, 1156, 1040), (8, 16, 13, 222), (77, 123, 90, 110), 30)
|
||||
draw.rounded_rectangle((44, 42, 58, 1040), radius=7, fill=accent)
|
||||
_rounded_panel(draw, (84, 100, 264, 280), (20, 38, 27, 245), (83, 147, 94, 155), 22)
|
||||
|
||||
icon = _decode_server_icon(str(data.get("icon") or ""))
|
||||
if icon is not None:
|
||||
image.alpha_composite(icon, (110, 126))
|
||||
else:
|
||||
_draw_creeper_icon(image, (110, 126, 238, 254), address)
|
||||
|
||||
title_font = _load_font(25, bold=True, font_path=font_path)
|
||||
address_font = _load_font(42, bold=True, font_path=font_path)
|
||||
status_font = _load_font(28, bold=True, font_path=font_path)
|
||||
label_font = _load_font(22, font_path=font_path)
|
||||
value_font = _load_font(29, bold=True, font_path=font_path)
|
||||
motd_font = _load_font(25, font_path=font_path)
|
||||
footer_font = _load_font(19, font_path=font_path)
|
||||
|
||||
draw.text((84, 66), "MINECRAFT SERVER STATUS", font=title_font, fill=(161, 196, 171, 255))
|
||||
shown_address = _ellipsize(draw, address, address_font, 790)
|
||||
draw.text((298, 112), shown_address, font=address_font, fill=(239, 247, 241, 255))
|
||||
|
||||
status_text = (
|
||||
"查询失败" if data.get("query_failed") else ("服务器在线" if online else "服务器离线")
|
||||
)
|
||||
status_width = int(draw.textlength(status_text, font=status_font)) + 58
|
||||
draw.rounded_rectangle(
|
||||
(298, 176, 298 + status_width, 226), radius=25, fill=accent_soft, outline=accent, width=2
|
||||
)
|
||||
draw.ellipse((316, 193, 330, 207), fill=accent)
|
||||
draw.text((342, 183), status_text, font=status_font, fill=accent)
|
||||
details = " · ".join(str(data.get(k) or "") for k in ("hostname", "software") if data.get(k))
|
||||
plugins = data.get("plugins")
|
||||
if isinstance(plugins, dict) and plugins.get("names"):
|
||||
details += f" · 插件 {len(plugins['names'])} 个"
|
||||
if details:
|
||||
draw.text(
|
||||
(298, 247),
|
||||
_ellipsize(draw, details.strip(" ·"), label_font, 780),
|
||||
font=label_font,
|
||||
fill=(145, 171, 152, 255),
|
||||
)
|
||||
|
||||
# 信息卡片
|
||||
latency = data.get("latency_ms")
|
||||
latency_text = f"{latency} ms" if latency is not None else "未提供"
|
||||
panels = [
|
||||
(84, 314, 392, 426, "游戏版本", str(data.get("version") or "未知")),
|
||||
(
|
||||
414,
|
||||
314,
|
||||
722,
|
||||
426,
|
||||
"在线玩家",
|
||||
f"{data.get('players_online', 0)} / {data.get('players_max', 0)}"
|
||||
if online
|
||||
else "- / -",
|
||||
),
|
||||
(744, 314, 1072, 426, "MC PING", latency_text),
|
||||
]
|
||||
for x1, y1, x2, y2, label, value in panels:
|
||||
_rounded_panel(draw, (x1, y1, x2, y2), (19, 35, 27, 230), (65, 104, 76, 100), 18)
|
||||
draw.text((x1 + 22, y1 + 16), label, font=label_font, fill=(145, 171, 152, 255))
|
||||
draw.text(
|
||||
(x1 + 22, y1 + 52),
|
||||
_ellipsize(draw, value, value_font, x2 - x1 - 44),
|
||||
font=value_font,
|
||||
fill=(237, 244, 239, 255),
|
||||
)
|
||||
|
||||
# 玩家数进度条
|
||||
players_online = int(data.get("players_online") or 0)
|
||||
players_max = int(data.get("players_max") or 0)
|
||||
ratio = min(players_online / players_max, 1.0) if players_max > 0 and online else 0
|
||||
draw.rounded_rectangle((436, 404, 700, 414), radius=5, fill=(40, 61, 47, 255))
|
||||
if ratio > 0:
|
||||
draw.rounded_rectangle((436, 404, 436 + int(264 * ratio), 414), radius=5, fill=accent)
|
||||
|
||||
# MOTD
|
||||
_rounded_panel(draw, (84, 452, 714, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18)
|
||||
draw.text((106, 468), "MOTD", font=label_font, fill=(145, 171, 152, 255))
|
||||
motd = str(data.get("motd") or ("暂无服务器标语" if online else "无法连接到该服务器"))
|
||||
for line_index, line in enumerate(_wrap_text(draw, motd, motd_font, 580, 2)):
|
||||
draw.text((106, 500 + line_index * 32), line, font=motd_font, fill=(226, 236, 229, 255))
|
||||
|
||||
# 在线玩家名单(Minecraft 状态协议可能只返回部分样本)
|
||||
_rounded_panel(draw, (736, 452, 1072, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18)
|
||||
player_list = [str(name) for name in (data.get("player_list") or []) if str(name).strip()]
|
||||
if player_list:
|
||||
public_count = len(player_list)
|
||||
player_label = f"在线玩家(已公开 {public_count}/{players_online})"
|
||||
if data.get("player_list_cached"):
|
||||
player_label = "公开玩家(API 缓存样本)"
|
||||
player_text = "、".join(player_list)
|
||||
elif online and players_online > 0:
|
||||
player_label = "在线玩家"
|
||||
player_text = "服务器未公开玩家名单"
|
||||
elif online:
|
||||
player_label = "在线玩家"
|
||||
player_text = "暂无玩家在线"
|
||||
else:
|
||||
player_label = "在线玩家"
|
||||
player_text = "-"
|
||||
draw.text(
|
||||
(758, 468),
|
||||
_ellipsize(draw, player_label, label_font, 292),
|
||||
font=label_font,
|
||||
fill=(145, 171, 152, 255),
|
||||
)
|
||||
for line_index, line in enumerate(_wrap_text(draw, player_text, label_font, 290, 2)):
|
||||
draw.text((758, 504 + line_index * 28), line, font=label_font, fill=(226, 236, 229, 255))
|
||||
|
||||
now = int(time.time()) if now is None else now
|
||||
_draw_history(draw, history or [], now, sample_interval, history_enabled, font_path)
|
||||
source = "公开 API(可能有缓存)" if data.get("source") == "api" else "Minecraft 直连"
|
||||
if data.get("query_failed"):
|
||||
source = "本次查询失败"
|
||||
update_time = datetime.fromtimestamp(now, CHINA_TIME).strftime("%m-%d %H:%M")
|
||||
footer = f"{bot_name} · itxiaohui · {source} · {update_time} (UTC+8)"
|
||||
draw.text(
|
||||
(84, 996),
|
||||
_ellipsize(draw, footer, footer_font, 1010),
|
||||
font=footer_font,
|
||||
fill=(116, 145, 125, 255),
|
||||
)
|
||||
|
||||
output = io.BytesIO()
|
||||
image.convert("RGB").save(output, format="PNG", optimize=True)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def history_segments(history: list[dict], now: int, interval: int) -> list[list[dict]]:
|
||||
"""Split at failures, offline responses, and missing samples instead of inventing a connecting line."""
|
||||
segments, current = [], []
|
||||
for point in sorted(history, key=lambda p: p["timestamp"]):
|
||||
if not now - 86400 <= point["timestamp"] <= now:
|
||||
continue
|
||||
valid = point.get("online") == 1 and point.get("players") is not None
|
||||
if not valid or (
|
||||
current and point["timestamp"] - current[-1]["timestamp"] > interval * 2.5
|
||||
):
|
||||
if current:
|
||||
segments.append(current)
|
||||
current = []
|
||||
if valid:
|
||||
current.append(point)
|
||||
if current:
|
||||
segments.append(current)
|
||||
return segments
|
||||
|
||||
|
||||
def _draw_history(draw, history, now, interval, enabled, font_path):
|
||||
_rounded_panel(draw, (84, 590, 1072, 974), (17, 31, 24, 230), (65, 104, 76, 90), 18)
|
||||
title = _load_font(25, True, font_path)
|
||||
font = _load_font(19, font_path=font_path)
|
||||
small = _load_font(17, font_path=font_path)
|
||||
draw.text((106, 606), "最近 24 小时 · 在线玩家波动", font=title, fill=(226, 236, 229))
|
||||
history = sorted(
|
||||
(p for p in history if now - 86400 <= p["timestamp"] <= now), key=lambda p: p["timestamp"]
|
||||
)
|
||||
counts = [
|
||||
p["players"] for p in history if p.get("online") == 1 and p.get("players") is not None
|
||||
]
|
||||
if counts:
|
||||
summary = f"最低 {min(counts)} / 最高 {max(counts)} / 采样均值 {sum(counts) / len(counts):.1f}"
|
||||
else:
|
||||
summary = "暂无成功的人数采样"
|
||||
draw.text((106, 644), summary, font=font, fill=(145, 171, 152))
|
||||
# Fixed rolling 24h axis: partial histories only occupy their actual time range.
|
||||
left, right, top, bottom = 162, 1034, 694, 874
|
||||
maximum = max(counts, default=1)
|
||||
step = max(1, math.ceil(maximum / 4))
|
||||
ceiling = step * 4
|
||||
for index in range(5):
|
||||
y = bottom - index * (bottom - top) / 4
|
||||
draw.line((left, y, right, y), fill=(48, 70, 55), width=1)
|
||||
label = str(index * step)
|
||||
draw.text(
|
||||
(left - 14 - draw.textlength(label, font=small), y - 12),
|
||||
label,
|
||||
font=small,
|
||||
fill=(116, 145, 125),
|
||||
)
|
||||
for index in range(5):
|
||||
x = left + index * (right - left) / 4
|
||||
draw.line((x, top, x, bottom), fill=(32, 51, 39), width=1)
|
||||
stamp = datetime.fromtimestamp(now - 86400 + index * 21600, CHINA_TIME).strftime("%H:%M")
|
||||
draw.text(
|
||||
(x - draw.textlength(stamp, font=small) / 2, 883),
|
||||
stamp,
|
||||
font=small,
|
||||
fill=(116, 145, 125),
|
||||
)
|
||||
|
||||
def coordinates(p):
|
||||
return (
|
||||
left + (p["timestamp"] - (now - 86400)) / 86400 * (right - left),
|
||||
bottom - p["players"] / ceiling * (bottom - top),
|
||||
)
|
||||
|
||||
for segment in history_segments(history, now, interval):
|
||||
points = [coordinates(p) for p in segment]
|
||||
if len(points) > 1:
|
||||
draw.line(points, fill=(91, 214, 111), width=3)
|
||||
for x, y in points:
|
||||
draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(123, 238, 141))
|
||||
for point in history:
|
||||
if point.get("online") != 1:
|
||||
x = left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left)
|
||||
color = (241, 96, 89) if point.get("online") == 0 else (212, 175, 99)
|
||||
draw.line((x, bottom - 6, x, bottom), fill=color, width=2)
|
||||
if not counts:
|
||||
text = "开始采集后将在这里显示曲线" if not history else "服务器离线或查询失败,暂无人数曲线"
|
||||
draw.text((left + 140, top + 70), text, font=font, fill=(145, 171, 152))
|
||||
if len(counts) == 1:
|
||||
note = "仅有 1 个人数采样,继续运行后自动形成曲线"
|
||||
else:
|
||||
note = f"人数采样 {len(counts)} 次 · 间隔 {interval // 60} 分钟 · 红:离线 黄:失败 空白:无数据"
|
||||
if not enabled:
|
||||
note = "后台采样已关闭,仅记录手动查询 · 空白时段没有数据"
|
||||
draw.text((106, 918), _ellipsize(draw, note, small, 936), font=small, fill=(116, 145, 125))
|
||||
if any(p.get("source") == "api" for p in history):
|
||||
draw.text(
|
||||
(106, 944),
|
||||
"部分采样来自公开 API,人数可能有缓存延迟 · 时间 UTC+8",
|
||||
font=small,
|
||||
fill=(212, 175, 99),
|
||||
)
|
||||
else:
|
||||
draw.text(
|
||||
(106, 944),
|
||||
"从首次查询或绑定开始积累 · 重启后保留历史 · 时间 UTC+8",
|
||||
font=small,
|
||||
fill=(116, 145, 125),
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""SQLite persistence outside the plugin checkout; every connection stays in a worker thread."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class MotdStore:
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
|
||||
def _run(self, operation):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(self.path, timeout=15) as db:
|
||||
db.row_factory = sqlite3.Row
|
||||
return operation(db)
|
||||
|
||||
async def initialize(self):
|
||||
def create(db):
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS bindings (
|
||||
scope TEXT PRIMARY KEY, address TEXT NOT NULL,
|
||||
updated_by TEXT NOT NULL, updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tracked (
|
||||
address TEXT PRIMARY KEY, touched_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS samples (
|
||||
address TEXT NOT NULL, timestamp INTEGER NOT NULL,
|
||||
online INTEGER, players INTEGER, source TEXT NOT NULL,
|
||||
PRIMARY KEY (address, timestamp)
|
||||
);
|
||||
""")
|
||||
|
||||
await asyncio.to_thread(self._run, create)
|
||||
|
||||
async def get_binding(self, scope: str) -> str | None:
|
||||
def query(db):
|
||||
row = db.execute("SELECT address FROM bindings WHERE scope=?", (scope,)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
return await asyncio.to_thread(self._run, query)
|
||||
|
||||
async def set_binding(self, scope: str, address: str, user: str):
|
||||
await asyncio.to_thread(
|
||||
self._run,
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"INSERT OR REPLACE INTO bindings VALUES (?, ?, ?, ?)",
|
||||
(scope, address, user, int(time.time())),
|
||||
).rowcount
|
||||
),
|
||||
)
|
||||
|
||||
async def clear_binding(self, scope: str):
|
||||
await asyncio.to_thread(
|
||||
self._run,
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"DELETE FROM bindings WHERE scope=?",
|
||||
(scope,),
|
||||
).rowcount
|
||||
),
|
||||
)
|
||||
|
||||
async def track(self, address: str, limit: int = 128):
|
||||
def insert(db):
|
||||
db.execute("INSERT OR REPLACE INTO tracked VALUES (?, ?)", (address, int(time.time())))
|
||||
db.execute(
|
||||
"""DELETE FROM tracked WHERE address IN (
|
||||
SELECT address FROM tracked ORDER BY touched_at DESC, address LIMIT -1 OFFSET ?
|
||||
)""",
|
||||
(limit,),
|
||||
)
|
||||
|
||||
await asyncio.to_thread(self._run, insert)
|
||||
|
||||
async def monitored_addresses(self, now: int | None = None) -> list[str]:
|
||||
now = int(time.time()) if now is None else now
|
||||
return await asyncio.to_thread(
|
||||
self._run,
|
||||
lambda db: [
|
||||
r[0]
|
||||
for r in db.execute(
|
||||
"SELECT address FROM bindings UNION SELECT address FROM tracked WHERE touched_at>=?",
|
||||
(now - 86400,),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
async def record(self, address: str, data: dict | None, timestamp: int | None = None):
|
||||
timestamp = int(time.time()) if timestamp is None else timestamp
|
||||
online = int(bool(data["online"])) if data is not None else None
|
||||
players = int(data.get("players_online", 0)) if online else None
|
||||
source = data.get("source", "api") if data else "error"
|
||||
await asyncio.to_thread(
|
||||
self._run,
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"INSERT OR REPLACE INTO samples VALUES (?, ?, ?, ?, ?)",
|
||||
(address, timestamp, online, players, source),
|
||||
).rowcount
|
||||
),
|
||||
)
|
||||
|
||||
async def history(self, address: str, now: int | None = None) -> list[dict]:
|
||||
now = int(time.time()) if now is None else now
|
||||
return await asyncio.to_thread(
|
||||
self._run,
|
||||
lambda db: [
|
||||
dict(r)
|
||||
for r in db.execute(
|
||||
"SELECT * FROM samples WHERE address=? AND timestamp BETWEEN ? AND ? ORDER BY timestamp",
|
||||
(address, now - 86400, now),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
async def prune(self, retention_hours: int = 48):
|
||||
now = int(time.time())
|
||||
|
||||
def clean(db):
|
||||
db.execute("DELETE FROM samples WHERE timestamp<?", (now - retention_hours * 3600,))
|
||||
db.execute("DELETE FROM tracked WHERE touched_at<?", (now - 86400,))
|
||||
|
||||
await asyncio.to_thread(self._run, clean)
|
||||
Reference in new issue
Block a user