diff --git a/README.md b/README.md index feda84c..b8b3218 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,14 @@ Minecraft Java 服务器状态查询插件,适用于 AstrBot 的 QQ 官方机 - `/motd`、`/mc`、`/mcstatus` 三个命令入口;群默认服务器查询与临时地址查询。 - 本群群主、群管理员或机器人管理员均可设置/清除群默认服务器,支持 `set / 设置`、`unset / clear / 清除 / 取消`。设置成功后立即查询。 -- 查询在线/离线、版本、MOTD、在线/上限人数、人数进度条、公开玩家样本、服务器图标。没有图标时显示像素苦力怕。 +- 查询在线/离线、版本、MOTD、在线/上限人数、人数进度条、完整显示已公开玩家名单、服务器图标。没有图标时显示像素苦力怕。 - Minecraft 状态握手和 ping/pong 测得的真实 RTT;保留域名 SRV 解析与显式端口。 - 保留原像素风图片;图片渲染或上传失败时回复文字,包含人数历史摘要。 - 原查询 API 地址、超时可配置;备用 API 返回的主机名、服务端软件和插件数量仍可显示。 ## 新增 24 小时图表 -每张状态卡下方显示滚动 24 小时人数曲线,以及采样最低/最高/平均人数。`/motd history` 或 `/motd 波动` 可以直接请求带曲线的卡片,也可附带地址。 +每张状态卡下方显示平滑圆润的滚动 24 小时人数曲线,使用渐变填充和圆角描边。曲线经过真实采样点,不额外制造人数峰值,以及采样最低/最高/平均人数。`/motd history` 或 `/motd 波动` 可以直接请求带曲线的卡片,也可附带地址。 默认每 300 秒采样,优先直连 Minecraft Java 状态协议,避免公开 API 缓存影响人数变化。直连失败时使用旧项目的 mcsrvstat.us API;图中会标注 API 样本可能有缓存。服务器不公开玩家名字时仍可记录总人数。直连成功时,软件、插件数量等额外信息仍从原 API 补充(缓存 1 小时),但不会覆盖直连的人数和 Ping;API 补充的玩家名单会注明缓存样本。 @@ -25,6 +25,14 @@ Minecraft Java 服务器状态查询插件,适用于 AstrBot 的 QQ 官方机 数据库在 AstrBot 的 `data/plugin_data/astrbot_plugin_motd/motd.db` 中,默认保留 48 小时,重载和重启后保留。后台只采集数据,用户发命令时才回复卡片。停用/卸载会取消后台任务。 +## MOTD 颜色与完整玩家名单 + +保留 Java 状态响应的原始 MOTD,支持 Minecraft `§0`–`§f` 颜色、`§x§R§R§G§G§B§B` / `§#RRGGBB` 十六进制颜色,以及 JSON 文本组件的颜色、粗体、斜体、下划线和删除线。MOTD 按原始换行和卡片宽度自动排版。 + +玩家名单使用独立的全宽区域,长名字自动换行,人数多时自动分页发送多张图片,不再用省略号裁剪或限制为两行。每页显示页码;只显示服务器实际返回的名字,不根据在线人数补造名单。 + +默认开启 `query_players`:状态响应公开的名单不足时,额外尝试 Minecraft UDP Query(最多等待 1.5 秒)。服务器管理员可以在 `server.properties` 中设置 `enable-query=true`,将 `query.port` 设置为游戏端口,并放行对应 UDP 端口,提供更完整的名单;不开启或查询失败仍正常显示状态协议已公开的名字。完整的实时名单优先于 API 缓存,补充使用 API 名单时明确标注缓存来源。参见 [mcstatus 查询说明](https://mcstatus.readthedocs.io/en/stable/api/basic/)。 + ## 安装 需要 Python 3.10+、AstrBot 4.16+(5.x 尚未验证)。按 [AstrBot 插件开发指南](https://docs.astrbot.app/dev/star/plugin-new.html) 的插件目录结构安装。 @@ -88,7 +96,7 @@ OneBot 支持读取群消息角色及查询成员信息。QQ 官方(WebSocket ## 配置 -在 WebUI 插件配置中调整:`bot_name`、`admin_ids`、`group_admin_ids`、`api_url`、`request_timeout`、`ping_timeout`、`history_enabled`、`sample_interval`、`retention_hours`、`monitor_servers`、`font_path`。后台采样参数修改后重载插件。 +在 WebUI 插件配置中调整:`bot_name`、`admin_ids`、`group_admin_ids`、`api_url`、`request_timeout`、`ping_timeout`、`query_players`、`history_enabled`、`sample_interval`、`retention_hours`、`monitor_servers`、`font_path`。后台采样参数修改后重载插件。 ## 本地验证与打包 diff --git a/_conf_schema.json b/_conf_schema.json index 3152e49..886884a 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -5,6 +5,7 @@ "api_url": {"description": "备用查询 API", "type": "string", "default": "https://api.mcsrvstat.us/2/{address}", "hint": "直连失败时使用,保留 {address} 占位符。响应应为 mcsrvstat.us 格式。"}, "request_timeout": {"description": "备用 API 超时(秒)", "type": "float", "default": 10.0}, "ping_timeout": {"description": "Minecraft 直连超时(秒)", "type": "float", "default": 4.0}, + "query_players": {"description": "尝试通过 Query 获取完整玩家名单", "type": "bool", "default": true, "hint": "状态协议只公开部分玩家时,尝试 UDP Query(最多额外等待 1.5 秒)。服务器需 enable-query=true 且开放对应 UDP 端口;不可用时保留已公开样本。"}, "history_enabled": {"description": "启用后台人数采样", "type": "bool", "default": true, "hint": "关闭时只记录手动查询;已有历史保留。修改后重载插件。"}, "sample_interval": {"description": "后台采样间隔(秒)", "type": "int", "default": 300, "hint": "默认 5 分钟,最低 60 秒。绑定的服务器会持续采样,临时查询的服务器会跟踪 24 小时。"}, "retention_hours": {"description": "历史保留时长(小时)", "type": "int", "default": 48, "hint": "最低 24 小时,图表固定显示最近 24 小时。"}, diff --git a/assets/motd-preview.png b/assets/motd-preview.png index 4d90071..d8e7c0c 100644 Binary files a/assets/motd-preview.png and b/assets/motd-preview.png differ diff --git a/main.py b/main.py index 205d6b3..0e45ba4 100644 --- a/main.py +++ b/main.py @@ -13,7 +13,7 @@ from astrbot.api.star import Context, Star, StarTools from .services.address import normalize_address from .services.mc_api import MinecraftServerAPI from .services.monitor import PlayerMonitor -from .services.motd_card import render_motd_card +from .services.motd_card import render_motd_cards from .services.permissions import get_group_role from .services.storage import MotdStore @@ -178,8 +178,8 @@ class MotdPlugin(Star): data = {"address": address, "online": False, "query_failed": True} path = self.data_dir / f"card-{uuid.uuid4().hex}.png" try: - image_bytes = await asyncio.to_thread( - render_motd_card, + cards = await asyncio.to_thread( + render_motd_cards, data, str(self.config.get("bot_name", "xiaohuicat")), history, @@ -188,9 +188,10 @@ class MotdPlugin(Star): self.monitor.enabled, str(self.config.get("font_path", "")), ) - await asyncio.to_thread(path.write_bytes, image_bytes) - # Await the adapter send so upload errors can use the original text fallback. - await event.send(event.image_result(str(path.resolve()))) + for image_bytes in cards: + await asyncio.to_thread(path.write_bytes, image_bytes) + # Finish each upload before replacing the local file with the next page. + await event.send(event.image_result(str(path.resolve()))) except Exception: logger.exception("MOTD 图片生成或发送失败: %s", address) text = self.api.format_server_info(None if data.get("query_failed") else data) diff --git a/metadata.yaml b/metadata.yaml index a8fb403..9e907df 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,7 +1,7 @@ name: astrbot_plugin_motd display_name: Minecraft MOTD 与玩家波动 desc: Minecraft Java 服务器状态图片、群默认服务器、真实 Ping、玩家名单和最近 24 小时人数波动图。 -version: v1.0.1 +version: v1.0.2 author: itxiaohui support_platforms: - qq_official diff --git a/services/chart.py b/services/chart.py new file mode 100644 index 0000000..0729963 --- /dev/null +++ b/services/chart.py @@ -0,0 +1,41 @@ +"""Shape-preserving interpolation: smoother strokes without new peaks or changed samples.""" + +import math + + +def smooth_points(points: list[tuple[float, float]], resolution: float = 1.0): + # Coincident timestamps may come from manually queried data; keep the last value. + unique = {} + for x, y in points: + unique[x] = y + points = sorted(unique.items()) + if len(points) < 2: + return points + widths = [b[0] - a[0] for a, b in zip(points, points[1:])] + slopes = [(b[1] - a[1]) / width for a, b, width in zip(points, points[1:], widths)] + tangents = [slopes[0]] + for index in range(1, len(points) - 1): + before, after = slopes[index - 1], slopes[index] + if before * after <= 0: + tangents.append(0.0) + else: + w1 = 2 * widths[index] + widths[index - 1] + w2 = widths[index] + 2 * widths[index - 1] + tangents.append((w1 + w2) / (w1 / before + w2 / after)) + tangents.append(slopes[-1]) + result = [points[0]] + for index, (start, end) in enumerate(zip(points, points[1:])): + width = widths[index] + steps = max(2, math.ceil(width / max(resolution, 0.1))) + for step in range(1, steps + 1): + t = step / steps + y = ( + (2 * t**3 - 3 * t**2 + 1) * start[1] + + (t**3 - 2 * t**2 + t) * width * tangents[index] + + (-2 * t**3 + 3 * t**2) * end[1] + + (t**3 - t**2) * width * tangents[index + 1] + ) + # Numerical guard only; monotone tangents already bound the interval. + y = max(min(start[1], end[1]), min(max(start[1], end[1]), y)) + result.append((start[0] + t * width, y)) + return result diff --git a/services/mc_api.py b/services/mc_api.py index ae15cb0..28ea960 100644 --- a/services/mc_api.py +++ b/services/mc_api.py @@ -22,6 +22,7 @@ class MinecraftServerAPI: 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.query_players = bool(mc_cfg.get("query_players", True)) self._metadata = OrderedDict() async def query(self, address: str) -> dict | None: @@ -40,6 +41,7 @@ class MinecraftServerAPI: "port": server.address.port, "version": status.version.name, "motd": status.motd.to_plain(), + "motd_raw": raw.get("description", status.motd.to_plain()), "players_online": status.players.online, "players_max": status.players.max, "player_list": [ @@ -50,16 +52,25 @@ class MinecraftServerAPI: "plugins": raw.get("plugins", {}), "icon": raw.get("favicon", ""), "source": "direct", - } + }, server try: - data = await asyncio.wait_for(direct(), timeout=self.ping_timeout + 2) + data, server = 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 + if self.query_players and len(data["player_list"]) < data["players_online"]: + try: + query = await asyncio.wait_for(server.async_query(tries=1), timeout=1.5) + names = [str(name).strip() for name in query.players.names if str(name).strip()] + if len(names) > len(data["player_list"]): + data["player_list"] = names + data["player_list_source"] = "query" + except Exception as exc: + logger.debug("MC Query 名单不可用,保留状态样本 %s: %s", address, exc) # 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) @@ -72,11 +83,17 @@ class MinecraftServerAPI: else: extra = cached[1] if extra and extra.get("online"): - for key in ("hostname", "software", "plugins", "icon", "player_list"): + for key in ("hostname", "software", "plugins", "icon"): if not data.get(key) and extra.get(key): data[key] = extra[key] - if key == "player_list": - data["player_list_cached"] = True + extra_names = extra.get("player_list") or [] + if ( + data.get("player_list_source") != "query" + and len(data["player_list"]) < data["players_online"] + and len(extra_names) > len(data["player_list"]) + ): + data["player_list"] = extra_names + data["player_list_cached"] = True return data @staticmethod @@ -175,7 +192,12 @@ class MinecraftServerAPI: try: async with httpx.AsyncClient(timeout=self.timeout) as client: - response = await client.get(url) + response = await client.get( + url, + headers={ + "User-Agent": "xiaohuicat-AstrBot-MOTD/1.0.2 (+https://github.com/itxiaohui66/astrbot_plugin_motd)" + }, + ) if response.status_code != 200: logger.warning(f"MC服务器查询失败: {address} HTTP {response.status_code}") @@ -190,13 +212,21 @@ class MinecraftServerAPI: "latency_ms": None, } - # 提取 MOTD 纯文本 + # Keep the raw color codes alongside the original plain fallback. motd_text = "" + motd_raw = "" motd = data.get("motd", {}) if isinstance(motd, dict): motd_text = " | ".join(motd.get("clean", [])) + raw_lines = motd.get("raw") + motd_raw = ( + "\n".join(raw_lines) + if isinstance(raw_lines, list) + else (raw_lines or motd_text) + ) elif isinstance(motd, str): motd_text = motd + motd_raw = motd players = data.get("players", {}) player_list = [] @@ -225,6 +255,7 @@ class MinecraftServerAPI: "port": resolved_port, "version": data.get("version", "未知"), "motd": motd_text, + "motd_raw": motd_raw, "players_online": players.get("online", 0), "players_max": players.get("max", 0), "player_list": player_list, @@ -298,8 +329,7 @@ class MinecraftServerAPI: player_list = data.get("player_list") or [] if player_list: lines.append( - f"👤 已公开玩家({len(player_list)}/{players_online}): " - + "、".join(player_list)[:400] + f"👤 已公开玩家({len(player_list)}/{players_online}): " + "、".join(player_list) ) elif players_online: lines.append("👤 服务器未公开玩家名单") diff --git a/services/minecraft_text.py b/services/minecraft_text.py new file mode 100644 index 0000000..4185856 --- /dev/null +++ b/services/minecraft_text.py @@ -0,0 +1,128 @@ +"""Minecraft legacy/hex and JSON chat formatting, kept separate from plain fallback text.""" + +import re +from dataclasses import dataclass, replace + +COLORS = { + "0": "#000000", + "1": "#0000AA", + "2": "#00AA00", + "3": "#00AAAA", + "4": "#AA0000", + "5": "#AA00AA", + "6": "#FFAA00", + "7": "#AAAAAA", + "8": "#555555", + "9": "#5555FF", + "a": "#55FF55", + "b": "#55FFFF", + "c": "#FF5555", + "d": "#FF55FF", + "e": "#FFFF55", + "f": "#FFFFFF", +} +NAMED_COLORS = dict( + zip( + ( + "black", + "dark_blue", + "dark_green", + "dark_aqua", + "dark_red", + "dark_purple", + "gold", + "gray", + "dark_gray", + "blue", + "green", + "aqua", + "red", + "light_purple", + "yellow", + "white", + ), + COLORS.values(), + ) +) + + +@dataclass(frozen=True) +class TextStyle: + color: str = "#E2ECE5" + bold: bool = False + italic: bool = False + underlined: bool = False + strikethrough: bool = False + + +@dataclass(frozen=True) +class TextRun: + text: str + style: TextStyle = TextStyle() + + +def _legacy(text: str, initial: TextStyle) -> list[TextRun]: + style, buffer, runs, index = initial, [], [], 0 + + def flush(): + if buffer: + runs.append(TextRun("".join(buffer), style)) + buffer.clear() + + while index < len(text): + if text[index] == "§" and index + 1 < len(text): + code = text[index + 1].lower() + hex_match = re.match(r"§[xX]((?:§[0-9a-fA-F]){6})|§#([0-9a-fA-F]{6})", text[index:]) + if hex_match: + flush() + color = hex_match[1].replace("§", "") if hex_match[1] else hex_match[2] + style = TextStyle(color="#" + color.upper()) + index += len(hex_match[0]) + continue + if code in COLORS or code in "rlomnk": + flush() + if code in COLORS: + style = TextStyle(color=COLORS[code]) + elif code == "r": + style = TextStyle() + elif code != "k": + style = replace( + style, + **{ + "l": {"bold": True}, + "o": {"italic": True}, + "n": {"underlined": True}, + "m": {"strikethrough": True}, + }[code], + ) + index += 2 + continue + buffer.append(text[index]) + index += 1 + flush() + return runs + + +def motd_runs(value, initial: TextStyle = TextStyle()) -> list[TextRun]: + """Parse strings, lists, and inherited JSON chat components without discarding colors.""" + if isinstance(value, str): + return _legacy(value.replace("\r\n", "\n").replace("\r", "\n"), initial) + if isinstance(value, list): + return [run for component in value for run in motd_runs(component, initial)] + if not isinstance(value, dict): + return [] if value is None else [TextRun(str(value), initial)] + style = initial + color = value.get("color") + if color == "reset": + style = TextStyle() + elif isinstance(color, str): + color = NAMED_COLORS.get(color, color) + if re.fullmatch(r"#[0-9a-fA-F]{6}", color): + style = replace(style, color=color.upper()) + for key in ("bold", "italic", "underlined", "strikethrough"): + if isinstance(value.get(key), bool): + style = replace(style, **{key: value[key]}) + runs = motd_runs(value.get("text", value.get("fallback", value.get("translate", ""))), style) + for component in value.get("extra", []) or []: + runs.extend(motd_runs(component, style)) + return runs diff --git a/services/motd_card.py b/services/motd_card.py index 57dab69..834809e 100644 --- a/services/motd_card.py +++ b/services/motd_card.py @@ -4,19 +4,19 @@ 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 +from PIL import Image, ImageChops, ImageColor, ImageDraw, ImageFont + +from .chart import smooth_points +from .minecraft_text import TextRun, motd_runs CARD_WIDTH = 1200 -CARD_HEIGHT = 1080 CHINA_TIME = timezone(timedelta(hours=8)) @@ -63,16 +63,17 @@ 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) + width, height = image.size + for y in range(height): + ratio = y / max(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)) + draw.line((0, y, 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 + y = (digest[(index + 9) % len(digest)] * 31 + index * 71) % height size = 24 + digest[(index + 17) % len(digest)] % 64 draw.rectangle((x, y, x + size, y + size), fill=palette[index % len(palette)]) @@ -138,31 +139,126 @@ def _ellipsize(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> st 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: +def _layout_motd(draw, runs, max_width, font_path): + lines, current, width = [], [], 0.0 + for run in runs: + font = _load_font(25, run.style.bold, font_path) + for char in run.text.replace("\t", " "): + if char == "\n": + lines.append(current) + current, width = [], 0.0 + continue + advance = draw.textlength(char, font=font) + if current and width + advance > max_width - 8: + lines.append(current) + current, width = [], 0.0 + if current and current[-1].style == run.style: + current[-1] = TextRun(current[-1].text + char, run.style) + else: + current.append(TextRun(char, run.style)) + width += advance + if current or not lines: 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] + return lines + + +def _draw_styled_line(image, position, runs, font_path): + x, y = position + draw = ImageDraw.Draw(image, "RGBA") + for run in runs: + font = _load_font(25, run.style.bold, font_path) + width = draw.textlength(run.text, font=font) + color = ImageColor.getrgb(run.style.color) + stroke = 1 if sum(color) < 180 else 0 + options = { + "font": font, + "fill": color, + "anchor": "lt", + "stroke_width": stroke, + "stroke_fill": (115, 145, 124), + } + if run.style.italic: + glyph = Image.new("RGBA", (math.ceil(width) + 16, 36)) + ImageDraw.Draw(glyph).text((4, 2), run.text, **options) + glyph = glyph.transform( + glyph.size, Image.Transform.AFFINE, (1, 0.2, -7, 0, 1, 0), Image.Resampling.BICUBIC + ) + image.alpha_composite(glyph, (int(x) - 4, int(y) - 2)) + else: + draw.text((x, y), run.text, **options) + if run.style.underlined: + draw.line((x, y + 28, x + width, y + 28), fill=color, width=1) + if run.style.strikethrough: + draw.line((x, y + 13, x + width, y + 13), fill=color, width=1) + x += width + + +def player_rows(names: list[str], font_path: str = "") -> list[dict]: + """Wrap entire names into badges, retaining every character and every supplied player.""" + measure = ImageDraw.Draw(Image.new("RGB", (1, 1))) + font = _load_font(21, font_path=font_path) + rows, chips, used, row_height = [], [], 0, 0 + for name in names: + lines, line = [], "" + for char in name: + if line and measure.textlength(line + char, font=font) > 276: + lines.append(line) + line = "" + line += char + lines.append(line) + width = math.ceil(max(measure.textlength(line, font=font) for line in lines)) + 32 + height = 20 + len(lines) * 28 + if chips and used + width > 944: + rows.append({"chips": chips, "height": row_height}) + chips, used, row_height = [], 0, 0 + chips.append({"name": name, "lines": lines, "width": width, "height": height}) + used += width + 10 + row_height = max(row_height, height) + if chips: + rows.append({"chips": chips, "height": row_height}) + return rows + + +def player_pages(names: list[str], font_path: str = "") -> list[list[str]]: + pages, page, height = [], [], 0 + for row in player_rows(names, font_path): + if page and height + row["height"] + 10 > 500: + pages.append(page) + page, height = [], 0 + page.extend(chip["name"] for chip in row["chips"]) + height += row["height"] + 10 + if page or not pages: + pages.append(page) + return pages + + +def render_motd_cards( + data: dict, + bot_name="xiaohuicat", + history=None, + now=None, + sample_interval=300, + history_enabled=True, + font_path="", +) -> list[bytes]: + """Paginate large public rosters instead of making names unreadable or silently dropping them.""" + names = [str(name) for name in (data.get("player_list") or []) if str(name).strip()] + pages = player_pages(names, font_path) + result = [] + for index, page in enumerate(pages, 1): + status = dict( + data, + player_list=page, + _player_total=len(names), + _player_page=index, + _player_pages=len(pages), + ) + result.append( + render_motd_card( + status, bot_name, history, now, sample_interval, history_enabled, font_path + ) + ) + return result def render_motd_card( @@ -180,13 +276,25 @@ def render_motd_card( 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)) + measure = ImageDraw.Draw(Image.new("RGB", (1, 1))) + fallback = "暂无服务器标语" if online else "无法连接到该服务器" + runs = motd_runs(data.get("motd_raw") or data.get("motd") or fallback) + motd_lines = _layout_motd(measure, runs, 940, font_path) + motd_bottom = 452 + max(116, 56 + 34 * len(motd_lines)) + names = [str(name) for name in (data.get("player_list") or []) if str(name).strip()] + rows = player_rows(names, font_path) + players_top = motd_bottom + 20 + players_height = max(108, 64 + sum(row["height"] + 10 for row in rows)) + history_top = players_top + players_height + 20 + card_height = history_top + 490 + + 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, (44, 42, 1156, card_height - 40), (8, 16, 13, 222), (77, 123, 90, 110), 30) + draw.rounded_rectangle((44, 42, 58, card_height - 40), 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 "")) @@ -200,7 +308,6 @@ def render_motd_card( 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)) @@ -263,22 +370,28 @@ def render_motd_card( 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) + # Full-width, dynamically sized colored MOTD; retain its original line breaks. + _rounded_panel(draw, (84, 452, 1072, motd_bottom), (17, 31, 24, 230), (65, 104, 76, 90), 20) 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)) + for index, line in enumerate(motd_lines): + _draw_styled_line(image, (106, 501 + index * 34), line, font_path) - # 在线玩家名单(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})" + # Full roster gets its own section and wraps at badge boundaries. + _rounded_panel( + draw, + (84, players_top, 1072, players_top + players_height), + (17, 31, 24, 230), + (65, 104, 76, 90), + 20, + ) + if names: + public_count = data.get("_player_total", len(names)) + player_label = f"在线玩家 · 已公开 {public_count} / {players_online}" if data.get("player_list_cached"): - player_label = "公开玩家(API 缓存样本)" - player_text = "、".join(player_list) + player_label += " · API 缓存样本" + elif data.get("player_list_source") == "query": + player_label += " · Query 名单" + player_text = "" elif online and players_online > 0: player_label = "在线玩家" player_text = "服务器未公开玩家名单" @@ -288,24 +401,51 @@ def render_motd_card( 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)) + draw.text((106, players_top + 16), player_label, font=label_font, fill=(145, 171, 152, 255)) + if data.get("_player_pages", 1) > 1: + page_label = f"{data['_player_page']} / {data['_player_pages']} 页" + draw.text( + (1048 - draw.textlength(page_label, font=label_font), players_top + 16), + page_label, + font=label_font, + fill=(116, 145, 125), + ) + name_font = _load_font(21, font_path=font_path) + row_y = players_top + 55 + for row in rows: + x = 106 + for chip in row["chips"]: + _rounded_panel( + draw, + (x, row_y, x + chip["width"], row_y + chip["height"]), + (29, 49, 37, 255), + (53, 82, 62, 180), + 12, + ) + for index, line in enumerate(chip["lines"]): + draw.text( + (x + 16, row_y + 10 + index * 28), + line, + font=name_font, + fill=(220, 238, 225), + anchor="lt", + ) + x += chip["width"] + 10 + row_y += row["height"] + 10 + if player_text: + draw.text((106, row_y + 2), player_text, font=label_font, fill=(166, 189, 173)) now = int(time.time()) if now is None else now - _draw_history(draw, history or [], now, sample_interval, history_enabled, font_path) + _draw_history( + image, history or [], now, sample_interval, history_enabled, font_path, history_top + ) 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), + (84, card_height - 83), _ellipsize(draw, footer, footer_font, 1010), font=footer_font, fill=(116, 145, 125, 255), @@ -336,12 +476,18 @@ def history_segments(history: list[dict], now: int, interval: int) -> list[list[ 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) +def _draw_history(image, history, now, interval, enabled, font_path, panel_top): + draw = ImageDraw.Draw(image, "RGBA") + _rounded_panel( + draw, (84, panel_top, 1072, panel_top + 384), (17, 31, 24, 230), (65, 104, 76, 90), 22 + ) 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)) + draw.text( + (106, panel_top + 16), "最近 24 小时 · 在线玩家波动", font=title, fill=(226, 236, 229) + ) + draw.text((928, panel_top + 22), "24H / UTC+8", font=small, fill=(116, 145, 125)) history = sorted( (p for p in history if now - 86400 <= p["timestamp"] <= now), key=lambda p: p["timestamp"] ) @@ -349,74 +495,129 @@ def _draw_history(draw, history, now, interval, enabled, font_path): 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}" + metrics = [ + f"最低 {min(counts)}", + f"最高 {max(counts)}", + f"均值 {sum(counts) / len(counts):.1f}", + ] + x = 106 + for text in metrics: + width = int(draw.textlength(text, font=font)) + 30 + _rounded_panel( + draw, (x, panel_top + 56, x + width, panel_top + 90), (27, 48, 35, 255), radius=13 + ) + draw.text((x + 15, panel_top + 62), text, font=font, fill=(157, 221, 176), anchor="lt") + x += width + 12 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 + draw.text((106, panel_top + 62), "暂无成功的人数采样", font=font, fill=(145, 171, 152)) + + # Supersampling keeps curved strokes and their round ends smooth on QQ images. + scale, width, height = 3, 988, 212 + layer = Image.new("RGBA", (width * scale, height * scale)) + chart = ImageDraw.Draw(layer, "RGBA") + left, right, top, bottom = 78, 950, 10, 180 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) + chart.line( + (left * scale, y * scale, right * scale, y * scale), fill=(48, 70, 55, 160), width=2 + ) label = str(index * step) draw.text( - (left - 14 - draw.textlength(label, font=small), y - 12), + (84 + left - 14 - draw.textlength(label, font=small), panel_top + 101 + y - 11), 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) + chart.line( + (x * scale, top * scale, x * scale, bottom * scale), fill=(40, 61, 47, 100), width=2 + ) stamp = datetime.fromtimestamp(now - 86400 + index * 21600, CHINA_TIME).strftime("%H:%M") draw.text( - (x - draw.textlength(stamp, font=small) / 2, 883), + (84 + x - draw.textlength(stamp, font=small) / 2, panel_top + 290), stamp, font=small, fill=(116, 145, 125), ) - def coordinates(p): + def coordinates(point): return ( - left + (p["timestamp"] - (now - 86400)) / 86400 * (right - left), - bottom - p["players"] / ceiling * (bottom - top), + left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left), + bottom - point["players"] / ceiling * (bottom - top), ) + gradient = Image.new("RGBA", layer.size) + gradient_draw = ImageDraw.Draw(gradient) + for y in range(top * scale, bottom * scale + 1): + alpha = int(48 * (1 - (y - top * scale) / ((bottom - top) * scale))) + 4 + gradient_draw.line((left * scale, y, right * scale, y), fill=(71, 218, 135, alpha)) + last_point = None 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)) + samples = [coordinates(point) for point in segment] + curve = smooth_points(samples, resolution=0.5) + scaled = [(x * scale, y * scale) for x, y in curve] + if len(curve) > 1: + mask = Image.new("L", layer.size) + ImageDraw.Draw(mask).polygon( + scaled + [(scaled[-1][0], bottom * scale), (scaled[0][0], bottom * scale)], fill=255 + ) + fill = gradient.copy() + fill.putalpha(ImageChops.multiply(gradient.getchannel("A"), mask)) + layer.alpha_composite(fill) + chart.line(scaled, fill=(47, 139, 90, 65), width=9 * scale, joint="curve") + chart.line(scaled, fill=(107, 231, 154, 255), width=3 * scale, joint="curve") + for x, y in samples[:1] + samples[-1:] if len(samples) > 1 else samples: + radius = 1.5 * scale + chart.ellipse( + (x * scale - radius, y * scale - radius, x * scale + radius, y * scale + radius), + fill=(107, 231, 154, 255), + ) + if samples: + last_point = samples[-1] + if last_point: + x, y = (coordinate * scale for coordinate in last_point) + chart.ellipse( + (x - 6 * scale, y - 6 * scale, x + 6 * scale, y + 6 * scale), fill=(67, 167, 106, 50) + ) + chart.ellipse( + (x - 3.5 * scale, y - 3.5 * scale, x + 3.5 * scale, y + 3.5 * scale), + fill=(191, 255, 212, 255), + ) 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) + color = (241, 96, 89, 255) if point.get("online") == 0 else (212, 175, 99, 255) + chart.rounded_rectangle( + ( + x * scale - 1 * scale, + (bottom - 5) * scale, + x * scale + 1 * scale, + bottom * scale, + ), + radius=scale, + fill=color, + ) + image.alpha_composite( + layer.resize((width, height), Image.Resampling.LANCZOS), (84, panel_top + 101) + ) if not counts: text = "开始采集后将在这里显示曲线" if not history else "服务器离线或查询失败,暂无人数曲线" - draw.text((left + 140, top + 70), text, font=font, fill=(145, 171, 152)) + draw.text((302, panel_top + 184), 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)) + draw.text( + (106, panel_top + 330), _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), - ) + text, color = "部分采样来自公开 API,人数可能有缓存延迟 · 时间 UTC+8", (212, 175, 99) else: - draw.text( - (106, 944), - "从首次查询或绑定开始积累 · 重启后保留历史 · 时间 UTC+8", - font=small, - fill=(116, 145, 125), - ) + text, color = "曲线经过实测采样点 · 缺失时段保持断线 · 时间 UTC+8", (116, 145, 125) + draw.text((106, panel_top + 356), text, font=small, fill=color) diff --git a/tests/test_api.py b/tests/test_api.py index d497388..b106f52 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -3,6 +3,7 @@ import json from types import SimpleNamespace import httpx +import pytest from services.mc_api import MinecraftServerAPI @@ -35,7 +36,7 @@ async def test_real_java_status_protocol_on_local_server(): "max": 50, "sample": [{"name": "Alex", "id": "00000000-0000-0000-0000-000000000000"}], }, - "description": {"text": "Hello server"}, + "description": {"text": "Hello server", "color": "gold"}, } ).encode() packet = b"\x00" + api._encode_varint(len(payload)) + payload @@ -58,6 +59,7 @@ async def test_real_java_status_protocol_on_local_server(): assert result["players_online"] == 2 and result["players_max"] == 50 assert result["player_list"] == ["Alex"] and result["version"] == "1.21.1" assert result["motd"] == "Hello server" and result["latency_ms"] >= 0 + assert result["motd_raw"] == {"text": "Hello server", "color": "gold"} # Exercise the migrated fallback ping/pong path too. latency = await api._measure_minecraft_latency("127.0.0.1", port, "127.0.0.1", 767) assert latency is not None and latency >= 0 @@ -82,7 +84,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch): "online": True, "version": "Paper 1.21", "port": 25565, - "motd": {"clean": ["First", "Second"]}, + "motd": {"clean": ["First", "Second"], "raw": ["§cFirst", "§bSecond"]}, "players": { "online": 5, "max": 20, @@ -100,6 +102,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch): api = MinecraftServerAPI({}) data = await api.query("mc.example.com") assert data["source"] == "api" and data["motd"] == "First | Second" + assert data["motd_raw"] == "§cFirst\n§bSecond" assert data["player_list"] == ["Steve", "Alex", "Third"] assert seen == ["https://api.mcsrvstat.us/2/mc.example.com"] # no forced :25565 text = api.format_server_info(data) @@ -155,3 +158,54 @@ async def test_srv_lookup_input_is_not_changed(monkeypatch): api._query_api = no_extra data = await api.query("mc.example.com") assert seen == ["mc.example.com"] and data["port"] == 25570 + + +@pytest.mark.parametrize("mode", ["query", "error", "disabled", "complete"]) +async def test_query_full_names_and_cache_never_replace_realtime_list(monkeypatch, mode): + calls = [] + direct_names = ["Alex", "Steve", "Third"] if mode == "complete" else ["Alex"] + + async def status(**kwargs): + return SimpleNamespace( + raw={"players": {"sample": [{"name": name} for name in direct_names]}}, + version=SimpleNamespace(name="1.21"), + motd=SimpleNamespace(to_plain=lambda: "Hello"), + players=SimpleNamespace(online=3, max=20), + latency=5, + ) + + async def query(**kwargs): + calls.append("query") + if mode == "error": + raise OSError("UDP disabled") + return SimpleNamespace(players=SimpleNamespace(names=["Alex", "Steve", "Third"])) + + async def lookup(*args, **kwargs): + return SimpleNamespace( + address=SimpleNamespace(host="test.example", port=25565), + async_status=status, + async_query=query, + ) + + monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", lookup) + api = MinecraftServerAPI({"query_players": mode != "disabled"}) + + async def cached(*args, **kwargs): + return { + "online": True, + "player_list": ["Old1", "Old2", "Old3", "Old4"], + "players_online": 99, + "latency_ms": 999, + } + + api._query_api = cached + data = await api.query("test.example") + assert data["players_online"] == 3 and data["latency_ms"] == 5 + assert data["source"] == "direct" + assert calls == (["query"] if mode in ("query", "error") else []) + if mode in ("query", "complete"): + assert data["player_list"] == ["Alex", "Steve", "Third"] + assert not data.get("player_list_cached") + else: + assert data["player_list"] == ["Old1", "Old2", "Old3", "Old4"] + assert data["player_list_cached"] diff --git a/tests/test_motd_visuals.py b/tests/test_motd_visuals.py new file mode 100644 index 0000000..a8adca3 --- /dev/null +++ b/tests/test_motd_visuals.py @@ -0,0 +1,126 @@ +import io + +import pytest +from PIL import Image, ImageDraw + +from services.chart import smooth_points +from services.minecraft_text import TextStyle, motd_runs +from services.motd_card import ( + _layout_motd, + player_pages, + player_rows, + render_motd_card, + render_motd_cards, +) + + +def test_legacy_colors_hex_and_reset(): + runs = motd_runs("§cRed §lBold §rPlain §x§1§2§3§4§5§6Hex §#ABCDEFMore") + assert "".join(run.text for run in runs) == "Red Bold Plain Hex More" + assert runs[0].style.color == "#FF5555" + assert runs[1].style.bold and runs[1].style.color == "#FF5555" + assert runs[2].style == TextStyle() + assert runs[3].style.color == "#123456" + assert runs[4].style.color == "#ABCDEF" + + +def test_json_component_inheritance_and_explicit_reset(): + runs = motd_runs( + { + "text": "A", + "color": "gold", + "bold": True, + "extra": [ + {"text": "B"}, + {"text": "C", "bold": False, "color": "#123456"}, + {"text": "D", "color": "reset"}, + ], + } + ) + assert "".join(run.text for run in runs) == "ABCD" + assert runs[1].style.bold and runs[1].style.color == "#FFAA00" + assert not runs[2].style.bold and runs[2].style.color == "#123456" + assert runs[3].style == TextStyle() + + +def test_wrapping_preserves_long_motd_and_line_styles(): + draw = ImageDraw.Draw(Image.new("RGB", (1, 1))) + text = "完整中文标语" * 100 + lines = _layout_motd(draw, motd_runs("§c" + text), 940, "") + assert len(lines) > 2 + assert "".join(run.text for line in lines for run in line) == text + assert all(run.style.color == "#FF5555" for line in lines for run in line) + + +def test_card_contains_real_colored_glyph_pixels(): + image = Image.open( + io.BytesIO( + render_motd_card( + { + "address": "example.test", + "online": True, + "motd_raw": "§c████ §b████ §x§1§2§3§4§5§6████", + }, + now=100000, + ) + ) + ) + colors = image.crop((100, 495, 800, 540)).getcolors(800 * 100) + colors = {color: count for count, color in colors} + for color in [(255, 85, 85), (85, 255, 255), (18, 52, 86)]: + assert colors.get(color, 0) > 20 + + +def test_player_wrap_preserves_long_names_and_pages_all_players(): + names = [f"Player_{i:03d}_LongName" for i in range(100)] + ["超长中文名字" * 20] + rows = player_rows(names) + chips = [chip for row in rows for chip in row["chips"]] + assert ["".join(chip["lines"]) for chip in chips] == names + assert all(sum(chip["width"] + 10 for chip in row["chips"]) - 10 <= 944 for row in rows) + pages = player_pages(names) + assert len(pages) > 1 and [name for page in pages for name in page] == names + + +def test_multiple_cards_actually_draw_every_player(monkeypatch): + names = [f"Player_{i:03d}_LongName" for i in range(100)] + drawn = [] + original = ImageDraw.ImageDraw.text + + def track(self, position, text, *args, **kwargs): + drawn.append(text) + return original(self, position, text, *args, **kwargs) + + monkeypatch.setattr(ImageDraw.ImageDraw, "text", track) + cards = render_motd_cards( + {"online": True, "address": "example.test", "player_list": names, "players_online": 100}, + now=100000, + ) + assert len(cards) > 1 + assert all(drawn.count(name) == 1 for name in names) + assert all(Image.open(io.BytesIO(card)).height < 1800 for card in cards) + + +@pytest.mark.parametrize( + "points", + [ + [(0, 0), (10, 100), (20, 0)], + [(0, 8), (1, 8), (20, 2), (30, 2)], + [(0, 0), (0.3, 2), (50, 4)], + [(0, 10), (8, 0), (15, 20), (30, 1)], + ], +) +def test_curve_passes_samples_and_does_not_invent_extrema(points): + curve = smooth_points(points, 0.25) + assert curve[0] == points[0] and curve[-1] == pytest.approx(points[-1]) + for x, y in points: + assert next(point[1] for point in curve if abs(point[0] - x) < 1e-8) == pytest.approx(y) + for start, end in zip(points, points[1:]): + for x, y in curve: + if start[0] <= x <= end[0]: + assert min(start[1], end[1]) - 1e-8 <= y <= max(start[1], end[1]) + 1e-8 + + +def test_single_sample_duplicate_timestamp_and_zero_series(): + assert smooth_points([(5, 0)]) == [(5, 0)] + assert smooth_points([(1, 0), (1, 2)]) == [(1, 2)] + assert all(y == 0 for x, y in smooth_points([(0, 0), (10, 0), (20, 0)])) diff --git a/tests/test_plugin.py b/tests/test_plugin.py index bd13bce..bd61bf0 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -222,3 +222,31 @@ async def test_group_grant_is_limited_to_one_group_and_adapter(plugin_class): assert "qq-main|group-openid|user-openid" in event.messages[-1][1] assert not plugin._is_admin(event) await plugin.terminate() + + +async def test_paged_images_uploaded_before_replacing_file_and_cleaned( + plugin_class, monkeypatch, tmp_path +): + plugin = plugin_class(object(), {"history_enabled": False}) + pages = [b"page-one", b"page-two", b"page-three"] + monkeypatch.setattr( + sys.modules[plugin_class.__module__], "render_motd_cards", lambda *args: pages + ) + + async def query(address): + return {"online": True, "address": address, "players_online": 100, "players_max": 200} + + plugin.api.query = query + uploaded = [] + + class UploadEvent(Event): + async def send(self, result): + if result[0] == "image": + uploaded.append(Path(result[1]).read_bytes()) + await super().send(result) + + event = UploadEvent() + await plugin.motd(event, "mc.example.com") + assert uploaded == pages + assert not list(tmp_path.glob("card-*.png")) + await plugin.terminate() diff --git a/tests/test_render_address.py b/tests/test_render_address.py index 872f1ee..38f117c 100644 --- a/tests/test_render_address.py +++ b/tests/test_render_address.py @@ -76,4 +76,4 @@ def test_card_handles_empty_history_offline_failure_and_zero(online, failed, his now=100000, ) image = Image.open(io.BytesIO(raw)) - assert image.format == "PNG" and image.size == (1200, 1080) + assert image.format == "PNG" and image.width == 1200 and image.height > 1500 diff --git a/tools/preview.py b/tools/preview.py index dbc04f9..c21a101 100644 --- a/tools/preview.py +++ b/tools/preview.py @@ -7,7 +7,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -from services.motd_card import render_motd_card +from services.motd_card import render_motd_cards def main(): @@ -26,9 +26,32 @@ def main(): "address": "mc.example.com:25565", "version": "1.21.1", "motd": "欢迎来到栗子服务器!生存 · 建筑 · 冒险,和朋友一起探索方块世界", + "motd_raw": { + "text": "xiaohuicat", + "color": "#80EAC0", + "bold": True, + "extra": [ + {"text": " 生存 · 建筑 · 冒险", "color": "gold", "bold": False}, + {"text": "\n欢迎和朋友一起探索方块世界!", "color": "aqua", "bold": False}, + {"text": " §d温馨社区 §a自由冒险"}, + ], + }, "players_online": history[-1]["players"], "players_max": 100, - "player_list": ["itxiaohui", "Steve", "Alex", "栗子玩家"], + "player_list": [ + "itxiaohui", + "Steve", + "Alex", + "栗子玩家", + "Builder_Orange", + "DreamExplorer", + "xiaohuicat", + "AdventureCat", + "RedStone_Master", + "Minecraft_Lover", + "Moonlight", + "世界探索者", + ], "latency_ms": 32.6, "software": "Paper", "plugins": {"names": ["Example"]}, @@ -41,11 +64,23 @@ def main(): "first": (data, history[-1:]), "offline": ({"online": False, "address": data["address"], "source": "api"}, history), "failed": ({"online": False, "address": data["address"], "query_failed": True}, []), + "many-players": ( + dict( + data, + player_list=[f"Player_{i:03d}_LongName" for i in range(1, 101)], + players_online=100, + ), + history, + ), } for name, (status, points) in examples.items(): - path = folder / f"motd-{name}.png" - path.write_bytes(render_motd_card(status, "xiaohuicat · 演示数据", points, now)) - print(path) + for index, card in enumerate( + render_motd_cards(status, "xiaohuicat · 演示数据", points, now), 1 + ): + suffix = "" if index == 1 else f"-{index}" + path = folder / f"motd-{name}{suffix}.png" + path.write_bytes(card) + print(path) if __name__ == "__main__":