Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
TBG1000 committed Jul 20, 2024
1 parent 55afa65 commit 3d9254c
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 96 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
<dependency>
<groupId>org.javacord</groupId>
<artifactId>javacord</artifactId>
<version>3.5.0</version>
<version>3.8.0</version>
<type>pom</type>
</dependency>
</dependencies>
Expand Down
6 changes: 0 additions & 6 deletions src/main/java/me/tbg/match/bot/BotConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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() {
Expand All @@ -38,8 +36,4 @@ public String getServerId() {
public String getMatchChannel() {
return matchChannel;
}

public String getMapImagesURL() {
return mapImagesURL;
}
}
56 changes: 34 additions & 22 deletions src/main/java/me/tbg/match/bot/DiscordBot.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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())
Expand All @@ -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 <t:" + Instant.now().getEpochSecond() + ":f> 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) {
Expand Down
130 changes: 76 additions & 54 deletions src/main/java/me/tbg/match/bot/MatchFinishListener.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<Competitor> 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<Competitor> 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<Competitor> 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 <t:"
+ Instant.now().getEpochSecond()
+ ":f> with **"
+ match.getPlayers().size()
+ (match.getPlayers().size() == 1 ? " player" : " players")
+ "** online.")
.addInlineField("Winner", winner.isEmpty() ? "_No winner_" : winner)
"Finished at <t:" + Instant.now().getEpochSecond() + ":f> 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<String, Integer> 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<String, Integer> teamScores = match.getCompetitors().stream()
.collect(Collectors.toMap(Competitor::getNameLegacy, team -> (int) scoreModule.getScore(team)));
embed.addInlineField("Scores", formatScores(teamScores));
} else {
Map<String, Integer> 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<String, Integer> 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<String, Integer> scores) {
return scores.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue() + " points")
.collect(Collectors.joining("\n"));
}

private String formatPodium(Map<String, Integer> 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());
}
}
29 changes: 16 additions & 13 deletions src/main/java/me/tbg/match/bot/MatchStartListener.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,29 +22,31 @@ 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 <t:"
+ Instant.now().getEpochSecond()
+ ":f> 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())
.addInlineField("Created by", bot.getMapAuthors(match))
.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());
}
}

0 comments on commit 3d9254c

Please sign in to comment.