From 3d9254c4d95edb672d240d61517be9696208a1f7 Mon Sep 17 00:00:00 2001
From: TBG <46306028+TBG1000@users.noreply.github.com>
Date: Fri, 19 Jul 2024 21:11:15 -0600
Subject: [PATCH] Cleanup
---
pom.xml | 2 +-
src/main/java/me/tbg/match/bot/BotConfig.java | 6 -
.../java/me/tbg/match/bot/DiscordBot.java | 56 +++++---
.../me/tbg/match/bot/MatchFinishListener.java | 130 ++++++++++--------
.../me/tbg/match/bot/MatchStartListener.java | 29 ++--
5 files changed, 127 insertions(+), 96 deletions(-)
diff --git a/pom.xml b/pom.xml
index 08c596c..08d334a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,7 +43,7 @@
org.javacord
javacord
- 3.5.0
+ 3.8.0
pom
diff --git a/src/main/java/me/tbg/match/bot/BotConfig.java b/src/main/java/me/tbg/match/bot/BotConfig.java
index a9f5bdf..2e10c49 100644
--- a/src/main/java/me/tbg/match/bot/BotConfig.java
+++ b/src/main/java/me/tbg/match/bot/BotConfig.java
@@ -9,7 +9,6 @@ public class BotConfig {
private String token;
private String serverId;
private String matchChannel;
- private String mapImagesURL;
public BotConfig(Configuration config) {
reload(config);
@@ -20,7 +19,6 @@ public void reload(Configuration config) {
this.token = config.getString("token");
this.serverId = config.getString("server");
this.matchChannel = config.getString("match-channel");
- this.mapImagesURL = config.getString("map-images-url");
}
public boolean isEnabled() {
@@ -38,8 +36,4 @@ public String getServerId() {
public String getMatchChannel() {
return matchChannel;
}
-
- public String getMapImagesURL() {
- return mapImagesURL;
- }
}
diff --git a/src/main/java/me/tbg/match/bot/DiscordBot.java b/src/main/java/me/tbg/match/bot/DiscordBot.java
index 4f85183..0242318 100644
--- a/src/main/java/me/tbg/match/bot/DiscordBot.java
+++ b/src/main/java/me/tbg/match/bot/DiscordBot.java
@@ -1,6 +1,11 @@
package me.tbg.match.bot;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
import java.time.Duration;
+import java.time.Instant;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.javacord.api.DiscordApi;
@@ -19,6 +24,8 @@
import tc.oc.pgm.rotation.pools.MapPool;
import tc.oc.pgm.api.integration.Integration;
+import javax.imageio.ImageIO;
+
public class DiscordBot {
private DiscordApi api;
@@ -78,30 +85,30 @@ public void sendMatchEmbed(EmbedBuilder embed, Match match) {
public String parseDuration(Duration duration) {
long hours = duration.toHours();
- long minutes = duration.toMinutes() - (hours * 60);
- long seconds = duration.getSeconds() - (hours * 60 * 60) - (minutes * 60);
+ long minutes = duration.toMinutes();
+ long seconds = duration.getSeconds();
+
+ StringBuilder result = new StringBuilder();
+
if (hours > 0) {
- return hours
- + (hours == 1 ? " hour " : " hours ")
- + minutes
- + (minutes == 1 ? " minute " : " minutes ")
- + seconds
- + (seconds == 1 ? " second" : " seconds");
- } else if (minutes > 0) {
- return minutes
- + (minutes == 1 ? " minute " : " minutes ")
- + seconds
- + (seconds == 1 ? " second" : " seconds");
- } else if (seconds > 0) {
- return seconds + (seconds == 1 ? " second" : " seconds");
+ result.append(hours)
+ .append(hours == 1 ? " hour " : " hours ");
+ }
+ if (minutes > 0) {
+ result.append(minutes)
+ .append(minutes == 1 ? " minute " : " minutes ");
}
- return "_Unavailable_";
+ if (seconds > 0 || result.length() == 0) {
+ result.append(seconds)
+ .append(seconds == 1 ? " second" : " seconds");
+ }
+
+ return result.length() > 0 ? result.toString().trim() : "_Unavailable_";
}
public String getMapPools(Match match) {
// Extracted from
// https://github.com/PGMDev/PGM/blob/dev/core/src/main/java/tc/oc/pgm/command/MapCommand.java
- // Line #253
if (PGM.get().getMapOrder() instanceof MapPoolManager) {
String mapPools =
((MapPoolManager) PGM.get().getMapOrder())
@@ -128,11 +135,16 @@ public String getMapGamemodes(Match match) {
.collect(Collectors.joining(", "));
}
- public String getMapImageUrl(MapInfo map) {
- String repo = config.getMapImagesURL();
- String mapName = map.getName().replace(":", "").replace(" ", "%20");
- String png = "/map.png";
- return repo + mapName + png;
+ public String getMatchDescription(Match match) {
+ int playerCount = match.getPlayers().size();
+ return "Started at with **"
+ + playerCount + (playerCount == 1 ? " player" : " players") + "** online.";
+ }
+
+ public BufferedImage getMapImage(MapInfo map) throws IOException {
+ Path sourceDir = map.getSource().getAbsoluteDir();
+ File pngFile = new File(sourceDir.toFile(), "map.png");
+ return ImageIO.read(pngFile);
}
public long getOnlineStaffCount(Match match) {
diff --git a/src/main/java/me/tbg/match/bot/MatchFinishListener.java b/src/main/java/me/tbg/match/bot/MatchFinishListener.java
index c216142..4e065f4 100644
--- a/src/main/java/me/tbg/match/bot/MatchFinishListener.java
+++ b/src/main/java/me/tbg/match/bot/MatchFinishListener.java
@@ -1,6 +1,7 @@
package me.tbg.match.bot;
import java.awt.*;
+import java.io.IOException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@@ -28,70 +29,91 @@ public void onMatchFinish(MatchFinishEvent event) {
MapInfo map = match.getMap();
ScoreMatchModule scoreModule = match.getModule(ScoreMatchModule.class);
TeamMatchModule teamModule = match.getModule(TeamMatchModule.class);
- Collection teams = match.getCompetitors();
-
- String winner = "";
- Color winnerColor = null;
- for (Competitor competitor : teams) {
- if (event.getWinners().contains(competitor)) {
- if (event.getWinners().size() == 1) {
- winner = competitor.getNameLegacy();
- winnerColor = new Color(competitor.getFullColor().asRGB());
- } else {
- winner = "Tie";
- winnerColor = Color.RED;
- }
- }
+
+ String winner = getWinner(event, match.getCompetitors());
+ Color winnerColor = getWinnerColor(event, match.getCompetitors());
+
+ EmbedBuilder matchInfo = createMatchInfoEmbed(match, map, winner, winnerColor);
+
+ addScoresToEmbed(matchInfo, match, scoreModule, teamModule);
+
+ addAdditionalInfoToEmbed(matchInfo, match, map);
+
+ try {
+ matchInfo.setThumbnail(bot.getMapImage(map));
+ } catch (IOException e) {
+ System.out.println("Unable to get map image for " + map.getName());
+ }
+
+ bot.sendMatchEmbed(matchInfo, match);
+ }
+
+ private String getWinner(MatchFinishEvent event, Collection teams) {
+ if (event.getWinners().size() == 1) {
+ return event.getWinners().iterator().next().getNameLegacy();
+ } else if (event.getWinners().isEmpty()) {
+ return "_No winner_";
+ } else {
+ return "Tie";
}
- EmbedBuilder matchInfo =
- new EmbedBuilder()
+ }
+
+ private Color getWinnerColor(MatchFinishEvent event, Collection teams) {
+ if (event.getWinners().size() == 1) {
+ return new Color(event.getWinners().iterator().next().getFullColor().asRGB());
+ } else {
+ return Color.RED;
+ }
+ }
+
+ private EmbedBuilder createMatchInfoEmbed(Match match, MapInfo map, String winner, Color winnerColor) {
+ return new EmbedBuilder()
.setColor(winnerColor)
.setTitle("Match #" + match.getId() + " has finished!")
- .setThumbnail(bot.getMapImageUrl(map))
.setDescription(
- "Finished at with **"
- + match.getPlayers().size()
- + (match.getPlayers().size() == 1 ? " player" : " players")
- + "** online.")
- .addInlineField("Winner", winner.isEmpty() ? "_No winner_" : winner)
+ "Finished at with **"
+ + match.getPlayers().size() + (match.getPlayers().size() == 1 ? " player" : " players") + "** online.")
+ .addInlineField("Winner", winner)
.addInlineField("Time", bot.parseDuration(match.getDuration()));
+ }
+
+ private void addScoresToEmbed(EmbedBuilder embed, Match match, ScoreMatchModule scoreModule, TeamMatchModule teamModule) {
if (scoreModule != null) {
if (teamModule != null) {
- Map teamScores = new HashMap<>();
- for (Competitor team : teams) {
- teamScores.put(team.getNameLegacy(), (int) scoreModule.getScore(team));
- }
- matchInfo.addInlineField(
- "Scores",
- teamScores.entrySet().stream()
- .map(e -> e.getKey() + ": " + e.getValue() + " points")
- .collect(Collectors.joining("\n")));
+ Map teamScores = match.getCompetitors().stream()
+ .collect(Collectors.toMap(Competitor::getNameLegacy, team -> (int) scoreModule.getScore(team)));
+ embed.addInlineField("Scores", formatScores(teamScores));
} else {
- Map playerScores = new HashMap<>();
- for (Competitor player : match.getCompetitors()) {
- playerScores.put(player.getNameLegacy(), (int) scoreModule.getScore(player));
- }
- matchInfo.addInlineField(
- "Podium",
- playerScores.entrySet().stream()
- .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
- .limit(3)
- .map(e -> e.getKey() + ": " + e.getValue() + " points")
- .collect(Collectors.joining("\n")));
+ Map playerScores = match.getCompetitors().stream()
+ .collect(Collectors.toMap(Competitor::getNameLegacy, player -> (int) scoreModule.getScore(player)));
+ embed.addInlineField("Podium", formatPodium(playerScores));
}
} else {
- matchInfo.addInlineField("\u200E", "\u200E");
+ embed.addInlineField("\u200E", "\u200E");
}
- matchInfo
- .addInlineField("Map", map.getName())
- .addInlineField("Version", map.getVersion().toString())
- .addInlineField("Gamemodes", bot.getMapGamemodes(match).toUpperCase())
- .addInlineField("Participants", String.valueOf(match.getParticipants().size()))
- .addInlineField("Observers", String.valueOf(match.getDefaultParty().getPlayers().size()))
- .addInlineField("Staff", String.valueOf(bot.getOnlineStaffCount(match)))
- .setFooter("Map tags: " + map.getTags().toString());
- bot.sendMatchEmbed(matchInfo, match);
+ }
+
+ private String formatScores(Map scores) {
+ return scores.entrySet().stream()
+ .map(e -> e.getKey() + ": " + e.getValue() + " points")
+ .collect(Collectors.joining("\n"));
+ }
+
+ private String formatPodium(Map scores) {
+ return scores.entrySet().stream()
+ .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
+ .limit(3)
+ .map(e -> e.getKey() + ": " + e.getValue() + " points")
+ .collect(Collectors.joining("\n"));
+ }
+
+ private void addAdditionalInfoToEmbed(EmbedBuilder embed, Match match, MapInfo map) {
+ embed.addInlineField("Map", map.getName())
+ .addInlineField("Version", map.getVersion().toString())
+ .addInlineField("Gamemodes", bot.getMapGamemodes(match).toUpperCase())
+ .addInlineField("Participants", String.valueOf(match.getParticipants().size()))
+ .addInlineField("Observers", String.valueOf(match.getDefaultParty().getPlayers().size()))
+ .addInlineField("Staff", String.valueOf(bot.getOnlineStaffCount(match)))
+ .setFooter("Map tags: " + map.getTags().toString());
}
}
diff --git a/src/main/java/me/tbg/match/bot/MatchStartListener.java b/src/main/java/me/tbg/match/bot/MatchStartListener.java
index 8aa9ca5..4663083 100644
--- a/src/main/java/me/tbg/match/bot/MatchStartListener.java
+++ b/src/main/java/me/tbg/match/bot/MatchStartListener.java
@@ -1,6 +1,7 @@
package me.tbg.match.bot;
import java.awt.*;
+import java.io.IOException;
import java.time.Instant;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -21,18 +22,22 @@ public MatchStartListener(DiscordBot bot) {
public void onMatchStart(MatchStartEvent event) {
Match match = event.getMatch();
MapInfo map = match.getMap();
- EmbedBuilder matchStartEmbed =
- new EmbedBuilder()
+ EmbedBuilder matchStartEmbed = createMatchStartEmbed(match, map);
+
+ try {
+ matchStartEmbed.setThumbnail(bot.getMapImage(map));
+ } catch (IOException e) {
+ System.out.println("Unable to get map image for " + map.getName());
+ }
+
+ bot.sendMatchEmbed(matchStartEmbed, match);
+ }
+
+ private EmbedBuilder createMatchStartEmbed(Match match, MapInfo map) {
+ return new EmbedBuilder()
.setColor(Color.WHITE)
.setTitle("Match #" + match.getId() + " has started!")
- .setThumbnail(bot.getMapImageUrl(map))
- .setDescription(
- "Started at with **"
- + match.getPlayers().size()
- + (match.getPlayers().size() == 1 ? " player" : " players")
- + "** online.")
+ .setDescription(bot.getMatchDescription(match))
.addInlineField("Map", map.getName())
.addInlineField("Version", map.getVersion().toString())
.addInlineField("Gamemodes", bot.getMapGamemodes(match).toUpperCase())
@@ -40,10 +45,8 @@ public void onMatchStart(MatchStartEvent event) {
.addInlineField("Pools", bot.getMapPools(match))
.addField("Objective", map.getDescription())
.addInlineField("Participants", String.valueOf(match.getParticipants().size()))
- .addInlineField(
- "Observers", String.valueOf(match.getDefaultParty().getPlayers().size()))
+ .addInlineField("Observers", String.valueOf(match.getDefaultParty().getPlayers().size()))
.addInlineField("Staff", String.valueOf(bot.getOnlineStaffCount(match)))
.setFooter("Map tags: " + map.getTags().toString());
- bot.sendMatchEmbed(matchStartEmbed, event.getMatch());
}
}