Xanemi-Dev

Develop a Minecraft plugin that serves as an API bridge between a Discord bot and the Minecraft server, facilitating real-time communication.Refer the images for what yo do

Kodari AI
KodariOct 22 at 3:19 pm 1
DiscordBridge
DiscordBridge is a Minecraft plugin that creates a real-time API bridge between Discord and the server. It listens for Discord bot webhook events and translates them into in-game commands, messages, and notifications. The plugin maintains a bidirectional communication channel, allowing players to interact with Discord channels and Discord users to influence server events. It features configurable webhook endpoints, message formatting, permission-based command execution, and automatic reconnection handling. The bridge supports custom event mapping, allowing server administrators to define which Discord messages trigger specific in-game actions, and provides a robust logging system for debugging and monitoring all cross-platform traffic.
  1. Create the Paper plugin scaffold and secure API configuration.

  2. Add authenticated endpoints for status, players, inventory, moderation, logs, chat, and stop/restart.

  3. Forward Minecraft join, leave, and chat events to an optional Discord webhook.

Created the DiscordBridge plugin with an authenticated HTTP API for server status, public address, online players, player inventories, logs, chat relay, kick/ban, and stop/restart controls. Minecraft join, leave, and chat events can also be forwarded to a Discord webhook.

API requests use Authorization: Bearer <token>. The plugin generates and saves a token in config.yml on first startup. The API binds to 127.0.0.1 by default; for remote bot access, configure network access carefully and use HTTPS through a trusted proxy or tunnel.

A plugin cannot start a server once it is stopped, so /control/start returns an error; starting requires the server host’s process manager.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
Code
5 604
src/main/java/com/kodari/discordbridge/DiscordBridgePlugin.java
package com.kodari.discordbridge;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

public final class DiscordBridgePlugin extends JavaPlugin implements Listener {
    private final long startedAt = System.currentTimeMillis();
    private final HttpClient webhookClient = HttpClient.newBuilder()
            .connectTimeout(java.time.Duration.ofSeconds(5))
            .build();
    private ApiServer apiServer;
    private URI webhookUri;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        String token = getConfig().getString("api.token", "").trim();
        if (token.isEmpty() || token.equalsIgnoreCase("CHANGE_ME")) {
            token = generateToken();
            getConfig().set("api.token", token);
            saveConfig();
            getLogger().warning("Generated and saved an API token in config.yml. Keep it secret.");
        }

        String webhook = getConfig().getString("discord-webhook-url", "").trim();
        if (!webhook.isEmpty()) {
            try {
                URI parsed = URI.create(webhook);
                if ("https".equalsIgnoreCase(parsed.getScheme())) {
                    webhookUri = parsed;
                } else {
                    getLogger().warning("discord-webhook-url must use HTTPS; webhook forwarding is disabled.");
                }
            } catch (IllegalArgumentException exception) {
                getLogger().warning("Invalid discord-webhook-url; webhook forwarding is disabled.");
            }
        }

        String bindAddress = getConfig().getString("api.bind-address", "127.0.0.1").trim();
        int port = getConfig().getInt("api.port", 8765);
        if (port < 1 || port > 65535) {
            getLogger().severe("api.port must be between 1 and 65535.");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        try {
            apiServer = new ApiServer(this, bindAddress, port, token);
            apiServer.start();
        } catch (Exception exception) {
            getLogger().log(Level.SEVERE, "Could not start the DiscordBridge API server.", exception);
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        getServer().getPluginManager().registerEvents(this, this);
        getLogger().info("DiscordBridge API listening on " + bindAddress + ":" + port + "/api/v1");
    }

    @Override
    public void onDisable() {
        if (apiServer != null) {
            apiServer.close();
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (args.length != 1 || !args[0].equalsIgnoreCase("status")) {
            sender.sendMessage("Usage: /bridge status");
            return true;
        }

        String state = apiServer != null && apiServer.isRunning() ? "running" : "stopped";
        sender.sendMessage("DiscordBridge API: " + state + " (port " + getConfig().getInt("api.port", 8765) + ")");
        return true;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        sendDiscordEvent("➡️ " + event.getPlayer().getName() + " joined the server.");
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        sendDiscordEvent("⬅️ " + event.getPlayer().getName() + " left the server.");
    }

    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        sendDiscordEvent("💬 " + event.getPlayer().getName() + ": " + event.getMessage());
    }

    <T> T onMainThread(java.util.concurrent.Callable<T> action) throws Exception {
        if (Bukkit.isPrimaryThread()) {
            return action.call();
        }

        CompletableFuture<T> future = new CompletableFuture<>();
        Bukkit.getScheduler().runTask(this, () -> {
            try {
                future.complete(action.call());
            } catch (Throwable throwable) {
                future.completeExceptionally(throwable);
            }
        });
        return future.get(5, TimeUnit.SECONDS);
    }

    long getUptimeSeconds() {
        return Math.max(0, (System.currentTimeMillis() - startedAt) / 1000);
    }

    String getPublicAddress() {
        return getConfig().getString("public-address", "");
    }

    String getRestartCommand() {
        return getConfig().getString("restart-command", "restart").trim();
    }

    private void sendDiscordEvent(String message) {
        if (webhookUri == null || !isEnabled()) {
            return;
        }

        String body = "{\"content\":\"" + escapeJson(message) + "\"}";
        HttpRequest request = HttpRequest.newBuilder(webhookUri)
                .timeout(java.time.Duration.ofSeconds(8))
                .header("Content-Type", "application/json; charset=utf-8")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        webhookClient.sendAsync(request, HttpResponse.BodyHandlers.discarding())
                .thenAccept(response -> {
                    if (response.statusCode() < 200 || response.statusCode() >= 300) {
                        getLogger().warning("Discord webhook returned HTTP " + response.statusCode() + ".");
                    }
                })
                .exceptionally(exception -> {
                    getLogger().log(Level.WARNING, "Could not send an event to the Discord webhook.", exception);
                    return null;
                });
    }

    private static String generateToken() {
        byte[] bytes = new byte[32];
        new SecureRandom().nextBytes(bytes);
        StringBuilder token = new StringBuilder(bytes.length * 2);
        for (byte value : bytes) {
            token.append(String.format("%02x", value & 0xff));
        }
        return token.toString();
    }

    private static String escapeJson(String value) {
        StringBuilder escaped = new StringBuilder(value.length() + 16);
        for (int i = 0; i < value.length(); i++) {
            char character = value.charAt(i);
            switch (character) {
                case '"' -> escaped.append("\\\"");
                case '\\' -> escaped.append("\\\\");
                case '\n' -> escaped.append("\\n");
                case '\r' -> escaped.append("\\r");
                case '\t' -> escaped.append("\\t");
                default -> {
                    if (character < 0x20) {
                        escaped.append(String.format("\\u%04x", (int) character));
                    } else {
                        escaped.append(character);
                    }
                }
            }
        }
        return escaped.toString();
    }
}