1 parent
8150f305f1
commit
63c472844f
4 files changed
+84
-1
No files matched your search
@@ -2,6 +2,8 @@
|
||||
|
||||
Prosty plugin do Minecrafta, który pokazuje status serwera i listę graczy na Discordzie. Gracze są sortowani według rang LuckPerms. Wiadomość odświeża się co 180 sekund. Komenda `/discord` pokazuje link do Discorda.
|
||||
|
||||
Plugin udostępnia również lekki endpoint JSON `http://adres-serwera:25568/status`. Port, adres nasłuchiwania i włączenie serwera można zmienić w sekcji `web` w `config.yml`. JSON zawiera `server-online`, liczbową wartość `online-players` oraz obiekt `online-players-nicks` z numerowanymi nickami.
|
||||
|
||||
Plugin zrobiłem dla siebie. Nie wiem, czy jest stabilny, więc używasz go na własną odpowiedzialność. Jeśli chcesz go przetestować, z chęcią przyjmę uwagi na adresie [hello@asmin.me](mailto:hello@asmin.me).
|
||||
|
||||
Możesz edytować kod. Jeśli opublikujesz własną wersję, dodaj moje autorstwo w creditsach.
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ plugins {
|
||||
}
|
||||
|
||||
group = 'me.asmin.discordbridge'
|
||||
version = providers.gradleProperty('buildVersion').getOrElse('1.0.0')
|
||||
version = providers.gradleProperty('buildVersion').getOrElse('1.0.2')
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
|
||||
@@ -23,10 +23,19 @@ import org.bukkit.scheduler.BukkitTask;
|
||||
import java.awt.Color;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
public final class AsminDiscordBridge extends JavaPlugin {
|
||||
private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)§[0-9A-FK-OR]");
|
||||
@@ -39,6 +48,9 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
private long channelId;
|
||||
private int embedColor;
|
||||
private volatile boolean shuttingDown;
|
||||
private HttpServer webServer;
|
||||
private ThreadPoolExecutor webExecutor;
|
||||
private final AtomicReference<String> webStatusJson = new AtomicReference<>("{\"server-online\":false,\"online-players\":0,\"online-players-nicks\":{}}\n");
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
@@ -48,6 +60,7 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
getConfig().options().copyDefaults(true);
|
||||
saveConfig();
|
||||
loadMemory();
|
||||
startWebServer();
|
||||
|
||||
getCommand("discord").setExecutor((sender, command, label, args) -> {
|
||||
String inviteLink = getConfig().getString("discord.invite-link", "https://classicmc.top/discord/");
|
||||
@@ -104,6 +117,9 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
if (refreshTask != null) {
|
||||
refreshTask.cancel();
|
||||
}
|
||||
updateWebStatus(false);
|
||||
if (webServer != null) webServer.stop(0);
|
||||
if (webExecutor != null) webExecutor.shutdownNow();
|
||||
|
||||
if (jda != null) {
|
||||
try {
|
||||
@@ -134,6 +150,7 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
}
|
||||
|
||||
private void publish(boolean online) {
|
||||
updateWebStatus(online);
|
||||
if (jda == null || shuttingDown) {
|
||||
return;
|
||||
}
|
||||
@@ -160,6 +177,65 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
);
|
||||
}
|
||||
|
||||
private void startWebServer() {
|
||||
if (!getConfig().getBoolean("web.enabled", true)) return;
|
||||
int port = Math.max(1, Math.min(65535, getConfig().getInt("web.port", 25568)));
|
||||
String host = getConfig().getString("web.host", "0.0.0.0").trim();
|
||||
try {
|
||||
webServer = HttpServer.create(new InetSocketAddress(host, port), 64);
|
||||
webExecutor = new ThreadPoolExecutor(1, 2, 30L, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(32), new ThreadPoolExecutor.AbortPolicy());
|
||||
webServer.setExecutor(webExecutor);
|
||||
webServer.createContext("/status", this::handleStatusRequest);
|
||||
webServer.start();
|
||||
getLogger().info("Serwer WWW działa na " + host + ":" + port + "/status");
|
||||
} catch (IOException | RuntimeException exception) {
|
||||
getLogger().severe("Nie udało się uruchomić serwera WWW na porcie " + port + ": " + exception.getMessage());
|
||||
if (webServer != null) webServer.stop(0);
|
||||
if (webExecutor != null) webExecutor.shutdownNow();
|
||||
webServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleStatusRequest(HttpExchange exchange) throws IOException {
|
||||
if (!"GET".equalsIgnoreCase(exchange.getRequestMethod()) || !"/status".equals(exchange.getRequestURI().getPath())) {
|
||||
exchange.getResponseHeaders().set("Allow", "GET");
|
||||
exchange.sendResponseHeaders(405, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
byte[] body = webStatusJson.get().getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
try (OutputStream output = exchange.getResponseBody()) { output.write(body); }
|
||||
}
|
||||
|
||||
private void updateWebStatus(boolean online) {
|
||||
if (webServer == null) return;
|
||||
List<String> names = online ? getServer().getOnlinePlayers().stream()
|
||||
.sorted(Comparator.comparingInt(this::getPlayerWeight).reversed()
|
||||
.thenComparing(Player::getName, String.CASE_INSENSITIVE_ORDER))
|
||||
.map(player -> ChatColor.stripColor(player.getName()))
|
||||
.toList() : Collections.emptyList();
|
||||
StringBuilder json = new StringBuilder(64 + names.size() * 24);
|
||||
json.append("{\"server-online\":").append(online)
|
||||
.append(",\"online-players\":").append(names.size())
|
||||
.append(",\"online-players-nicks\":{");
|
||||
for (int i = 0; i < names.size(); i++) {
|
||||
if (i > 0) json.append(',');
|
||||
json.append('"').append(i + 1).append("\":\"").append(jsonEscape(names.get(i))).append('"');
|
||||
}
|
||||
json.append("}}\n");
|
||||
webStatusJson.set(json.toString());
|
||||
}
|
||||
|
||||
private String jsonEscape(String value) {
|
||||
if (value == null) return "";
|
||||
return value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
.replace("\r", "\\r").replace("\n", "\\n");
|
||||
}
|
||||
|
||||
private MessageEmbed createEmbed(boolean online) {
|
||||
String status = online ? "🟢 ONLINE" : "🔴 OFFLINE";
|
||||
StringBuilder players = new StringBuilder();
|
||||
|
||||
@@ -7,3 +7,8 @@ server:
|
||||
title-img: "https://asmin.me/cdn/classicmc/logo-horizontal.webp"
|
||||
embed-color: "#90EE90"
|
||||
refresh-seconds: 180
|
||||
|
||||
web:
|
||||
enabled: true
|
||||
host: "0.0.0.0"
|
||||
port: 25568
|
||||
Reference in new issue
Block a user