From 22a0dc4a97ceb5a3d162f3cc303277e205b780b6 Mon Sep 17 00:00:00 2001 From: beanbeanjuice Date: Wed, 19 Jun 2024 03:22:26 -0400 Subject: [PATCH] Added Coherent Messages to the Discord Bot --- .../SimpleProxyChatBungee.java | 2 +- .../SimpleProxyChatVelocity.java | 2 +- .../simpleproxychat/discord/Bot.java | 68 ++++++++++++------- 3 files changed, 46 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatBungee.java b/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatBungee.java index 3bd058a..90eb038 100644 --- a/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatBungee.java +++ b/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatBungee.java @@ -52,7 +52,7 @@ public void onEnable() { epochHelper = new EpochHelper(config); this.getLogger().info("Attempting to initialize Discord bot... (if enabled)"); - discordBot = new Bot(this.config); + discordBot = new Bot(this.config, this.getLogger()::warning); this.getProxy().getScheduler().runAsync(this, () -> { try { discordBot.start(); diff --git a/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatVelocity.java b/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatVelocity.java index 49babbe..2a50d56 100644 --- a/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatVelocity.java +++ b/src/main/java/com/beanbeanjuice/simpleproxychat/SimpleProxyChatVelocity.java @@ -78,7 +78,7 @@ public SimpleProxyChatVelocity(ProxyServer proxyServer, Logger logger, @DataDire public void onProxyInitialization(ProxyInitializeEvent event) { // Initialize discord bot. this.getLogger().info("Attempting to initialize Discord bot... (if enabled)"); - discordBot = new Bot(this.config); + discordBot = new Bot(this.config, this.getLogger()::warn); // Bot ready. this.proxyServer.getScheduler().buildTask(this, () -> { diff --git a/src/main/java/com/beanbeanjuice/simpleproxychat/discord/Bot.java b/src/main/java/com/beanbeanjuice/simpleproxychat/discord/Bot.java index 77248a6..89e53fc 100644 --- a/src/main/java/com/beanbeanjuice/simpleproxychat/discord/Bot.java +++ b/src/main/java/com/beanbeanjuice/simpleproxychat/discord/Bot.java @@ -8,6 +8,7 @@ import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; @@ -18,17 +19,20 @@ import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Consumer; import java.util.stream.Collectors; public class Bot { private final Config config; + private final Consumer errorLogger; private JDA bot; private final Queue runnables; - public Bot(Config config) { + public Bot(final Config config, final Consumer errorLogger) { this.config = config; + this.errorLogger = errorLogger; runnables = new ConcurrentLinkedQueue<>(); if (!config.getAsBoolean(ConfigDataKey.USE_DISCORD)) { @@ -37,39 +41,51 @@ public Bot(Config config) { } } - public void sendMessage(String message) { + public void sendMessage(final String messageToSend) { if (bot == null) return; - message = Helper.sanitize(message); + this.getBotTextChannel().ifPresentOrElse( + (mainTextChannel) -> { + String message = Helper.sanitize(messageToSend); + message = Arrays.stream(message.split(" ")).map((originalString) -> { + if (!originalString.startsWith("@")) return originalString; + String name = originalString.replace("@", ""); - message = Arrays.stream(message.split(" ")).map((originalString) -> { - if (!originalString.startsWith("@")) return originalString; - String name = originalString.replace("@", ""); + List potentialMembers = mainTextChannel.getMembers(); + Optional potentialMember = potentialMembers + .stream() + .filter((member) -> ((member.getNickname() != null && member.getNickname().equalsIgnoreCase(name)) || member.getEffectiveName().equalsIgnoreCase(name))) + .findFirst(); - List potentialMembers = bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID)).getMembers(); - Optional potentialMember = potentialMembers - .stream() - .filter((member) -> ((member.getNickname() != null && member.getNickname().equalsIgnoreCase(name)) || member.getEffectiveName().equalsIgnoreCase(name))) - .findFirst(); + return potentialMember.map(IMentionable::getAsMention).orElse(originalString); + }).collect(Collectors.joining(" ")); + + mainTextChannel.sendMessage(message).queue(); + }, + () -> errorLogger.accept("There was an error sending a message to Discord. Does the channel exist? Does the bot have access to the channel?") + ); - return potentialMember.map(IMentionable::getAsMention).orElse(originalString); - }).collect(Collectors.joining(" ")); - bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID)).sendMessage(message).queue(); } /** * Embed needs to be sanitized before running this function. * @param embed The {@link MessageEmbed} to send in the channel. */ - public void sendMessageEmbed(MessageEmbed embed) { + public void sendMessageEmbed(final MessageEmbed embed) { if (bot == null) return; - bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID)) - .sendMessageEmbeds(sanitizeEmbed(embed)) - .queue(); + + this.getBotTextChannel().ifPresentOrElse( + (channel) -> channel.sendMessageEmbeds(sanitizeEmbed(embed)).queue(), + () -> errorLogger.accept("There was an error sending a message to Discord. Does the channel exist? Does the bot have access to the channel?") + ); } - private MessageEmbed sanitizeEmbed(MessageEmbed oldEmbed) { + public Optional getBotTextChannel() { + return Optional.ofNullable(bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID))); + } + + private MessageEmbed sanitizeEmbed(final MessageEmbed oldEmbed) { EmbedBuilder embedBuilder = new EmbedBuilder(oldEmbed); if (oldEmbed.getTitle() != null) @@ -107,12 +123,16 @@ private MessageEmbed sanitizeEmbed(MessageEmbed oldEmbed) { return embedBuilder.build(); } - public void updateChannelTopic(String topic) { + public void updateChannelTopic(final String topic) { if (bot == null) return; - bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID)).getManager().setTopic(topic).queue(); + + this.getBotTextChannel().ifPresentOrElse( + (textChannel) -> textChannel.getManager().setTopic(topic).queue(), + () -> errorLogger.accept("There was an error updating the Discord channel topic. Does the channel exist? Does the bot have access to the channel?") + ); } - public void channelUpdaterFunction(int players) { + public void channelUpdaterFunction(final int players) { if (bot == null) return; String topicMessage = config.getAsString(ConfigDataKey.DISCORD_TOPIC_ONLINE).replace("%online%", String.valueOf(players)); this.updateChannelTopic(topicMessage); @@ -122,7 +142,7 @@ public Optional getJDA() { return Optional.ofNullable(bot); } - public void addRunnableToQueue(Runnable runnable) { + public void addRunnableToQueue(final Runnable runnable) { runnables.add(runnable); } @@ -176,7 +196,7 @@ public void updateStatus() { }); } - public void sendProxyStatus(boolean isStart) { + public void sendProxyStatus(final boolean isStart) { if (!config.getAsBoolean(ConfigDataKey.DISCORD_PROXY_STATUS_ENABLED)) return; if (isStart) {