Skip to content

Commit

Permalink
chore: spotless
Browse files Browse the repository at this point in the history
  • Loading branch information
yHSJ committed Dec 17, 2024
1 parent 7ae3155 commit e9b8f0c
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 96 deletions.
171 changes: 84 additions & 87 deletions app/src/main/java/fi/sundae/bot/commands/MatchHistoryCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
import fi.sundae.bot.api.MatchResult;
import fi.sundae.bot.api.MatchResultSerializer;
import fi.sundae.bot.tournament.MatchResultEmbed;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
Expand All @@ -39,44 +37,47 @@ public MatchHistoryCommand(String channelId, String adminRoleId) {
protected void execute(SlashCommandEvent event) {
event.deferReply(true).queue();
if (Objects.requireNonNull(event.getMember()).getRoles().stream()
.noneMatch(role -> role.getId().equals(ADMIN_ROLE_ID))) {
.noneMatch(role -> role.getId().equals(ADMIN_ROLE_ID))) {
event.getHook().editOriginalEmbeds(getNotAllowedEmbed()).queue();
return;
}

LOGGER.info("Fetching match history...");
TextChannel channel = event.getJDA().getTextChannelById(CHANNEL_ID);
fetchAllMessages(channel)
.thenAccept(
messages -> {
LOGGER.info("Parsing messages");
try {
List<MatchResultEmbed> matchResults = new ArrayList<>();
for (Message message : messages) {
if (!message.getContentRaw().isEmpty() || message.getEmbeds().isEmpty()) {
continue;
}

MessageEmbed embed = message.getEmbeds().get(0);
matchResults.add(new MatchResultEmbed(embed));
LOGGER.info("Finished parsing message | message ID: {}", message.getId());
}

Gson gson =
new GsonBuilder()
.registerTypeAdapter(MatchResult.class, new MatchResultSerializer())
.create();

LOGGER.info("Building JSON");

event.getHook().editOriginal("```" + gson.toJson(matchResults) + "```").queue();
} catch (Exception e) {
LOGGER.error("Failed parsing messages", e);
event.getHook()
.editOriginal("There was an error fetching message history. Check the logs for more " +
"info").queue();
}
});
.thenAccept(
messages -> {
LOGGER.info("Parsing messages");
try {
List<MatchResultEmbed> matchResults = new ArrayList<>();
for (Message message : messages) {
if (!message.getContentRaw().isEmpty() || message.getEmbeds().isEmpty()) {
continue;
}

MessageEmbed embed = message.getEmbeds().get(0);
matchResults.add(new MatchResultEmbed(embed));
LOGGER.info("Finished parsing message | message ID: {}", message.getId());
}

Gson gson =
new GsonBuilder()
.registerTypeAdapter(MatchResult.class, new MatchResultSerializer())
.create();

LOGGER.info("Building JSON");

event.getHook().editOriginal("```" + gson.toJson(matchResults) + "```").queue();
} catch (Exception e) {
LOGGER.error("Failed parsing messages", e);
event
.getHook()
.editOriginal(
"There was an error fetching message history. Check the logs for more "
+ "info")
.queue();
}
});
}

public CompletableFuture<List<Message>> fetchAllMessages(TextChannel channel) {
Expand All @@ -89,71 +90,67 @@ public CompletableFuture<List<Message>> fetchAllMessages(TextChannel channel) {
}

private void fetchMessagesBefore(
TextChannel channel,
String lastMessageId,
List<Message> messages,
CompletableFuture<List<Message>> future
) {
TextChannel channel,
String lastMessageId,
List<Message> messages,
CompletableFuture<List<Message>> future) {
LOGGER.info("Fetching messages | last message id: {}", lastMessageId);
int fetchLimit = 100; // limit imposed by Discord
if (lastMessageId == null) {

channel
.getHistory()
.retrievePast(fetchLimit)
.queue(
retrievedMessages -> {
List<Message> filteredMessages =
retrievedMessages.stream()
.filter(
message -> channel.getJDA().getSelfUser()
.equals(message.getAuthor()))
.collect(Collectors.toCollection(ArrayList::new));
messages.addAll(filteredMessages);

if (filteredMessages.size() < fetchLimit) {
future.complete(messages);
} else {
String oldestMessageId =
retrievedMessages.get(retrievedMessages.size() - 1).getId();
fetchMessagesBefore(channel, oldestMessageId, messages, future);
}
},
error -> {
LOGGER.error("failed to fetch messages", error);
future.completeExceptionally(error);
}
);
.getHistory()
.retrievePast(fetchLimit)
.queue(
retrievedMessages -> {
List<Message> filteredMessages =
retrievedMessages.stream()
.filter(
message -> channel.getJDA().getSelfUser().equals(message.getAuthor()))
.collect(Collectors.toCollection(ArrayList::new));
messages.addAll(filteredMessages);

if (filteredMessages.size() < fetchLimit) {
future.complete(messages);
} else {
String oldestMessageId =
retrievedMessages.get(retrievedMessages.size() - 1).getId();
fetchMessagesBefore(channel, oldestMessageId, messages, future);
}
},
error -> {
LOGGER.error("failed to fetch messages", error);
future.completeExceptionally(error);
});
} else {
channel
.getHistoryBefore(lastMessageId, fetchLimit)
.queue(
history -> {
List<Message> retrievedMessages = history.getRetrievedHistory();
messages.addAll(retrievedMessages);

if (retrievedMessages.size() < fetchLimit) {
LOGGER.info("Retrieved all messages. Completing future...");
future.complete(messages);
} else {
String oldestMessageId =
retrievedMessages.get(retrievedMessages.size() - 1).getId();
fetchMessagesBefore(channel, oldestMessageId, messages, future);
}
},
error -> {
LOGGER.error("failed to fetch messages", error);
future.completeExceptionally(error);
}
);
.getHistoryBefore(lastMessageId, fetchLimit)
.queue(
history -> {
List<Message> retrievedMessages = history.getRetrievedHistory();
messages.addAll(retrievedMessages);

if (retrievedMessages.size() < fetchLimit) {
LOGGER.info("Retrieved all messages. Completing future...");
future.complete(messages);
} else {
String oldestMessageId =
retrievedMessages.get(retrievedMessages.size() - 1).getId();
fetchMessagesBefore(channel, oldestMessageId, messages, future);
}
},
error -> {
LOGGER.error("failed to fetch messages", error);
future.completeExceptionally(error);
});
}
}

private MessageEmbed getNotAllowedEmbed() {
return new EmbedBuilder()
.setColor(Color.RED)
.setTitle("Permission Denied")
.setDescription("Only a tournament admin can use this command.")
.build();
.setColor(Color.RED)
.setTitle("Permission Denied")
.setDescription("Only a tournament admin can use this command.")
.build();
}
}
15 changes: 6 additions & 9 deletions app/src/main/java/fi/sundae/bot/tournament/MatchResultEmbed.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.dv8tion.jda.api.entities.MessageEmbed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MatchResultEmbed {
private String playerOne;
Expand All @@ -19,7 +17,6 @@ public class MatchResultEmbed {
private long playerOneKills, playerTwoKills;
private MatchResult result;


public MatchResultEmbed(MessageEmbed embed) {
Color embedColor = embed.getColor();
if (Color.RED.equals(embedColor)) {
Expand Down Expand Up @@ -57,13 +54,13 @@ public MatchResultEmbed(MessageEmbed embed) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(Objects.requireNonNull(field.getValue()));
List<Long> numbers = new ArrayList<>();
while (matcher.find()) {
long number = Long.parseLong(matcher.group(1).trim());
numbers.add(number);
}
while (matcher.find()) {
long number = Long.parseLong(matcher.group(1).trim());
numbers.add(number);
}

playerOneKills = numbers.get(0);
playerTwoKills = numbers.get(1);
playerOneKills = numbers.get(0);
playerTwoKills = numbers.get(1);
}
}
}
Expand Down

0 comments on commit e9b8f0c

Please sign in to comment.