Ayush

Add this section to your prompt:

Track ALL Players Automatically

* Automatically track every player who joins the server.

* Include all known and unknown players.

* No manual registration required.

* Track players using UUID, even if they change their Minecraft username.

* Include online and offline players in the all-time leaderboard.

* Never ignore a player because their data is missing.

* Save every player's complete playtime history.

* Send hourly and daily Discord reports for all tracked players.

* Show player name, UUID, first join date, last seen date, total days, hours and minutes.

* Include players who joined in the past, not just newly joined players.

* If historical data is unavailable, show Unknown instead of inventing dates or playtime.

Kodari AI
KodariNov 9 at 3:59 pm 2
PlaytimeTracker
Automatically tracks all players who join the server, including known and unknown players, without manual registration. Uses UUIDs to track players even if they change usernames. Maintains an all-time leaderboard covering both online and offline players. Saves complete playtime history for every player. Sends hourly and daily Discord reports for all tracked players, showing player name, UUID, first join date, last seen date, total days, hours, and minutes. Includes players who joined in the past; if historical data is unavailable, displays `Unknown` instead of inventing dates or playtime.
  • Track known players by UUID and retain playtime snapshots across restarts.

  • Add an all-time leaderboard and configurable hourly and daily Discord webhook reports, using Unknown where history isn’t available.

Created the playtime tracker with /playtimeleaderboard and hourly and daily Discord reports. Set discord.webhook-url in config.yml to enable reports.

Historical fields that the server cannot provide display as Unknown. Past playtime cannot be recovered if the server no longer has its statistics.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
5 287
src/main/java/com/kodari/playtimetracker/PlaytimeTracker.java
package com.kodari.playtimetracker;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.Statistic;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;

public final class PlaytimeTracker extends JavaPlugin implements Listener {
    private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
    private final Map<UUID, Record> records = new LinkedHashMap<>();
    private final ExecutorService reports = Executors.newSingleThreadExecutor();
    private File dataFile;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        dataFile = new File(getDataFolder(), "players.yml");
        loadRecords();
        refreshAll();
        saveRecords();
        Bukkit.getPluginManager().registerEvents(this, this);
        Bukkit.getScheduler().runTaskTimer(this, () -> {
            refreshAll();
            saveRecords();
        }, 1200L, 1200L);
        Bukkit.getScheduler().runTaskTimer(this, () -> report("Hourly"), 72000L, 72000L);
        Bukkit.getScheduler().runTaskTimer(this, () -> report("Daily"), 1728000L, 1728000L);
    }

    @Override
    public void onDisable() {
        refreshAll();
        saveRecords();
        reports.shutdown();
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        refresh(event.getPlayer());
        saveRecords();
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        refresh(event.getPlayer());
        records.get(event.getPlayer().getUniqueId()).lastSeen = System.currentTimeMillis();
        saveRecords();
    }

    private void loadRecords() {
        YamlConfiguration yaml = YamlConfiguration.loadConfiguration(dataFile);
        ConfigurationSection section = yaml.getConfigurationSection("players");
        if (section == null) return;
        for (String key : section.getKeys(false)) {
            try {
                UUID id = UUID.fromString(key);
                ConfigurationSection player = section.getConfigurationSection(key);
                if (player == null) continue;
                Record record = new Record(id);
                record.name = player.getString("name");
                record.firstJoin = player.getLong("first-join", 0);
                record.lastSeen = player.getLong("last-seen", 0);
                record.ticks = player.getLong("playtime-ticks", -1);
                records.put(id, record);
            } catch (IllegalArgumentException ex) {
                getLogger().warning("Skipping invalid player UUID in players.yml: " + key);
            }
        }
    }

    private void refreshAll() {
        for (OfflinePlayer player : Bukkit.getOfflinePlayers()) refresh(player);
        for (Player player : Bukkit.getOnlinePlayers()) refresh(player);
    }

    private void refresh(OfflinePlayer player) {
        Record record = records.computeIfAbsent(player.getUniqueId(), Record::new);
        if (player.getName() != null) record.name = player.getName();
        long first = player.getFirstPlayed();
        if (first > 0 && (record.firstJoin == 0 || first < record.firstJoin)) record.firstJoin = first;
        long last = player.getLastPlayed();
        if (last > record.lastSeen) record.lastSeen = last;
        if (player.isOnline()) record.lastSeen = System.currentTimeMillis();
        try {
            int ticks = player.getStatistic(Statistic.PLAY_ONE_MINUTE);
            if (ticks > 0) record.ticks = Math.max(record.ticks, (long) ticks);
        } catch (RuntimeException ex) {
            getLogger().fine("Playtime unavailable for " + player.getUniqueId() + ": " + ex.getMessage());
        }
    }

    private void saveRecords() {
        YamlConfiguration yaml = new YamlConfiguration();
        for (Record record : records.values()) {
            String path = "players." + record.id + ".";
            if (record.name != null) yaml.set(path + "name", record.name);
            yaml.set(path + "first-join", record.firstJoin);
            yaml.set(path + "last-seen", record.lastSeen);
            yaml.set(path + "playtime-ticks", record.ticks);
        }
        try {
            yaml.save(dataFile);
        } catch (IOException ex) {
            getLogger().log(Level.SEVERE, "Could not save player tracking data", ex);
        }
    }

    private List<Record> leaderboard() {
        List<Record> sorted = new ArrayList<>(records.values());
        sorted.sort(Comparator.comparingLong((Record record) -> record.ticks).reversed()
                .thenComparing(record -> record.id.toString()));
        return sorted;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        int page = 1;
        if (args.length > 1) return false;
        if (args.length == 1) {
            try {
                page = Integer.parseInt(args[0]);
            } catch (NumberFormatException ex) {
                sender.sendMessage(ChatColor.RED + "Page must be a positive number.");
                return true;
            }
        }
        refreshAll();
        List<Record> sorted = leaderboard();
        int pages = Math.max(1, (sorted.size() + 9) / 10);
        if (page < 1 || page > pages) {
            sender.sendMessage(ChatColor.RED + "Choose a page from 1 to " + pages + ".");
            return true;
        }
        sender.sendMessage(ChatColor.GOLD + "All-time playtime leaderboard (" + page + "/" + pages + ")");
        for (int i = (page - 1) * 10; i < Math.min(page * 10, sorted.size()); i++) {
            Record r = sorted.get(i);
            sender.sendMessage(ChatColor.YELLOW + "#" + (i + 1) + " " + name(r) + " (" + r.id + ") " + ChatColor.WHITE + duration(r.ticks));
            sender.sendMessage(ChatColor.GRAY + "First joined: " + date(r.firstJoin) + " | Last seen: " + date(r.lastSeen));
        }
        return true;
    }

    private void report(String period) {
        if (!getConfig().getBoolean("discord." + period.toLowerCase(java.util.Locale.ROOT) + "-reports", true)) return;
        String webhook = getConfig().getString("discord.webhook-url", "").trim();
        if (webhook.isEmpty()) return;
        refreshAll();
        saveRecords();
        List<String> chunks = new ArrayList<>();
        String header = period + " playtime report (" + DATE.format(Instant.now()) + ")\n";
        StringBuilder current = new StringBuilder(header);
        for (Record r : leaderboard()) {
            String line = name(r) + " | " + r.id + " | First: " + date(r.firstJoin)
                    + " | Last: " + date(r.lastSeen) + " | Playtime: " + duration(r.ticks) + "\n";
            if (current.length() + line.length() > 1900) {
                chunks.add(current.toString());
                current = new StringBuilder(header);
            }
            current.append(line);
        }
        if (records.isEmpty()) current.append("No tracked players.\n");
        chunks.add(current.toString());
        reports.execute(() -> {
            for (String chunk : chunks) sendWebhook(webhook, chunk);
        });
    }

    private void sendWebhook(String webhook, String content) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(webhook);
            if (!"https".equalsIgnoreCase(url.getProtocol()) ||