Skip to content

Commit dd02f65

Browse files
committed
Reformat punishment history and escape names on playtime leaderboard
1 parent 91293ff commit dd02f65

4 files changed

Lines changed: 127 additions & 63 deletions

File tree

‎src/main/java/com/diamondfire/helpbot/bot/command/impl/stats/individualized/HistoryCommand.java‎

Lines changed: 66 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import com.diamondfire.helpbot.sys.externalfile.ExternalFileUtil;
1414
import com.diamondfire.helpbot.util.*;
1515
import net.dv8tion.jda.api.EmbedBuilder;
16+
import net.dv8tion.jda.api.entities.*;
1617
import net.dv8tion.jda.api.requests.restaction.MessageCreateAction;
1718
import net.dv8tion.jda.api.utils.FileUpload;
1819

@@ -55,7 +56,9 @@ public Permission getPermission() {
5556

5657
@Override
5758
protected void execute(CommandEvent event, Player player) {
58-
if (!Permission.MODERATION.hasPermission(event.getMember()) && !event.getMember().getEffectiveName().equals(player.name())) {
59+
// No player argument means the member's own (linked) account was used.
60+
boolean self = event.getArgument("player") == null || event.getMember().getEffectiveName().equalsIgnoreCase(player.name());
61+
if (!self && !Permission.MODERATION.hasPermission(event.getMember())) {
5962
PresetBuilder activePunishmentsPreset = new PresetBuilder()
6063
.withPreset(
6164
new InformativeReply(InformativeReplyType.ERROR, "You must be a moderator inorder to see other peoples history!")
@@ -73,90 +76,66 @@ protected void execute(CommandEvent event, Player player) {
7376
.fetch();
7477

7578
event.getMember().getUser().openPrivateChannel().queue((privateChannel) -> {
76-
// Retrieve active punishments
79+
// Recap: summary counts and any active punishments.
7780
{
78-
PresetBuilder activePunishmentsPreset = new PresetBuilder()
81+
List<Punishment> active = punishments.stream().filter((punishment) -> punishment.active).toList();
82+
83+
PresetBuilder recapPreset = new PresetBuilder()
7984
.withPreset(
8085
new MinecraftUserPreset(player),
81-
new InformativeReply(InformativeReplyType.INFO, "History Recap", null)
86+
active.isEmpty()
87+
? new InformativeReply(InformativeReplyType.INFO, "History Recap", null)
88+
: new InformativeReply(InformativeReplyType.ERROR, "Active Punishments", null)
8289
);
83-
EmbedBuilder embed = activePunishmentsPreset.getEmbed();
84-
85-
List<String> activePunishments = new ArrayList<>();
86-
int warnings = 0;
87-
int yearlyWarnings = 0;
88-
for (Punishment punishment : punishments) {
89-
if (punishment.active) {
90-
activePunishments.add(punishment.toString());
91-
}
92-
if (punishment.type == PunishmentType.WARN) {
93-
if (ChronoUnit.DAYS.between(punishment.startTime.toInstant(), Instant.now()) <= 365) {
94-
yearlyWarnings++;
95-
}
96-
warnings++;
97-
}
98-
}
99-
punishments.removeIf((punishment) -> punishment.active);
90+
EmbedBuilder embed = recapPreset.getEmbed();
10091

101-
if (activePunishments.size() > 0) {
102-
activePunishmentsPreset.withPreset(new InformativeReply(InformativeReplyType.ERROR, "Active Punishments", null));
103-
EmbedUtil.addFields(embed, activePunishments, "", true);
104-
105-
String duration = null;
106-
int warningReq = 0;
107-
if (warnings < 4 && warnings > 1) {
108-
duration = "30 minute";
109-
warningReq = 4 - warnings;
110-
} else if (warnings < 5) {
111-
duration = "1 hour";
112-
warningReq = 5 - warnings;
113-
} else if (warnings < 6) {
114-
duration = "12 hour";
115-
warningReq = 6 - warnings;
92+
if (punishments.isEmpty()) {
93+
embed.setDescription("No punishments here, keep up the good work!");
94+
} else {
95+
StringBuilder description = new StringBuilder(summarize(punishments));
96+
for (Punishment punishment : active) {
97+
description.append("\n\n").append(punishment.format());
11698
}
11799

118-
// if (duration != null) {
119-
// embed.addField("Tempban", String.format("\u26A0 If you receive **%s** more active %s, you will receive a **%s** tempban!", warningReq, StringUtil.sCheck("warning", warningReq), duration), false);
120-
// }
121-
122-
} else if (punishments.size() == 0) {
123-
embed.setDescription("No punishments here, keep up the good work!");
100+
embed.setDescription(description.length() > MessageEmbed.DESCRIPTION_MAX_LENGTH
101+
? description.substring(0, MessageEmbed.DESCRIPTION_MAX_LENGTH - 1) + "…"
102+
: description.toString());
124103
}
125-
//
126-
// if (yearlyWarnings > 10) {
127-
// embed.setColor(Color.RED);
128-
// embed.addField("Tempban", String.format("\u26A0 If you receive **%s** more %s this year, you will receive a **45** day tempban!", 20 - yearlyWarnings, StringUtil.sCheck("warning", 20 - yearlyWarnings)), false);
129-
// }
130104

131105
msgs.add(privateChannel.sendMessageEmbeds(embed.build()));
106+
punishments.removeIf((punishment) -> punishment.active);
132107
}
133108

134-
// Retrieve normal punishments
135-
{
136-
PresetBuilder punishmentsPreset = new PresetBuilder()
137-
.withPreset(
138-
new InformativeReply(InformativeReplyType.INFO, "Punishment History", null)
139-
);
140-
EmbedBuilder presetBuilder = punishmentsPreset.getEmbed();
141-
List<String> punishmentStrings = new ArrayList<>();
109+
// Past punishments, newest first, split over as many embeds as needed.
110+
if (!punishments.isEmpty()) {
111+
punishments.sort(Comparator.comparing((Punishment punishment) -> punishment.startTime).reversed());
112+
113+
List<MessageEmbed> embeds = new ArrayList<>();
114+
StringBuilder page = new StringBuilder();
115+
int total = 0;
142116
for (Punishment punishment : punishments) {
143-
punishmentStrings.add(punishment.toString());
117+
String entry = punishment.format();
118+
if (page.length() + entry.length() + 2 > MessageEmbed.DESCRIPTION_MAX_LENGTH) {
119+
embeds.add(historyEmbed(page.toString(), embeds.isEmpty()));
120+
page.setLength(0);
121+
}
122+
123+
page.append(page.isEmpty() ? "" : "\n\n").append(entry);
124+
total += entry.length() + 2;
144125
}
126+
embeds.add(historyEmbed(page.toString(), embeds.isEmpty()));
145127

146-
EmbedUtil.addFields(presetBuilder, punishmentStrings, "", "", true);
147-
if (punishmentStrings.size() == 0) {
148-
} else if (presetBuilder.isValidLength()) {
149-
msgs.add(privateChannel.sendMessageEmbeds(presetBuilder.build()));
128+
if (embeds.size() <= Message.MAX_EMBED_COUNT && total < MessageEmbed.EMBED_MAX_LENGTH_BOT - 100) {
129+
msgs.add(privateChannel.sendMessageEmbeds(embeds));
150130
} else {
151131
try {
152132
File sendFile = ExternalFileUtil.generateFile("history.txt");
153-
Files.writeString(sendFile.toPath(), String.join("\n", punishmentStrings));
133+
Files.writeString(sendFile.toPath(), String.join("\n\n", punishments.stream().map(Punishment::toString).toList()));
154134
msgs.add(privateChannel.sendFiles(FileUpload.fromData(sendFile)));
155135
} catch (IOException exception) {
156136
exception.printStackTrace();
157137
}
158138
}
159-
160139
}
161140

162141
MessageCreateAction action = msgs.get(0);
@@ -187,4 +166,29 @@ protected void execute(CommandEvent event, Player player) {
187166
});
188167
}
189168

169+
private static MessageEmbed historyEmbed(String description, boolean first) {
170+
EmbedBuilder embed = new PresetBuilder()
171+
.withPreset(new InformativeReply(InformativeReplyType.INFO, first ? "Punishment History" : null, null))
172+
.getEmbed();
173+
return embed.setDescription(description).build();
174+
}
175+
176+
private static String summarize(List<Punishment> punishments) {
177+
Map<PunishmentType, Integer> counts = new EnumMap<>(PunishmentType.class);
178+
int yearlyWarnings = 0;
179+
for (Punishment punishment : punishments) {
180+
counts.merge(punishment.type, 1, Integer::sum);
181+
if (punishment.type == PunishmentType.WARN && ChronoUnit.DAYS.between(punishment.startTime.toInstant(), Instant.now()) <= 365) {
182+
yearlyWarnings++;
183+
}
184+
}
185+
186+
int warnings = counts.getOrDefault(PunishmentType.WARN, 0);
187+
return String.format("**%s** %s (%s in the past year) · **%s** %s · **%s** %s · **%s** %s",
188+
warnings, StringUtil.sCheck("warning", warnings), yearlyWarnings,
189+
counts.getOrDefault(PunishmentType.MUTE, 0), StringUtil.sCheck("mute", counts.getOrDefault(PunishmentType.MUTE, 0)),
190+
counts.getOrDefault(PunishmentType.KICK, 0), StringUtil.sCheck("kick", counts.getOrDefault(PunishmentType.KICK, 0)),
191+
counts.getOrDefault(PunishmentType.BAN, 0), StringUtil.sCheck("ban", counts.getOrDefault(PunishmentType.BAN, 0)));
192+
}
193+
190194
}

‎src/main/java/com/diamondfire/helpbot/bot/command/impl/stats/individualized/PlaytimeCommand.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ protected void execute(CommandEvent event, Player player) {
9494
String name = set.getString("name");
9595
String line = String.format("`#%s` %s - %s",
9696
FormatUtil.formatNumber(rank),
97-
name == null ? "Unknown Player" : StringUtil.display(name),
97+
name == null ? "Unknown Player" : StringUtil.escapeName(name),
9898
FormatUtil.formatMilliTime(set.getLong("play_time_ms")));
9999

100100
lines.add(set.getString("uuid").equals(uuid) ? "**" + line + "**" : line);

‎src/main/java/com/diamondfire/helpbot/df/punishments/Punishment.java‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.diamondfire.helpbot.util.*;
44

5+
import net.dv8tion.jda.api.utils.TimeFormat;
6+
57
import java.sql.Timestamp;
68
import java.time.Instant;
79

@@ -48,6 +50,56 @@ private String formatExpire() {
4850
return FormatUtil.formatDate(removeDate) + (removeByName.equals("#expired") ? " Automatically" : " (Removed by staff)");
4951
}
5052

53+
/**
54+
* Discord markdown view of this punishment, using timestamps that render in the viewer's timezone.
55+
*/
56+
public String format() {
57+
StringBuilder builder = new StringBuilder();
58+
builder.append("**").append(typeName()).append("**");
59+
if (untilTime != null && (type == PunishmentType.MUTE || type == PunishmentType.BAN)) {
60+
builder.append(" (").append(FormatUtil.formatMilliTime(untilTime.getTime() - startTime.getTime())).append(")");
61+
} else if (untilTime == null && (type == PunishmentType.MUTE || type == PunishmentType.BAN)) {
62+
builder.append(" (Permanent)");
63+
}
64+
builder.append(" · ").append(TimeFormat.DATE_SHORT.format(startTime.getTime()));
65+
66+
String reasonGiven = reason.isBlank() ? "*No reason given*" : reason.trim().replace("\n", " ").replace("\r", "");
67+
builder.append("\n> ").append(reasonGiven);
68+
69+
String status = formatStatus();
70+
if (status != null) {
71+
builder.append("\n*").append(status).append("*");
72+
}
73+
74+
return builder.toString();
75+
}
76+
77+
private String typeName() {
78+
return switch (type) {
79+
case WARN -> "Warning";
80+
case KICK -> "Kick";
81+
case MUTE -> "Mute";
82+
case BAN -> "Ban";
83+
};
84+
}
85+
86+
private String formatStatus() {
87+
if (type == PunishmentType.KICK) {
88+
return null;
89+
}
90+
91+
if (active) {
92+
return untilTime == null ? "Active, does not expire" : "Active, expires " + TimeFormat.RELATIVE.format(untilTime.getTime());
93+
}
94+
95+
if (removeDate != null && removeByName != null && !removeByName.equals("#expired")) {
96+
return "Removed by staff " + TimeFormat.RELATIVE.format(removeDate.getTime());
97+
}
98+
99+
Timestamp ended = removeDate != null ? removeDate : untilTime;
100+
return ended == null ? "Expired" : "Expired " + TimeFormat.RELATIVE.format(ended.getTime());
101+
}
102+
51103
@Override
52104
public String toString() {
53105
String reasonGiven = reason.isBlank() ? "No Reason Given" : reason;

‎src/main/java/com/diamondfire/helpbot/util/StringUtil.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ public static List<String> splitBy(String string, int byAmt) {
8888
public static String display(String string) {
8989
return MarkdownSanitizer.escape(StringUtil.stripColorCodes(string));
9090
}
91+
92+
/**
93+
* Escapes every markdown character in a name, so names like {@code a_b} never get formatted
94+
* (the sanitizer leaves lone underscores alone, which Discord can still pair up).
95+
*/
96+
public static String escapeName(String name) {
97+
return name.replaceAll("([\\\\*_~`|>\\[\\]()#-])", "\\\\$1");
98+
}
9199

92100
public static String fromMiniMessage(String expression) {
93101
Matcher matcher = UNICODE_PATTERN.matcher(expression);

0 commit comments

Comments
 (0)