-
-
Notifications
You must be signed in to change notification settings - Fork 111
Feature/leaderboard command #1465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
barsh404error
wants to merge
5
commits into
Together-Java:develop
Choose a base branch
from
barsh404error:feature/leaderboard-command
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+177
−0
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9bb9883
feat: add /leaderboard command showing top helpers hall of fame
barsh404error 23b6d5f
/leaderboard command showing top helpers hall of fame
barsh404error 94b6922
refactor: use Instant instead of OffsetDateTime and extract fetchNewM…
barsh404error 7ce48b6
used requireNonNull for guild and included pattern in channel not fou…
barsh404error f6fa45a
fixed compile pattern in constructor, added leaderboard exclusion con…
barsh404error File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
146 changes: 146 additions & 0 deletions
146
...ication/src/main/java/org/togetherjava/tjbot/features/leaderboard/LeaderboardCommand.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| package org.togetherjava.tjbot.features.leaderboard; | ||
|
|
||
| import net.dv8tion.jda.api.EmbedBuilder; | ||
| import net.dv8tion.jda.api.entities.Guild; | ||
| import net.dv8tion.jda.api.entities.Member; | ||
| import net.dv8tion.jda.api.entities.Message; | ||
| import net.dv8tion.jda.api.entities.User; | ||
| import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; | ||
| import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import org.togetherjava.tjbot.config.Config; | ||
| import org.togetherjava.tjbot.features.CommandVisibility; | ||
| import org.togetherjava.tjbot.features.SlashCommandAdapter; | ||
| import org.togetherjava.tjbot.features.tophelper.TopHelpersService; | ||
| import org.togetherjava.tjbot.features.utils.Colors; | ||
|
|
||
| import java.util.Comparator; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.StringJoiner; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| /** | ||
| * Implements the {@code /leaderboard} slash command, which displays the all-time top helpers | ||
| * leaderboard by reading the hall-of-fame channel history. | ||
| */ | ||
| public final class LeaderboardCommand extends SlashCommandAdapter { | ||
| private static final Logger logger = LoggerFactory.getLogger(LeaderboardCommand.class); | ||
|
|
||
| private static final String COMMAND_NAME = "leaderboard"; | ||
| private static final int TOP_LIMIT = 10; | ||
| private static final int HISTORY_LIMIT = 500; | ||
|
|
||
| private static final String MEDAL_FIRST = "🥇"; | ||
| private static final String MEDAL_SECOND = "🥈"; | ||
| private static final String MEDAL_THIRD = "🥉"; | ||
| private static final String BULLET = "▸"; | ||
|
|
||
| private final Config config; | ||
|
|
||
| public LeaderboardCommand(Config config) { | ||
| super(COMMAND_NAME, "Show the all-time top helpers leaderboard", CommandVisibility.GUILD); | ||
| this.config = config; | ||
| } | ||
|
|
||
| @Override | ||
| public void onSlashCommand(SlashCommandInteractionEvent event) { | ||
| Guild guild = event.getGuild(); | ||
| if (guild == null) { | ||
| event.reply("This command can only be used inside a server.") | ||
| .setEphemeral(true) | ||
| .queue(); | ||
| return; | ||
| } | ||
|
|
||
| event.deferReply().queue(); | ||
|
|
||
| Pattern channelPattern = | ||
|
surajkumar marked this conversation as resolved.
Outdated
|
||
| Pattern.compile(config.getTopHelpers().getAnnouncementChannelPattern()); | ||
| TextChannel hallOfFame = guild.getTextChannels() | ||
| .stream() | ||
| .filter(channel -> channelPattern.matcher(channel.getName()).find()) | ||
| .findFirst() | ||
| .orElse(null); | ||
|
|
||
| if (hallOfFame == null) { | ||
| event.getHook().editOriginal("Could not find the hall of fame channel.").queue(); | ||
|
surajkumar marked this conversation as resolved.
Outdated
|
||
| return; | ||
| } | ||
|
|
||
| hallOfFame.getIterableHistory().takeAsync(HISTORY_LIMIT).thenAccept(messages -> { | ||
|
surajkumar marked this conversation as resolved.
Outdated
|
||
| Map<Long, Integer> winsByUser = countWins(messages); | ||
|
|
||
| List<Map.Entry<Long, Integer>> sorted = winsByUser.entrySet() | ||
| .stream() | ||
| .sorted(Map.Entry.<Long, Integer>comparingByValue(Comparator.reverseOrder())) | ||
| .limit(TOP_LIMIT) | ||
| .toList(); | ||
|
|
||
| if (sorted.isEmpty()) { | ||
| event.getHook().editOriginal("No top helper data found.").queue(); | ||
| return; | ||
| } | ||
|
|
||
| List<Long> ids = sorted.stream().map(Map.Entry::getKey).toList(); | ||
|
|
||
| guild.retrieveMembersByIds(ids).onSuccess(members -> { | ||
| Map<Long, Member> memberById = TopHelpersService.mapUserIdToMember(members); | ||
|
|
||
| StringJoiner description = new StringJoiner("\n"); | ||
| for (int i = 0; i < sorted.size(); i++) { | ||
| Map.Entry<Long, Integer> entry = sorted.get(i); | ||
| Member member = memberById.get(entry.getKey()); | ||
| String name = TopHelpersService.getUsernameDisplay(member); | ||
| int wins = entry.getValue(); | ||
| description.add("%s **%s** — %d month%s".formatted(rankPrefix(i), name, wins, | ||
| wins == 1 ? "" : "s")); | ||
| } | ||
|
|
||
| EmbedBuilder embed = new EmbedBuilder().setTitle("🏆 Top Helpers — Hall of Fame") | ||
| .setDescription(description.toString()) | ||
| .setColor(Colors.SUCCESS_COLOR) | ||
| .setFooter("Times awarded Top Helper"); | ||
|
|
||
| event.getHook().editOriginalEmbeds(embed.build()).queue(); | ||
|
|
||
| }).onError(error -> { | ||
| logger.error("Failed to retrieve members for leaderboard", error); | ||
| event.getHook() | ||
| .editOriginal("Failed to load member data, please try again.") | ||
| .queue(); | ||
| }); | ||
|
|
||
| }).exceptionally(error -> { | ||
| logger.error("Failed to read hall of fame channel", error); | ||
| event.getHook().editOriginal("Failed to read the hall of fame channel.").queue(); | ||
| return null; | ||
| }); | ||
| } | ||
|
|
||
| private static Map<Long, Integer> countWins(List<Message> messages) { | ||
| Map<Long, Integer> wins = new HashMap<>(); | ||
| for (Message message : messages) { | ||
| String content = message.getContentRaw(); | ||
| if (!content.toLowerCase().contains("top helper")) { | ||
|
surajkumar marked this conversation as resolved.
Outdated
surajkumar marked this conversation as resolved.
Outdated
|
||
| continue; | ||
| } | ||
| for (User user : message.getMentions().getUsers()) { | ||
| wins.merge(user.getIdLong(), 1, Integer::sum); | ||
| } | ||
| } | ||
| return wins; | ||
| } | ||
|
|
||
| private static String rankPrefix(int zeroBasedIndex) { | ||
| return switch (zeroBasedIndex) { | ||
| case 0 -> MEDAL_FIRST; | ||
| case 1 -> MEDAL_SECOND; | ||
| case 2 -> MEDAL_THIRD; | ||
| default -> BULLET + " #" + (zeroBasedIndex + 1); | ||
| }; | ||
| } | ||
| } | ||
4 changes: 4 additions & 0 deletions
4
application/src/main/java/org/togetherjava/tjbot/features/leaderboard/package-info.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| @MethodsReturnNonnullByDefault | ||
| package org.togetherjava.tjbot.features.leaderboard; | ||
|
|
||
| import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.