Skip to content

Add server activity leaderboard#312

Open
Anheledir wants to merge 1 commit intomainfrom
codex/work-on-issue-#65-and-create-pr
Open

Add server activity leaderboard#312
Anheledir wants to merge 1 commit intomainfrom
codex/work-on-issue-#65-and-create-pr

Conversation

@Anheledir
Copy link
Owner

@Anheledir Anheledir commented Jun 5, 2025

Summary

  • add UserLeftNotification to reset activity points when a member leaves a guild
  • expose GetTopUsers in IGuildMemberRepository
  • implement leaderboard retrieval in repository
  • update EntityLifecycleHandler and DiscordEventListener for new notification
  • add /user leaderboard command
  • update translations and README
  • add unit tests for leaderboard data access

Fixes #65


https://chatgpt.com/codex/tasks/task_e_684200304e1c8324a44fd34abfd81136

Summary by CodeRabbit

  • New Features
    • Introduced an activity leaderboard command to display the most active users in your Discord server.
  • Localization
    • Added leaderboard-related translations in English, German, Spanish, and French.
  • Bug Fixes
    • Activity points for users are now reset when a user leaves the server.
  • Documentation
    • Updated the README to mention the new activity leaderboard feature.
  • Tests
    • Added and updated tests to cover leaderboard functionality and ensure correct ordering and limits.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 5, 2025

Walkthrough

A leaderboard feature for server activity was implemented. This includes a slash command to display the most active users, repository methods to fetch top users, localization for leaderboard strings, event handling for user departures (resetting activity points), and updates to documentation and tests to support these changes.

Changes

File(s) Change Summary
BaseBotService/Commands/UserModule.cs, BaseBotService/Data/Interfaces/IGuildMemberRepository.cs, BaseBotService/Data/Repositories/GuildMemberRepository.cs Added leaderboard slash command, repository method for top users, and integrated repository into the command.
BaseBotService/Core/DiscordEventListener.cs, BaseBotService/Core/Messages/UserLeftNotification.cs, BaseBotService/Interactions/EntityLifecycleHandler.cs Added event handling and notification for user leaving, resetting their activity points.
BaseBotService/Locales/en.ftl, BaseBotService/Locales/de.ftl, BaseBotService/Locales/es.ftl, BaseBotService/Locales/fr.ftl Added localization strings for leaderboard title and entries.
BaseBotServiceTests/Commands/UserModuleTests.cs, BaseBotServiceTests/Data/Repositories/GuildMemberRepositoryTests.cs Updated and added tests for leaderboard command and repository method.
README.md Added "Activity Leaderboard" to key features.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Discord
    participant UserModule
    participant IGuildMemberRepository
    participant TranslationService

    User->>Discord: Issues /leaderboard command
    Discord->>UserModule: Calls LeaderboardAsync(amount)
    UserModule->>IGuildMemberRepository: GetTopUsers(guildId, amount)
    IGuildMemberRepository-->>UserModule: Returns top users
    UserModule->>TranslationService: Get localized leaderboard title and entries
    TranslationService-->>UserModule: Localized strings
    UserModule->>Discord: Responds with leaderboard embed
Loading
sequenceDiagram
    participant Discord
    participant DiscordEventListener
    participant Mediator
    participant EntityLifecycleHandler
    participant GuildMemberRepository

    Discord-->>DiscordEventListener: UserLeft event
    DiscordEventListener->>Mediator: Publish UserLeftNotification
    Mediator->>EntityLifecycleHandler: Handle(UserLeftNotification)
    EntityLifecycleHandler->>GuildMemberRepository: Find member, set ActivityPoints to 0
    GuildMemberRepository-->>EntityLifecycleHandler: Update complete
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement overall Top-10 leaderboard (users appear after time on server) (#65)
Set activity points to zero when leaving a server (#65)
Add a command to show server's top-10 leaderboard (#65)
Add optional parameter for command (max top-100) (#65)
Update documentation to reflect new leaderboard feature (#65)

Poem

In the burrows of code, a leaderboard grew,
Now bunnies can see who’s most active—who knew?
When a user hops out, their points are reset,
And with slash commands, the top list you’ll get.
Multilingual cheers from this rabbit’s domain,
For activity tracked, with much to gain!
🥕🏆

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added documentation Improvements or additions to documentation enhancement New feature or request core Changes that change the behavior of some core-features testing New or modified testing scripts labels Jun 5, 2025
@sonarqubecloud
Copy link

sonarqubecloud bot commented Jun 5, 2025

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
README.md (1)

24-24: Apply the grammar suggestion from static analysis.

The static analysis tool correctly identifies that "on your server" is more conventional than "in your server" when referring to Discord servers.

-- **Activity Leaderboard:** See which members are most active in your server.
+- **Activity Leaderboard:** See which members are most active on your server.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~24-~24: The preposition “on” seems more likely in this position than the preposition “in”.
Context: ...rd:** See which members are most active in your server. - **Announcement of New Ar...

(AI_EN_LECTOR_REPLACEMENT_PREPOSITION_IN_ON)

BaseBotService/Data/Interfaces/IGuildMemberRepository.cs (1)

40-46: Well-documented interface method addition.

The method signature and documentation follow good practices. Consider documenting behavior for edge cases like negative limit values in the XML documentation.

 /// <summary>
 /// Gets the top users of a guild ordered by their activity points.
 /// </summary>
 /// <param name="guildId">The unique identifier of the guild.</param>
-/// <param name="limit">The maximum number of users to return.</param>
+/// <param name="limit">The maximum number of users to return. Must be positive.</param>
 /// <returns>An enumerable of <see cref="GuildMemberHC"/> ordered by activity points.</returns>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a736070 and 0559eba.

📒 Files selected for processing (13)
  • BaseBotService/Commands/UserModule.cs (2 hunks)
  • BaseBotService/Core/DiscordEventListener.cs (1 hunks)
  • BaseBotService/Core/Messages/UserLeftNotification.cs (1 hunks)
  • BaseBotService/Data/Interfaces/IGuildMemberRepository.cs (1 hunks)
  • BaseBotService/Data/Repositories/GuildMemberRepository.cs (1 hunks)
  • BaseBotService/Interactions/EntityLifecycleHandler.cs (2 hunks)
  • BaseBotService/Locales/de.ftl (1 hunks)
  • BaseBotService/Locales/en.ftl (1 hunks)
  • BaseBotService/Locales/es.ftl (1 hunks)
  • BaseBotService/Locales/fr.ftl (1 hunks)
  • BaseBotServiceTests/Commands/UserModuleTests.cs (2 hunks)
  • BaseBotServiceTests/Data/Repositories/GuildMemberRepositoryTests.cs (1 hunks)
  • README.md (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
BaseBotService/Core/DiscordEventListener.cs (1)
BaseBotService/Core/Messages/UserLeftNotification.cs (2)
  • UserLeftNotification (4-14)
  • UserLeftNotification (9-13)
BaseBotService/Data/Interfaces/IGuildMemberRepository.cs (1)
BaseBotService/Data/Models/GuildMemberHC.cs (1)
  • GuildMemberHC (5-21)
BaseBotServiceTests/Data/Repositories/GuildMemberRepositoryTests.cs (1)
BaseBotServiceTests/FakeDataHelper.cs (1)
  • FakeDataHelper (12-140)
🪛 LanguageTool
README.md

[uncategorized] ~24-~24: The preposition “on” seems more likely in this position than the preposition “in”.
Context: ...rd:** See which members are most active in your server. - **Announcement of New Ar...

(AI_EN_LECTOR_REPLACEMENT_PREPOSITION_IN_ON)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (12)
BaseBotService/Core/DiscordEventListener.cs (1)

44-44: LGTM! Event handler follows established pattern.

The UserLeft event handler implementation is consistent with other event handlers in the class and properly integrates with the mediator pattern.

BaseBotServiceTests/Commands/UserModuleTests.cs (3)

16-16: LGTM! Proper dependency field addition.

The new repository field follows the established pattern for dependency injection in the test class.


27-27: LGTM! Correct mock initialization.

The repository mock is properly initialized using NSubstitute in the SetUp method.


30-30: LGTM! Constructor dependency injection updated correctly.

The UserModule constructor call properly includes the new guild member repository dependency.

BaseBotService/Locales/en.ftl (1)

141-142: LGTM! Well-structured localization entries for the leaderboard feature.

The new localization entries follow the established Fluent pattern and use appropriate variable names for displaying leaderboard data.

BaseBotService/Core/Messages/UserLeftNotification.cs (1)

4-14: LGTM! Clean and well-structured notification class.

The class follows proper encapsulation patterns with read-only properties and constructor initialization.

BaseBotServiceTests/Data/Repositories/GuildMemberRepositoryTests.cs (1)

95-117: LGTM! Comprehensive test coverage for GetTopUsers method.

The test properly verifies both the count limitation and the correct ordering by ActivityPoints in descending order. The test follows good AAA (Arrange-Act-Assert) pattern and uses appropriate assertions.

BaseBotService/Interactions/EntityLifecycleHandler.cs (2)

7-7: LGTM! Proper interface implementation for the new notification handler.

The class signature correctly implements the new INotificationHandler<UserLeftNotification> interface.


58-71:

Details

❓ Verification inconclusive

Consider the business logic: reset vs. remove activity points.

The implementation correctly handles the UserLeftNotification with proper logging and null checking. However, consider whether resetting ActivityPoints to 0 is the intended behavior vs. completely removing the guild member record when a user leaves.

If users can rejoin and should start fresh, resetting to 0 makes sense. If the record should be preserved for historical purposes, this is correct. If the record should be deleted entirely, consider using DeleteUser instead.

Verify the intended business logic for user departure:


🏁 Script executed:

#!/bin/bash
# Description: Check if there are any business requirements or documentation about activity point handling when users leave

# Search for any documentation or comments about user departure handling
rg -i "user.*left|leave.*guild|activity.*point.*reset" --type md
rg -i "user.*left|leave.*guild|activity.*point.*reset" -A 3 -B 3

# Look for any existing patterns of handling user departures
ast-grep --pattern 'ActivityPoints = 0'
ast-grep --pattern 'DeleteUser($_, $_)'

Length of output: 69947


Verify intended behavior for UserLeftNotification handling

I didn’t find any docs or code patterns (e.g. DeleteUser) detailing what should happen to a member’s record when they leave. Currently we:

  • In BaseBotService/Interactions/EntityLifecycleHandler.cs (lines 58–71), on UserLeftNotification:
    • Retrieve the guild member
    • Set ActivityPoints = 0
    • Call _guildMemberRepository.UpdateUser(member)

Please confirm with your product or requirements whether:

  • Users should rejoin with a fresh slate (reset points to 0)
  • The record should be retained for history (keep & update elsewhere)
  • The record should be deleted entirely (invoke a DeleteUser(...) instead)
BaseBotService/Commands/UserModule.cs (3)

23-23: LGTM! Proper dependency injection field addition.

The new repository field follows the established pattern of other dependencies in the class.


25-25: LGTM! Constructor properly updated for dependency injection.

The constructor correctly accepts and assigns the new IGuildMemberRepository dependency following the established pattern.

Also applies to: 31-31


252-283: Well-implemented leaderboard command with proper error handling.

The implementation demonstrates several good practices:

  • Input validation with Math.Clamp to ensure safe bounds
  • Null-safe user lookup with fallback to member ID when user has left the guild
  • Proper use of translation service for localization
  • Consistent embed building pattern following the existing codebase style

The method handles the edge case where users may have left the guild by providing a fallback display name, which maintains leaderboard integrity.

Comment on lines +42 to +46
public IEnumerable<GuildMemberHC> GetTopUsers(ulong guildId, int limit)
=> _guildMembers
.Find(a => a.GuildId == guildId)
.OrderByDescending(u => u.ActivityPoints)
.Take(limit);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation for the limit parameter.

The implementation is correct but should validate the limit parameter to prevent potential issues with negative values.

 public IEnumerable<GuildMemberHC> GetTopUsers(ulong guildId, int limit)
-    => _guildMembers
+{
+    if (limit < 0)
+        throw new ArgumentOutOfRangeException(nameof(limit), "Limit must be non-negative.");
+        
+    return _guildMembers
         .Find(a => a.GuildId == guildId)
         .OrderByDescending(u => u.ActivityPoints)
         .Take(limit);
+}

Note: For very large guilds, consider implementing database-level ordering and limiting to improve performance, though the current approach should be sufficient for typical Discord server sizes.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public IEnumerable<GuildMemberHC> GetTopUsers(ulong guildId, int limit)
=> _guildMembers
.Find(a => a.GuildId == guildId)
.OrderByDescending(u => u.ActivityPoints)
.Take(limit);
public IEnumerable<GuildMemberHC> GetTopUsers(ulong guildId, int limit)
{
if (limit < 0)
throw new ArgumentOutOfRangeException(nameof(limit), "Limit must be non-negative.");
return _guildMembers
.Find(a => a.GuildId == guildId)
.OrderByDescending(u => u.ActivityPoints)
.Take(limit);
}
🤖 Prompt for AI Agents
In BaseBotService/Data/Repositories/GuildMemberRepository.cs around lines 42 to
46, the GetTopUsers method lacks validation for the limit parameter, which could
lead to issues if a negative value is passed. Add input validation to check if
limit is less than or equal to zero and handle it appropriately, such as
returning an empty collection or throwing an ArgumentException. This ensures the
method behaves predictably and prevents potential runtime errors.

Comment on lines +137 to +138
leaderboard-title = Top { $amount } active users
leaderboard-entry = { $rank }. { $user } - { $points } pts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Translate strings to German for proper localization.

The leaderboard strings are in English within the German localization file. For proper internationalization, these should be translated to German.

-leaderboard-title = Top { $amount } active users
-leaderboard-entry = { $rank }. { $user } - { $points } pts
+leaderboard-title = Top { $amount } aktive Benutzer
+leaderboard-entry = { $rank }. { $user } - { $points } Punkte
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
leaderboard-title = Top { $amount } active users
leaderboard-entry = { $rank }. { $user } - { $points } pts
leaderboard-title = Top { $amount } aktive Benutzer
leaderboard-entry = { $rank }. { $user } - { $points } Punkte
🤖 Prompt for AI Agents
In BaseBotService/Locales/de.ftl around lines 137 to 138, the leaderboard
strings are still in English, which is incorrect for the German localization
file. Translate the strings "Top { $amount } active users" and "{ $rank }. {
$user } - { $points } pts" into proper German equivalents to ensure correct
localization.

Comment on lines +137 to +138
leaderboard-title = Top { $amount } active users
leaderboard-entry = { $rank }. { $user } - { $points } pts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Translate strings to Spanish for proper localization.

The leaderboard strings are in English within the Spanish localization file. For proper internationalization, these should be translated to Spanish.

-leaderboard-title = Top { $amount } active users
-leaderboard-entry = { $rank }. { $user } - { $points } pts
+leaderboard-title = Top { $amount } usuarios activos
+leaderboard-entry = { $rank }. { $user } - { $points } pts

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In BaseBotService/Locales/es.ftl around lines 137 to 138, the leaderboard
strings are still in English within the Spanish localization file. Translate
"Top { $amount } active users" and "{ $rank }. { $user } - { $points } pts" into
Spanish to ensure proper localization and internationalization.

Comment on lines +137 to +138
leaderboard-title = Top { $amount } active users
leaderboard-entry = { $rank }. { $user } - { $points } pts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Translate strings to French for proper localization.

The leaderboard strings are in English within the French localization file. For proper internationalization, these should be translated to French.

-leaderboard-title = Top { $amount } active users
-leaderboard-entry = { $rank }. { $user } - { $points } pts
+leaderboard-title = Top { $amount } utilisateurs actifs
+leaderboard-entry = { $rank }. { $user } - { $points } pts
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
leaderboard-title = Top { $amount } active users
leaderboard-entry = { $rank }. { $user } - { $points } pts
leaderboard-title = Top { $amount } utilisateurs actifs
leaderboard-entry = { $rank }. { $user } - { $points } pts
🤖 Prompt for AI Agents
In BaseBotService/Locales/fr.ftl at lines 137 to 138, the leaderboard strings
are still in English. Translate "Top { $amount } active users" and "{ $rank }. {
$user } - { $points } pts" into French to ensure proper localization. Replace
the English text with accurate French equivalents while keeping the variable
placeholders intact.

Comment on lines +1 to +2
using Discord.WebSocket;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing using statement for MediatR.

The INotification interface requires a using statement for MediatR.

Apply this diff to add the missing using statement:

 using Discord.WebSocket;
+using MediatR;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
using Discord.WebSocket;
using Discord.WebSocket;
using MediatR;
🤖 Prompt for AI Agents
In BaseBotService/Core/Messages/UserLeftNotification.cs at the top of the file
around lines 1 to 2, add the missing using statement for MediatR by including
"using MediatR;". This is necessary because the INotification interface used in
the file is defined in the MediatR namespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex core Changes that change the behavior of some core-features documentation Improvements or additions to documentation enhancement New feature or request testing New or modified testing scripts

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Create a leaderboard for the server activity

1 participant