From 9b0e27340080eda20feac4f5b5289bcea1fce2a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:51:02 +0000 Subject: [PATCH] Add the activity command: weekly player activity totals for a region group activity (Ambassador, Admin) reads /player-activity-weekly.json, which the Civ13 host writes beside its player activity database, and replies with totals only (active and new players, sessions, deaths, trips, hours per region). Unexpected fields, bad numbers and odd region names are dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2USzsPRACAXT87D6UA --- .github/workflows/status-heartbeat.yml | 6 + docs/shard-group.md | 5 + src/Civ13/GameServer.php | 2 + .../Commands/Civ13GameServerActivity.php | 35 ++++++ src/Civ13/MessageServiceManager.php | 1 + src/Civ13/PlayerActivityTotals.php | 111 ++++++++++++++++++ tests/local/player-activity-totals.php | 52 ++++++++ 7 files changed, 212 insertions(+) create mode 100644 src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php create mode 100644 src/Civ13/PlayerActivityTotals.php create mode 100644 tests/local/player-activity-totals.php diff --git a/.github/workflows/status-heartbeat.yml b/.github/workflows/status-heartbeat.yml index f25268bd..1a42a97d 100644 --- a/.github/workflows/status-heartbeat.yml +++ b/.github/workflows/status-heartbeat.yml @@ -14,6 +14,9 @@ on: - 'src/Civ13/PortableProfile.php' - 'src/Civ13/RegionRoster.php' - 'tests/local/heartbeat*.php' + - 'src/Civ13/PlayerActivityTotals.php' + - 'src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php' + - 'tests/local/player-activity-totals.php' - '.github/workflows/status-heartbeat.yml' permissions: @@ -43,5 +46,8 @@ jobs: - run: php tests/local/heartbeat-playercount.php - run: php -l src/Civ13/RegionRoster.php - run: php tests/local/heartbeat-roster.php + - run: php -l src/Civ13/PlayerActivityTotals.php + - run: php -l src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php + - run: php tests/local/player-activity-totals.php - run: php -l src/Civ13/ServerPlayLink.php - run: php tests/local/play-link.php diff --git a/docs/shard-group.md b/docs/shard-group.md index f9748a46..00cc8ef0 100644 --- a/docs/shard-group.md +++ b/docs/shard-group.md @@ -40,6 +40,11 @@ DreamDaemon itself. | `restart`, panel Restart, `/restart_server` | `restart --region=`, announced in OOC first | | `update` | `update --region=` | | `hoststatus` | `status --region=`: region name, port, world ready, players, last action, map | +| `activity` (Ambassador, Admin) | none: reads `/player-activity-weekly.json` from the server's `region_group` | + +`activity` shows the group's weekly player activity totals (active players, +new players, sessions, deaths, trips, hours per region). The Civ13 host writes the +file beside its activity database; it holds no player names, research or recipe ids. start, stop, restart and update are accepted within seconds and finish in the script's detached worker; `hoststatus` shows progress. The bot runs as the same diff --git a/src/Civ13/GameServer.php b/src/Civ13/GameServer.php index 12298381..d1fb85bf 100644 --- a/src/Civ13/GameServer.php +++ b/src/Civ13/GameServer.php @@ -1111,6 +1111,8 @@ public function HostStatus(): PromiseInterface $control = $this->gaiaHost; return $control->request('status')->then(static fn (array $status): string => $control::describe($status)); } + /** The shard group file (Civ13 scripts/shard-group) this server heads, or '' when it has none. */ + public function regionGroupFile(): string { return $this->regionGroupFile; } public function hasGaiaHost(): bool { return $this->gaiaHost !== null; } public function hasSystemdUnit(): bool { return $this->systemdUnit !== null; } /** Accepted means systemd queued the job; hoststatus shows the unit's state. */ diff --git a/src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php b/src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php new file mode 100644 index 00000000..77478799 --- /dev/null +++ b/src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php @@ -0,0 +1,35 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13\MessageCommand\Commands; + +use Civ13\MessageCommand\Civ13GameServerMessageCommand; +use Civ13\PlayerActivityTotals; +use Discord\Parts\Channel\Message; +use React\Promise\PromiseInterface; + +/** + * Handles the "activity" command: the region group's weekly player activity totals (no player names). + */ +class Civ13GameServerActivity extends Civ13GameServerMessageCommand +{ + /** + * @inheritDoc + */ + public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface + { + $totals = PlayerActivityTotals::read($this->gameserver->regionGroupFile(), $why); + + return $this->civ13->reply($message, $totals === null ? 'No player activity: '.$why.'.' : PlayerActivityTotals::describe($totals)); + } +} diff --git a/src/Civ13/MessageServiceManager.php b/src/Civ13/MessageServiceManager.php index 5e9060b8..742ebc97 100644 --- a/src/Civ13/MessageServiceManager.php +++ b/src/Civ13/MessageServiceManager.php @@ -312,6 +312,7 @@ function (Message $message, string $command, array $message_filtered) use (&$gam ->offsetSet("{$gameserver->key}update", new Commands\Civ13GameServerUpdate($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}manage", new Commands\Civ13GameServerManage($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}hoststatus", new Commands\Civ13GameServerHostStatus($this->civ13, $gameserver), ['Ambassador']) + ->offsetSet("{$gameserver->key}activity", new Commands\Civ13GameServerActivity($this->civ13, $gameserver), ['Ambassador', 'Admin']) ->offsetSet("{$gameserver->key}mapswap", new Commands\Civ13GameServerMapSwap($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}panic", new Commands\Civ13GameServerPanic($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}ban", new Commands\Civ13GameServerBan($this->civ13, $gameserver), ['Admin']) diff --git a/src/Civ13/PlayerActivityTotals.php b/src/Civ13/PlayerActivityTotals.php new file mode 100644 index 00000000..4080f9c5 --- /dev/null +++ b/src/Civ13/PlayerActivityTotals.php @@ -0,0 +1,111 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13; + +/** + * Weekly player activity totals for a Civ13 region group (Civ13 docs/player-activity.md). The game host writes + * `/player-activity-weekly.json` beside its activity database; it holds totals only (no account + * names, research or recipe ids), so it is safe to show in Discord. Read-only: the bot never opens the database. + */ +final class PlayerActivityTotals +{ + public const FILE = 'player-activity-weekly.json'; + private const MAX_BYTES = 65536; + + /** The totals for the group in this shard group file, or null with a reason in $why. */ + public static function read(string $groupFile, ?string &$why = null): ?array + { + $why = null; + if ($groupFile === '') { + $why = 'this server has no region group'; + + return null; + } + $group = self::json($groupFile, 1048576); + if (! is_array($group) || ! is_string($group['root'] ?? null) || $group['root'] === '') { + $why = 'the region group file is unreadable'; + + return null; + } + $totals = self::json(rtrim($group['root'], '/\\').'/'.self::FILE, self::MAX_BYTES); + if (! is_array($totals)) { + $why = 'no activity totals yet (the recorder is off or the host has not read any yet)'; + + return null; + } + + return self::clean($totals); + } + + /** Keep only the expected totals, as whole numbers and plain region names. */ + public static function clean(array $raw): array + { + $int = static fn (mixed $value): int => is_int($value) || (is_float($value) && is_finite($value)) ? max(0, (int) $value) : 0; + $num = static fn (mixed $value): float => is_int($value) || (is_float($value) && is_finite($value)) ? max(0.0, round((float) $value, 1)) : 0.0; + $active = is_array($raw['active'] ?? null) ? $raw['active'] : []; + $regions = []; + foreach (is_array($raw['hours_by_region'] ?? null) ? array_slice($raw['hours_by_region'], 0, 24) : [] as $row) { + if (is_array($row) && is_string($row['region'] ?? null) && preg_match('/^[A-Za-z0-9_-]{1,40}$/D', $row['region']) === 1) { + $regions[$row['region']] = $num($row['hours'] ?? 0); + } + } + $generated = is_string($raw['generated'] ?? null) && preg_match('/^[0-9: UTC-]{10,24}$/D', $raw['generated']) === 1 ? $raw['generated'] : ''; + + return [ + 'generated' => $generated, + 'active' => ['day' => $int($active['day'] ?? 0), 'week' => $int($active['week'] ?? 0), 'month' => $int($active['month'] ?? 0)], + 'new_this_week' => $int($raw['new_this_week'] ?? 0), + 'sessions_this_week' => $int($raw['sessions_this_week'] ?? 0), + 'session_minutes_median' => $num($raw['session_minutes_median'] ?? 0), + 'deaths_this_week' => $int($raw['deaths_this_week'] ?? 0), + 'trips_this_week' => $int($raw['trips_this_week'] ?? 0), + 'hours_by_region' => $regions, + ]; + } + + /** A short Discord message: totals only. */ + public static function describe(array $totals): string + { + $a = $totals['active']; + $lines = [ + '**Player activity**'.($totals['generated'] !== '' ? " ({$totals['generated']})" : ''), + "Active players: {$a['day']} today, {$a['week']} this week, {$a['month']} this month. New this week: {$totals['new_this_week']}.", + "Play sessions this week: {$totals['sessions_this_week']}, median {$totals['session_minutes_median']} minutes.", + "Deaths this week: {$totals['deaths_this_week']}. Trips between lands: {$totals['trips_this_week']}.", + ]; + if ($totals['hours_by_region']) { + $parts = []; + foreach ($totals['hours_by_region'] as $region => $hours) { + $parts[] = ucfirst($region).' '.$hours.' h'; + } + $lines[] = 'Hours played this week: '.implode(', ', $parts).'.'; + } + + return implode("\n", $lines); + } + + private static function json(string $path, int $limit): mixed + { + clearstatcache(true, $path); + $bytes = @is_file($path) ? @file_get_contents($path, false, null, 0, $limit + 1) : false; + if (! is_string($bytes) || strlen($bytes) > $limit) { + return null; + } + try { + return json_decode($bytes, true, 16, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return null; + } + } +} diff --git a/tests/local/player-activity-totals.php b/tests/local/player-activity-totals.php new file mode 100644 index 00000000..c819aec0 --- /dev/null +++ b/tests/local/player-activity-totals.php @@ -0,0 +1,52 @@ + $root, 'regions' => [['id' => 'gaia']]])); + +// Nothing written yet, and no group at all. +check(PlayerActivityTotals::read($group, $why) === null && str_contains($why, 'no activity totals yet'), 'A missing totals file was not reported'); +check(PlayerActivityTotals::read('', $why) === null && $why === 'this server has no region group', 'A server without a group was not reported'); +file_put_contents($root.'/'.PlayerActivityTotals::FILE, '{not json'); +check(PlayerActivityTotals::read($group) === null, 'A broken totals file was read'); + +// Totals only: unexpected fields (names, ids) are dropped and bad values become zero. +file_put_contents($root.'/'.PlayerActivityTotals::FILE, json_encode([ + 'generated' => '2026-11-16 00:15 UTC', + 'active' => ['day' => 3, 'week' => 9, 'month' => 20], + 'new_this_week' => 2, 'sessions_this_week' => 14, 'session_minutes_median' => 37.25, + 'deaths_this_week' => -5, 'trips_this_week' => 'many', + 'hours_by_region' => [['region' => 'gaia', 'hours' => 12.5], ['region' => '<@everyone>', 'hours' => 1], ['region' => 'europe', 'hours' => 2]], + 'churn' => [['account' => 'alice']], +])); +$totals = PlayerActivityTotals::read($group); +check(is_array($totals) && ! isset($totals['churn']), 'Unexpected fields were kept'); +check($totals['deaths_this_week'] === 0 && $totals['trips_this_week'] === 0, 'Bad numbers were kept'); +check($totals['hours_by_region'] === ['gaia' => 12.5, 'europe' => 2.0], 'Region names were not filtered'); +$text = PlayerActivityTotals::describe($totals); +check(str_contains($text, 'Active players: 3 today, 9 this week, 20 this month. New this week: 2.'), 'Totals line changed: '.$text); +check(str_contains($text, 'median 37.3 minutes') && str_contains($text, 'Gaia 12.5 h, Europe 2 h'), 'Session or hours line changed: '.$text); +check(! str_contains($text, 'alice') && ! str_contains($text, '@'), 'A player name or mention reached the message'); + +// An oversized file is refused. +file_put_contents($root.'/'.PlayerActivityTotals::FILE, str_repeat(' ', 70000).'{}'); +check(PlayerActivityTotals::read($group) === null, 'An oversized totals file was read'); + +array_map('unlink', glob($root.'/*')); +rmdir($root); +echo "PASS player activity totals\n";