Files
src
pom.xml
README.md
Code
5 299
src/main/java/com/kaizensmp/chat/KaizenSMPChat.java
package com.kaizensmp.chat;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.session.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicLong;
public final class KaizenSMPChat extends JavaPlugin implements Listener {
private final AtomicLong generation = new AtomicLong();
private final Object connectionLock = new Object();
private volatile JDA connection;
private volatile String status = "Starting";
private volatile Settings settings;
private record Settings(boolean enabled, String token, String guildId, String channelId,
String format, boolean consoleLogs, boolean inbound) { }
@Override
public void onEnable() {
saveDefaultConfig();
getServer().getPluginManager().registerEvents(this, this);
startBridge();
}
private void startBridge() {
FileConfiguration config = getConfig();
Settings next = new Settings(config.getBoolean("settings.enabled", true),
config.getString("discord.bot-token", "").trim(),
config.getString("discord.guild-id", "").trim(),
config.getString("discord.channel-id", "").trim(),
config.getString("settings.format", "⛏️ {player}: {message}"),
config.getBoolean("settings.console-logs", true),
config.getBoolean("settings.discord-to-minecraft", false));
long current;
JDA old;
synchronized (connectionLock) {
current = generation.incrementAndGet();
old = connection;
connection = null;
settings = next;
status = next.enabled() ? "Connecting" : "Disabled";
}
if (old != null) old.shutdownNow();
if (!next.enabled()) return;
if (next.token().isEmpty() || !next.guildId().matches("[0-9]{1,20}")
|| !next.channelId().matches("[0-9]{1,20}")) {
status = "Invalid or missing credentials / IDs";
getLogger().warning("Discord bridge not started: configure a bot token, guild ID, and channel ID.");
return;
}
Bukkit.getScheduler().runTaskAsynchronously(this, () -> connect(next, current));
}
private void connect(Settings config, long current) {
try {
EnumSet<GatewayIntent> intents = EnumSet.of(GatewayIntent.GUILD_MESSAGES);
if (config.inbound()) intents.add(GatewayIntent.MESSAGE_CONTENT);
JDA client = JDABuilder.createDefault(config.token())
.enableIntents(intents)
.addEventListeners(new DiscordListener(config, current))
.build();
synchronized (connectionLock) {
if (generation.get() != current) {
client.shutdownNow();
return;
}
connection = client;
}
} catch (Exception ex) {
if (generation.get() == current) {
status = "Connection failed";
getLogger().warning("Discord connection failed. Check the token, intents, and network configuration.");
}
}
}
private TextChannel channel(JDA client, Settings config) {
Guild guild = client.getGuildById(config.guildId());
if (guild == null) return null;
return guild.getTextChannelById(config.channelId());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event) {
Settings config = settings;
JDA client = connection;
if (config == null || !config.enabled() || client == null || client.getStatus() != JDA.Status.CONNECTED) return;
TextChannel target = channel(client, config);
if (target == null) return;
String message = config.format().replace("{player}", event.getPlayer().getName())
.replace("{message}", event.getMessage());
if (message.isBlank()) return;
if (message.length() > 2000) message = message.substring(0, 2000);
long current = generation.get();
try {
target.sendMessage(message).setAllowedMentions(EnumSet.noneOf(net.dv8tion.jda.api.entities.Message.MentionType.class))
.queue(success -> {
if (generation.get() == current && config.consoleLogs()) getLogger().info("Relayed a Minecraft chat message to Discord.");
}, failure -> {
if (generation.get() == current) getLogger().warning("Could not relay a chat message to Discord; check channel permissions and connectivity.");
});
} catch (RuntimeException ex) {
if (generation.get() == current) getLogger().warning("Could not queue a Discord chat message.");
}
}
private final class DiscordListener extends ListenerAdapter {
private final Settings config;
private final long current;
private DiscordListener(Settings config, long current) {
this.config = config;
this.current = current;
}
@Override
public void onReady(ReadyEvent event) {
if (generation.get() != current) return;
TextChannel target = channel(event.getJDA(), config);
if (target == null) {
status = "Guild or text channel not found";
getLogger().warning("Discord guild or text channel not found. Check IDs and the bot's access.");
} else {
status = "Connected";
if (config.consoleLogs()) getLogger().info("Discord bridge connected.");
}
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
if (generation.get() != current || !config.inbound() || event.getAuthor().isBot()
|| event.isWebhookMessage() || !event.isFromGuild()
|| !event.getGuild().getId().equals(config.guildId())
|| !event.getChannel().getId().equals(config.channelId())) return;
String content = event.getMessage().getContentDisplay();
if (content.isBlank()) return;
String name = event.getMember() == null ? event.getAuthor().getName() : event.getMember().getEffectiveName();
String line = ChatColor.AQUA + "[Discord] " + ChatColor.RESET
+ clean(name) + ": " + clean(content);
try {
Bukkit.getScheduler().runTask(KaizenSMPChat.this, () -> {
if (generation.get() == current && isEnabled()) Bukkit.broadcastMessage(line);
});
} catch (IllegalStateException ignored) {
// The server is shutting down.
}
}
}
private String clean(String text) {
return text.replace('§', ' ').replace('\n', ' ').replace('\r', ' ');
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("kaizensmpchat.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission.");
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
reloadConfig();
startBridge();
sender.sendMessage(ChatColor.GREEN + "KaizenSMPchat reloaded. Use /kschat status to check the connection.");
} else if (args.length == 1 && args[0].equalsIgnoreCase("status")) {
JDA client = connection;
String display = status;
if (client != null && client.getStatus() != JDA.Status.CONNECTED && display.equals("Connected")) {
display = "Disconnected or reconnecting";
}
sender.sendMessage(ChatColor.AQUA + "KaizenSMPchat: " + ChatColor.WHITE + display);
} else {
sender.sendMessage(ChatColor.AQUA + "/kschat help" + ChatColor.GRAY + " - Show commands");
sender.sendMessage(ChatColor.AQUA + "/kschat status" + ChatColor.GRAY + " - Show bridge status");
sender.sendMessage(ChatColor.AQUA + "/kschat reload" + ChatColor.GRAY + " - Reload configuration and reconnect");
}
return true;
}
@Override
public void onDisable() {
JDA old;
synchronized (connectionLock) {
generation.incrementAndGet();