Skip to content

Commit

Permalink
Merge pull request #186 from beanbeanjuice/185-discord-bot-error-mess…
Browse files Browse the repository at this point in the history
…ages

Added Coherent Messages to the Discord Bot
  • Loading branch information
beanbeanjuice committed Jun 19, 2024
2 parents ff78ea0 + 22a0dc4 commit 89923f0
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, () -> {
Expand Down
68 changes: 44 additions & 24 deletions src/main/java/com/beanbeanjuice/simpleproxychat/discord/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<String> errorLogger;
private JDA bot;

private final Queue<Runnable> runnables;

public Bot(Config config) {
public Bot(final Config config, final Consumer<String> errorLogger) {
this.config = config;
this.errorLogger = errorLogger;
runnables = new ConcurrentLinkedQueue<>();

if (!config.getAsBoolean(ConfigDataKey.USE_DISCORD)) {
Expand All @@ -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<Member> potentialMembers = mainTextChannel.getMembers();
Optional<Member> potentialMember = potentialMembers
.stream()
.filter((member) -> ((member.getNickname() != null && member.getNickname().equalsIgnoreCase(name)) || member.getEffectiveName().equalsIgnoreCase(name)))
.findFirst();

List<Member> potentialMembers = bot.getTextChannelById(config.getAsString(ConfigDataKey.CHANNEL_ID)).getMembers();
Optional<Member> 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<TextChannel> 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)
Expand Down Expand Up @@ -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);
Expand All @@ -122,7 +142,7 @@ public Optional<JDA> getJDA() {
return Optional.ofNullable(bot);
}

public void addRunnableToQueue(Runnable runnable) {
public void addRunnableToQueue(final Runnable runnable) {
runnables.add(runnable);
}

Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 89923f0

Please sign in to comment.