lorenzorapattonipc-hue
📎 1 file 2,569 chars
📄
pasted-code-1774186186578.txt
txt 73 lines
▶
Create a Paper 1.21.1 Minecraft plugin called ServerSync that automatically connects to a remote dashboard without any manual setup beyond pasting an API key. Requirements:

config.yml — only one thing the server owner needs to fill in:
yamlapi-key: 'PASTE_YOUR_KEY_HERE'
dashboard-url: 'https://yourapp.base44.app'
sync-interval: 60
heartbeat-interval: 30
debug: false

On Plugin Startup:

Read the API key from config.yml
If key is the default placeholder, print a clear message in console:
[ServerSync] ⚠ No API key set! Go to your dashboard, copy your key, and paste it into plugins/ServerSync/config.yml
If key exists, call POST /api/connect with:

API key in header
Server name (from server.properties), MC version, plugin version, max players


If connection succeeds: print [ServerSync] ✅ Connected to dashboard!
If connection fails: print [ServerSync] ❌ Could not reach dashboard. Check your API key and internet connection. and retry every 60 seconds


Heartbeat:

Every 30 seconds call POST /api/heartbeat with:

Current TPS
RAM used / max RAM
Online player count
Server uptime in seconds




Events — call POST /api/event for each:

Player join: { type: "player_join", player, uuid, timestamp }
Player leave: { type: "player_leave", player, uuid, playtime, timestamp }
Player death: { type: "player_death", player, killer (if player), message, timestamp }
Player kill: { type: "player_kill", killer, victim, timestamp }
Chat message: { type: "chat", player, message, timestamp }


Player Data Sync:

Every sync-interval seconds, call POST /api/players/sync with an array of all online players including: name, uuid, balance (via Vault), kills, deaths, playtime, health, location (world, x, y, z)


Command Polling:

Every 5 seconds call GET /api/commands/pending
Dashboard returns a list of pending commands like:
json[
  { "id": "abc123", "type": "kick", "player": "Steve", "reason": "AFK" },
  { "id": "def456", "type": "give_money", "player": "Alex", "amount": 500 },
  { "id": "ghi789", "type": "broadcast", "message": "Server restart in 5 min" },
  { "id": "jkl012", "type": "ban", "player": "Griefer99", "reason": "Hacking" }
]

Execute each command in-game immediately
Call POST /api/commands/complete with the command id after each one


General:

All HTTP calls are async (never block main thread)
Uses MiniMessage for all console + in-game text
api-version: '1.21' in plugin.yml
Java 21
Clean commented code
Depends on Vault (soft-depend, gracefully handles if not installed)
Kodari AI
KodariMar 22 at 1:31 pm 13,546 (v2)

I’ll create a Paper 1.21.1 plugin that automatically syncs server data with a remote dashboard via REST API.

ServerSync
Automatic server synchronization plugin that connects to a remote dashboard with minimal configuration. Syncs real-time server metrics (TPS, RAM, player data), logs events (joins, deaths, chat), and executes remote commands. Features zero-config connection with just an API key, async HTTP operations, Vault economy integration, and MiniMessage formatting. Perfect for server owners who want centralized monitoring and control.

ServerSync plugin created successfully! Here’s what was implemented:

Core Features:

  • ✅ One-config setup with API key validation

  • ✅ Automatic connection to dashboard with retry logic

  • ✅ Async HTTP operations (Java’s HttpClient)

  • ✅ MiniMessage formatting throughout

  • ✅ Vault economy integration (soft-depend)

Syncing Systems:

  • Connection - Sends server info on startup, retries every 60s on failure

  • Heartbeat - TPS, RAM usage, player count, uptime every 30s

  • Player Sync - Full player data with Vault balance, stats, location every 60s

  • Event Logging - Join, leave, death, kill, chat events sent instantly

  • Command Polling - Fetches and executes dashboard commands every 5s

Remote Commands:

  • kick - Kicks player with reason

  • give_money - Deposits money via Vault

  • broadcast - Server-wide message

  • ban - Bans and kicks player

Console Messages:

  • Clear warning if API key not set

  • Success/failure messages on connection

  • Vault integration status

All HTTP calls are async, executes commands on main thread, handles gracefully when Vault isn’t installed.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
Code
16 749
src/main/java/com/serversync/ServerSync.java
package com.serversync;

import com.serversync.api.ApiClient;
import com.serversync.config.ConfigManager;
import com.serversync.listener.ChatListener;
import com.serversync.listener.PlayerEventListener;
import com.serversync.sync.CommandPollTask;
import com.serversync.sync.ConnectionManager;
import com.serversync.sync.HeartbeatTask;
import com.serversync.sync.PlayerSyncTask;
import com.serversync.util.ColorUtil;
import com.serversync.util.ServerUtil;
import lombok.Getter;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

@Getter
public class ServerSync extends JavaPlugin {
    private ConfigManager configManager;
    private ApiClient apiClient;
    private ConnectionManager connectionManager;
    private ServerUtil serverUtil;
    private Economy economy;
    private boolean vaultEnabled = false;
    
    private HeartbeatTask heartbeatTask;
    private PlayerSyncTask playerSyncTask;
    private CommandPollTask commandPollTask;
    
    @Override
    public void onEnable() {
        saveDefaultConfig();
        
        this.configManager = new ConfigManager(this);
        this.serverUtil = new ServerUtil(this);
        this.apiClient = new ApiClient(this);
        
        if (!configManager.isApiKeySet()) {
            getServer().getConsoleSender().sendMessage(
                ColorUtil.colorize("<yellow>[ServerSync] <red>⚠ No API key set! Go to your dashboard, copy your key, and paste it into plugins/ServerSync/config.yml")
            );
            return;
        }
        
        setupVault();
        
        this.connectionManager = new ConnectionManager(this);
        connectionManager.connect();
        
        registerListeners();
        startTasks();
        
        getServer().getConsoleSender().sendMessage(
            ColorUtil.colorize("<yellow>[ServerSync] <gray>Plugin enabled. Connecting to dashboard...")
        );
    }
    
    @Override
    public void onDisable() {
        if (heartbeatTask != null) {
            heartbeatTask.cancel();
        }
        if (playerSyncTask != null) {
            playerSyncTask.cancel();
        }
        if (commandPollTask != null) {
            commandPollTask.cancel();
        }
        
        getServer().getConsoleSender().sendMessage(
            ColorUtil.colorize("<yellow>[ServerSync] <gray>Plugin disabled.")
        );
    }
    
    private void setupVault() {
        if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
            getServer().getConsoleSender().sendMessage(
                ColorUtil.colorize("<yellow>[ServerSync] <gray>Vault not found. Economy features disabled.")
            );
            return;
        }
        
        RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
        if (rsp != null) {
            economy = rsp.getProvider();
            vaultEnabled = true;
            getServer().getConsoleSender().sendMessage(
                ColorUtil.colorize("<yellow>[ServerSync] <green>Vault economy integration enabled.")
            );
        }
    }
    
    private void registerListeners() {
        Bukkit.getPluginManager().registerEvents(new PlayerEventListener(this), this);
        Bukkit.getPluginManager().registerEvents(new ChatListener(this), this);
    }
    
    private void startTasks() {
        long heartbeatTicks = configManager.getHeartbeatInterval() * 20L;
        this.heartbeatTask = new HeartbeatTask(this);
        heartbeatTask.runTaskTimerAsynchronously(this, heartbeatTicks, heartbeatTicks);
        
        long syncTicks = configManager.getSyncInterval() * 20L;
        this.playerSyncTask = new PlayerSyncTask(this);
        playerSyncTask.runTaskTimerAsynchronously(this, syncTicks, syncTicks);
        
        this.commandPollTask = new CommandPollTask(this);
        commandPollTask.runTaskTimerAsynchronously(this, 100L, 100L);
    }
    
    public void onConnectionSuccess() {
        getServer().getConsoleSender().sendMessage(
            ColorUtil.colorize("<yellow>[ServerSync] <green>✅ Connected to dashboard!")
        );
    }
    
    public void onConnectionFailed() {
        getServer().getConsoleSender().sendMessage(
            ColorUtil.colorize("<yellow>[ServerSync] <red>❌ Could not reach dashboard. Check your API key and internet connection.")
        );
    }
}