Franco Gadea

create a plugin for miencraft spigot/paper with this code

📎 1 file 2,244 chars
📄
pasted-code-1787947532610.txt
txt 60 lines
▶
// Plugin Spigot (Java)
public class RobloxMirror extends JavaPlugin {
    private BukkitRunnable task;
    private Entity npc;

    @Override
    public void onEnable() {
        task = new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    String json = getDataFromAPI("https://tu-backend.com/roblox-player");
                    JSONObject data = new JSONObject(json);

                    Location loc = new Location(Bukkit.getWorld("world"),
                        data.getDouble("x"),
                        data.getDouble("y"),
                        data.getDouble("z"));

                    if (npc == null) {
                        npc = spawnSteveNPC(data.getString("username"), loc);
                    } else {
                        npc.teleport(loc);
                    }

                    // Animaciones básicas
                    if (data.getString("state").equals("walking")) {
                        npc.setVelocity(new Vector(0.2, 0, 0)); // simular caminar
                    } else if (data.getString("state").equals("jumping")) {
                        npc.setVelocity(new Vector(0, 0.5, 0)); // simular salto
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        task.runTaskTimer(this, 0L, 10L); // cada 0.5 segundos (10 ticks)
    }

    private Entity spawnSteveNPC(String name, Location loc) {
        Player npc = (Player) Bukkit.getServer().getOfflinePlayer(name);
        return loc.getWorld().spawn(loc, Player.class);
    }

    private String getDataFromAPI(String url) throws Exception {
        java.net.URL u = new java.net.URL(url);
        java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u.openConnection();
        conn.setRequestMethod("GET");
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        return content.toString();
    }
}

`
Kodari AI
KodariAug 28 at 8:09 pm 1
RobloxMirror
A Spigot/Paper plugin that mirrors a Roblox player's position and state into Minecraft. It periodically fetches JSON data from a backend API containing the Roblox player's coordinates and movement state, then spawns or teleports a Steve NPC to match. The plugin simulates walking and jumping animations by applying velocity vectors based on the fetched state. It uses a scheduled BukkitRunnable task running every 10 ticks (0.5 seconds) to poll the API, handles NPC lifecycle (spawning on first data, teleporting thereafter), and includes error handling for API failures. The plugin requires a backend endpoint returning x, y, z, username, and state fields.
  1. Create the Gradle project and plugin metadata.

  2. Implement asynchronous API polling with safe main-thread NPC updates.

  3. Add configuration and clean shutdown handling.

Created the RobloxMirror Spigot/Paper plugin with:

  • Asynchronous API polling to avoid blocking the server thread.

  • Configurable API URL, world, update interval, and HTTP timeouts.

  • ArmorStand-based Steve-style NPC with player head and username.

  • Position synchronization for x, y, and z.

  • Walking, jumping, and idle velocity animations.

  • HTTP status validation and JSON field validation.

  • NPC cleanup and task cancellation on plugin shutdown.

  • Gradle build configuration and plugin metadata.

The implementation uses an ArmorStand because Bukkit/Spigot cannot spawn real Player entities with World#spawn.

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

import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.profiles.builder.XSkull;
import com.cryptomorin.xseries.profiles.objects.Profileable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.ArmorStand;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;

public class RobloxMirror extends JavaPlugin {
    private static final Pattern STRING_VALUE = Pattern.compile("\\\"([^\\\"]+)\\\"\\s*:\\s*\\\"([^\\\"]*)\\\"");
    private static final Pattern NUMBER_VALUE = Pattern.compile("\\\"([^\\\"]+)\\\"\\s*:\\s*(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)");

    private BukkitRunnable task;
    private ArmorStand npc;
    private String npcUsername;

    @Override
    public void onEnable() {
        saveDefaultConfig();

        final String apiUrl = getConfig().getString("api-url", "");
        final int connectTimeout = Math.max(1, getConfig().getInt("connect-timeout-millis", 3000));
        final int readTimeout = Math.max(1, getConfig().getInt("read-timeout-millis", 3000));
        final long interval = Math.max(1L, getConfig().getLong("update-interval-ticks", 10L));

        if (apiUrl.trim().isEmpty()) {
            getLogger().severe("api-url is empty; RobloxMirror has been disabled.");
            Bukkit.getPluginManager().disablePlugin(this);
            return;
        }

        task = new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    RemotePlayerData data = parseData(getDataFromAPI(apiUrl, connectTimeout, readTimeout));
                    Bukkit.getScheduler().runTask(RobloxMirror.this, () -> updateNpc(data));
                } catch (Exception exception) {
                    getLogger().warning("Unable to update the Roblox mirror: " + exception.getMessage());
                }
            }
        };
        task.runTaskTimerAsynchronously(this, 0L, interval);
    }

    @Override
    public void onDisable() {
        if (task != null) {
            task.cancel();
            task = null;
        }

        if (npc != null && !npc.isDead()) {
            npc.remove();
        }
        npc = null;
        npcUsername = null;
    }

    private void updateNpc(RemotePlayerData data) {
        if (!isEnabled()) {
            return;
        }

        World world = Bukkit.getWorld(getConfig().getString("world", "world"));
        if (world == null) {
            getLogger().warning("Configured world does not exist: " + getConfig().getString("world", "world"));
            return;
        }

        Location location = new Location(world, data.getX(), data.getY(), data.getZ());
        if (npc == null || npc.isDead() || !npc.getWorld().equals(world)) {
            if (npc != null && !npc.isDead()) {
                npc.remove();
            }
            npc = spawnSteveNpc(data.getUsername(), location);
        } else {
            npc.teleport(location);
            if (!data.getUsername().equals(npcUsername)) {
                npc.setCustomName(data.getUsername());
                npc.getEquipment().setHelmet(createHead(data.getUsername()));
            }
        }

        npcUsername = data.getUsername();
        applyAnimation(data.getState());
    }

    private ArmorStand spawnSteveNpc(String name, Location location) {
        ArmorStand stand = location.getWorld().spawn(location, ArmorStand.class);
        stand.setCustomName(name);
        stand.setCustomNameVisible(true);
        stand.setGravity(false);
        stand.setInvulnerable(true);
        stand.setPersistent(false);
        stand.setBasePlate(false);
        stand.setArms(true);
        stand.getEquipment().setHelmet(createHead(name));
        return stand;
    }

    private ItemStack createHead(String username) {
        try {
            return XSkull.createItem().profile(Profileable.detect(username)).apply();
        } catch (RuntimeException exception) {
            return XMaterial.matchXMaterial("PLAYER_HEAD").map(XMaterial::parseItem).orElse(null);
        }
    }

    private void applyAnimation(String state) {
        String normalizedState = state.toLowerCase(Locale.ROOT);
        if ("walking".equals(normalizedState)) {
            npc.setVelocity(new Vector(0.2, 0.0, 0.0));
        } else if ("jumping".equals(normalizedState)) {
            npc.setVelocity(new Vector(0.0, 0.5, 0.0));
        } else {
            npc.setVelocity(new Vector(0.0, 0.0, 0.0));
        }
    }

    private String getDataFromAPI(String endpoint, int connectTimeout, int readTimeout) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(endpoint).openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Accept", "application/json");

        try {
            int responseCode = connection.getResponseCode();
            if (responseCode < 200 || responseCode >= 300) {
                throw new IOException("API returned HTTP " + responseCode);
            }

            StringBuilder content = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            }
            return content.toString();
        } finally {
            connection.disconnect();
        }
    }

    private RemotePlayerData parseData(String json) throws IOException {
        String username = extractString(json, "username");
        String state = extractString(json, "state");
        double x = extractNumber(json, "x");
        double y = extractNumber(json, "y");
        double z = extractNumber(json, "z");

        if (username.trim().isEmpty()) {
            throw new IOException("API response contains an empty username");
        }
        if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
            throw new IOException("API response contains invalid coordinates");
        }
        return new RemotePlayerData(username, state, x, y, z);
    }

    private String extractString(String json, String key) throws IOException {
        Matcher matcher = STRING_VALUE.matcher(json);
        while (matcher.find()) {
            if (key.equals(matcher.group(1))) {
                return matcher.group(2);
            }
        }
        throw new IOException("API response is missing string field: " + key);
    }

    private double extractNumber(String json, String key) throws IOException {
        Matcher matcher = NUMBER_VALUE.matcher(json);
        while (matcher.find()) {
            if (key.equals(matcher.group(1))) {
                try {
                    return Double.parseDouble(matcher.group(2));
                } catch (NumberFormatException exception) {
                    throw new IOException("Invalid numeric field: " + key, exception);
                }
            }
        }
        throw new IOException("API response is missing numeric field: " + key);