Add server chat slash commands for me and uptime

This commit is contained in:
Jage9
2026-02-27 04:33:54 -05:00
parent 10e7a01e73
commit 464d39f78b
9 changed files with 179 additions and 2 deletions

View File

@@ -280,6 +280,7 @@ class BroadcastChatMessagePacket(BasePacket):
senderId: str | None = None
senderNickname: str | None = None
system: bool = False
action: bool = False
class PongPacket(BasePacket):

View File

@@ -184,6 +184,7 @@ class SignalingServer:
self._clock_announce_task: asyncio.Task[None] | None = None
self._clock_top_of_hour_markers: dict[str, str] = {}
self._clock_alarm_markers: dict[str, str] = {}
self._started_at_monotonic = time.monotonic()
@staticmethod
def _resolve_server_version() -> str:
@@ -1572,6 +1573,81 @@ class SignalingServer:
AdminActionResultPacket(type="admin_action_result", ok=ok, action=action, message=message),
)
@staticmethod
def _format_duration(total_seconds: int) -> str:
"""Format a duration value as compact human-readable text."""
seconds = max(0, int(total_seconds))
days, remainder = divmod(seconds, 24 * 60 * 60)
hours, remainder = divmod(remainder, 60 * 60)
minutes, secs = divmod(remainder, 60)
parts: list[str] = []
if days:
parts.append(f"{days}d")
if hours:
parts.append(f"{hours}h")
if minutes:
parts.append(f"{minutes}m")
if secs or not parts:
parts.append(f"{secs}s")
return " ".join(parts)
def _format_uptime(self) -> str:
"""Return current server uptime text."""
elapsed_seconds = int(max(0.0, time.monotonic() - self._started_at_monotonic))
return self._format_duration(elapsed_seconds)
async def _handle_chat_command(self, client: ClientConnection, message: str) -> bool:
"""Handle slash commands in chat input; return True when handled."""
if not message.startswith("/"):
return False
command_line = message[1:]
command_token, separator, remainder = command_line.partition(" ")
command = command_token.casefold()
if command == "me":
if not separator or remainder == "":
await self._send(
client.websocket,
BroadcastChatMessagePacket(
type="chat_message",
message="Usage: /me <action>",
system=True,
),
)
return True
await self._broadcast(
BroadcastChatMessagePacket(
type="chat_message",
message=f"{client.nickname} {remainder}",
senderId=client.id,
senderNickname=client.nickname,
system=False,
action=True,
)
)
return True
if command == "up":
await self._send(
client.websocket,
BroadcastChatMessagePacket(
type="chat_message",
message=f"Server uptime: {self._format_uptime()}",
system=True,
),
)
return True
await self._send(
client.websocket,
BroadcastChatMessagePacket(
type="chat_message",
message=f"Unknown command: /{command_token}",
system=True,
),
)
return True
async def _handle_admin_packet(self, client: ClientConnection, packet: ClientPacket) -> bool:
"""Handle role/user administration packets with permission checks."""
@@ -2023,6 +2099,8 @@ class SignalingServer:
),
)
return
if await self._handle_chat_command(client, packet.message):
return
await self._broadcast(
BroadcastChatMessagePacket(
type="chat_message",

View File

@@ -413,3 +413,87 @@ async def test_update_position_rate_reject_sends_self_correction(monkeypatch: py
assert correction.id == "u1"
assert correction.x == 5
assert correction.y == 5
@pytest.mark.asyncio
async def test_chat_me_command_broadcasts_action(monkeypatch: pytest.MonkeyPatch) -> None:
server = SignalingServer("127.0.0.1", 8765, None, None)
ws = _fake_ws()
client = ClientConnection(websocket=ws, id="u1", nickname="Tester")
server.clients[ws] = client
broadcast_payloads: list[object] = []
send_payloads: list[object] = []
async def fake_broadcast(packet: object, exclude: ServerConnection | None = None) -> None:
broadcast_payloads.append(packet)
async def fake_send(websocket: ServerConnection, packet: object) -> None:
send_payloads.append(packet)
monkeypatch.setattr(server, "_broadcast", fake_broadcast)
monkeypatch.setattr(server, "_send", fake_send)
await server._handle_message(client, json.dumps({"type": "chat_message", "message": "/Me waves hello"}))
assert send_payloads == []
assert len(broadcast_payloads) == 1
packet = broadcast_payloads[0]
assert getattr(packet, "type", "") == "chat_message"
assert packet.action is True
assert packet.system is False
assert packet.message == "Tester waves hello"
@pytest.mark.asyncio
async def test_chat_up_command_sends_sender_only(monkeypatch: pytest.MonkeyPatch) -> None:
server = SignalingServer("127.0.0.1", 8765, None, None)
ws = _fake_ws()
client = ClientConnection(websocket=ws, id="u1", nickname="Tester")
server.clients[ws] = client
broadcast_payloads: list[object] = []
send_payloads: list[object] = []
async def fake_broadcast(packet: object, exclude: ServerConnection | None = None) -> None:
broadcast_payloads.append(packet)
async def fake_send(websocket: ServerConnection, packet: object) -> None:
send_payloads.append(packet)
monkeypatch.setattr(server, "_broadcast", fake_broadcast)
monkeypatch.setattr(server, "_send", fake_send)
monkeypatch.setattr(server, "_format_uptime", lambda: "1h 2m 3s")
await server._handle_message(client, json.dumps({"type": "chat_message", "message": "/UP"}))
assert broadcast_payloads == []
assert len(send_payloads) == 1
packet = send_payloads[0]
assert getattr(packet, "type", "") == "chat_message"
assert packet.system is True
assert packet.message == "Server uptime: 1h 2m 3s"
@pytest.mark.asyncio
async def test_chat_command_requires_leading_slash(monkeypatch: pytest.MonkeyPatch) -> None:
server = SignalingServer("127.0.0.1", 8765, None, None)
ws = _fake_ws()
client = ClientConnection(websocket=ws, id="u1", nickname="Tester")
server.clients[ws] = client
broadcast_payloads: list[object] = []
async def fake_broadcast(packet: object, exclude: ServerConnection | None = None) -> None:
broadcast_payloads.append(packet)
monkeypatch.setattr(server, "_broadcast", fake_broadcast)
await server._handle_message(client, json.dumps({"type": "chat_message", "message": " /up"}))
assert len(broadcast_payloads) == 1
packet = broadcast_payloads[0]
assert getattr(packet, "type", "") == "chat_message"
assert packet.system is False
assert packet.action is False
assert packet.message == " /up"