2 Commits
17 changed files with 1115 additions and 124 deletions

No files matched your search

+23 -6
View File
@@ -7,15 +7,15 @@ Minecraft Java 服务器状态查询插件,适用于 AstrBot 的 QQ 官方机
## 保留的功能 ## 保留的功能
- `/motd`、`/mc`、`/mcstatus` 三个命令入口;群默认服务器查询与临时地址查询。 - `/motd`、`/mc`、`/mcstatus` 三个命令入口;群默认服务器查询与临时地址查询。
- 机器人管理员设置/清除群默认服务器,支持 `set / 设置`、`unset / clear / 清除 / 取消`。设置成功后立即查询。 - 本群群主、群管理员或机器人管理员均可设置/清除群默认服务器,支持 `set / 设置`、`unset / clear / 清除 / 取消`。设置成功后立即查询。
- 查询在线/离线、版本、MOTD、在线/上限人数、人数进度条、公开玩家样本、服务器图标。没有图标时显示像素苦力怕。 - 查询在线/离线、版本、MOTD、在线/上限人数、人数进度条、完整显示已公开玩家名单、服务器图标。没有图标时显示像素苦力怕。
- Minecraft 状态握手和 ping/pong 测得的真实 RTT;保留域名 SRV 解析与显式端口。 - Minecraft 状态握手和 ping/pong 测得的真实 RTT;保留域名 SRV 解析与显式端口。
- 保留原像素风图片;图片渲染或上传失败时回复文字,包含人数历史摘要。 - 保留原像素风图片;图片渲染或上传失败时回复文字,包含人数历史摘要。
- 原查询 API 地址、超时可配置;备用 API 返回的主机名、服务端软件和插件数量仍可显示。 - 原查询 API 地址、超时可配置;备用 API 返回的主机名、服务端软件和插件数量仍可显示。
## 新增 24 小时图表 ## 新增 24 小时图表
每张状态卡下方显示滚动 24 小时人数曲线,以及采样最低/最高/平均人数。`/motd history` 或 `/motd 波动` 可以直接请求带曲线的卡片,也可附带地址。 每张状态卡下方显示平滑圆润的滚动 24 小时人数曲线,使用渐变填充和圆角描边。曲线经过真实采样点,不额外制造人数峰值,以及采样最低/最高/平均人数。`/motd history` 或 `/motd 波动` 可以直接请求带曲线的卡片,也可附带地址。
默认每 300 秒采样,优先直连 Minecraft Java 状态协议,避免公开 API 缓存影响人数变化。直连失败时使用旧项目的 mcsrvstat.us API;图中会标注 API 样本可能有缓存。服务器不公开玩家名字时仍可记录总人数。直连成功时,软件、插件数量等额外信息仍从原 API 补充(缓存 1 小时),但不会覆盖直连的人数和 Ping;API 补充的玩家名单会注明缓存样本。 默认每 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 小时,重载和重启后保留。后台只采集数据,用户发命令时才回复卡片。停用/卸载会取消后台任务。 数据库在 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) 的插件目录结构安装。 需要 Python 3.10+、AstrBot 4.16+(5.x 尚未验证)。按 [AstrBot 插件开发指南](https://docs.astrbot.app/dev/star/plugin-new.html) 的插件目录结构安装。
@@ -69,17 +77,26 @@ Windows 自动使用系统微软雅黑。Linux / Docker 建议在 AstrBot 运行
| `/motd` | 查询本群默认服务器,并显示波动图 | | `/motd` | 查询本群默认服务器,并显示波动图 |
| `/motd mc.example.com` | 临时查询,不改变群默认设置 | | `/motd mc.example.com` | 临时查询,不改变群默认设置 |
| `/motd mc.example.com:25565` | 指定端口查询 | | `/motd mc.example.com:25565` | 指定端口查询 |
| `/motd set mc.example.com` | 管理员设置本群服务器并立即查询 | | `/motd set mc.example.com` | 群主/群管理员/机器人管理员设置本群服务器并立即查询 |
| `/motd unset` | 管理员清除本群服务器 | | `/motd unset` | 群主/群管理员/机器人管理员清除本群服务器 |
| `/motd identity` | 查看当前用户在本群的授权标识(不会授予权限) |
| `/motd history` | 默认服务器的状态与 24 小时波动 | | `/motd history` | 默认服务器的状态与 24 小时波动 |
| `/motd history mc.example.com` | 指定服务器的状态与波动 | | `/motd history mc.example.com` | 指定服务器的状态与波动 |
| `/motd help` | 帮助 | | `/motd help` | 帮助 |
私聊可以临时查询地址;默认服务器设置/清除在群聊中使用。当前查询 Minecraft **Java 版**,保持旧项目的查询范围。 私聊可以临时查询地址;默认服务器设置/清除在群聊中使用。当前查询 Minecraft **Java 版**,保持旧项目的查询范围。
### 群管理权限
`set` 和 `unset` 都允许本群群主、本群管理员以及机器人管理员操作,普通群成员可以查询状态和历史。群角色取自平台消息中的 `sender.role` / `author.member_role`;消息没有角色时尝试通过平台群成员接口核实,不能用 AstrBot 全局 `event.is_admin()` 代替群角色。
OneBot 支持读取群消息角色及查询成员信息。QQ 官方(WebSocket / Webhook)支持读取消息原始角色,并复用当前适配器的鉴权请求查询 `/v2/groups/{group_openid}/members/{member_openid}`。实际可用性取决于机器人接口权限;[QQ SDK 的群成员接口说明](https://zhinjs.github.io/qq-official-bot/api/group.html#群成员查询) 介绍了接口权限限制。角色无法核实会明确提示,不会把普通成员当作管理员。
如果 QQ 官方接口无法提供角色,可以由机器人管理员配置**单群授权**:让该群管理人员在对应群发送 `/motd identity`,把返回的 `平台ID|群ID|用户ID` 加入插件 `group_admin_ids`。该授权只允许此人在此群管理 MOTD,不会获得全局机器人权限,也不对其他群生效。群管理人员变更后应移除旧授权。
## 配置 ## 配置
在 WebUI 插件配置中调整:`bot_name`、`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`。后台采样参数修改后重载插件。
## 本地验证与打包 ## 本地验证与打包
+2
View File
@@ -1,9 +1,11 @@
{ {
"bot_name": {"description": "状态卡署名", "type": "string", "default": "xiaohuicat"}, "bot_name": {"description": "状态卡署名", "type": "string", "default": "xiaohuicat"},
"admin_ids": {"description": "额外机器人管理员 ID", "type": "list", "default": [], "hint": "AstrBot 管理员自动拥有权限。QQ 官方机器人请填写平台用户 ID/openid,可通过 /sid 查看,不要填写旧机器人的数字 QQ 号。"}, "admin_ids": {"description": "额外机器人管理员 ID", "type": "list", "default": [], "hint": "AstrBot 管理员自动拥有权限。QQ 官方机器人请填写平台用户 ID/openid,可通过 /sid 查看,不要填写旧机器人的数字 QQ 号。"},
"group_admin_ids": {"description": "本群管理授权(平台无法获取群角色时)", "type": "list", "default": [], "hint": "通常自动识别群主/群管理员,无需填写。QQ 官方接口无法获取角色时,让该群管理人员在对应群发送 /motd identity,把返回的 平台ID|群ID|用户ID 填入此列表,只授权该用户管理该群 MOTD,不授予全局机器人管理权限。群管理人员变更后请及时移除旧授权。"},
"api_url": {"description": "备用查询 API", "type": "string", "default": "https://api.mcsrvstat.us/2/{address}", "hint": "直连失败时使用,保留 {address} 占位符。响应应为 mcsrvstat.us 格式。"}, "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}, "request_timeout": {"description": "备用 API 超时(秒)", "type": "float", "default": 10.0},
"ping_timeout": {"description": "Minecraft 直连超时(秒)", "type": "float", "default": 4.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": "关闭时只记录手动查询;已有历史保留。修改后重载插件。"}, "history_enabled": {"description": "启用后台人数采样", "type": "bool", "default": true, "hint": "关闭时只记录手动查询;已有历史保留。修改后重载插件。"},
"sample_interval": {"description": "后台采样间隔(秒)", "type": "int", "default": 300, "hint": "默认 5 分钟,最低 60 秒。绑定的服务器会持续采样,临时查询的服务器会跟踪 24 小时。"}, "sample_interval": {"description": "后台采样间隔(秒)", "type": "int", "default": 300, "hint": "默认 5 分钟,最低 60 秒。绑定的服务器会持续采样,临时查询的服务器会跟踪 24 小时。"},
"retention_hours": {"description": "历史保留时长(小时)", "type": "int", "default": 48, "hint": "最低 24 小时,图表固定显示最近 24 小时。"}, "retention_hours": {"description": "历史保留时长(小时)", "type": "int", "default": 48, "hint": "最低 24 小时,图表固定显示最近 24 小时。"},
Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 155 KiB

+42 -9
View File
@@ -13,14 +13,16 @@ from astrbot.api.star import Context, Star, StarTools
from .services.address import normalize_address from .services.address import normalize_address
from .services.mc_api import MinecraftServerAPI from .services.mc_api import MinecraftServerAPI
from .services.monitor import PlayerMonitor 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 from .services.storage import MotdStore
HELP = """Minecraft MOTD 查询 HELP = """Minecraft MOTD 查询
/motd 查询本群默认服务器 /motd 查询本群默认服务器
/motd 服务器地址 临时查询(不改变默认设置) /motd 服务器地址 临时查询(不改变默认设置)
/motd set 服务器地址 设置本群服务器(机器人管理员) /motd set 服务器地址 设置本群服务器(群主/群管理员/机器人管理员)
/motd unset 清除本群设置(机器人管理员) /motd unset 清除本群设置(群主/群管理员/机器人管理员)
/motd identity 查看本群授权标识(平台无法识别群角色时使用)
/motd history [服务器地址] 查看最近 24 小时玩家波动 /motd history [服务器地址] 查看最近 24 小时玩家波动
/motd help 查看帮助 /motd help 查看帮助
别名:/mc、/mcstatus;设置、清除、取消、波动、趋势也可使用。 别名:/mc、/mcstatus;设置、清除、取消、波动、趋势也可使用。
@@ -70,6 +72,19 @@ class MotdPlugin(Star):
str(value) for value in self.config.get("admin_ids", []) str(value) for value in self.config.get("admin_ids", [])
} }
@staticmethod
def _group_authorization_key(event):
return f"{event.get_platform_id()}|{event.get_group_id()}|{event.get_sender_id()}"
async def _can_manage_group(self, event):
if self._is_admin(event):
return True, True
# Manual grants are confined to one adapter instance, group and user.
if self._group_authorization_key(event) in self.config.get("group_admin_ids", []):
return True, True
role = await get_group_role(event)
return role in {"owner", "admin"}, role is not None
@filter.command("motd", alias={"mc", "mcstatus"}) @filter.command("motd", alias={"mc", "mcstatus"})
async def motd(self, event: AstrMessageEvent, action: str = "", address: str = ""): async def motd(self, event: AstrMessageEvent, action: str = "", address: str = ""):
"""查询 Minecraft 状态、设置群默认服务器,以及查看 24 小时玩家波动图。""" """查询 Minecraft 状态、设置群默认服务器,以及查看 24 小时玩家波动图。"""
@@ -93,12 +108,18 @@ class MotdPlugin(Star):
if verb in {"help", "帮助"}: if verb in {"help", "帮助"}:
await event.send(event.plain_result(HELP)) await event.send(event.plain_result(HELP))
return return
if verb in {"set", "设置", "unset", "clear", "清除", "取消"}: if verb in {"identity", "身份"}:
if not self._is_admin(event): if not event.get_group_id():
await event.send(event.plain_result("⚠️ 请在群内查看授权标识。"))
else:
await event.send( await event.send(
event.plain_result("❌ 只有机器人管理员可以设置或清除本群 MOTD 服务器。") event.plain_result(
"本群授权标识(仅供机器人管理员配置,本命令不会授予权限):\n"
+ self._group_authorization_key(event)
)
) )
return return
if verb in {"set", "设置", "unset", "clear", "清除", "取消"}:
if not event.get_group_id(): if not event.get_group_id():
await event.send( await event.send(
event.plain_result( event.plain_result(
@@ -106,6 +127,17 @@ class MotdPlugin(Star):
) )
) )
return return
allowed, verified = await self._can_manage_group(event)
if not allowed:
message = "❌ 只有本群群主、群管理员或机器人管理员可以设置或清除 MOTD 服务器。"
if not verified:
message += (
"\n⚠️ 平台未提供可用的群角色信息,暂时无法核实身份。"
"请检查群成员查询接口权限,或发送 /motd identity,"
"由机器人管理员在插件配置 group_admin_ids 中按群授权。"
)
await event.send(event.plain_result(message))
return
if verb in {"set", "设置"}: if verb in {"set", "设置"}:
if not address: if not address:
raise ValueError("格式: /motd set 服务器地址") raise ValueError("格式: /motd set 服务器地址")
@@ -146,8 +178,8 @@ class MotdPlugin(Star):
data = {"address": address, "online": False, "query_failed": True} data = {"address": address, "online": False, "query_failed": True}
path = self.data_dir / f"card-{uuid.uuid4().hex}.png" path = self.data_dir / f"card-{uuid.uuid4().hex}.png"
try: try:
image_bytes = await asyncio.to_thread( cards = await asyncio.to_thread(
render_motd_card, render_motd_cards,
data, data,
str(self.config.get("bot_name", "xiaohuicat")), str(self.config.get("bot_name", "xiaohuicat")),
history, history,
@@ -156,8 +188,9 @@ class MotdPlugin(Star):
self.monitor.enabled, self.monitor.enabled,
str(self.config.get("font_path", "")), str(self.config.get("font_path", "")),
) )
for image_bytes in cards:
await asyncio.to_thread(path.write_bytes, image_bytes) await asyncio.to_thread(path.write_bytes, image_bytes)
# Await the adapter send so upload errors can use the original text fallback. # Finish each upload before replacing the local file with the next page.
await event.send(event.image_result(str(path.resolve()))) await event.send(event.image_result(str(path.resolve())))
except Exception: except Exception:
logger.exception("MOTD 图片生成或发送失败: %s", address) logger.exception("MOTD 图片生成或发送失败: %s", address)
+1 -1
View File
@@ -1,7 +1,7 @@
name: astrbot_plugin_motd name: astrbot_plugin_motd
display_name: Minecraft MOTD 与玩家波动 display_name: Minecraft MOTD 与玩家波动
desc: Minecraft Java 服务器状态图片、群默认服务器、真实 Ping、玩家名单和最近 24 小时人数波动图。 desc: Minecraft Java 服务器状态图片、群默认服务器、真实 Ping、玩家名单和最近 24 小时人数波动图。
version: v1.0.0 version: v1.0.2
author: itxiaohui author: itxiaohui
support_platforms: support_platforms:
- qq_official - qq_official
+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
+38 -8
View File
@@ -22,6 +22,7 @@ class MinecraftServerAPI:
self.timeout: float = mc_cfg.get("request_timeout", 10) self.timeout: float = mc_cfg.get("request_timeout", 10)
self.ping_timeout: float = mc_cfg.get("ping_timeout", 4) self.ping_timeout: float = mc_cfg.get("ping_timeout", 4)
self.default_port: int = mc_cfg.get("default_port", 25565) self.default_port: int = mc_cfg.get("default_port", 25565)
self.query_players = bool(mc_cfg.get("query_players", True))
self._metadata = OrderedDict() self._metadata = OrderedDict()
async def query(self, address: str) -> dict | None: async def query(self, address: str) -> dict | None:
@@ -40,6 +41,7 @@ class MinecraftServerAPI:
"port": server.address.port, "port": server.address.port,
"version": status.version.name, "version": status.version.name,
"motd": status.motd.to_plain(), "motd": status.motd.to_plain(),
"motd_raw": raw.get("description", status.motd.to_plain()),
"players_online": status.players.online, "players_online": status.players.online,
"players_max": status.players.max, "players_max": status.players.max,
"player_list": [ "player_list": [
@@ -50,16 +52,25 @@ class MinecraftServerAPI:
"plugins": raw.get("plugins", {}), "plugins": raw.get("plugins", {}),
"icon": raw.get("favicon", ""), "icon": raw.get("favicon", ""),
"source": "direct", "source": "direct",
} }, server
try: 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: except Exception as exc:
logger.debug("MC 直连失败,使用原公开 API %s: %s", address, exc) logger.debug("MC 直连失败,使用原公开 API %s: %s", address, exc)
data = await self._query_api(address) data = await self._query_api(address)
if data is not None: if data is not None:
data["source"] = "api" data["source"] = "api"
return data 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 # Java status does not normally expose software/plugin names. Preserve the
# old API's extra fields while NEVER replacing direct player counts or RTT. # old API's extra fields while NEVER replacing direct player counts or RTT.
cached = self._metadata.get(address) cached = self._metadata.get(address)
@@ -72,10 +83,16 @@ class MinecraftServerAPI:
else: else:
extra = cached[1] extra = cached[1]
if extra and extra.get("online"): 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): if not data.get(key) and extra.get(key):
data[key] = extra[key] data[key] = extra[key]
if key == "player_list": 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 data["player_list_cached"] = True
return data return data
@@ -175,7 +192,12 @@ class MinecraftServerAPI:
try: try:
async with httpx.AsyncClient(timeout=self.timeout) as client: 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: if response.status_code != 200:
logger.warning(f"MC服务器查询失败: {address} HTTP {response.status_code}") logger.warning(f"MC服务器查询失败: {address} HTTP {response.status_code}")
@@ -190,13 +212,21 @@ class MinecraftServerAPI:
"latency_ms": None, "latency_ms": None,
} }
# 提取 MOTD 纯文本 # Keep the raw color codes alongside the original plain fallback.
motd_text = "" motd_text = ""
motd_raw = ""
motd = data.get("motd", {}) motd = data.get("motd", {})
if isinstance(motd, dict): if isinstance(motd, dict):
motd_text = " | ".join(motd.get("clean", [])) 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): elif isinstance(motd, str):
motd_text = motd motd_text = motd
motd_raw = motd
players = data.get("players", {}) players = data.get("players", {})
player_list = [] player_list = []
@@ -225,6 +255,7 @@ class MinecraftServerAPI:
"port": resolved_port, "port": resolved_port,
"version": data.get("version", "未知"), "version": data.get("version", "未知"),
"motd": motd_text, "motd": motd_text,
"motd_raw": motd_raw,
"players_online": players.get("online", 0), "players_online": players.get("online", 0),
"players_max": players.get("max", 0), "players_max": players.get("max", 0),
"player_list": player_list, "player_list": player_list,
@@ -298,8 +329,7 @@ class MinecraftServerAPI:
player_list = data.get("player_list") or [] player_list = data.get("player_list") or []
if player_list: if player_list:
lines.append( lines.append(
f"👤 已公开玩家({len(player_list)}/{players_online}): " f"👤 已公开玩家({len(player_list)}/{players_online}): " + "、".join(player_list)
+ "、".join(player_list)[:400]
) )
elif players_online: elif players_online:
lines.append("👤 服务器未公开玩家名单") 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
+291 -90
View File
@@ -4,19 +4,19 @@ from __future__ import annotations
import base64 import base64
import hashlib import hashlib
import html
import io import io
import math import math
import re
import time import time
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from functools import lru_cache from functools import lru_cache
from pathlib import Path 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_WIDTH = 1200
CARD_HEIGHT = 1080
CHINA_TIME = timezone(timedelta(hours=8)) 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") draw = ImageDraw.Draw(image, "RGBA")
top = (12, 23, 18) top = (12, 23, 18)
bottom = (22, 49, 34) bottom = (22, 49, 34)
for y in range(CARD_HEIGHT): width, height = image.size
ratio = y / max(CARD_HEIGHT - 1, 1) 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)) 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() digest = hashlib.sha256(seed_text.encode("utf-8")).digest()
palette = [(17, 39, 26, 255), (20, 46, 29, 255), (15, 34, 24, 255)] palette = [(17, 39, 26, 255), (20, 46, 29, 255), (15, 34, 24, 255)]
for index in range(34): for index in range(34):
x = (digest[index % len(digest)] * 47 + index * 113) % CARD_WIDTH 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 size = 24 + digest[(index + 17) % len(digest)] % 64
draw.rectangle((x, y, x + size, y + size), fill=palette[index % len(palette)]) 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 return text + suffix
def _wrap_text( def _layout_motd(draw, runs, max_width, font_path):
draw: ImageDraw.ImageDraw, text: str, font, max_width: int, max_lines: int = 2 lines, current, width = [], [], 0.0
) -> list[str]: for run in runs:
clean = ( font = _load_font(25, run.style.bold, font_path)
html.unescape(re.sub(r"§.", "", str(text))).replace("\r", " ").replace("\n", " ").strip() for char in run.text.replace("\t", " "):
) if char == "\n":
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) lines.append(current)
current = char current, width = [], 0.0
if len(lines) == max_lines: continue
break 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: else:
current = candidate current.append(TextRun(char, run.style))
if len(lines) < max_lines and current: width += advance
if current or not lines:
lines.append(current) lines.append(current)
consumed = "".join(lines) return lines
if len(consumed) < len(clean) and lines:
lines[-1] = _ellipsize(draw, lines[-1] + "...", font, max_width)
return lines[:max_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( 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 = (91, 214, 111, 255) if online else (241, 96, 89, 255)
accent_soft = (27, 67, 37, 255) if online else (76, 31, 29, 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_pixel_background(image, address)
draw = ImageDraw.Draw(image, "RGBA") draw = ImageDraw.Draw(image, "RGBA")
# 主面板和左侧像素饰条 # 主面板和左侧像素饰条
_rounded_panel(draw, (44, 42, 1156, 1040), (8, 16, 13, 222), (77, 123, 90, 110), 30) _rounded_panel(draw, (44, 42, 1156, card_height - 40), (8, 16, 13, 222), (77, 123, 90, 110), 30)
draw.rounded_rectangle((44, 42, 58, 1040), radius=7, fill=accent) 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) _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 "")) 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) status_font = _load_font(28, bold=True, font_path=font_path)
label_font = _load_font(22, font_path=font_path) label_font = _load_font(22, font_path=font_path)
value_font = _load_font(29, bold=True, 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) footer_font = _load_font(19, font_path=font_path)
draw.text((84, 66), "MINECRAFT SERVER STATUS", font=title_font, fill=(161, 196, 171, 255)) 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: if ratio > 0:
draw.rounded_rectangle((436, 404, 436 + int(264 * ratio), 414), radius=5, fill=accent) draw.rounded_rectangle((436, 404, 436 + int(264 * ratio), 414), radius=5, fill=accent)
# MOTD # Full-width, dynamically sized colored MOTD; retain its original line breaks.
_rounded_panel(draw, (84, 452, 714, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18) _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)) draw.text((106, 468), "MOTD", font=label_font, fill=(145, 171, 152, 255))
motd = str(data.get("motd") or ("暂无服务器标语" if online else "无法连接到该服务器")) for index, line in enumerate(motd_lines):
for line_index, line in enumerate(_wrap_text(draw, motd, motd_font, 580, 2)): _draw_styled_line(image, (106, 501 + index * 34), line, font_path)
draw.text((106, 500 + line_index * 32), line, font=motd_font, fill=(226, 236, 229, 255))
# 在线玩家名单(Minecraft 状态协议可能只返回部分样本) # Full roster gets its own section and wraps at badge boundaries.
_rounded_panel(draw, (736, 452, 1072, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18) _rounded_panel(
player_list = [str(name) for name in (data.get("player_list") or []) if str(name).strip()] draw,
if player_list: (84, players_top, 1072, players_top + players_height),
public_count = len(player_list) (17, 31, 24, 230),
player_label = f"在线玩家(已公开 {public_count}/{players_online})" (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"): if data.get("player_list_cached"):
player_label = "公开玩家(API 缓存样本)" player_label += " · API 缓存样本"
player_text = "、".join(player_list) elif data.get("player_list_source") == "query":
player_label += " · Query 名单"
player_text = ""
elif online and players_online > 0: elif online and players_online > 0:
player_label = "在线玩家" player_label = "在线玩家"
player_text = "服务器未公开玩家名单" player_text = "服务器未公开玩家名单"
@@ -288,24 +401,51 @@ def render_motd_card(
else: else:
player_label = "在线玩家" player_label = "在线玩家"
player_text = "-" player_text = "-"
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( draw.text(
(758, 468), (1048 - draw.textlength(page_label, font=label_font), players_top + 16),
_ellipsize(draw, player_label, label_font, 292), page_label,
font=label_font, font=label_font,
fill=(145, 171, 152, 255), fill=(116, 145, 125),
) )
for line_index, line in enumerate(_wrap_text(draw, player_text, label_font, 290, 2)): name_font = _load_font(21, font_path=font_path)
draw.text((758, 504 + line_index * 28), line, font=label_font, fill=(226, 236, 229, 255)) 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 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 直连" source = "公开 API(可能有缓存)" if data.get("source") == "api" else "Minecraft 直连"
if data.get("query_failed"): if data.get("query_failed"):
source = "本次查询失败" source = "本次查询失败"
update_time = datetime.fromtimestamp(now, CHINA_TIME).strftime("%m-%d %H:%M") update_time = datetime.fromtimestamp(now, CHINA_TIME).strftime("%m-%d %H:%M")
footer = f"{bot_name} · itxiaohui · {source} · {update_time} (UTC+8)" footer = f"{bot_name} · itxiaohui · {source} · {update_time} (UTC+8)"
draw.text( draw.text(
(84, 996), (84, card_height - 83),
_ellipsize(draw, footer, footer_font, 1010), _ellipsize(draw, footer, footer_font, 1010),
font=footer_font, font=footer_font,
fill=(116, 145, 125, 255), fill=(116, 145, 125, 255),
@@ -336,12 +476,18 @@ def history_segments(history: list[dict], now: int, interval: int) -> list[list[
return segments return segments
def _draw_history(draw, history, now, interval, enabled, font_path): def _draw_history(image, history, now, interval, enabled, font_path, panel_top):
_rounded_panel(draw, (84, 590, 1072, 974), (17, 31, 24, 230), (65, 104, 76, 90), 18) 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) title = _load_font(25, True, font_path)
font = _load_font(19, font_path=font_path) font = _load_font(19, font_path=font_path)
small = _load_font(17, 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( history = sorted(
(p for p in history if now - 86400 <= p["timestamp"] <= now), key=lambda p: p["timestamp"] (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 p["players"] for p in history if p.get("online") == 1 and p.get("players") is not None
] ]
if counts: 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: else:
summary = "暂无成功的人数采样" draw.text((106, panel_top + 62), "暂无成功的人数采样", font=font, fill=(145, 171, 152))
draw.text((106, 644), summary, font=font, fill=(145, 171, 152))
# Fixed rolling 24h axis: partial histories only occupy their actual time range. # Supersampling keeps curved strokes and their round ends smooth on QQ images.
left, right, top, bottom = 162, 1034, 694, 874 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) maximum = max(counts, default=1)
step = max(1, math.ceil(maximum / 4)) step = max(1, math.ceil(maximum / 4))
ceiling = step * 4 ceiling = step * 4
for index in range(5): for index in range(5):
y = bottom - index * (bottom - top) / 4 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) label = str(index * step)
draw.text( 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, label,
font=small, font=small,
fill=(116, 145, 125), fill=(116, 145, 125),
) )
for index in range(5): for index in range(5):
x = left + index * (right - left) / 4 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") stamp = datetime.fromtimestamp(now - 86400 + index * 21600, CHINA_TIME).strftime("%H:%M")
draw.text( draw.text(
(x - draw.textlength(stamp, font=small) / 2, 883), (84 + x - draw.textlength(stamp, font=small) / 2, panel_top + 290),
stamp, stamp,
font=small, font=small,
fill=(116, 145, 125), fill=(116, 145, 125),
) )
def coordinates(p): def coordinates(point):
return ( return (
left + (p["timestamp"] - (now - 86400)) / 86400 * (right - left), left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left),
bottom - p["players"] / ceiling * (bottom - top), 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): for segment in history_segments(history, now, interval):
points = [coordinates(p) for p in segment] samples = [coordinates(point) for point in segment]
if len(points) > 1: curve = smooth_points(samples, resolution=0.5)
draw.line(points, fill=(91, 214, 111), width=3) scaled = [(x * scale, y * scale) for x, y in curve]
for x, y in points: if len(curve) > 1:
draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(123, 238, 141)) 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: for point in history:
if point.get("online") != 1: if point.get("online") != 1:
x = left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left) x = left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left)
color = (241, 96, 89) if point.get("online") == 0 else (212, 175, 99) color = (241, 96, 89, 255) if point.get("online") == 0 else (212, 175, 99, 255)
draw.line((x, bottom - 6, x, bottom), fill=color, width=2) 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: if not counts:
text = "开始采集后将在这里显示曲线" if not history else "服务器离线或查询失败,暂无人数曲线" 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: if len(counts) == 1:
note = "仅有 1 个人数采样,继续运行后自动形成曲线" note = "仅有 1 个人数采样,继续运行后自动形成曲线"
else: else:
note = f"人数采样 {len(counts)} 次 · 间隔 {interval // 60} 分钟 · 红:离线 黄:失败 空白:无数据" note = f"人数采样 {len(counts)} 次 · 间隔 {interval // 60} 分钟 · 红:离线 黄:失败 空白:无数据"
if not enabled: if not enabled:
note = "后台采样已关闭,仅记录手动查询 · 空白时段没有数据" 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): if any(p.get("source") == "api" for p in history):
draw.text( text, color = "部分采样来自公开 API,人数可能有缓存延迟 · 时间 UTC+8", (212, 175, 99)
(106, 944),
"部分采样来自公开 API,人数可能有缓存延迟 · 时间 UTC+8",
font=small,
fill=(212, 175, 99),
)
else: else:
draw.text( text, color = "曲线经过实测采样点 · 缺失时段保持断线 · 时间 UTC+8", (116, 145, 125)
(106, 944), draw.text((106, panel_top + 356), text, font=small, fill=color)
"从首次查询或绑定开始积累 · 重启后保留历史 · 时间 UTC+8",
font=small,
fill=(116, 145, 125),
)
+100
View File
@@ -0,0 +1,100 @@
"""Resolve the sender's group role without confusing it with AstrBot's global admin role."""
import asyncio
import logging
from collections.abc import Mapping
from urllib.parse import quote
logger = logging.getLogger(__name__)
ROLES = {"owner", "admin", "member"}
def field(value, key, default=None):
return value.get(key, default) if isinstance(value, Mapping) else getattr(value, key, default)
def role_of(value):
for key in ("member_role", "role"):
role = field(value, key)
if isinstance(role, str) and role.lower() in ROLES:
return role.lower()
return None
async def get_group_role(event) -> str | None:
"""Return owner/admin/member, or None if the platform cannot verify membership."""
group_id, user_id = str(event.get_group_id()), str(event.get_sender_id())
if not group_id or not user_id:
return None
platform = event.get_platform_name()
message = getattr(event, "message_obj", None)
raw = field(message, "raw_message")
if platform == "aiocqhttp":
if (
field(raw, "group_id", group_id) is not None
and str(field(raw, "group_id", group_id)) != group_id
):
return None
if str(field(field(raw, "sender"), "user_id", user_id)) != user_id:
return None
role = role_of(field(raw, "sender"))
elif platform in {"qq_official", "qq_official_webhook"}:
# New AstrBot parsers retain raw_data even when botpy drops author fields.
raw_data = field(raw, "raw_data")
if str(field(raw_data, "group_openid", field(raw, "group_openid", group_id))) != group_id:
return None
author = field(raw_data, "author", field(raw, "author"))
if str(field(author, "member_openid", user_id)) != user_id:
return None
role = role_of(field(raw_data, "author")) or role_of(field(raw, "author"))
else:
return None
if role:
return role
async def lookup():
bot = getattr(event, "bot", None)
if platform == "aiocqhttp":
routing = {}
self_id = field(raw, "self_id")
if self_id is not None:
routing["self_id"] = self_id
info = await bot.call_action(
"get_group_member_info",
group_id=int(group_id),
user_id=int(user_id),
no_cache=True,
**routing,
)
if not isinstance(info, Mapping):
return None
if str(info.get("user_id", "")) != user_id or str(info.get("group_id", "")) != group_id:
return None
return role_of(info)
# Reuse the adapter's authenticated SDK client; do not duplicate secrets.
from botpy.http import Route
info = await bot.api._http.request(
Route(
"GET",
"/v2/groups/{group_openid}/members/{member_openid}",
group_openid=quote(group_id, safe=""),
member_openid=quote(user_id, safe=""),
)
)
if not isinstance(info, Mapping):
return None
# Some clients wrap the member response; never accept a different user's role.
info = info.get("data", info)
if not isinstance(info, Mapping) or str(info.get("member_openid", "")) != user_id:
return None
response_group = info.get("group_openid")
if response_group is not None and str(response_group) != group_id:
return None
return role_of(info)
try:
return await asyncio.wait_for(lookup(), timeout=5)
except Exception as exc:
logger.warning("MOTD 群角色查询不可用 (%s): %s", platform, type(exc).__name__)
return None
+56 -2
View File
@@ -3,6 +3,7 @@ import json
from types import SimpleNamespace from types import SimpleNamespace
import httpx import httpx
import pytest
from services.mc_api import MinecraftServerAPI from services.mc_api import MinecraftServerAPI
@@ -35,7 +36,7 @@ async def test_real_java_status_protocol_on_local_server():
"max": 50, "max": 50,
"sample": [{"name": "Alex", "id": "00000000-0000-0000-0000-000000000000"}], "sample": [{"name": "Alex", "id": "00000000-0000-0000-0000-000000000000"}],
}, },
"description": {"text": "Hello server"}, "description": {"text": "Hello server", "color": "gold"},
} }
).encode() ).encode()
packet = b"\x00" + api._encode_varint(len(payload)) + payload 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["players_online"] == 2 and result["players_max"] == 50
assert result["player_list"] == ["Alex"] and result["version"] == "1.21.1" assert result["player_list"] == ["Alex"] and result["version"] == "1.21.1"
assert result["motd"] == "Hello server" and result["latency_ms"] >= 0 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. # Exercise the migrated fallback ping/pong path too.
latency = await api._measure_minecraft_latency("127.0.0.1", port, "127.0.0.1", 767) latency = await api._measure_minecraft_latency("127.0.0.1", port, "127.0.0.1", 767)
assert latency is not None and latency >= 0 assert latency is not None and latency >= 0
@@ -82,7 +84,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch):
"online": True, "online": True,
"version": "Paper 1.21", "version": "Paper 1.21",
"port": 25565, "port": 25565,
"motd": {"clean": ["First", "Second"]}, "motd": {"clean": ["First", "Second"], "raw": ["§cFirst", "§bSecond"]},
"players": { "players": {
"online": 5, "online": 5,
"max": 20, "max": 20,
@@ -100,6 +102,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch):
api = MinecraftServerAPI({}) api = MinecraftServerAPI({})
data = await api.query("mc.example.com") data = await api.query("mc.example.com")
assert data["source"] == "api" and data["motd"] == "First | Second" assert data["source"] == "api" and data["motd"] == "First | Second"
assert data["motd_raw"] == "§cFirst\n§bSecond"
assert data["player_list"] == ["Steve", "Alex", "Third"] assert data["player_list"] == ["Steve", "Alex", "Third"]
assert seen == ["https://api.mcsrvstat.us/2/mc.example.com"] # no forced :25565 assert seen == ["https://api.mcsrvstat.us/2/mc.example.com"] # no forced :25565
text = api.format_server_info(data) 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 api._query_api = no_extra
data = await api.query("mc.example.com") data = await api.query("mc.example.com")
assert seen == ["mc.example.com"] and data["port"] == 25570 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"]
+126
View File
@@ -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)]))
+115
View File
@@ -0,0 +1,115 @@
import sys
import types
import pytest
from services.permissions import get_group_role
class Event:
def __init__(self, platform="qq_official", raw=None, group="g", user="u", bot=None):
self.platform, self.group, self.user, self.bot = platform, group, user, bot
self.message_obj = types.SimpleNamespace(raw_message=raw)
def get_group_id(self):
return self.group
def get_sender_id(self):
return self.user
def get_platform_name(self):
return self.platform
@pytest.mark.parametrize("role", ["owner", "admin", "member"])
async def test_official_preserved_raw_data(role):
raw = types.SimpleNamespace(
author=types.SimpleNamespace(member_openid="u"),
raw_data={"author": {"member_openid": "u", "member_role": role}, "group_openid": "g"},
)
assert await get_group_role(Event(raw=raw)) == role
@pytest.fixture
def fake_botpy(monkeypatch):
class Route:
def __init__(self, method, path, **kwargs):
self.method, self.path, self.parameters = method, path, kwargs
module = types.ModuleType("botpy.http")
module.Route = Route
monkeypatch.setitem(sys.modules, "botpy", types.ModuleType("botpy"))
monkeypatch.setitem(sys.modules, "botpy.http", module)
@pytest.mark.parametrize("platform", ["qq_official", "qq_official_webhook"])
@pytest.mark.parametrize("role", ["owner", "admin", "member"])
async def test_official_authenticated_member_lookup(fake_botpy, platform, role):
seen = []
async def request(route):
seen.append(route)
return {"member_openid": "u", "member_role": role}
bot = types.SimpleNamespace(
api=types.SimpleNamespace(_http=types.SimpleNamespace(request=request))
)
assert await get_group_role(Event(platform=platform, bot=bot)) == role
assert seen[0].method == "GET"
assert seen[0].path == "/v2/groups/{group_openid}/members/{member_openid}"
assert seen[0].parameters == {"group_openid": "g", "member_openid": "u"}
@pytest.mark.parametrize(
"response",
[
{"member_openid": "wrong-user", "member_role": "owner"},
{"member_openid": "u", "member_role": "admin", "group_openid": "wrong-group"},
{"code": 11253, "message": "API not enabled"},
None,
],
)
async def test_wrong_identity_or_unavailable_official_api_never_grants(fake_botpy, response):
async def request(route):
return response
bot = types.SimpleNamespace(
api=types.SimpleNamespace(_http=types.SimpleNamespace(request=request))
)
assert await get_group_role(Event(bot=bot)) is None
async def test_onebot_live_lookup_passes_routing_and_no_cache():
seen = []
async def action(name, **kwargs):
seen.append((name, kwargs))
return {"user_id": 2, "group_id": 1, "role": "owner"}
bot = types.SimpleNamespace(call_action=action)
event = Event("aiocqhttp", raw={"self_id": 123}, group="1", user="2", bot=bot)
assert await get_group_role(event) == "owner"
assert seen == [
("get_group_member_info", {"group_id": 1, "user_id": 2, "no_cache": True, "self_id": 123})
]
async def test_api_failure_denies_without_crashing(fake_botpy):
async def request(route):
raise PermissionError("not enabled")
bot = types.SimpleNamespace(
api=types.SimpleNamespace(_http=types.SimpleNamespace(request=request))
)
assert await get_group_role(Event(bot=bot)) is None
async def test_mismatched_incoming_author_and_message_text_do_not_grant():
assert (
await get_group_role(
Event(raw={"author": {"member_openid": "wrong", "member_role": "owner"}})
)
is None
)
assert await get_group_role(Event(raw={"content": '{"member_role": "owner"}'})) is None
assert await get_group_role(Event(raw={"author": {"member_role": "admin"}}, group="")) is None
+106 -2
View File
@@ -10,8 +10,19 @@ import pytest
class Event: class Event:
def __init__(self, platform="qq-main", group="group-openid", admin=False, image_error=False): def __init__(
self,
platform="qq-main",
group="group-openid",
admin=False,
image_error=False,
platform_name="qq_official",
raw=None,
user="user-openid",
):
self.platform, self.group, self.admin = platform, group, admin self.platform, self.group, self.admin = platform, group, admin
self.platform_name, self.user = platform_name, user
self.message_obj = types.SimpleNamespace(raw_message=raw)
self.image_error = image_error self.image_error = image_error
self.unified_msg_origin = f"{platform}:private:user" self.unified_msg_origin = f"{platform}:private:user"
self.messages = [] self.messages = []
@@ -23,8 +34,11 @@ class Event:
def get_platform_id(self): def get_platform_id(self):
return self.platform return self.platform
def get_platform_name(self):
return self.platform_name
def get_sender_id(self): def get_sender_id(self):
return "user-openid" return self.user
def is_admin(self): def is_admin(self):
return self.admin return self.admin
@@ -146,3 +160,93 @@ async def test_missing_default_invalid_and_private_setting(plugin_class):
await plugin.motd(event, "help") await plugin.motd(event, "help")
assert "/mcstatus" in event.messages[-1][1] assert "/mcstatus" in event.messages[-1][1]
await plugin.terminate() await plugin.terminate()
@pytest.mark.parametrize("platform_name", ["qq_official", "qq_official_webhook", "aiocqhttp"])
@pytest.mark.parametrize("role", ["owner", "admin", "member"])
async def test_group_roles_can_set_and_clear_only_when_privileged(
plugin_class, platform_name, role
):
plugin = plugin_class(object(), {"history_enabled": False})
async def no_send(*args):
pass
plugin._query_and_send = no_send
raw = (
{"sender": {"role": role}}
if platform_name == "aiocqhttp"
else {"author": {"member_role": role}}
)
event = Event(platform_name=platform_name, raw=raw)
await plugin.motd(event, "set", "a.test")
scope = plugin._scope(event)
if role == "member":
assert await plugin.store.get_binding(scope) is None
assert "暂时无法核实" not in event.messages[-1][1]
await plugin.store.set_binding(scope, "original.test", "bot-admin")
await plugin.motd(event, "unset")
assert await plugin.store.get_binding(scope) == "original.test"
else:
assert await plugin.store.get_binding(scope) == "a.test"
await plugin.motd(event, "unset")
assert await plugin.store.get_binding(scope) is None
await plugin.terminate()
async def test_group_grant_is_limited_to_one_group_and_adapter(plugin_class):
plugin = plugin_class(
object(),
{"history_enabled": False, "group_admin_ids": ["qq-main|group-openid|user-openid"]},
)
async def no_send(*args):
pass
plugin._query_and_send = no_send
event = Event()
await plugin.motd(event, "set", "a.test")
assert await plugin.store.get_binding(plugin._scope(event)) == "a.test"
for outsider in [
Event(group="another-group"),
Event(platform="another-bot"),
Event(user="another-user"),
]:
await plugin.motd(outsider, "set", "unauthorized.test")
assert "无法核实" in outsider.messages[-1][1]
if outsider.group != event.group or outsider.platform != event.platform:
assert await plugin.store.get_binding(plugin._scope(outsider)) is None
else:
assert await plugin.store.get_binding(plugin._scope(outsider)) == "a.test"
await plugin.motd(event, "identity")
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()
+1 -1
View File
@@ -76,4 +76,4 @@ def test_card_handles_empty_history_offline_failure_and_zero(online, failed, his
now=100000, now=100000,
) )
image = Image.open(io.BytesIO(raw)) 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
+6 -1
View File
@@ -1,5 +1,6 @@
"""Build an installable archive without local data, test stubs, or development downloads.""" """Build an installable archive without local data, test stubs, or development downloads."""
import re
from pathlib import Path from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile from zipfile import ZIP_DEFLATED, ZipFile
@@ -7,7 +8,11 @@ ROOT = Path(__file__).resolve().parents[1]
def main(): def main():
target = ROOT / "dist" / "astrbot_plugin_motd-v1.0.0.zip" metadata = (ROOT / "metadata.yaml").read_text(encoding="utf-8")
version = re.search(r"^version:\s*(v[0-9]+\.[0-9]+\.[0-9]+)\s*$", metadata, re.MULTILINE).group(
1
)
target = ROOT / "dist" / f"astrbot_plugin_motd-{version}.zip"
target.parent.mkdir(exist_ok=True) target.parent.mkdir(exist_ok=True)
files = ( files = (
[ [
+39 -4
View File
@@ -7,7 +7,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT))
from services.motd_card import render_motd_card from services.motd_card import render_motd_cards
def main(): def main():
@@ -26,9 +26,32 @@ def main():
"address": "mc.example.com:25565", "address": "mc.example.com:25565",
"version": "1.21.1", "version": "1.21.1",
"motd": "欢迎来到栗子服务器!生存 · 建筑 · 冒险,和朋友一起探索方块世界", "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_online": history[-1]["players"],
"players_max": 100, "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, "latency_ms": 32.6,
"software": "Paper", "software": "Paper",
"plugins": {"names": ["Example"]}, "plugins": {"names": ["Example"]},
@@ -41,10 +64,22 @@ def main():
"first": (data, history[-1:]), "first": (data, history[-1:]),
"offline": ({"online": False, "address": data["address"], "source": "api"}, history), "offline": ({"online": False, "address": data["address"], "source": "api"}, history),
"failed": ({"online": False, "address": data["address"], "query_failed": True}, []), "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(): for name, (status, points) in examples.items():
path = folder / f"motd-{name}.png" for index, card in enumerate(
path.write_bytes(render_motd_card(status, "xiaohuicat · 演示数据", points, now)) 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) print(path)