-
-
Notifications
You must be signed in to change notification settings - Fork 101
Auto-prune of full helper roles #495
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
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
168 changes: 168 additions & 0 deletions
168
application/src/main/java/org/togetherjava/tjbot/commands/help/AutoPruneHelperRoutine.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,168 @@ | ||
package org.togetherjava.tjbot.commands.help; | ||
|
||
import net.dv8tion.jda.api.JDA; | ||
import net.dv8tion.jda.api.entities.Guild; | ||
import net.dv8tion.jda.api.entities.Member; | ||
import net.dv8tion.jda.api.entities.Role; | ||
import net.dv8tion.jda.api.entities.TextChannel; | ||
import org.jetbrains.annotations.NotNull; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.togetherjava.tjbot.commands.Routine; | ||
import org.togetherjava.tjbot.config.Config; | ||
import org.togetherjava.tjbot.db.Database; | ||
import org.togetherjava.tjbot.moderation.ModAuditLogWriter; | ||
|
||
import java.time.Duration; | ||
import java.time.Instant; | ||
import java.time.Period; | ||
import java.util.*; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
import static org.togetherjava.tjbot.db.generated.tables.HelpChannelMessages.HELP_CHANNEL_MESSAGES; | ||
|
||
/** | ||
* Due to a technical limitation in Discord, roles with more than 100 users can not be ghost-pinged | ||
* into helper threads. | ||
* <p> | ||
* This routine mitigates the problem by automatically pruning inactive users from helper roles | ||
* approaching this limit. | ||
*/ | ||
public final class AutoPruneHelperRoutine implements Routine { | ||
private static final Logger logger = LoggerFactory.getLogger(AutoPruneHelperRoutine.class); | ||
|
||
private static final int ROLE_FULL_LIMIT = 100; | ||
private static final int ROLE_FULL_THRESHOLD = 95; | ||
private static final int PRUNE_MEMBER_AMOUNT = 10; | ||
private static final Period INACTIVE_AFTER = Period.ofDays(90); | ||
private static final int RECENTLY_JOINED_DAYS = 7; | ||
|
||
private final HelpSystemHelper helper; | ||
private final ModAuditLogWriter modAuditLogWriter; | ||
private final Database database; | ||
private final List<String> allCategories; | ||
|
||
/** | ||
* Creates a new instance. | ||
* | ||
* @param config to determine all helper categories | ||
* @param helper the helper to use | ||
* @param modAuditLogWriter to inform mods when manual pruning becomes necessary | ||
* @param database to determine whether an user is inactive | ||
*/ | ||
public AutoPruneHelperRoutine(@NotNull Config config, @NotNull HelpSystemHelper helper, | ||
@NotNull ModAuditLogWriter modAuditLogWriter, @NotNull Database database) { | ||
allCategories = config.getHelpSystem().getCategories(); | ||
this.helper = helper; | ||
this.modAuditLogWriter = modAuditLogWriter; | ||
this.database = database; | ||
} | ||
|
||
@Override | ||
public @NotNull Schedule createSchedule() { | ||
return new Schedule(ScheduleMode.FIXED_RATE, 0, 1, TimeUnit.HOURS); | ||
} | ||
|
||
@Override | ||
public void runRoutine(@NotNull JDA jda) { | ||
jda.getGuildCache().forEach(this::pruneForGuild); | ||
} | ||
|
||
private void pruneForGuild(@NotNull Guild guild) { | ||
TextChannel overviewChannel = guild.getTextChannels() | ||
.stream() | ||
.filter(channel -> helper.isOverviewChannelName(channel.getName())) | ||
.findAny() | ||
.orElseThrow(); | ||
Instant now = Instant.now(); | ||
|
||
allCategories.stream() | ||
.map(category -> helper.handleFindRoleForCategory(category, guild)) | ||
.filter(Optional::isPresent) | ||
.map(Optional::orElseThrow) | ||
.forEach(role -> pruneRoleIfFull(role, overviewChannel, now)); | ||
} | ||
|
||
private void pruneRoleIfFull(@NotNull Role role, @NotNull TextChannel overviewChannel, | ||
@NotNull Instant when) { | ||
role.getGuild().findMembersWithRoles(role).onSuccess(members -> { | ||
if (isRoleFull(members)) { | ||
logger.debug("Helper role {} is full, starting to prune.", role.getName()); | ||
pruneRole(role, members, overviewChannel, when); | ||
} | ||
}); | ||
} | ||
|
||
private boolean isRoleFull(@NotNull Collection<?> members) { | ||
return members.size() >= ROLE_FULL_THRESHOLD; | ||
} | ||
|
||
private void pruneRole(@NotNull Role role, @NotNull List<? extends Member> members, | ||
@NotNull TextChannel overviewChannel, @NotNull Instant when) { | ||
List<Member> membersShuffled = new ArrayList<>(members); | ||
Collections.shuffle(membersShuffled); | ||
|
||
List<Member> membersToPrune = membersShuffled.stream() | ||
.filter(member -> isMemberInactive(member, when)) | ||
.limit(PRUNE_MEMBER_AMOUNT) | ||
.toList(); | ||
if (membersToPrune.size() < PRUNE_MEMBER_AMOUNT) { | ||
warnModsAbout( | ||
"Attempting to prune helpers from role **%s** (%d members), but only found %d inactive users. That is less than expected, the category might eventually grow beyond the limit." | ||
.formatted(role.getName(), members.size(), membersToPrune.size()), | ||
role.getGuild()); | ||
} | ||
if (members.size() - membersToPrune.size() >= ROLE_FULL_LIMIT) { | ||
warnModsAbout( | ||
"The helper role **%s** went beyond its member limit (%d), despite automatic pruning. It will not function correctly anymore. Please manually prune some users." | ||
.formatted(role.getName(), ROLE_FULL_LIMIT), | ||
role.getGuild()); | ||
} | ||
|
||
logger.info("Pruning {} users {} from role {}", membersToPrune.size(), membersToPrune, | ||
role.getName()); | ||
membersToPrune.forEach(member -> pruneMemberFromRole(member, role, overviewChannel)); | ||
} | ||
|
||
private boolean isMemberInactive(@NotNull Member member, @NotNull Instant when) { | ||
if (member.hasTimeJoined()) { | ||
Instant memberJoined = member.getTimeJoined().toInstant(); | ||
if (Duration.between(memberJoined, when).toDays() <= RECENTLY_JOINED_DAYS) { | ||
// New users are protected from purging to not immediately kick them out of the role | ||
// again | ||
return false; | ||
} | ||
} | ||
|
||
Instant latestActiveMoment = when.minus(INACTIVE_AFTER); | ||
|
||
// Has no recent help message | ||
return database.read(context -> context.fetchCount(HELP_CHANNEL_MESSAGES, | ||
HELP_CHANNEL_MESSAGES.GUILD_ID.eq(member.getGuild().getIdLong()) | ||
.and(HELP_CHANNEL_MESSAGES.AUTHOR_ID.eq(member.getIdLong())) | ||
.and(HELP_CHANNEL_MESSAGES.SENT_AT.greaterThan(latestActiveMoment)))) == 0; | ||
} | ||
|
||
private void pruneMemberFromRole(@NotNull Member member, @NotNull Role role, | ||
@NotNull TextChannel overviewChannel) { | ||
Guild guild = member.getGuild(); | ||
|
||
String dmMessage = | ||
""" | ||
You seem to have been inactive for some time in server **%s**, hence we removed you from the **%s** role. | ||
If that was a mistake, just head back to %s and select the role again. | ||
Sorry for any inconvenience caused by this 🙇""" | ||
.formatted(guild.getName(), role.getName(), overviewChannel.getAsMention()); | ||
|
||
guild.removeRoleFromMember(member, role) | ||
.flatMap(any -> member.getUser().openPrivateChannel()) | ||
.flatMap(channel -> channel.sendMessage(dmMessage)) | ||
.queue(); | ||
} | ||
|
||
private void warnModsAbout(@NotNull String message, @NotNull Guild guild) { | ||
logger.warn(message); | ||
|
||
modAuditLogWriter.write("Auto-prune helpers", message, null, Instant.now(), guild); | ||
} | ||
} |
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
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
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
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.