Stop disconnecting

This commit is contained in:
Business Goose 2022-03-31 03:24:03 +01:00
parent 25b7c61d21
commit 27f939f26e
No known key found for this signature in database
GPG key ID: 77DCA801362E9645

View file

@ -1,11 +1,12 @@
package me.StevenLawson.TotalFreedomMod.discord.bridge; package me.StevenLawson.TotalFreedomMod.discord.bridge;
import java.util.Optional;
import java.util.regex.Pattern;
import me.StevenLawson.TotalFreedomMod.Log; import me.StevenLawson.TotalFreedomMod.Log;
import me.StevenLawson.TotalFreedomMod.admin.AdminList; import me.StevenLawson.TotalFreedomMod.admin.AdminList;
import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry; import me.StevenLawson.TotalFreedomMod.config.ConfigurationEntry;
import me.StevenLawson.TotalFreedomMod.config.MainConfig; import me.StevenLawson.TotalFreedomMod.config.MainConfig;
import me.StevenLawson.TotalFreedomMod.discord.command.DiscordCommandManager; import me.StevenLawson.TotalFreedomMod.discord.command.DiscordCommandManager;
import me.StevenLawson.TotalFreedomMod.player.PlayerRank;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.HoverEvent;
@ -21,14 +22,9 @@ import org.javacord.api.entity.message.MessageAuthor;
import org.javacord.api.entity.server.Server; import org.javacord.api.entity.server.Server;
import org.javacord.api.entity.user.User; import org.javacord.api.entity.user.User;
import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.event.message.MessageCreateEvent;
import org.javacord.api.event.message.MessageEvent;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class DiscordBridge { public class DiscordBridge {
private static DiscordApi DISCORD_API; private static DiscordApi DISCORD_API;
private static TextChannel CHANNEL; private static TextChannel CHANNEL;
private static TextChannel ADMIN_CHANNEL; private static TextChannel ADMIN_CHANNEL;
@ -38,30 +34,36 @@ public class DiscordBridge {
boolean isAdmin = false; boolean isAdmin = false;
try { try {
isAdmin = message.getChannel().getIdAsString().equalsIgnoreCase(ADMIN_CHANNEL.getIdAsString()); isAdmin = message.getChannel().getIdAsString()
} catch (Exception ignored) {} .equalsIgnoreCase(ADMIN_CHANNEL.getIdAsString());
} catch (Exception ignored) {
}
String content = message.getMessage().getReadableContent(); String content = message.getMessage().getReadableContent();
String prefix = MainConfig.getString(ConfigurationEntry.DISCORD_PREFIX); String prefix = MainConfig.getString(ConfigurationEntry.DISCORD_PREFIX);
MessageAuthor author = message.getMessage().getAuthor(); MessageAuthor author = message.getMessage().getAuthor();
if (author.isBotUser() || !message.isServerMessage()) return; if (author.isBotUser() || !message.isServerMessage()) {
return;
}
Optional<Server> server = message.getServer(); Optional<Server> server = message.getServer();
Optional<User> user = author.asUser(); Optional<User> user = author.asUser();
if(prefix == null) { if (prefix == null) {
Log.severe("Bot prefix does not exist. Stopping bot..."); Log.severe("Bot prefix does not exist. Stopping bot...");
stop(); stop();
return; return;
} }
if(!server.isPresent()) { if (!server.isPresent()) {
Log.warning("Discord server wasn't present in message, this may be a sign you've not properly configured the intents for your bot."); Log.warning(
"Discord server wasn't present in message, this may be a sign you've not properly configured the intents for your bot.");
return; return;
} }
if(!user.isPresent()) { if (!user.isPresent()) {
Log.warning("Unable to get user of message author. This may be a sign you've not properly configured the intents for your bot."); Log.warning(
"Unable to get user of message author. This may be a sign you've not properly configured the intents for your bot.");
return; return;
} }
@ -71,27 +73,33 @@ public class DiscordBridge {
Optional<Message> referenced = message.getMessage().getReferencedMessage(); Optional<Message> referenced = message.getMessage().getReferencedMessage();
String reply = ""; String reply = "";
if(referenced.isPresent()) { if (referenced.isPresent()) {
Message replyingTo = referenced.get(); Message replyingTo = referenced.get();
reply = String.format(ChatColor.GRAY + "" + ChatColor.YELLOW + "%s" + ChatColor.GRAY + " %s\n" + ChatColor.WHITE, replyingTo.getAuthor().getDiscriminatedName(), replyingTo.getReadableContent()); reply = String.format(
ChatColor.GRAY + "" + ChatColor.YELLOW + "%s" + ChatColor.GRAY + " %s\n"
+ ChatColor.WHITE, replyingTo.getAuthor().getDiscriminatedName(),
replyingTo.getReadableContent());
} }
String format = MainConfig.getString((isAdmin) ? ConfigurationEntry.DISCORD_ADMIN_FORMAT : ConfigurationEntry.DISCORD_FORMAT); String format = MainConfig.getString((isAdmin) ? ConfigurationEntry.DISCORD_ADMIN_FORMAT
: ConfigurationEntry.DISCORD_FORMAT);
format = format.replace("{TAG}", author.getDiscriminatedName()); format = format.replace("{TAG}", author.getDiscriminatedName());
format = format.replace("{USERNAME}", author.getName()); format = format.replace("{USERNAME}", author.getName());
BaseComponent[] components = TextComponent.fromLegacyText(ChatColor.translateAlternateColorCodes('&', String.format(format, content))); BaseComponent[] components = TextComponent.fromLegacyText(
ChatColor.translateAlternateColorCodes('&', String.format(format, content)));
TextComponent component = new TextComponent(reply); TextComponent component = new TextComponent(reply);
for (BaseComponent baseComponent : components) { for (BaseComponent baseComponent : components) {
component.addExtra(baseComponent); component.addExtra(baseComponent);
} }
if(message.getMessageAttachments().size() > 0) { if (message.getMessageAttachments().size() > 0) {
int i = 0; int i = 0;
for (MessageAttachment messageAttachment : message.getMessageAttachments()) { for (MessageAttachment messageAttachment : message.getMessageAttachments()) {
String url = messageAttachment.getProxyUrl().toString(); String url = messageAttachment.getProxyUrl().toString();
ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url); ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
TextComponent warningComponent = new TextComponent("WARNING: By clicking on this text, your client will open:\n\n"); TextComponent warningComponent = new TextComponent(
"WARNING: By clicking on this text, your client will open:\n\n");
warningComponent.setColor(net.md_5.bungee.api.ChatColor.RED); warningComponent.setColor(net.md_5.bungee.api.ChatColor.RED);
warningComponent.setBold(true); warningComponent.setBold(true);
TextComponent urlComponent = new TextComponent(url); TextComponent urlComponent = new TextComponent(url);
@ -99,8 +107,10 @@ public class DiscordBridge {
urlComponent.setUnderlined(true); urlComponent.setUnderlined(true);
urlComponent.setBold(false); urlComponent.setBold(false);
warningComponent.addExtra(urlComponent); warningComponent.addExtra(urlComponent);
HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{warningComponent}); HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT,
TextComponent mediaComponent = new TextComponent((i == 0 && content.isEmpty()) ? "[Media]" : " [Media]"); new BaseComponent[]{warningComponent});
TextComponent mediaComponent = new TextComponent(
(i == 0 && content.isEmpty()) ? "[Media]" : " [Media]");
mediaComponent.setColor(net.md_5.bungee.api.ChatColor.YELLOW); mediaComponent.setColor(net.md_5.bungee.api.ChatColor.YELLOW);
mediaComponent.setClickEvent(clickEvent); mediaComponent.setClickEvent(clickEvent);
mediaComponent.setHoverEvent(hoverEvent); mediaComponent.setHoverEvent(hoverEvent);
@ -109,11 +119,9 @@ public class DiscordBridge {
} }
} }
if(isAdmin) { if (isAdmin) {
for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
{ if (AdminList.isSuperAdmin(player)) {
if (AdminList.isSuperAdmin(player))
{
player.spigot().sendMessage(component); player.spigot().sendMessage(component);
} }
} }
@ -136,8 +144,10 @@ public class DiscordBridge {
.login() .login()
.join(); .join();
Optional<TextChannel> channelFuture = DISCORD_API.getTextChannelById(MainConfig.getString(ConfigurationEntry.DISCORD_CHANNEL)); Optional<TextChannel> channelFuture = DISCORD_API.getTextChannelById(
Optional<TextChannel> adminChannelFuture = DISCORD_API.getTextChannelById(MainConfig.getString(ConfigurationEntry.DISCORD_ADMIN_CHANNEL)); MainConfig.getString(ConfigurationEntry.DISCORD_CHANNEL));
Optional<TextChannel> adminChannelFuture = DISCORD_API.getTextChannelById(
MainConfig.getString(ConfigurationEntry.DISCORD_ADMIN_CHANNEL));
if (!channelFuture.isPresent()) { if (!channelFuture.isPresent()) {
Log.warning("TFM 4.3 Reloaded could not find your channel, stopping!"); Log.warning("TFM 4.3 Reloaded could not find your channel, stopping!");
@ -155,9 +165,12 @@ public class DiscordBridge {
ADMIN_CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent); ADMIN_CHANNEL.addMessageCreateListener(DiscordBridge::onMessageCreateEvent);
} }
} catch (Exception e) { } catch (Exception e) {
Log.warning("Uh oh! It looks like TFM 4.3 Reloaded Discord couldn't start! Please check you have defined the bot's token & channel and also given it the correct permissions! (Read Messages and Send Messages)"); Log.warning(
Log.warning("If you've already set that up however, you may to read the exception below."); "Uh oh! It looks like TFM 4.3 Reloaded Discord couldn't start! Please check you have defined the bot's token & channel and also given it the correct permissions! (Read Messages and Send Messages)");
Log.warning("If this is a bug with TFM 4.3 Reloaded, please report it at https://github.com/TheDeus-Group/TFM-4.3-Reloaded/issues or https://code.cat.casa/TheDeus-Group/TFM-4.3-Reloaded/issues"); Log.warning(
"If you've already set that up however, you may to read the exception below.");
Log.warning(
"If this is a bug with TFM 4.3 Reloaded, please report it at https://github.com/TheDeus-Group/TFM-4.3-Reloaded/issues or https://code.cat.casa/TheDeus-Group/TFM-4.3-Reloaded/issues");
e.printStackTrace(); e.printStackTrace();
return; return;
} }
@ -183,7 +196,9 @@ public class DiscordBridge {
} }
public static void transmitMessage(String message, boolean disconnectAfterwards) { public static void transmitMessage(String message, boolean disconnectAfterwards) {
if (CHANNEL == null) return; if (CHANNEL == null) {
return;
}
if (!disconnectAfterwards) { if (!disconnectAfterwards) {
CHANNEL.sendMessage(sanitizeMessage(message)); CHANNEL.sendMessage(sanitizeMessage(message));
} else { } else {
@ -191,7 +206,7 @@ public class DiscordBridge {
CHANNEL.sendMessage(sanitizeMessage(message)).get(); CHANNEL.sendMessage(sanitizeMessage(message)).get();
} catch (Exception ignored) { } catch (Exception ignored) {
} }
CountDownLatch shutdownWaiter = new CountDownLatch(1); /*CountDownLatch shutdownWaiter = new CountDownLatch(1);
Thread t = new Thread(() -> { Thread t = new Thread(() -> {
DISCORD_API.addLostConnectionListener(lostConnectionEvent -> shutdownWaiter.countDown()); DISCORD_API.addLostConnectionListener(lostConnectionEvent -> shutdownWaiter.countDown());
@ -202,7 +217,7 @@ public class DiscordBridge {
} catch (InterruptedException ignored) { } catch (InterruptedException ignored) {
} }
}); });
t.start(); t.start();*/
} }
} }
@ -211,7 +226,9 @@ public class DiscordBridge {
} }
public static void transmitAdminMessage(String message, boolean disconnectAfterwards) { public static void transmitAdminMessage(String message, boolean disconnectAfterwards) {
if (ADMIN_CHANNEL == null) return; if (ADMIN_CHANNEL == null) {
return;
}
if (!disconnectAfterwards) { if (!disconnectAfterwards) {
ADMIN_CHANNEL.sendMessage(sanitizeMessage(message)); ADMIN_CHANNEL.sendMessage(sanitizeMessage(message));
} else { } else {
@ -219,7 +236,7 @@ public class DiscordBridge {
ADMIN_CHANNEL.sendMessage(sanitizeMessage(message)).get(); ADMIN_CHANNEL.sendMessage(sanitizeMessage(message)).get();
} catch (Exception ignored) { } catch (Exception ignored) {
} }
DISCORD_API.disconnect(); //DISCORD_API.disconnect();
} }
} }
@ -234,8 +251,7 @@ public class DiscordBridge {
Log.info("TFM 4.3 Reloaded Discord stopped."); Log.info("TFM 4.3 Reloaded Discord stopped.");
} }
public static String fullySanitizeDiscordMessage(String message) public static String fullySanitizeDiscordMessage(String message) {
{
String partiallySanitized = sanitizeMessage(message); String partiallySanitized = sanitizeMessage(message);
return partiallySanitized.replaceAll("([`_~*|\\\\])", "\\\\$1"); return partiallySanitized.replaceAll("([`_~*|\\\\])", "\\\\$1");
} }