Improve smooth player chart, colored MOTD and complete paged player names

This commit is contained in:
itxiaohui committed 2026-10-06 14:46:30 +08:00
1 parent 1bbecbfaa1
commit bd1cf2ff4c
14 files changed
+775 -122

No files matched your search

+41
View File
@@ -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
+39 -9
View File
@@ -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("👤 服务器未公开玩家名单")
+128
View File
@@ -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
+296 -95
View File
@@ -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)