commit 2144e218ec3c8f8dad1fad7630d4118f9eb369ec Author: itxiaohui <177289791+itxiaohui66@users.noreply.github.com> Date: Mon Oct 5 12:22:51 2026 +0800 Release xiaohuicat MOTD plugin with 24-hour player history diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..20816c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.venv/ +.dev/ +dist/ +data/ +*.db +*.db-wal +*.db-shm diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..05b296d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 itxiaohui + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..373a6f1 --- /dev/null +++ b/README.md @@ -0,0 +1,103 @@ +# Minecraft MOTD 与玩家波动(AstrBot) + +Minecraft Java 服务器状态查询插件,适用于 AstrBot 的 QQ 官方机器人(WebSocket / Webhook)与 OneBot。保留 xiaohuicat 原机器人项目的全部 MOTD 功能,新增最近 24 小时玩家人数波动图。默认卡片署名为 `xiaohuicat`。 + +![状态卡与 24 小时玩家波动图(演示数据)](assets/motd-preview.png) + +## 保留的功能 + +- `/motd`、`/mc`、`/mcstatus` 三个命令入口;群默认服务器查询与临时地址查询。 +- 机器人管理员设置/清除群默认服务器,支持 `set / 设置`、`unset / clear / 清除 / 取消`。设置成功后立即查询。 +- 查询在线/离线、版本、MOTD、在线/上限人数、人数进度条、公开玩家样本、服务器图标。没有图标时显示像素苦力怕。 +- Minecraft 状态握手和 ping/pong 测得的真实 RTT;保留域名 SRV 解析与显式端口。 +- 保留原像素风图片;图片渲染或上传失败时回复文字,包含人数历史摘要。 +- 原查询 API 地址、超时可配置;备用 API 返回的主机名、服务端软件和插件数量仍可显示。 + +## 新增 24 小时图表 + +每张状态卡下方显示滚动 24 小时人数曲线,以及采样最低/最高/平均人数。`/motd history` 或 `/motd 波动` 可以直接请求带曲线的卡片,也可附带地址。 + +默认每 300 秒采样,优先直连 Minecraft Java 状态协议,避免公开 API 缓存影响人数变化。直连失败时使用旧项目的 mcsrvstat.us API;图中会标注 API 样本可能有缓存。服务器不公开玩家名字时仍可记录总人数。直连成功时,软件、插件数量等额外信息仍从原 API 补充(缓存 1 小时),但不会覆盖直连的人数和 Ping;API 补充的玩家名单会注明缓存样本。 + +群绑定的服务器持续采样;临时查询的地址从最近一次手动查询起自动跟踪 24 小时(最多跟踪最近 128 个临时地址)。多群绑定同一地址只采样一次。配置 `monitor_servers` 可添加永久跟踪地址。清除群绑定后,之前临时跟踪的剩余时间内仍可能采样;若别的群仍有绑定,会继续采样。 + +**首次使用不会补造过去的记录。** 首次只有一个点,持续运行后逐渐形成曲线;完整的 24 小时图需要运行采集 24 小时。停机、查询失败和离线均断开曲线,离线用红色标记、失败用黄色标记,在线 0 人会正常显示 0。时间以 UTC+8 显示。平均值是成功的人数采样平均值,不是按时间加权的全天均值。 + +数据库在 AstrBot 的 `data/plugin_data/astrbot_plugin_motd/motd.db` 中,默认保留 48 小时,重载和重启后保留。后台只采集数据,用户发命令时才回复卡片。停用/卸载会取消后台任务。 + +## 安装 + +需要 Python 3.10+、AstrBot 4.16+(5.x 尚未验证)。按 [AstrBot 插件开发指南](https://docs.astrbot.app/dev/star/plugin-new.html) 的插件目录结构安装。 + +### 文件夹安装 + +将插件的整个目录复制到 **AstrBot 根目录** 的 `data/plugins/astrbot_plugin_motd/`,确认 `main.py`、`metadata.yaml`、`_conf_schema.json`、`services/` 位于同一层。在 AstrBot 使用的 Python 环境执行: + +```bash +python -m pip install -r data/plugins/astrbot_plugin_motd/requirements.txt +``` + +随后在 AstrBot WebUI 重启/重载插件。也可从 [Releases](https://github.com/itxiaohui66/astrbot_plugin_motd/releases) 下载插件 ZIP,在支持本地 ZIP 安装的插件管理页面导入。 + +### 从 GitHub 安装 + +在 AstrBot WebUI 的插件管理中选择通过链接安装,填写: + +```text +https://github.com/itxiaohui66/astrbot_plugin_motd +``` + +### QQ 官方机器人 + +1. 按 [AstrBot QQ 官方平台接入文档](https://docs.astrbot.app/platform/qqofficial.html) 接入机器人。 +2. 使用 AstrBot 的 `/sid` 获取平台 ID,按 [内置命令文档](https://docs.astrbot.app/use/command.html) 在 WebUI 设置管理员,或填入本插件的 `admin_ids`。 +3. 群内 @机器人发送 `/motd set 你的服务器地址`。 +4. 群内 @机器人发送 `/motd` 或 `/motd history`。 + +插件使用 AstrBot 通用本地图片消息,由 QQ 适配器负责上传,无需 OneBot 的 `base64://` 消息。旧项目中的数字 QQ 群号与官方机器人的 group openid 不同,因此**需要在新机器人所在群重新绑定默认服务器**。管理员也应使用官方平台 ID,不能直接复制旧数字 QQ 号。 + +指令前缀遵循 AstrBot 的唤醒配置,默认使用 `/`。官方机器人实际接收范围、图片发送权限与平台审核以你的 QQ 机器人配置为准。 + +### 中文字体 + +Windows 自动使用系统微软雅黑。Linux / Docker 建议在 AstrBot 运行环境安装 `fonts-noto-cjk`,或将中文字体放到容器可读位置,并在 `font_path` 填写绝对路径。没有中文字体时卡片可能显示方框。 + +## 指令 + +| 指令 | 功能 | +| --- | --- | +| `/motd` | 查询本群默认服务器,并显示波动图 | +| `/motd mc.example.com` | 临时查询,不改变群默认设置 | +| `/motd mc.example.com:25565` | 指定端口查询 | +| `/motd set mc.example.com` | 管理员设置本群服务器并立即查询 | +| `/motd unset` | 管理员清除本群服务器 | +| `/motd history` | 默认服务器的状态与 24 小时波动 | +| `/motd history mc.example.com` | 指定服务器的状态与波动 | +| `/motd help` | 帮助 | + +私聊可以临时查询地址;默认服务器设置/清除在群聊中使用。当前查询 Minecraft **Java 版**,保持旧项目的查询范围。 + +## 配置 + +在 WebUI 插件配置中调整:`bot_name`、`admin_ids`、`api_url`、`request_timeout`、`ping_timeout`、`history_enabled`、`sample_interval`、`retention_hours`、`monitor_servers`、`font_path`。后台采样参数修改后重载插件。 + +## 本地验证与打包 + +```bash +python -m pip install -r requirements-dev.txt +python -m pytest +python -m ruff check . +python -m ruff format --check . +python tools/preview.py +python tools/package.py +``` + +自动测试覆盖实际 Minecraft 协议模拟、直连/API 切换、群设置隔离与管理员权限、后台采样、持久化、失败断线和图片降级。最终的官方 QQ 收发仍需在你实际运行的 AstrBot 和机器人账号中联调。 + +## 来源 + +命令行为、原 Minecraft API 服务、像素卡片基础移植自 itxiaohui 的原机器人项目 `liziqqbotpy`,对应模块为 `plugins/mc_motd.py`、`services/mc_api.py`、`services/motd_card.py`。保留 `itxiaohui` 技术支持署名。插件入口和消息发送依据 [AstrBot 官方开发文档](https://docs.astrbot.app/dev/star/plugin-new.html) 重写;直连查询使用 [mcstatus](https://github.com/py-mine/mcstatus)。 + +## 许可证 + +本项目以 [MIT 许可证](LICENSE) 开源。 diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..af3366d --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ +"""AstrBot Minecraft MOTD plugin package.""" diff --git a/_conf_schema.json b/_conf_schema.json new file mode 100644 index 0000000..5896efc --- /dev/null +++ b/_conf_schema.json @@ -0,0 +1,12 @@ +{ + "bot_name": {"description": "状态卡署名", "type": "string", "default": "xiaohuicat"}, + "admin_ids": {"description": "额外机器人管理员 ID", "type": "list", "default": [], "hint": "AstrBot 管理员自动拥有权限。QQ 官方机器人请填写平台用户 ID/openid,可通过 /sid 查看,不要填写旧机器人的数字 QQ 号。"}, + "api_url": {"description": "备用查询 API", "type": "string", "default": "https://api.mcsrvstat.us/2/{address}", "hint": "直连失败时使用,保留 {address} 占位符。响应应为 mcsrvstat.us 格式。"}, + "request_timeout": {"description": "备用 API 超时(秒)", "type": "float", "default": 10.0}, + "ping_timeout": {"description": "Minecraft 直连超时(秒)", "type": "float", "default": 4.0}, + "history_enabled": {"description": "启用后台人数采样", "type": "bool", "default": true, "hint": "关闭时只记录手动查询;已有历史保留。修改后重载插件。"}, + "sample_interval": {"description": "后台采样间隔(秒)", "type": "int", "default": 300, "hint": "默认 5 分钟,最低 60 秒。绑定的服务器会持续采样,临时查询的服务器会跟踪 24 小时。"}, + "retention_hours": {"description": "历史保留时长(小时)", "type": "int", "default": 48, "hint": "最低 24 小时,图表固定显示最近 24 小时。"}, + "monitor_servers": {"description": "额外持续采样服务器", "type": "list", "default": [], "hint": "域名或 IP,可附带端口。这些服务器无需在群内绑定也会持续采样。"}, + "font_path": {"description": "自定义中文字体文件绝对路径", "type": "string", "default": "", "hint": "留空自动查找 Noto Sans CJK、文泉驿或 Windows 微软雅黑。Linux 建议安装 fonts-noto-cjk,路径须在 AstrBot 运行环境内可读。"} +} diff --git a/assets/motd-preview.png b/assets/motd-preview.png new file mode 100644 index 0000000..4d90071 Binary files /dev/null and b/assets/motd-preview.png differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..e24d16b --- /dev/null +++ b/main.py @@ -0,0 +1,178 @@ +"""AstrBot MOTD plugin, using platform-neutral messages for official QQ bots.""" + +import asyncio +import contextlib +import json +import time +import uuid + +from astrbot.api import AstrBotConfig, logger +from astrbot.api.event import AstrMessageEvent, filter +from astrbot.api.star import Context, Star, StarTools + +from .services.address import normalize_address +from .services.mc_api import MinecraftServerAPI +from .services.monitor import PlayerMonitor +from .services.motd_card import render_motd_card +from .services.storage import MotdStore + +HELP = """Minecraft MOTD 查询 +/motd 查询本群默认服务器 +/motd 服务器地址 临时查询(不改变默认设置) +/motd set 服务器地址 设置本群服务器(机器人管理员) +/motd unset 清除本群设置(机器人管理员) +/motd history [服务器地址] 查看最近 24 小时玩家波动 +/motd help 查看帮助 +别名:/mc、/mcstatus;设置、清除、取消、波动、趋势也可使用。 +服务器地址示例:mc.example.com 或 mc.example.com:25565 +每张状态卡自带 24 小时波动图;首次使用从当前时刻开始积累。""" + + +class MotdPlugin(Star): + def __init__(self, context: Context, config: AstrBotConfig): + super().__init__(context) + self.config = config + self.data_dir = StarTools.get_data_dir("astrbot_plugin_motd") + self.store = MotdStore(self.data_dir / "motd.db") + self.api = MinecraftServerAPI(config) + self._ready = False + self._init_lock = asyncio.Lock() + self.monitor = PlayerMonitor( + self.api, + self.store, + interval=max(60, int(config.get("sample_interval", 300))), + retention_hours=max(24, int(config.get("retention_hours", 48))), + enabled=bool(config.get("history_enabled", True)), + addresses=[ + normalize_address(a) for a in config.get("monitor_servers", []) if a.strip() + ], + ) + + async def initialize(self): + async with self._init_lock: + if self._ready: + return + await self.store.initialize() + self.monitor.start() + self._ready = True + + @staticmethod + def _scope(event: AstrMessageEvent) -> str: + # Official QQ uses group openids, which differ from old OneBot numeric group IDs. + # Include the adapter instance to prevent collisions between bots/platforms. + group = event.get_group_id() + if group: + return json.dumps([event.get_platform_id(), "group", group], ensure_ascii=False) + return event.unified_msg_origin + + def _is_admin(self, event): + return event.is_admin() or str(event.get_sender_id()) in { + str(value) for value in self.config.get("admin_ids", []) + } + + @filter.command("motd", alias={"mc", "mcstatus"}) + async def motd(self, event: AstrMessageEvent, action: str = "", address: str = ""): + """查询 Minecraft 状态、设置群默认服务器,以及查看 24 小时玩家波动图。""" + try: + await self.initialize() + await self._handle(event, action, address) + except ValueError as exc: + await event.send(event.plain_result(f"❌ {exc}")) + except Exception: + logger.exception("MOTD 插件处理失败") + await event.send( + event.plain_result("❌ MOTD 处理失败,请稍后重试或查看 AstrBot 日志。") + ) + finally: + event.stop_event() + + async def _handle(self, event, action, address): + action = action.strip() + verb = action.lower() + scope = self._scope(event) + if verb in {"help", "帮助"}: + await event.send(event.plain_result(HELP)) + return + if verb in {"set", "设置", "unset", "clear", "清除", "取消"}: + if not self._is_admin(event): + await event.send( + event.plain_result("❌ 只有机器人管理员可以设置或清除本群 MOTD 服务器。") + ) + return + if not event.get_group_id(): + await event.send( + event.plain_result( + "⚠️ 请在群内设置或清除默认服务器;私聊可使用 /motd 服务器地址。" + ) + ) + return + if verb in {"set", "设置"}: + if not address: + raise ValueError("格式: /motd set 服务器地址") + address = normalize_address(address) + await self.store.set_binding(scope, address, event.get_sender_id()) + await event.send(event.plain_result(f"✅ 已将本群 MOTD 服务器设为: {address}")) + await self._query_and_send(event, address) + else: + if address: + raise ValueError("格式: /motd unset") + await self.store.clear_binding(scope) + await event.send(event.plain_result("✅ 已清除本群 MOTD 服务器设置。")) + return + if verb in {"history", "chart", "波动", "趋势", "历史"}: + target = address or await self.store.get_binding(scope) + else: + if address: + raise ValueError("格式: /motd 服务器地址;查看帮助: /motd help") + target = action or await self.store.get_binding(scope) + if not target: + await event.send( + event.plain_result( + "⚠️ 本群还没有设置 MOTD 服务器。\n管理员请使用: /motd set 服务器地址\n" + "也可以临时查询: /motd 服务器地址" + ) + ) + return + await self._query_and_send(event, normalize_address(target)) + + async def _query_and_send(self, event, address): + await self.store.track(address) + await event.send(event.plain_result(f"🔍 正在查询 {address} ...")) + data = await self.monitor.query(address) + now = int(time.time()) + history = await self.store.history(address, now) + if data is None: + # Keep the previous history visible even when the current query failed. + data = {"address": address, "online": False, "query_failed": True} + path = self.data_dir / f"card-{uuid.uuid4().hex}.png" + try: + image_bytes = await asyncio.to_thread( + render_motd_card, + data, + str(self.config.get("bot_name", "xiaohuicat")), + history, + now, + self.monitor.interval, + self.monitor.enabled, + str(self.config.get("font_path", "")), + ) + await asyncio.to_thread(path.write_bytes, image_bytes) + # Await the adapter send so upload errors can use the original text fallback. + await event.send(event.image_result(str(path.resolve()))) + except Exception: + logger.exception("MOTD 图片生成或发送失败: %s", address) + text = self.api.format_server_info(None if data.get("query_failed") else data) + counts = [p["players"] for p in history if p["players"] is not None] + if counts: + text += ( + f"\n24小时采样: {len(counts)} 次,人数最低 {min(counts)},最高 {max(counts)}" + ) + else: + text += "\n24小时波动: 暂无成功采样,正在积累历史。" + await event.send(event.plain_result(text)) + finally: + with contextlib.suppress(OSError): + path.unlink(missing_ok=True) + + async def terminate(self): + await self.monitor.close() diff --git a/metadata.yaml b/metadata.yaml new file mode 100644 index 0000000..361639a --- /dev/null +++ b/metadata.yaml @@ -0,0 +1,11 @@ +name: astrbot_plugin_motd +display_name: Minecraft MOTD 与玩家波动 +desc: Minecraft Java 服务器状态图片、群默认服务器、真实 Ping、玩家名单和最近 24 小时人数波动图。 +version: v1.0.0 +author: itxiaohui +support_platforms: + - qq_official + - qq_official_webhook + - aiocqhttp +astrbot_version: ">=4.16,<5" +repo: "https://github.com/itxiaohui66/astrbot_plugin_motd" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5916b6d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,15 @@ +[tool.ruff] +target-version = "py310" +line-length = 100 +extend-exclude = [".dev", "dist"] + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] + +[tool.ruff.lint.per-file-ignores] +"tools/preview.py" = ["E402"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] +pythonpath = ["."] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..2e91335 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,4 @@ +-r requirements.txt +pytest>=8,<10 +pytest-asyncio>=0.24,<2 +ruff>=0.9,<1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3769912 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +httpx>=0.27,<1 +Pillow>=10.4,<13 +mcstatus>=12,<15 diff --git a/services/__init__.py b/services/__init__.py new file mode 100644 index 0000000..15c1919 --- /dev/null +++ b/services/__init__.py @@ -0,0 +1 @@ +"""MOTD 查询、存储和图片服务。""" diff --git a/services/address.py b/services/address.py new file mode 100644 index 0000000..de7a479 --- /dev/null +++ b/services/address.py @@ -0,0 +1,31 @@ +"""Validate Minecraft addresses without changing implicit SRV semantics.""" + +import ipaddress +import re + +LABEL = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$") + + +def normalize_address(value: str) -> str: + value = value.strip().lower() + if not value or len(value) > 259 or "/" in value: + raise ValueError("服务器地址格式不正确。请输入域名或 IP,可附带 :端口。") + # Brackets make IPv6 + port unambiguous. + if value.startswith("["): + match = re.fullmatch(r"\[([^]]+)\](?::([0-9]{1,5}))?", value) + if not match: + raise ValueError("IPv6 地址请使用 [IPv6]:端口 格式。") + try: + ipaddress.IPv6Address(match[1]) + except ValueError as exc: + raise ValueError("IPv6 地址格式不正确。") from exc + port = match[2] + else: + host, separator, port = value.partition(":") + if len(host) > 253 or not all(LABEL.fullmatch(p) for p in host.split(".")): + raise ValueError("服务器地址格式不正确。") + if separator and (not port.isascii() or not port.isdigit()): + raise ValueError("端口必须是 1 到 65535 的整数。") + if port and not 1 <= int(port) <= 65535: + raise ValueError("端口必须是 1 到 65535 的整数。") + return value diff --git a/services/mc_api.py b/services/mc_api.py new file mode 100644 index 0000000..ae15cb0 --- /dev/null +++ b/services/mc_api.py @@ -0,0 +1,313 @@ +"""Minecraft Java 直连查询、真实 Ping 和原项目公开 API 备用服务。""" + +import asyncio +import logging +import struct +import time +from collections import OrderedDict +from urllib.parse import quote + +import httpx +from mcstatus import JavaServer + +logger = logging.getLogger("qqbot.mc_api") + + +class MinecraftServerAPI: + """Minecraft 服务器状态查询客户端""" + + def __init__(self, config: dict): + mc_cfg = config.get("mc_status", config) + self.api_url: str = mc_cfg.get("api_url", "https://api.mcsrvstat.us/2/{address}") + self.timeout: float = mc_cfg.get("request_timeout", 10) + self.ping_timeout: float = mc_cfg.get("ping_timeout", 4) + self.default_port: int = mc_cfg.get("default_port", 25565) + self._metadata = OrderedDict() + + async def query(self, address: str) -> dict | None: + """Prefer uncached Java status for player history; retain the original public API fallback.""" + + async def direct(): + server = await JavaServer.async_lookup(address, timeout=self.ping_timeout) + status = await server.async_status(tries=1) + raw = status.raw + sample = raw.get("players", {}).get("sample", []) or [] + return { + "online": True, + "address": address, + "hostname": "", + "ip": server.address.host, + "port": server.address.port, + "version": status.version.name, + "motd": status.motd.to_plain(), + "players_online": status.players.online, + "players_max": status.players.max, + "player_list": [ + str(p.get("name", "")) for p in sample if isinstance(p, dict) and p.get("name") + ], + "latency_ms": round(status.latency, 1), + "software": raw.get("software", ""), + "plugins": raw.get("plugins", {}), + "icon": raw.get("favicon", ""), + "source": "direct", + } + + try: + data = await asyncio.wait_for(direct(), timeout=self.ping_timeout + 2) + except Exception as exc: + logger.debug("MC 直连失败,使用原公开 API %s: %s", address, exc) + data = await self._query_api(address) + if data is not None: + data["source"] = "api" + return data + # Java status does not normally expose software/plugin names. Preserve the + # old API's extra fields while NEVER replacing direct player counts or RTT. + cached = self._metadata.get(address) + if not cached or time.monotonic() - cached[0] >= 3600: + extra = await self._query_api(address, measure_latency=False) + self._metadata[address] = (time.monotonic(), extra) + self._metadata.move_to_end(address) + while len(self._metadata) > 128: + self._metadata.popitem(last=False) + else: + extra = cached[1] + if extra and extra.get("online"): + for key in ("hostname", "software", "plugins", "icon", "player_list"): + if not data.get(key) and extra.get(key): + data[key] = extra[key] + if key == "player_list": + data["player_list_cached"] = True + return data + + @staticmethod + def _encode_varint(value: int) -> bytes: + value &= 0xFFFFFFFF + encoded = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + encoded.append(byte | (0x80 if value else 0)) + if not value: + return bytes(encoded) + + @classmethod + def _encode_string(cls, value: str) -> bytes: + raw = value.encode("utf-8") + return cls._encode_varint(len(raw)) + raw + + @staticmethod + async def _read_varint(reader: asyncio.StreamReader) -> int: + value = 0 + for position in range(5): + byte = (await reader.readexactly(1))[0] + value |= (byte & 0x7F) << (7 * position) + if not byte & 0x80: + return value + raise ValueError("Minecraft VarInt 过长") + + async def _measure_minecraft_latency( + self, connect_host: str, port: int, handshake_host: str, protocol: int + ) -> float | None: + """执行 Minecraft Java 状态握手与 ping/pong,返回真实 RTT。""" + + async def probe() -> float: + reader, writer = await asyncio.open_connection(connect_host, port) + try: + handshake = ( + self._encode_varint(0) + + self._encode_varint(protocol) + + self._encode_string(handshake_host) + + struct.pack(">H", port) + + self._encode_varint(1) + ) + writer.write(self._encode_varint(len(handshake)) + handshake) + writer.write(b"\x01\x00") # status request: length=1, packet id=0 + await writer.drain() + + packet_length = await self._read_varint(reader) + if not 1 <= packet_length <= 2_097_152: + raise ValueError("Minecraft 状态响应大小超出限制") + if await self._read_varint(reader) != 0: + raise ValueError("非法的 Minecraft 状态响应") + json_length = await self._read_varint(reader) + if not 0 <= json_length <= packet_length: + raise ValueError("非法的 Minecraft JSON 长度") + await reader.readexactly(json_length) + + payload = int(time.time_ns() // 1_000_000) + ping_packet = self._encode_varint(1) + struct.pack(">q", payload) + started = time.perf_counter() + writer.write(self._encode_varint(len(ping_packet)) + ping_packet) + await writer.drain() + if await self._read_varint(reader) != 9: + raise ValueError("非法的 Minecraft pong 长度") + if await self._read_varint(reader) != 1: + raise ValueError("非法的 Minecraft pong 响应") + if await reader.readexactly(8) != struct.pack(">q", payload): + raise ValueError("Minecraft pong 校验失败") + return round((time.perf_counter() - started) * 1000, 1) + finally: + writer.close() + try: + await writer.wait_closed() + except Exception: + pass + + try: + return await asyncio.wait_for(probe(), timeout=self.ping_timeout) + except Exception as exc: + logger.warning("Minecraft Ping 测量失败 %s:%s: %s", connect_host, port, exc) + return None + + async def _query_api(self, address: str, measure_latency: bool = True) -> dict | None: + """ + 查询 Minecraft 服务器状态 + + Args: + address: 服务器地址,如 "mc.hypixel.net" 或 "mc.example.com:25565" + + Returns: + 服务器信息字典,失败返回 None + """ + # 不要给纯域名强制补 :25565。查询服务会先解析 + # _minecraft._tcp SRV 记录;只有用户显式填写端口时才固定端口。 + url = self.api_url.format(address=quote(address, safe="")) + + try: + async with httpx.AsyncClient(timeout=self.timeout) as client: + response = await client.get(url) + + if response.status_code != 200: + logger.warning(f"MC服务器查询失败: {address} HTTP {response.status_code}") + return None + + data = response.json() + + if not data.get("online", False): + return { + "online": False, + "address": address, + "latency_ms": None, + } + + # 提取 MOTD 纯文本 + motd_text = "" + motd = data.get("motd", {}) + if isinstance(motd, dict): + motd_text = " | ".join(motd.get("clean", [])) + elif isinstance(motd, str): + motd_text = motd + + players = data.get("players", {}) + player_list = [] + for player in players.get("list", []) or []: + if isinstance(player, dict): + name = player.get("name") or player.get("username") or "" + else: + name = str(player) + name = name.strip() + if name: + player_list.append(name) + resolved_ip = str(data.get("ip") or "") + resolved_port = int(data.get("port") or self.default_port) + protocol = int(data.get("protocol") or 47) + handshake_host = address.rsplit(":", 1)[0] if ":" in address else address + latency_ms = None + if resolved_ip and measure_latency: + latency_ms = await self._measure_minecraft_latency( + resolved_ip, resolved_port, handshake_host, protocol + ) + return { + "online": True, + "address": address, + "hostname": data.get("hostname", ""), + "ip": data.get("ip", ""), + "port": resolved_port, + "version": data.get("version", "未知"), + "motd": motd_text, + "players_online": players.get("online", 0), + "players_max": players.get("max", 0), + "player_list": player_list, + "latency_ms": latency_ms, + "software": data.get("software", ""), + "plugins": data.get("plugins", {}), + "icon": data.get("icon", ""), + } + + except httpx.TimeoutException: + logger.error(f"MC服务器查询超时: {address}") + return None + except Exception as e: + logger.error(f"MC服务器查询失败 ({address}): {e}") + return None + + def format_server_info(self, data: dict | None) -> str: + """格式化服务器信息为文本""" + if not data: + return "❌ 无法查询该服务器,请检查地址是否正确。" + + if not data.get("online", False): + addr = data.get("address", "未知服务器") + return f"⚠️ 服务器离线\n🖥️ 地址: {addr}" + + # 在线服务器 + lines = [ + "🟢 服务器在线", + ] + + if data.get("hostname"): + lines.append(f"🏷️ 名称: {data['hostname']}") + + addr = data.get("address", "") + if addr: + lines.append(f"🖥️ 地址: {addr}") + + lines.append(f"📦 版本: {data.get('version', '未知')}") + + if data.get("software"): + lines.append(f"🔧 服务端: {data['software']}") + + motd = data.get("motd", "") + if motd: + # 限制标语长度 + if len(motd) > 200: + motd = motd[:200] + "..." + lines.append(f"📝 标语: {motd}") + + players_online = data.get("players_online", 0) + players_max = data.get("players_max", 0) + # 玩家数进度条 + if players_max > 0: + bar_len = 10 + ratio = min(players_online / players_max, 1.0) + filled = int(bar_len * ratio) + bar = "█" * filled + "░" * (bar_len - filled) + lines.append(f"👥 在线: {players_online}/{players_max} [{bar}]") + else: + lines.append(f"👥 在线: {players_online}") + + latency = data.get("latency_ms") + lines.append(f"📡 MC Ping: {latency}ms" if latency is not None else "📡 MC Ping: 未提供") + + # 如果安装了插件,显示数量 + plugins = data.get("plugins", {}) + if isinstance(plugins, dict) and plugins.get("names"): + plug_count = len(plugins["names"]) + lines.append(f"🔌 插件: {plug_count} 个") + + player_list = data.get("player_list") or [] + if player_list: + lines.append( + f"👤 已公开玩家({len(player_list)}/{players_online}): " + + "、".join(player_list)[:400] + ) + elif players_online: + lines.append("👤 服务器未公开玩家名单") + else: + lines.append("👤 暂无玩家在线") + if data.get("source") == "api": + lines.append("数据来源: 公开 API(可能有缓存)") + if data.get("player_list_cached"): + lines.append("玩家名单来源: API 缓存样本") + + return "\n".join(lines) diff --git a/services/monitor.py b/services/monitor.py new file mode 100644 index 0000000..3cb9aa9 --- /dev/null +++ b/services/monitor.py @@ -0,0 +1,78 @@ +"""Shared query cache and bounded background sampling, with clean cancellation.""" + +import asyncio +import logging +import time +from collections import OrderedDict + +logger = logging.getLogger(__name__) + + +class PlayerMonitor: + def __init__(self, api, store, interval=300, retention_hours=48, enabled=True, addresses=()): + self.api, self.store = api, store + self.interval, self.retention_hours, self.enabled = interval, retention_hours, enabled + self.addresses = set(addresses) + self._semaphore = asyncio.Semaphore(4) + self._cache = OrderedDict() + self._pending = {} + self._task = None + + async def query(self, address: str): + cached = self._cache.get(address) + if cached and time.monotonic() - cached[0] < 15: + return cached[1] + # Concurrent requests for the same server share one query and one sample. + if address not in self._pending: + self._pending[address] = asyncio.create_task(self._fetch(address)) + task = self._pending[address] + try: + return await asyncio.shield(task) + finally: + if task.done() and self._pending.get(address) is task: + self._pending.pop(address, None) + + async def _fetch(self, address): + async with self._semaphore: + try: + data = await self.api.query(address) + except Exception: + logger.exception("MOTD 查询异常: %s", address) + data = None + await self.store.record(address, data) + self._cache[address] = (time.monotonic(), data) + self._cache.move_to_end(address) + while len(self._cache) > 128: + self._cache.popitem(last=False) + return data + + def start(self): + if self.enabled and self._task is None: + self._task = asyncio.create_task(self._loop(), name="motd-player-monitor") + + async def sample_once(self): + addresses = set(await self.store.monitored_addresses()) | self.addresses + results = await asyncio.gather(*(self.query(a) for a in addresses), return_exceptions=True) + for address, result in zip(addresses, results): + if isinstance(result, Exception): + logger.error("MOTD 采样失败 %s: %s", address, result) + await self.store.prune(self.retention_hours) + + async def _loop(self): + while True: + started = time.monotonic() + try: + await self.sample_once() + except Exception: + logger.exception("MOTD 后台采样异常") + await asyncio.sleep(max(1, self.interval - (time.monotonic() - started))) + + async def close(self): + tasks = list(self._pending.values()) + if self._task: + tasks.append(self._task) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + self._pending.clear() + self._task = None diff --git a/services/motd_card.py b/services/motd_card.py new file mode 100644 index 0000000..57dab69 --- /dev/null +++ b/services/motd_card.py @@ -0,0 +1,422 @@ +"""Minecraft MOTD 图片卡片渲染器。""" + +from __future__ import annotations + +import base64 +import hashlib +import html +import io +import math +import re +import time +from datetime import datetime, timedelta, timezone +from functools import lru_cache +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont + +CARD_WIDTH = 1200 +CARD_HEIGHT = 1080 +CHINA_TIME = timezone(timedelta(hours=8)) + + +@lru_cache(maxsize=64) +def _load_font( + size: int, bold: bool = False, font_path: str = "" +) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: + """优先使用服务器上的中文字体,兼容 Windows 本地预览。""" + names = ( + [ + "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc", + "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", + "C:/Windows/Fonts/msyhbd.ttc", + "C:/Windows/Fonts/simhei.ttf", + ] + if bold + else [ + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", + "C:/Windows/Fonts/msyh.ttc", + "C:/Windows/Fonts/simsun.ttc", + ] + ) + for name in ([font_path] if font_path else []) + names: + if Path(name).exists(): + return ImageFont.truetype(name, size=size) + try: + return ImageFont.truetype("DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf", size=size) + except OSError: + return ImageFont.load_default() + + +def _rounded_panel( + draw: ImageDraw.ImageDraw, + box: tuple[int, int, int, int], + fill: tuple[int, int, int, int], + outline: tuple[int, int, int, int] | None = None, + radius: int = 22, +) -> None: + draw.rounded_rectangle(box, radius=radius, fill=fill, outline=outline, width=2) + + +def _draw_pixel_background(image: Image.Image, seed_text: str) -> None: + draw = ImageDraw.Draw(image, "RGBA") + top = (12, 23, 18) + bottom = (22, 49, 34) + for y in range(CARD_HEIGHT): + ratio = y / max(CARD_HEIGHT - 1, 1) + color = tuple(int(top[i] + (bottom[i] - top[i]) * ratio) for i in range(3)) + draw.line((0, y, CARD_WIDTH, y), fill=(*color, 255)) + + digest = hashlib.sha256(seed_text.encode("utf-8")).digest() + palette = [(17, 39, 26, 255), (20, 46, 29, 255), (15, 34, 24, 255)] + for index in range(34): + x = (digest[index % len(digest)] * 47 + index * 113) % CARD_WIDTH + y = (digest[(index + 9) % len(digest)] * 31 + index * 71) % CARD_HEIGHT + size = 24 + digest[(index + 17) % len(digest)] % 64 + draw.rectangle((x, y, x + size, y + size), fill=palette[index % len(palette)]) + + +def _decode_server_icon(icon_value: str) -> Image.Image | None: + if not icon_value: + return None + if len(icon_value) > 1_000_000: + return None + try: + encoded = icon_value.split(",", 1)[1] if "," in icon_value else icon_value + source = Image.open(io.BytesIO(base64.b64decode(encoded))) + if source.width > 512 or source.height > 512: + return None + icon = source.convert("RGBA") + return icon.resize((128, 128), Image.Resampling.NEAREST) + except Exception: + return None + + +def _draw_creeper_icon(image: Image.Image, box: tuple[int, int, int, int], seed_text: str) -> None: + """服务器没有图标时,绘制像素风苦力怕头像。""" + x1, y1, x2, y2 = box + size = x2 - x1 + cell = max(size // 8, 1) + draw = ImageDraw.Draw(image, "RGBA") + digest = hashlib.md5(seed_text.encode("utf-8")).digest() + greens = [(72, 160, 72, 255), (83, 177, 79, 255), (55, 139, 65, 255), (101, 188, 88, 255)] + for row in range(8): + for col in range(8): + color = greens[digest[(row * 8 + col) % len(digest)] % len(greens)] + draw.rectangle( + (x1 + col * cell, y1 + row * cell, x1 + (col + 1) * cell, y1 + (row + 1) * cell), + fill=color, + ) + dark = (15, 31, 22, 255) + for col, row, width, height in ( + (1, 2, 2, 2), + (5, 2, 2, 2), + (3, 4, 2, 2), + (2, 5, 4, 2), + (2, 7, 1, 1), + (5, 7, 1, 1), + ): + draw.rectangle( + ( + x1 + col * cell, + y1 + row * cell, + x1 + (col + width) * cell, + y1 + (row + height) * cell, + ), + fill=dark, + ) + + +def _ellipsize(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> str: + text = str(text) + if draw.textlength(text, font=font) <= max_width: + return text + suffix = "..." + while text and draw.textlength(text + suffix, font=font) > max_width: + text = text[:-1] + return text + suffix + + +def _wrap_text( + draw: ImageDraw.ImageDraw, text: str, font, max_width: int, max_lines: int = 2 +) -> list[str]: + clean = ( + html.unescape(re.sub(r"§.", "", str(text))).replace("\r", " ").replace("\n", " ").strip() + ) + if not clean: + return [] + lines: list[str] = [] + current = "" + for char in clean: + candidate = current + char + if current and draw.textlength(candidate, font=font) > max_width: + lines.append(current) + current = char + if len(lines) == max_lines: + break + else: + current = candidate + if len(lines) < max_lines and current: + lines.append(current) + consumed = "".join(lines) + if len(consumed) < len(clean) and lines: + lines[-1] = _ellipsize(draw, lines[-1] + "...", font, max_width) + return lines[:max_lines] + + +def render_motd_card( + data: dict, + bot_name: str = "xiaohuicat", + history: list[dict] | None = None, + now: int | None = None, + sample_interval: int = 300, + history_enabled: bool = True, + font_path: str = "", +) -> bytes: + """把 MOTD 查询结果渲染为 PNG 字节。""" + address = str(data.get("address") or "未知服务器") + online = bool(data.get("online")) + accent = (91, 214, 111, 255) if online else (241, 96, 89, 255) + accent_soft = (27, 67, 37, 255) if online else (76, 31, 29, 255) + + image = Image.new("RGBA", (CARD_WIDTH, CARD_HEIGHT), (12, 23, 18, 255)) + _draw_pixel_background(image, address) + draw = ImageDraw.Draw(image, "RGBA") + + # 主面板和左侧像素饰条 + _rounded_panel(draw, (44, 42, 1156, 1040), (8, 16, 13, 222), (77, 123, 90, 110), 30) + draw.rounded_rectangle((44, 42, 58, 1040), radius=7, fill=accent) + _rounded_panel(draw, (84, 100, 264, 280), (20, 38, 27, 245), (83, 147, 94, 155), 22) + + icon = _decode_server_icon(str(data.get("icon") or "")) + if icon is not None: + image.alpha_composite(icon, (110, 126)) + else: + _draw_creeper_icon(image, (110, 126, 238, 254), address) + + title_font = _load_font(25, bold=True, font_path=font_path) + address_font = _load_font(42, bold=True, font_path=font_path) + status_font = _load_font(28, bold=True, font_path=font_path) + label_font = _load_font(22, font_path=font_path) + value_font = _load_font(29, bold=True, font_path=font_path) + motd_font = _load_font(25, font_path=font_path) + footer_font = _load_font(19, font_path=font_path) + + draw.text((84, 66), "MINECRAFT SERVER STATUS", font=title_font, fill=(161, 196, 171, 255)) + shown_address = _ellipsize(draw, address, address_font, 790) + draw.text((298, 112), shown_address, font=address_font, fill=(239, 247, 241, 255)) + + status_text = ( + "查询失败" if data.get("query_failed") else ("服务器在线" if online else "服务器离线") + ) + status_width = int(draw.textlength(status_text, font=status_font)) + 58 + draw.rounded_rectangle( + (298, 176, 298 + status_width, 226), radius=25, fill=accent_soft, outline=accent, width=2 + ) + draw.ellipse((316, 193, 330, 207), fill=accent) + draw.text((342, 183), status_text, font=status_font, fill=accent) + details = " · ".join(str(data.get(k) or "") for k in ("hostname", "software") if data.get(k)) + plugins = data.get("plugins") + if isinstance(plugins, dict) and plugins.get("names"): + details += f" · 插件 {len(plugins['names'])} 个" + if details: + draw.text( + (298, 247), + _ellipsize(draw, details.strip(" ·"), label_font, 780), + font=label_font, + fill=(145, 171, 152, 255), + ) + + # 信息卡片 + latency = data.get("latency_ms") + latency_text = f"{latency} ms" if latency is not None else "未提供" + panels = [ + (84, 314, 392, 426, "游戏版本", str(data.get("version") or "未知")), + ( + 414, + 314, + 722, + 426, + "在线玩家", + f"{data.get('players_online', 0)} / {data.get('players_max', 0)}" + if online + else "- / -", + ), + (744, 314, 1072, 426, "MC PING", latency_text), + ] + for x1, y1, x2, y2, label, value in panels: + _rounded_panel(draw, (x1, y1, x2, y2), (19, 35, 27, 230), (65, 104, 76, 100), 18) + draw.text((x1 + 22, y1 + 16), label, font=label_font, fill=(145, 171, 152, 255)) + draw.text( + (x1 + 22, y1 + 52), + _ellipsize(draw, value, value_font, x2 - x1 - 44), + font=value_font, + fill=(237, 244, 239, 255), + ) + + # 玩家数进度条 + players_online = int(data.get("players_online") or 0) + players_max = int(data.get("players_max") or 0) + ratio = min(players_online / players_max, 1.0) if players_max > 0 and online else 0 + draw.rounded_rectangle((436, 404, 700, 414), radius=5, fill=(40, 61, 47, 255)) + if ratio > 0: + draw.rounded_rectangle((436, 404, 436 + int(264 * ratio), 414), radius=5, fill=accent) + + # MOTD + _rounded_panel(draw, (84, 452, 714, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18) + draw.text((106, 468), "MOTD", font=label_font, fill=(145, 171, 152, 255)) + motd = str(data.get("motd") or ("暂无服务器标语" if online else "无法连接到该服务器")) + for line_index, line in enumerate(_wrap_text(draw, motd, motd_font, 580, 2)): + draw.text((106, 500 + line_index * 32), line, font=motd_font, fill=(226, 236, 229, 255)) + + # 在线玩家名单(Minecraft 状态协议可能只返回部分样本) + _rounded_panel(draw, (736, 452, 1072, 568), (17, 31, 24, 230), (65, 104, 76, 90), 18) + player_list = [str(name) for name in (data.get("player_list") or []) if str(name).strip()] + if player_list: + public_count = len(player_list) + player_label = f"在线玩家(已公开 {public_count}/{players_online})" + if data.get("player_list_cached"): + player_label = "公开玩家(API 缓存样本)" + player_text = "、".join(player_list) + elif online and players_online > 0: + player_label = "在线玩家" + player_text = "服务器未公开玩家名单" + elif online: + player_label = "在线玩家" + player_text = "暂无玩家在线" + else: + player_label = "在线玩家" + player_text = "-" + draw.text( + (758, 468), + _ellipsize(draw, player_label, label_font, 292), + font=label_font, + fill=(145, 171, 152, 255), + ) + for line_index, line in enumerate(_wrap_text(draw, player_text, label_font, 290, 2)): + draw.text((758, 504 + line_index * 28), line, font=label_font, fill=(226, 236, 229, 255)) + + now = int(time.time()) if now is None else now + _draw_history(draw, history or [], now, sample_interval, history_enabled, font_path) + source = "公开 API(可能有缓存)" if data.get("source") == "api" else "Minecraft 直连" + if data.get("query_failed"): + source = "本次查询失败" + update_time = datetime.fromtimestamp(now, CHINA_TIME).strftime("%m-%d %H:%M") + footer = f"{bot_name} · itxiaohui · {source} · {update_time} (UTC+8)" + draw.text( + (84, 996), + _ellipsize(draw, footer, footer_font, 1010), + font=footer_font, + fill=(116, 145, 125, 255), + ) + + output = io.BytesIO() + image.convert("RGB").save(output, format="PNG", optimize=True) + return output.getvalue() + + +def history_segments(history: list[dict], now: int, interval: int) -> list[list[dict]]: + """Split at failures, offline responses, and missing samples instead of inventing a connecting line.""" + segments, current = [], [] + for point in sorted(history, key=lambda p: p["timestamp"]): + if not now - 86400 <= point["timestamp"] <= now: + continue + valid = point.get("online") == 1 and point.get("players") is not None + if not valid or ( + current and point["timestamp"] - current[-1]["timestamp"] > interval * 2.5 + ): + if current: + segments.append(current) + current = [] + if valid: + current.append(point) + if current: + segments.append(current) + return segments + + +def _draw_history(draw, history, now, interval, enabled, font_path): + _rounded_panel(draw, (84, 590, 1072, 974), (17, 31, 24, 230), (65, 104, 76, 90), 18) + title = _load_font(25, True, font_path) + font = _load_font(19, font_path=font_path) + small = _load_font(17, font_path=font_path) + draw.text((106, 606), "最近 24 小时 · 在线玩家波动", font=title, fill=(226, 236, 229)) + history = sorted( + (p for p in history if now - 86400 <= p["timestamp"] <= now), key=lambda p: p["timestamp"] + ) + counts = [ + p["players"] for p in history if p.get("online") == 1 and p.get("players") is not None + ] + if counts: + summary = f"最低 {min(counts)} / 最高 {max(counts)} / 采样均值 {sum(counts) / len(counts):.1f}" + else: + summary = "暂无成功的人数采样" + draw.text((106, 644), summary, font=font, fill=(145, 171, 152)) + # Fixed rolling 24h axis: partial histories only occupy their actual time range. + left, right, top, bottom = 162, 1034, 694, 874 + maximum = max(counts, default=1) + step = max(1, math.ceil(maximum / 4)) + ceiling = step * 4 + for index in range(5): + y = bottom - index * (bottom - top) / 4 + draw.line((left, y, right, y), fill=(48, 70, 55), width=1) + label = str(index * step) + draw.text( + (left - 14 - draw.textlength(label, font=small), y - 12), + label, + font=small, + fill=(116, 145, 125), + ) + for index in range(5): + x = left + index * (right - left) / 4 + draw.line((x, top, x, bottom), fill=(32, 51, 39), width=1) + stamp = datetime.fromtimestamp(now - 86400 + index * 21600, CHINA_TIME).strftime("%H:%M") + draw.text( + (x - draw.textlength(stamp, font=small) / 2, 883), + stamp, + font=small, + fill=(116, 145, 125), + ) + + def coordinates(p): + return ( + left + (p["timestamp"] - (now - 86400)) / 86400 * (right - left), + bottom - p["players"] / ceiling * (bottom - top), + ) + + for segment in history_segments(history, now, interval): + points = [coordinates(p) for p in segment] + if len(points) > 1: + draw.line(points, fill=(91, 214, 111), width=3) + for x, y in points: + draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(123, 238, 141)) + for point in history: + if point.get("online") != 1: + x = left + (point["timestamp"] - (now - 86400)) / 86400 * (right - left) + color = (241, 96, 89) if point.get("online") == 0 else (212, 175, 99) + draw.line((x, bottom - 6, x, bottom), fill=color, width=2) + if not counts: + text = "开始采集后将在这里显示曲线" if not history else "服务器离线或查询失败,暂无人数曲线" + draw.text((left + 140, top + 70), text, font=font, fill=(145, 171, 152)) + if len(counts) == 1: + note = "仅有 1 个人数采样,继续运行后自动形成曲线" + else: + note = f"人数采样 {len(counts)} 次 · 间隔 {interval // 60} 分钟 · 红:离线 黄:失败 空白:无数据" + if not enabled: + note = "后台采样已关闭,仅记录手动查询 · 空白时段没有数据" + draw.text((106, 918), _ellipsize(draw, note, small, 936), font=small, fill=(116, 145, 125)) + if any(p.get("source") == "api" for p in history): + draw.text( + (106, 944), + "部分采样来自公开 API,人数可能有缓存延迟 · 时间 UTC+8", + font=small, + fill=(212, 175, 99), + ) + else: + draw.text( + (106, 944), + "从首次查询或绑定开始积累 · 重启后保留历史 · 时间 UTC+8", + font=small, + fill=(116, 145, 125), + ) diff --git a/services/storage.py b/services/storage.py new file mode 100644 index 0000000..5a82f68 --- /dev/null +++ b/services/storage.py @@ -0,0 +1,128 @@ +"""SQLite persistence outside the plugin checkout; every connection stays in a worker thread.""" + +import asyncio +import sqlite3 +import time +from pathlib import Path + + +class MotdStore: + def __init__(self, path: Path): + self.path = Path(path) + + def _run(self, operation): + self.path.parent.mkdir(parents=True, exist_ok=True) + with sqlite3.connect(self.path, timeout=15) as db: + db.row_factory = sqlite3.Row + return operation(db) + + async def initialize(self): + def create(db): + db.execute("PRAGMA journal_mode=WAL") + db.executescript(""" + CREATE TABLE IF NOT EXISTS bindings ( + scope TEXT PRIMARY KEY, address TEXT NOT NULL, + updated_by TEXT NOT NULL, updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS tracked ( + address TEXT PRIMARY KEY, touched_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS samples ( + address TEXT NOT NULL, timestamp INTEGER NOT NULL, + online INTEGER, players INTEGER, source TEXT NOT NULL, + PRIMARY KEY (address, timestamp) + ); + """) + + await asyncio.to_thread(self._run, create) + + async def get_binding(self, scope: str) -> str | None: + def query(db): + row = db.execute("SELECT address FROM bindings WHERE scope=?", (scope,)).fetchone() + return row[0] if row else None + + return await asyncio.to_thread(self._run, query) + + async def set_binding(self, scope: str, address: str, user: str): + await asyncio.to_thread( + self._run, + lambda db: ( + db.execute( + "INSERT OR REPLACE INTO bindings VALUES (?, ?, ?, ?)", + (scope, address, user, int(time.time())), + ).rowcount + ), + ) + + async def clear_binding(self, scope: str): + await asyncio.to_thread( + self._run, + lambda db: ( + db.execute( + "DELETE FROM bindings WHERE scope=?", + (scope,), + ).rowcount + ), + ) + + async def track(self, address: str, limit: int = 128): + def insert(db): + db.execute("INSERT OR REPLACE INTO tracked VALUES (?, ?)", (address, int(time.time()))) + db.execute( + """DELETE FROM tracked WHERE address IN ( + SELECT address FROM tracked ORDER BY touched_at DESC, address LIMIT -1 OFFSET ? + )""", + (limit,), + ) + + await asyncio.to_thread(self._run, insert) + + async def monitored_addresses(self, now: int | None = None) -> list[str]: + now = int(time.time()) if now is None else now + return await asyncio.to_thread( + self._run, + lambda db: [ + r[0] + for r in db.execute( + "SELECT address FROM bindings UNION SELECT address FROM tracked WHERE touched_at>=?", + (now - 86400,), + ) + ], + ) + + async def record(self, address: str, data: dict | None, timestamp: int | None = None): + timestamp = int(time.time()) if timestamp is None else timestamp + online = int(bool(data["online"])) if data is not None else None + players = int(data.get("players_online", 0)) if online else None + source = data.get("source", "api") if data else "error" + await asyncio.to_thread( + self._run, + lambda db: ( + db.execute( + "INSERT OR REPLACE INTO samples VALUES (?, ?, ?, ?, ?)", + (address, timestamp, online, players, source), + ).rowcount + ), + ) + + async def history(self, address: str, now: int | None = None) -> list[dict]: + now = int(time.time()) if now is None else now + return await asyncio.to_thread( + self._run, + lambda db: [ + dict(r) + for r in db.execute( + "SELECT * FROM samples WHERE address=? AND timestamp BETWEEN ? AND ? ORDER BY timestamp", + (address, now - 86400, now), + ) + ], + ) + + async def prune(self, retention_hours: int = 48): + now = int(time.time()) + + def clean(db): + db.execute("DELETE FROM samples WHERE timestamp= 0 + # Exercise the migrated fallback ping/pong path too. + latency = await api._measure_minecraft_latency("127.0.0.1", port, "127.0.0.1", 767) + assert latency is not None and latency >= 0 + finally: + server.close() + await server.wait_closed() + + +async def test_api_fallback_and_player_normalization(monkeypatch): + async def unavailable(*args, **kwargs): + raise OSError("direct unavailable") + + monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", unavailable) + real_client = httpx.AsyncClient + seen = [] + + def response(request): + seen.append(str(request.url)) + return httpx.Response( + 200, + json={ + "online": True, + "version": "Paper 1.21", + "port": 25565, + "motd": {"clean": ["First", "Second"]}, + "players": { + "online": 5, + "max": 20, + "list": ["Steve", {"name": "Alex"}, {"username": "Third"}], + }, + "plugins": {"names": ["Example"]}, + "software": "Paper", + }, + ) + + monkeypatch.setattr( + "services.mc_api.httpx.AsyncClient", + lambda **kwargs: real_client(transport=httpx.MockTransport(response), **kwargs), + ) + api = MinecraftServerAPI({}) + data = await api.query("mc.example.com") + assert data["source"] == "api" and data["motd"] == "First | Second" + assert data["player_list"] == ["Steve", "Alex", "Third"] + assert seen == ["https://api.mcsrvstat.us/2/mc.example.com"] # no forced :25565 + text = api.format_server_info(data) + assert "Steve" in text and "插件: 1 个" in text and "缓存" in text + + +async def test_api_offline_different_from_transport_error(monkeypatch): + async def unavailable(*args, **kwargs): + raise OSError("down") + + monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", unavailable) + real_client = httpx.AsyncClient + status = [200] + monkeypatch.setattr( + "services.mc_api.httpx.AsyncClient", + lambda **kwargs: real_client( + transport=httpx.MockTransport( + lambda req: httpx.Response(status[0], json={"online": False}) + ), + **kwargs, + ), + ) + api = MinecraftServerAPI({}) + assert (await api.query("a.test"))["online"] is False + status[0] = 503 + assert await api.query("a.test") is None + + +async def test_srv_lookup_input_is_not_changed(monkeypatch): + seen = [] + + async def status(**kwargs): + return SimpleNamespace( + raw={}, + version=SimpleNamespace(name="1.21"), + motd=SimpleNamespace(to_plain=lambda: "Hi"), + players=SimpleNamespace(online=0, max=20), + latency=5, + ) + + async def lookup(address, **kwargs): + seen.append(address) + return SimpleNamespace( + address=SimpleNamespace(host="srv-target.test", port=25570), async_status=status + ) + + monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", lookup) + api = MinecraftServerAPI({}) + + async def no_extra(*args, **kwargs): + return None + + api._query_api = no_extra + data = await api.query("mc.example.com") + assert seen == ["mc.example.com"] and data["port"] == 25570 diff --git a/tests/test_plugin.py b/tests/test_plugin.py new file mode 100644 index 0000000..d63a1d1 --- /dev/null +++ b/tests/test_plugin.py @@ -0,0 +1,148 @@ +"""Framework-free adapter contract tests; the actual QQ account needs deployment verification.""" + +import importlib.util +import logging +import sys +import types +from pathlib import Path + +import pytest + + +class Event: + def __init__(self, platform="qq-main", group="group-openid", admin=False, image_error=False): + self.platform, self.group, self.admin = platform, group, admin + self.image_error = image_error + self.unified_msg_origin = f"{platform}:private:user" + self.messages = [] + self.stopped = False + + def get_group_id(self): + return self.group + + def get_platform_id(self): + return self.platform + + def get_sender_id(self): + return "user-openid" + + def is_admin(self): + return self.admin + + def plain_result(self, text): + return ("text", text) + + def image_result(self, path): + return ("image", path) + + def stop_event(self): + self.stopped = True + + async def send(self, result): + if result[0] == "image": + assert Path(result[1]).is_file() + if self.image_error: + raise RuntimeError("QQ upload failed") + self.messages.append(result) + + +@pytest.fixture +def plugin_class(monkeypatch, tmp_path): + class Star: + def __init__(self, context): + self.context = context + + def command(name, alias): + def decorate(func): + func.registered_aliases = alias + return func + + return decorate + + modules = { + "astrbot": types.ModuleType("astrbot"), + "astrbot.api": types.ModuleType("astrbot.api"), + "astrbot.api.event": types.ModuleType("astrbot.api.event"), + "astrbot.api.star": types.ModuleType("astrbot.api.star"), + } + modules["astrbot.api"].AstrBotConfig = dict + modules["astrbot.api"].logger = logging.getLogger("test") + modules["astrbot.api.event"].AstrMessageEvent = Event + modules["astrbot.api.event"].filter = types.SimpleNamespace(command=command) + modules["astrbot.api.star"].Star = Star + modules["astrbot.api.star"].Context = object + modules["astrbot.api.star"].StarTools = types.SimpleNamespace( + get_data_dir=lambda name: tmp_path + ) + for name, module in modules.items(): + monkeypatch.setitem(sys.modules, name, module) + root = Path(__file__).resolve().parents[1] + package = types.ModuleType("plugin_under_test") + package.__path__ = [str(root)] + monkeypatch.setitem(sys.modules, "plugin_under_test", package) + spec = importlib.util.spec_from_file_location("plugin_under_test.main", root / "main.py") + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + return module.MotdPlugin + + +async def test_permission_binding_scope_aliases_and_clear(plugin_class): + plugin = plugin_class(object(), {"history_enabled": False}) + + async def no_send(*args): + pass + + plugin._query_and_send = no_send + ordinary = Event() + await plugin.motd(ordinary, "set", "mc.example.com") + assert "管理员" in ordinary.messages[-1][1] + assert await plugin.store.get_binding(plugin._scope(ordinary)) is None + admin = Event(admin=True) + await plugin.motd(admin, "设置", "MC.Example.COM") + assert await plugin.store.get_binding(plugin._scope(admin)) == "mc.example.com" + assert await plugin.store.get_binding(plugin._scope(Event(platform="second-bot"))) is None + await plugin.motd(admin, "清除") + assert await plugin.store.get_binding(plugin._scope(admin)) is None + assert admin.stopped and plugin.motd.registered_aliases == {"mc", "mcstatus"} + await plugin.terminate() + + +async def test_query_image_fallback_and_file_cleanup(plugin_class, tmp_path): + plugin = plugin_class(object(), {"history_enabled": False}) + + async def query(address): + return { + "online": True, + "address": address, + "players_online": 5, + "players_max": 20, + "player_list": ["Alex"], + "source": "direct", + } + + plugin.api.query = query + event = Event(image_error=True) + await plugin.motd(event, "mc.example.com") + assert "Alex" in event.messages[-1][1] and "人数最低 5" in event.messages[-1][1] + assert not list(tmp_path.glob("card-*.png")) + success = Event() + await plugin.motd(success, "history", "mc.example.com") + assert success.messages[-1][0] == "image" + assert not list(tmp_path.glob("card-*.png")) + await plugin.terminate() + + +async def test_missing_default_invalid_and_private_setting(plugin_class): + plugin = plugin_class(object(), {"history_enabled": False}) + event = Event() + await plugin.motd(event) + assert "还没有设置" in event.messages[-1][1] + await plugin.motd(event, "https://bad") + assert "格式不正确" in event.messages[-1][1] + private = Event(group="", admin=True) + await plugin.motd(private, "set", "a.test") + assert "请在群内" in private.messages[-1][1] + await plugin.motd(event, "help") + assert "/mcstatus" in event.messages[-1][1] + await plugin.terminate() diff --git a/tests/test_render_address.py b/tests/test_render_address.py new file mode 100644 index 0000000..872f1ee --- /dev/null +++ b/tests/test_render_address.py @@ -0,0 +1,79 @@ +import io + +import pytest +from PIL import Image + +from services.address import normalize_address +from services.motd_card import history_segments, render_motd_card + + +@pytest.mark.parametrize( + "address", ["mc.example.com", "127.0.0.1:25565", "localhost", "[::1]:25565", "[2001:db8::1]"] +) +def test_valid_address(address): + assert normalize_address(" " + address.upper() + " ") == address + + +@pytest.mark.parametrize( + "address", + [ + "", + "https://a.test", + "a.test:0", + "a.test:65536", + "a.test:", + "../a", + "-a.test", + "a..test", + "[broken]:1", + "a.test:1", + "a.test;command", + ], +) +def test_invalid_address(address): + with pytest.raises(ValueError): + normalize_address(address) + + +def test_history_does_not_bridge_offline_errors_or_shutdown(): + points = [ + {"timestamp": stamp, "online": online, "players": players} + for stamp, online, players in [ + (100000, 1, 0), + (100300, 1, 2), + (100600, 0, None), + (100900, 1, 5), + (101200, None, None), + (101500, 1, 7), + (110000, 1, 10), + ] + ] + segments = history_segments(points, 110000, 300) + assert [[p["players"] for p in segment] for segment in segments] == [[0, 2], [5], [7], [10]] + + +@pytest.mark.parametrize( + "online,failed,history", + [ + (True, False, []), + (False, False, []), + (False, True, []), + (True, False, [{"timestamp": 100000, "online": 1, "players": 0}]), + ], +) +def test_card_handles_empty_history_offline_failure_and_zero(online, failed, history): + raw = render_motd_card( + { + "online": online, + "query_failed": failed, + "address": "mc.example.com", + "icon": "invalid-base64", + "motd": "中文标语 " * 100, + "players_online": 0, + "players_max": 0, + }, + history=history, + now=100000, + ) + image = Image.open(io.BytesIO(raw)) + assert image.format == "PNG" and image.size == (1200, 1080) diff --git a/tests/test_storage_monitor.py b/tests/test_storage_monitor.py new file mode 100644 index 0000000..1d0bf8a --- /dev/null +++ b/tests/test_storage_monitor.py @@ -0,0 +1,101 @@ +import asyncio + +from services.monitor import PlayerMonitor +from services.storage import MotdStore + + +async def test_binding_isolation_persistence_and_history_window(tmp_path): + path = tmp_path / "motd.db" + store = MotdStore(path) + await store.initialize() + await store.set_binding("bot-a:group-1", "one.test", "admin") + await store.set_binding("bot-b:group-1", "two.test", "admin") + await store.record( + "one.test", {"online": True, "players_online": 0, "source": "direct"}, 100000 + ) + await store.record("one.test", {"online": False}, 100300) + await store.record("one.test", None, 100600) + await store.record("one.test", {"online": True, "players_online": 9}, 1) + reloaded = MotdStore(path) + await reloaded.initialize() + assert await reloaded.get_binding("bot-a:group-1") == "one.test" + assert await reloaded.get_binding("bot-b:group-1") == "two.test" + assert [(p["online"], p["players"]) for p in await reloaded.history("one.test", 101000)] == [ + (1, 0), + (0, None), + (None, None), + ] + await reloaded.clear_binding("bot-a:group-1") + assert await reloaded.get_binding("bot-a:group-1") is None + assert await reloaded.get_binding("bot-b:group-1") == "two.test" + + +async def test_tracking_expiry_bindings_and_prune(tmp_path, monkeypatch): + monkeypatch.setattr("services.storage.time.time", lambda: 200000) + store = MotdStore(tmp_path / "motd.db") + await store.initialize() + await store.track("temporary.test") + await store.set_binding("a", "permanent.test", "admin") + assert set(await store.monitored_addresses(200001)) == {"temporary.test", "permanent.test"} + assert await store.monitored_addresses(286401) == ["permanent.test"] + await store.record("temporary.test", {"online": True, "players_online": 4}, 1) + await store.record("temporary.test", {"online": True, "players_online": 5}, 199999) + await store.prune(48) + assert len(await store.history("temporary.test", 200000)) == 1 + + +async def test_concurrent_queries_and_background_sampling(tmp_path): + class API: + calls = 0 + + async def query(self, address): + self.calls += 1 + await asyncio.sleep(0.02) + return {"online": True, "players_online": 3, "source": "direct"} + + store = MotdStore(tmp_path / "motd.db") + await store.initialize() + await store.set_binding("group-a", "same.test", "a") + await store.set_binding("group-b", "same.test", "a") + api = API() + monitor = PlayerMonitor(api, store, addresses=["extra.test"]) + result = await asyncio.gather(*(monitor.query("same.test") for _ in range(5))) + assert api.calls == 1 and all(p["players_online"] == 3 for p in result) + await monitor.sample_once() + assert api.calls == 2 # same.test cached, extra.test polled + assert len(await store.history("extra.test")) == 1 + monitor.start() + task = monitor._task + await monitor.close() + assert task.done() and not monitor._pending + + +async def test_api_exception_records_unknown_not_zero(tmp_path): + class API: + async def query(self, address): + raise OSError("network down") + + store = MotdStore(tmp_path / "motd.db") + await store.initialize() + monitor = PlayerMonitor(API(), store) + assert await monitor.query("a.test") is None + point = (await store.history("a.test"))[0] + assert point["players"] is None and point["online"] is None + + +async def test_cancellation_joins_inflight_queries(tmp_path): + started = asyncio.Event() + + class API: + async def query(self, address): + started.set() + await asyncio.Event().wait() + + store = MotdStore(tmp_path / "motd.db") + await store.initialize() + monitor = PlayerMonitor(API(), store) + request = asyncio.create_task(monitor.query("a.test")) + await started.wait() + await monitor.close() + results = await asyncio.gather(request, return_exceptions=True) + assert isinstance(results[0], asyncio.CancelledError) diff --git a/tools/package.py b/tools/package.py new file mode 100644 index 0000000..16e81de --- /dev/null +++ b/tools/package.py @@ -0,0 +1,35 @@ +"""Build an installable archive without local data, test stubs, or development downloads.""" + +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + target = ROOT / "dist" / "astrbot_plugin_motd-v1.0.0.zip" + target.parent.mkdir(exist_ok=True) + files = ( + [ + ROOT / n + for n in ( + "__init__.py", + "main.py", + "metadata.yaml", + "_conf_schema.json", + "requirements.txt", + "README.md", + "LICENSE", + ) + ] + + sorted((ROOT / "services").glob("*.py")) + + sorted((ROOT / "assets").glob("*.png")) + ) + with ZipFile(target, "w", ZIP_DEFLATED) as archive: + for path in files: + archive.write(path, "astrbot_plugin_motd/" + path.relative_to(ROOT).as_posix()) + print(target) + + +if __name__ == "__main__": + main() diff --git a/tools/preview.py b/tools/preview.py new file mode 100644 index 0000000..dbc04f9 --- /dev/null +++ b/tools/preview.py @@ -0,0 +1,52 @@ +"""Render synthetic examples: generated data is never written to the plugin database.""" + +import math +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from services.motd_card import render_motd_card + + +def main(): + now = int(time.time()) + history = [] + for i in range(289): + stamp = now - 86400 + i * 300 + players = max(0, int(45 + 25 * math.sin(i / 32) + 10 * math.sin(i / 7))) + history.append({"timestamp": stamp, "online": 1, "players": players, "source": "direct"}) + # Include a gap and downtime to verify broken curves. + history = [p for i, p in enumerate(history) if not 85 <= i < 100] + for point in history[165:175]: + point.update(online=0, players=None) + data = { + "online": True, + "address": "mc.example.com:25565", + "version": "1.21.1", + "motd": "欢迎来到栗子服务器!生存 · 建筑 · 冒险,和朋友一起探索方块世界", + "players_online": history[-1]["players"], + "players_max": 100, + "player_list": ["itxiaohui", "Steve", "Alex", "栗子玩家"], + "latency_ms": 32.6, + "software": "Paper", + "plugins": {"names": ["Example"]}, + "source": "direct", + } + folder = ROOT / "dist" / "previews" + folder.mkdir(parents=True, exist_ok=True) + examples = { + "24h": (data, history), + "first": (data, history[-1:]), + "offline": ({"online": False, "address": data["address"], "source": "api"}, history), + "failed": ({"online": False, "address": data["address"], "query_failed": True}, []), + } + for name, (status, points) in examples.items(): + path = folder / f"motd-{name}.png" + path.write_bytes(render_motd_card(status, "xiaohuicat · 演示数据", points, now)) + print(path) + + +if __name__ == "__main__": + main()