Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1d44fe961 | ||
|
|
4c7f145f97 | ||
|
|
63c472844f | ||
|
|
8150f305f1 | ||
|
|
d593368c5f | ||
|
|
87f6c8ab1a | ||
|
|
895a33dc2f |
No files matched your search
@@ -22,7 +22,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Java 17
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
@@ -73,7 +73,7 @@ jobs:
|
||||
release="$(curl --fail-with-body -sS -X POST "$api/releases" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"AsminDiscordBridge $VERSION\",\"body\":\"Automatyczny build AsminDiscordBridge $VERSION.\",\"draft\":false,\"prerelease\":false}")"
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"AsminDiscordBridge $VERSION\",\"body\":\"AsminDiscordBridge $VERSION.\",\"draft\":false,\"prerelease\":false}")"
|
||||
release_id="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])' <<< "$release")"
|
||||
curl --fail-with-body -sS -X POST "$api/releases/$release_id/assets?name=$jar" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# AsminDiscordBridge
|
||||
|
||||
Prosty plugin do Minecrafta, który pokazuje na Discordzie, czy serwer jest online oraz kto aktualnie gra. Lista graczy jest sortowana według rangi z LuckPerms. Wiadomość odświeża się co 180 sekund, a jej ID plugin zapamiętuje w `memory.yml`, żeby po restarcie edytować tę samą wiadomość.
|
||||
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 jest napisany pod moje własne potrzeby. Kod jest „taki sobie” i nie wiem, czy będzie stabilny — **nie odpowiadam za jego działanie**. Jeśli chcesz go użyć albo poeksperymentować, zapraszam. Chętnie przyjmę feedback w Pull Requeście albo na adresie [hello@asmin.me](mailto:hello@asmin.me).
|
||||
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.
|
||||
|
||||
Możesz edytować kod. Jeśli jednak zamierzasz opublikować własną wersję, proszę o uznanie mojego autorstwa w creditsach.
|
||||
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.
|
||||
|
||||
**Autor:** [Asmin_](https://asmin.me)
|
||||
+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()
|
||||
|
||||
@@ -8,6 +8,8 @@ import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
|
||||
import net.dv8tion.jda.api.events.session.ReadyEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.LuckPermsProvider;
|
||||
import net.luckperms.api.model.user.User;
|
||||
@@ -21,9 +23,21 @@ 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.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
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]");
|
||||
@@ -36,11 +50,28 @@ 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() {
|
||||
saveDefaultConfig();
|
||||
getConfig().addDefault("discord.invite-link", "https://classicmc.top/discord/");
|
||||
getConfig().addDefault("server.title-img", "https://asmin.me/cdn/classicmc/logo-horizontal.webp");
|
||||
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/");
|
||||
Component message = Component.text("Discord: ")
|
||||
.append(Component.text(inviteLink).clickEvent(ClickEvent.openUrl(inviteLink)));
|
||||
sender.sendMessage(message);
|
||||
return true;
|
||||
});
|
||||
getCommand("discord").setTabCompleter((sender, command, alias, args) -> Collections.emptyList());
|
||||
|
||||
String token = getConfig().getString("discord.token", "").trim();
|
||||
String configuredChannel = getConfig().getString("discord.channel-id", "").trim();
|
||||
@@ -88,6 +119,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 {
|
||||
@@ -118,6 +152,7 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
}
|
||||
|
||||
private void publish(boolean online) {
|
||||
updateWebStatus(online);
|
||||
if (jda == null || shuttingDown) {
|
||||
return;
|
||||
}
|
||||
@@ -144,8 +179,101 @@ 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 {
|
||||
String origin = exchange.getRequestHeaders().getFirst("Origin");
|
||||
String allowedOrigin = getAllowedOrigin(origin);
|
||||
if (allowedOrigin != null) {
|
||||
exchange.getResponseHeaders().set("Access-Control-Allow-Origin", allowedOrigin);
|
||||
exchange.getResponseHeaders().set("Vary", "Origin");
|
||||
}
|
||||
if ("OPTIONS".equalsIgnoreCase(exchange.getRequestMethod())) {
|
||||
if (allowedOrigin == null) {
|
||||
exchange.sendResponseHeaders(403, -1);
|
||||
} else {
|
||||
exchange.getResponseHeaders().set("Access-Control-Allow-Methods", "GET, OPTIONS");
|
||||
exchange.getResponseHeaders().set("Access-Control-Allow-Headers", "Content-Type");
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
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 String getAllowedOrigin(String origin) {
|
||||
if (origin == null || origin.isBlank()) return null;
|
||||
try {
|
||||
URI uri = new URI(origin);
|
||||
String host = uri.getHost();
|
||||
if (host == null || !("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))) {
|
||||
return null;
|
||||
}
|
||||
for (String domain : getConfig().getStringList("web.alloweddomains")) {
|
||||
String allowed = domain == null ? "" : domain.trim().toLowerCase();
|
||||
if (!allowed.isEmpty() && host.equals(allowed)) return origin;
|
||||
}
|
||||
} catch (URISyntaxException ignored) {
|
||||
// Niepoprawny Origin nie dostaje nagłówków CORS.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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 brand = getConfig().getString("server.brand", "ClassicMC.top");
|
||||
String status = online ? "🟢 ONLINE" : "🔴 OFFLINE";
|
||||
StringBuilder players = new StringBuilder();
|
||||
|
||||
@@ -169,12 +297,11 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
|
||||
EmbedBuilder embed = new EmbedBuilder()
|
||||
.setColor(new Color(embedColor))
|
||||
.setTitle(brand)
|
||||
.setImage(getConfig().getString("server.title-img", "https://asmin.me/cdn/classicmc/logo-horizontal.webp"))
|
||||
.addField("Status Serwera", status, false)
|
||||
.addField("Aktywni gracze / Online Players (" + (online ? getServer().getOnlinePlayers().size() : 0) + ")",
|
||||
players.toString(), false)
|
||||
.setFooter("AsminDiscordBridge • odświeżanie co "
|
||||
+ Math.max(30L, getConfig().getLong("server.refresh-seconds", 180L)) + " s");
|
||||
.setFooter("AsminDiscordBridge");
|
||||
return embed.build();
|
||||
}
|
||||
|
||||
@@ -200,7 +327,6 @@ public final class AsminDiscordBridge extends JavaPlugin {
|
||||
String translated = ChatColor.translateAlternateColorCodes('&', prefix);
|
||||
String plain = ChatColor.stripColor(translated);
|
||||
if (plain == null || plain.isEmpty()) return "";
|
||||
// Discord nie obsługuje własnych kolorów tekstu w embedach; zachowujemy pogrubienie prefixu.
|
||||
return LEGACY_COLOR.matcher(translated).find() && translated.matches("(?s).*§[lL].*")
|
||||
? "**" + plain + "** " : plain + " ";
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
# Token utworzysz w Discord Developer Portal. Nie udostępniaj go publicznie.
|
||||
discord:
|
||||
token: "WSTAW_TOKEN_BOTA"
|
||||
channel-id: "WSTAW_ID_KANALU"
|
||||
invite-link: "https://classicmc.top/discord/"
|
||||
|
||||
server:
|
||||
brand: "ClassicMC.top"
|
||||
# Kolor paska embeda w formacie HEX (domyślnie jasna zieleń).
|
||||
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
|
||||
alloweddomains:
|
||||
- "classicmc.top"
|
||||
@@ -6,3 +6,6 @@ author: Asmin_
|
||||
website: https://asmin.me
|
||||
description: Prosty status serwera Minecraft na Discordzie.
|
||||
softdepend: [LuckPerms]
|
||||
commands:
|
||||
discord:
|
||||
description: Pokazuje link do Discorda serwera.
|
||||
Reference in new issue
Block a user