11package org .togetherjava .tjbot .commands .help ;
22
3+ import com .github .benmanes .caffeine .cache .Cache ;
4+ import com .github .benmanes .caffeine .cache .Caffeine ;
35import net .dv8tion .jda .api .entities .Guild ;
46import net .dv8tion .jda .api .entities .Message ;
57import net .dv8tion .jda .api .entities .Role ;
1416import org .togetherjava .tjbot .commands .SlashCommandVisibility ;
1517import org .togetherjava .tjbot .config .Config ;
1618
19+ import java .time .Instant ;
20+ import java .time .temporal .ChronoUnit ;
1721import java .util .Optional ;
22+ import java .util .concurrent .TimeUnit ;
1823
1924/**
2025 * Implements the {@code /change-help-category} command, which is able to change the category of a
2934public final class ChangeHelpCategoryCommand extends SlashCommandAdapter {
3035 private static final String CATEGORY_OPTION = "category" ;
3136
37+ private static final int COOLDOWN_DURATION_VALUE = 1 ;
38+ private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit .HOURS ;
39+
3240 private final HelpSystemHelper helper ;
41+ private final Cache <Long , Instant > helpThreadIdToLastCategoryChange ;
3342
3443 /**
3544 * Creates a new instance.
@@ -49,6 +58,11 @@ public ChangeHelpCategoryCommand(@NotNull Config config, @NotNull HelpSystemHelp
4958
5059 getData ().addOptions (category );
5160
61+ helpThreadIdToLastCategoryChange = Caffeine .newBuilder ()
62+ .maximumSize (1_000 )
63+ .expireAfterAccess (COOLDOWN_DURATION_VALUE , TimeUnit .of (COOLDOWN_DURATION_UNIT ))
64+ .build ();
65+
5266 this .helper = helper ;
5367 }
5468
@@ -66,6 +80,16 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) {
6680 return ;
6781 }
6882
83+ if (isHelpThreadOnCooldown (helpThread )) {
84+ event
85+ .reply ("Please wait a bit, this command can only be used once per %d %s."
86+ .formatted (COOLDOWN_DURATION_VALUE , COOLDOWN_DURATION_UNIT ))
87+ .setEphemeral (true )
88+ .queue ();
89+ return ;
90+ }
91+ helpThreadIdToLastCategoryChange .put (helpThread .getIdLong (), Instant .now ());
92+
6993 event .deferReply ().queue ();
7094
7195 helper .renameChannelToCategoryTitle (helpThread , category )
@@ -96,4 +120,13 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) {
96120 return action .flatMap (any -> helpThread .sendMessage (headsUpWithoutRole )
97121 .flatMap (message -> message .editMessage (headsUpWithRole )));
98122 }
123+
124+ private boolean isHelpThreadOnCooldown (@ NotNull ThreadChannel helpThread ) {
125+ return Optional
126+ .ofNullable (helpThreadIdToLastCategoryChange .getIfPresent (helpThread .getIdLong ()))
127+ .map (lastCategoryChange -> lastCategoryChange .plus (COOLDOWN_DURATION_VALUE ,
128+ COOLDOWN_DURATION_UNIT ))
129+ .filter (Instant .now ()::isBefore )
130+ .isPresent ();
131+ }
99132}
0 commit comments