diff --git a/application/src/main/java/org/togetherjava/tjbot/Application.java b/application/src/main/java/org/togetherjava/tjbot/Application.java index fed19cc192..97d038c5c8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/Application.java +++ b/application/src/main/java/org/togetherjava/tjbot/Application.java @@ -82,13 +82,10 @@ public static void runBot(Config config) { .enableIntents(GatewayIntent.GUILD_MEMBERS) .build(); + jda.awaitReady(); BotCore core = new BotCore(jda, database, config); jda.addEventListener(core); - jda.awaitReady(); - // We fire the event manually, since the core might be added too late to receive the - // actual event fired from JDA - core.onReady(jda); logger.info("Bot is ready"); } catch (LoginException e) { logger.error("Failed to login", e); diff --git a/application/src/main/java/org/togetherjava/tjbot/CommandReloading.java b/application/src/main/java/org/togetherjava/tjbot/CommandReloading.java new file mode 100644 index 0000000000..54108595ae --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/CommandReloading.java @@ -0,0 +1,101 @@ +package org.togetherjava.tjbot; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.requests.RestAction; +import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; +import org.jetbrains.annotations.Contract; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.BotCommand; +import org.togetherjava.tjbot.commands.CommandVisibility; +import org.togetherjava.tjbot.commands.system.CommandProvider; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * Offers utility functions for reloading all commands. + */ +public class CommandReloading { + private static final Logger logger = LoggerFactory.getLogger(CommandReloading.class); + + /** + * According to Discord + * docs, there can be a maximum of 110 commands, 100 slash, and 5 context each. + *

+ * Because this bot most of the time operates in only 1 server, chances of exceeding this limit + * is low. + */ + public static final int MAX_COMMAND_COUNT = 110; + + private CommandReloading() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Reloads all commands based on the given {@link CommandProvider}. + * + * @param jda the JDA to update commands on + * @param commandProvider the {@link CommandProvider} to grab commands from + */ + public static void reloadCommands(final JDA jda, final CommandProvider commandProvider) { + logger.info("Reloading commands..."); + List actions = + Collections.synchronizedList(new ArrayList<>(MAX_COMMAND_COUNT)); + + // Reload global commands + actions.add(updateCommandsIf(command -> CommandVisibility.GLOBAL == command.getVisibility(), + getGlobalUpdateAction(jda), commandProvider)); + + // Reload guild commands (potentially many guilds) + // NOTE Storing the guild actions in a list is potentially dangerous since the + // bot might theoretically be part of so many guilds that it exceeds the max size of + // list. However, correctly reducing RestActions in a stream is not trivial. + getGuildUpdateActions(jda) + .map(updateAction -> updateCommandsIf( + command -> CommandVisibility.GUILD == command.getVisibility(), updateAction, + commandProvider)) + .forEach(actions::add); + logger.debug("Reloading commands over {} action-upstreams", actions.size()); + + // Send message when all are done + RestAction.allOf(actions).queue(a -> logger.debug("Commands successfully reloaded!")); + } + + /** + * Updates all commands given by the command provider which pass the given filter by pushing + * through the given action upstream. + * + * @param commandFilter filter that matches commands that should be uploaded + * @param updateAction the upstream to update commands + * @return the given upstream for chaining + */ + @Contract("_, _, _ -> param2") + private static CommandListUpdateAction updateCommandsIf( + final Predicate commandFilter, + final CommandListUpdateAction updateAction, final CommandProvider commandProvider) { + commandProvider.getInteractors() + .stream() + .filter(BotCommand.class::isInstance) + .map(BotCommand.class::cast) + .filter(commandFilter) + .map(BotCommand::getData) + .forEach(updateAction::addCommands); + + return updateAction; + } + + private static CommandListUpdateAction getGlobalUpdateAction(final JDA jda) { + return jda.updateCommands(); + } + + private static Stream getGuildUpdateActions(final JDA jda) { + return jda.getGuildCache().stream().map(Guild::updateCommands); + } + +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java new file mode 100644 index 0000000000..0795c12d76 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java @@ -0,0 +1,75 @@ +package org.togetherjava.tjbot.commands; + +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.api.interactions.commands.build.Commands; + +import java.util.List; + +/** + * Represents a Discord command. + *

+ * All commands have to implement this interface. For convenience, there is a + * {@link BotCommandAdapter} available that implemented most methods already. A new command can then + * be registered by adding it to {@link Features}. + *

+ * Commands can either be visible globally in Discord or just to specific guilds. Some + * configurations can be made via {@link CommandData}, which is then to be returned by + * {@link #getData()} where the system will then pick it up from. + *

+ * After registration, the system will notify a command whenever one of its corresponding command + * method, buttons ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus + * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + *

+ * Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. + */ +public interface BotCommand extends UserInteractor { + + /** + * {@inheritDoc} + *

+ * Requirements for this are documented in + * {@link net.dv8tion.jda.api.interactions.commands.build.Commands Commands}. If your command is + * a slash-command, take a look at + * {@link net.dv8tion.jda.api.interactions.commands.build.Commands#slash(String, String) + * Commands#slash(String, String)}. For context commands, use + * {@link Commands#context(Command.Type, String) Commands#context(Command.Type, String)}. + * + * @return the name of the interactor + */ + String getName(); + + /** + * Gets the type of this command. + *

+ * After registration of the command, the type must not change anymore. + * + * @return the type of the command + */ + Command.Type getType(); + + /** + * Gets the visibility of this command. + *

+ * After registration of the command, the visibility must not change anymore. + * + * @return the visibility of the command + */ + CommandVisibility getVisibility(); + + /** + * Gets the command data belonging to this command. + *

+ * See {@link net.dv8tion.jda.api.interactions.commands.build.Commands Commands} for details on + * how to create and configure instances of it. + *

+ * This method may be called multiple times, implementations must not create new data each time + * but instead configure it once beforehand. The core system will automatically call this method + * to register the command to Discord. + * + * @return the command data of this command + */ + CommandData getData(); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java new file mode 100644 index 0000000000..c03d0b82ca --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java @@ -0,0 +1,136 @@ +package org.togetherjava.tjbot.commands; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import org.jetbrains.annotations.Contract; +import org.togetherjava.tjbot.commands.componentids.ComponentId; +import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; +import org.togetherjava.tjbot.commands.componentids.Lifespan; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +/** + * Adapter implementation of a {@link BotCommand}. The minimal setup only requires implementation of + * their respective command method. A new command can then be registered by adding it to + * {@link Features}. + *

+ * Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and + * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The + * default implementation is empty, the adapter will not react to such events. + *

+ *

+ * The adapter manages some getters for you, you've to create the {@link CommandData} yourself. See + * {@link #BotCommandAdapter(CommandData, CommandVisibility)}} for more info on that. Minimal + * modifications can be done on the {@link CommandData} returned by {@link #getData()}. + *

+ *

+ * If implementations want to add buttons or selection menus, it is highly advised to use component + * IDs generated by {@link #generateComponentId(String...)}, which will automatically create IDs + * that are valid per {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)}. + *

+ *

+ * Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. + * Registration of commands can be done in {@link Features}. + */ +public abstract class BotCommandAdapter implements BotCommand { + private final String name; + private final Command.Type type; + private final CommandVisibility visibility; + private final CommandData data; + private ComponentIdGenerator componentIdGenerator; + + /** + * Creates a new adapter with the given data. + * + * @param data the data for this command + * @param visibility the visibility of the command + */ + protected BotCommandAdapter(CommandData data, CommandVisibility visibility) { + this.data = Objects.requireNonNull(data, "The data shouldn't be null"); + this.visibility = Objects.requireNonNull(visibility, "The visibility shouldn't be null"); + + this.name = data.getName(); + this.type = data.getType(); + } + + @Override + public final String getName() { + return name; + } + + @Override + public Command.Type getType() { + return type; + } + + @Override + public final CommandVisibility getVisibility() { + return visibility; + } + + @Override + public CommandData getData() { + return data; + } + + @Override + @Contract(mutates = "this") + public final void acceptComponentIdGenerator(ComponentIdGenerator generator) { + componentIdGenerator = + Objects.requireNonNull(generator, "The given generator cannot be null"); + } + + @SuppressWarnings("NoopMethodInAbstractClass") + @Override + public void onButtonClick(ButtonInteractionEvent event, List args) { + // Adapter does not react by default, subclasses may change this behavior + } + + @SuppressWarnings("NoopMethodInAbstractClass") + @Override + public void onSelectionMenu(SelectMenuInteractionEvent event, List args) { + // Adapter does not react by default, subclasses may change this behavior + } + + /** + * Helper method to generate component IDs that are considered valid per + * {@link #acceptComponentIdGenerator(ComponentIdGenerator)}. + *

+ * They can be used to create buttons or selection menus and transport additional data + * throughout the event (e.g. the user id who created the button dialog). + *

+ * IDs generated by this method have a regular lifespan, meaning that they might get evicted and + * expire after not being used for a long time. Use + * {@link #generateComponentId(Lifespan, String...)} to set other lifespans, if desired. + * + * @param args the extra arguments that should be part of the ID + * @return the generated component ID + */ + @SuppressWarnings("OverloadedVarargsMethod") + protected final String generateComponentId(String... args) { + return generateComponentId(Lifespan.REGULAR, args); + } + + /** + * Helper method to generate component IDs that are considered valid per + * {@link #acceptComponentIdGenerator(ComponentIdGenerator)}. + *

+ * They can be used to create buttons or selection menus and transport additional data + * throughout the event (e.g. the user id who created the button dialog). + * + * @param lifespan the lifespan of the component id, controls when an id that was not used for a + * long time might be evicted and expire + * @param args the extra arguments that should be part of the ID + * @return the generated component ID + */ + @SuppressWarnings({"OverloadedVarargsMethod", "WeakerAccess"}) + protected final String generateComponentId(Lifespan lifespan, String... args) { + return componentIdGenerator.generate(new ComponentId(getName(), Arrays.asList(args)), + lifespan); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandVisibility.java b/application/src/main/java/org/togetherjava/tjbot/commands/CommandVisibility.java similarity index 89% rename from application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandVisibility.java rename to application/src/main/java/org/togetherjava/tjbot/commands/CommandVisibility.java index e0d184c764..f8a2284590 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandVisibility.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/CommandVisibility.java @@ -3,7 +3,7 @@ /** * Visibility of a slash command, i.e. in which context it can be used by users. */ -public enum SlashCommandVisibility { +public enum CommandVisibility { /** * The command can be used within the context of a guild. */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index c348b607f8..3a23925122 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -97,6 +97,10 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new RejoinModerationRoleListener(actionsStore, config)); features.add(new OnGuildLeaveCloseThreadListener(database)); + // Message context commands + + // User context commands + // Slash commands features.add(new LogLevelCommand()); features.add(new PingCommand()); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java new file mode 100644 index 0000000000..5a29c0c873 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java @@ -0,0 +1,62 @@ +package org.togetherjava.tjbot.commands; + +import net.dv8tion.jda.api.entities.Emoji; +import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.api.interactions.components.ComponentInteraction; +import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; +import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; + +import java.util.List; + +/** + * A message context-command is a command, accessible when right-clicking on a message. + * + *

+ * Represents a Discord message context-command. Mostly decorating + * {@link net.dv8tion.jda.api.interactions.commands.Command}. + *

+ * All message context-commands have to implement this interface. For convenience, there is a + * {@link BotCommandAdapter} available that implemented most methods already. A new command can then + * be registered by adding it to {@link Features}. + *

+ *

+ * Context commands can either be visible globally in Discord or just to specific guilds. Minor + * adjustments can be made via {@link CommandData}, which is then to be returned by + * {@link #getData()} where the system will then pick it up from. + *

+ * After registration, the system will notify a command whenever one of its corresponding message + * context-commands ({@link #onMessageContext(MessageContextInteractionEvent)}), buttons + * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus + * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + *

+ *

+ * Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. + */ +public interface MessageContextCommand extends BotCommand { + + /** + * Triggered by the core system when a message context-command corresponding to this + * implementation (based on {@link #getData()}) has been triggered. + *

+ * This method may be called multithreaded. In particular, there are no guarantees that it will + * be executed on the same thread repeatedly or on the same thread that other event methods have + * been called on. + *

+ * Details are available in the given event and the event also enables implementations to + * respond to it. + *

+ * Buttons or menus have to be created with a component ID (see + * {@link ComponentInteraction#getComponentId()}, + * {@link net.dv8tion.jda.api.interactions.components.buttons.Button#of(ButtonStyle, String, Emoji)}) + * in a very specific format, otherwise the core system will fail to identify the command that + * corresponded to the button or menu click event and is unable to route it back. + *

+ * See {@link #acceptComponentIdGenerator(ComponentIdGenerator)} for more info. + * + * @param event the event that triggered this + */ + void onMessageContext(MessageContextInteractionEvent event); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java index 9618c7412f..53b5456d65 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java @@ -1,29 +1,33 @@ package org.togetherjava.tjbot.commands; import net.dv8tion.jda.api.entities.Emoji; +import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.Commands; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import net.dv8tion.jda.api.interactions.components.ComponentInteraction; import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; -import org.togetherjava.tjbot.commands.componentids.ComponentId; import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; -import org.togetherjava.tjbot.commands.componentids.Lifespan; import java.util.List; /** + * A slash-command is a command in Discord, with slash (/) as the prefix. These commands offer + * enhanced functionality and superior UX over text-commands. An example slash-command is the + * `/thread` command, this allows you to create threads using your keyboard. + * + *

* Represents a Discord slash-command. Mostly decorating - * {@link net.dv8tion.jda.api.interactions.commands.Command}. + * {@link net.dv8tion.jda.api.interactions.commands.Command Command}. *

* All slash commands have to implement this interface. For convenience, there is a * {@link SlashCommandAdapter} available that implemented most methods already. A new command can * then be registered by adding it to {@link Features}. *

- *

* Slash commands can either be visible globally in Discord or just to specific guilds. They can * have subcommands, options, menus and more. This can be configured via {@link CommandData}, which * is then to be returned by {@link #getData()} where the system will then pick it up from. @@ -33,32 +37,21 @@ * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. *

- *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. */ -public interface SlashCommand extends UserInteractor { +public interface SlashCommand extends BotCommand { /** * Gets the description of the command. *

* Requirements for this are documented in {@link Commands#slash(String, String)}. *

- *

* After registration of the command, the description must not change anymore. * * @return the description of the command */ String getDescription(); - /** - * Gets the visibility of this command. - *

- * After registration of the command, the visibility must not change anymore. - * - * @return the visibility of the command - */ - SlashCommandVisibility getVisibility(); - /** * Gets the command data belonging to this command. *

@@ -67,7 +60,6 @@ public interface SlashCommand extends UserInteractor { *

* See {@link CommandData} for details on how to create and configure instances of it. *

- *

* This method may be called multiple times, implementations must not create new data each time * but instead configure it once beforehand. The core system will automatically call this method * to register the command to Discord. @@ -80,7 +72,7 @@ public interface SlashCommand extends UserInteractor { * Triggered by the core system when a slash command corresponding to this implementation (based * on {@link #getData()}) has been triggered. *

- * This method may be called multi-threaded. In particular, there are no guarantees that it will + * This method may be called multithreaded. In particular, there are no guarantees that it will * be executed on the same thread repeatedly or on the same thread that other event methods have * been called on. *

@@ -93,26 +85,34 @@ public interface SlashCommand extends UserInteractor { * in a very specific format, otherwise the core system will fail to identify the command that * corresponded to the button or menu click event and is unable to route it back. *

- * The component ID has to be a UUID-string (see {@link java.util.UUID}), which is associated to - * a specific database entry, containing meta information about the command being executed. Such - * a database entry can be created and a UUID be obtained by using - * {@link ComponentIdGenerator#generate(ComponentId, Lifespan)}, as provided by the instance - * given to {@link #acceptComponentIdGenerator(ComponentIdGenerator)} during system setup. The - * required {@link ComponentId} instance accepts optional extra arguments, which, if provided, - * can be picked up during the corresponding event (see - * {@link #onButtonClick(ButtonInteractionEvent, List)}, - * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)}). + * See {@link #acceptComponentIdGenerator(ComponentIdGenerator)} for more info on the ID's. + * + * @param event the event that triggered this + */ + void onSlashCommand(SlashCommandInteractionEvent event); + + /** + * Autocompletion is comparable, but not the same as slash-command choices. Choices allow you to + * set a static list of {@value OptionData#MAX_CHOICES} possible "choices" to the commmand. + * Autocomplete allows you to dynamically give the user a list of + * {@value OptionData#MAX_CHOICES} possible choices. These choices can be generated based on the + * input of the user, the functionality is comparable to Google's autocompletion when searching + * for something. The given choices are not enforced by Discord, the user can + * ignore auto-completion and send whatever they want. *

- * Alternatively, if {@link SlashCommandAdapter} has been extended, it also offers a handy - * {@link SlashCommandAdapter#generateComponentId(String...)} method to ease the flow. + * Triggered by the core system when a slash command's autocomplete corresponding to this + * implementation (based on {@link #getData()}) has been triggered. Don't forget to enable + * autocomplete using {@link OptionData#setAutoComplete(boolean)}! *

- * See Component-IDs on - * our Wiki for more details and examples of how to use component IDs. + * This method may be called multithreaded. In particular, there are no guarantees that it will + * be executed on the same thread repeatedly or on the same thread that other event methods have + * been called on. *

- * This method will be called in a multi-threaded context and the event may not be hold valid - * forever. + * Details are available in the given event and the event also enables implementations to + * respond to it.
+ * See {@link #acceptComponentIdGenerator(ComponentIdGenerator)} for more info on the ID's. * * @param event the event that triggered this */ - void onSlashCommand(SlashCommandInteractionEvent event); + void onAutoComplete(CommandAutoCompleteInteractionEvent event); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java index cc071fd767..9923a15ea4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands; +import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; @@ -11,13 +12,8 @@ import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Unmodifiable; -import org.togetherjava.tjbot.commands.componentids.ComponentId; -import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; -import org.togetherjava.tjbot.commands.componentids.Lifespan; -import java.util.Arrays; import java.util.List; -import java.util.Objects; import java.util.function.Function; import java.util.stream.IntStream; @@ -30,18 +26,15 @@ * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The * default implementation is empty, the adapter will not react to such events. *

- *

* The adapter manages all command related data itself, which can be provided during construction - * (see {@link #SlashCommandAdapter(String, String, SlashCommandVisibility)}). In order to add - * options, subcommands or similar command configurations, use {@link #getData()} and mutate the - * returned data object (see {@link CommandData} for details on how to work with this class). - *

+ * (see {@link #SlashCommandAdapter(String, String, CommandVisibility)}). In order to add options, + * subcommands or similar command configurations, use {@link #getData()} and mutate the returned + * data object (see {@link CommandData} for details on how to work with this class). *

* If implementations want to add buttons or selection menus, it is highly advised to use component * IDs generated by {@link #generateComponentId(String...)}, which will automatically create IDs * that are valid per {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)}. *

- *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. A minimal * setup would consist of a class like * @@ -63,12 +56,9 @@ *

* and registration of an instance of that class in {@link Features}. */ -public abstract class SlashCommandAdapter implements SlashCommand { - private final String name; +public abstract class SlashCommandAdapter extends BotCommandAdapter implements SlashCommand { private final String description; - private final SlashCommandVisibility visibility; private final SlashCommandData data; - private ComponentIdGenerator componentIdGenerator; /** * Creates a new adapter with the given data. @@ -79,18 +69,11 @@ public abstract class SlashCommandAdapter implements SlashCommand { * {@link SlashCommandData#setDescription(String)} * @param visibility the visibility of the command */ - protected SlashCommandAdapter(String name, String description, - SlashCommandVisibility visibility) { - this.name = name; + protected SlashCommandAdapter(String name, String description, CommandVisibility visibility) { + super(Commands.slash(name, description), visibility); this.description = description; - this.visibility = visibility; - - data = Commands.slash(name, description); - } - @Override - public final String getName() { - return name; + this.data = (SlashCommandData) super.getData(); } @Override @@ -98,70 +81,17 @@ public final String getDescription() { return description; } - @Override - public final SlashCommandVisibility getVisibility() { - return visibility; - } - @Override public final SlashCommandData getData() { return data; } - @Override - public final void acceptComponentIdGenerator(ComponentIdGenerator generator) { - componentIdGenerator = generator; - } - - @SuppressWarnings("NoopMethodInAbstractClass") - @Override - public void onButtonClick(ButtonInteractionEvent event, List args) { - // Adapter does not react by default, subclasses may change this behavior - } - @SuppressWarnings("NoopMethodInAbstractClass") @Override - public void onSelectionMenu(SelectMenuInteractionEvent event, List args) { + public void onAutoComplete(CommandAutoCompleteInteractionEvent event) { // Adapter does not react by default, subclasses may change this behavior } - /** - * Helper method to generate component IDs that are considered valid per - * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)}. - *

- * They can be used to create buttons or selection menus and transport additional data - * throughout the event (e.g. the user id who created the button dialog). - *

- * IDs generated by this method have a regular lifespan, meaning that they might get evicted and - * expire after not being used for a long time. Use - * {@link #generateComponentId(Lifespan, String...)} to set other lifespans, if desired. - * - * @param args the extra arguments that should be part of the ID - * @return the generated component ID - */ - @SuppressWarnings("OverloadedVarargsMethod") - protected final String generateComponentId(String... args) { - return generateComponentId(Lifespan.REGULAR, args); - } - - /** - * Helper method to generate component IDs that are considered valid per - * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)}. - *

- * They can be used to create buttons or selection menus and transport additional data - * throughout the event (e.g. the user id who created the button dialog). - * - * @param lifespan the lifespan of the component id, controls when an id that was not used for a - * long time might be evicted and expire - * @param args the extra arguments that should be part of the ID - * @return the generated component ID - */ - @SuppressWarnings({"OverloadedVarargsMethod", "WeakerAccess"}) - protected final String generateComponentId(Lifespan lifespan, String... args) { - return Objects.requireNonNull(componentIdGenerator) - .generate(new ComponentId(getName(), Arrays.asList(args)), lifespan); - } - /** * Copies the given option multiple times. *

diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java new file mode 100644 index 0000000000..95e278bbad --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java @@ -0,0 +1,63 @@ +package org.togetherjava.tjbot.commands; + +import net.dv8tion.jda.api.entities.Emoji; +import net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.api.interactions.components.ComponentInteraction; +import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; +import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; + +import java.util.List; + +/** + * A user context-command is a command, accessible when right-clicking on a member in a guild. These + * commands aren't accessible within DM's. + * + *

+ * Represents a Discord user context-command. Mostly decorating + * {@link net.dv8tion.jda.api.interactions.commands.Command}. + *

+ * All user context-commands have to implement this interface. For convenience, there is a + * {@link BotCommandAdapter} available that implemented most methods already. A new command can then + * be registered by adding it to {@link Features}. + *

+ *

+ * Context commands can either be visible globally in Discord or just to specific guilds. Minor + * adjustments can be made via {@link CommandData}, which is then to be returned by + * {@link #getData()} where the system will then pick it up from. + *

+ * After registration, the system will notify a command whenever one of its corresponding user + * context-commands ({@link #onUserContext(UserContextInteractionEvent)}), buttons + * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus + * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + *

+ *

+ * Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. + */ +public interface UserContextCommand extends BotCommand { + + /** + * Triggered by the core system when a user context-command corresponding to this implementation + * (based on {@link #getData()}) has been triggered. + *

+ * This method may be called multithreaded. In particular, there are no guarantees that it will + * be executed on the same thread repeatedly or on the same thread that other event methods have + * been called on. + *

+ * Details are available in the given event and the event also enables implementations to + * respond to it. + *

+ * Buttons or menus have to be created with a component ID (see + * {@link ComponentInteraction#getComponentId()}, + * {@link net.dv8tion.jda.api.interactions.components.buttons.Button#of(ButtonStyle, String, Emoji)}) + * in a very specific format, otherwise the core system will fail to identify the command that + * corresponded to the button or menu click event and is unable to route it back. + *

+ * See {@link #acceptComponentIdGenerator(ComponentIdGenerator)} for more info. + * + * @param event the event that triggered this + */ + void onUserContext(UserContextInteractionEvent event); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java index b46cb8069b..65311be4bc 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java @@ -3,24 +3,26 @@ import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; +import org.togetherjava.tjbot.commands.componentids.ComponentId; import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator; +import org.togetherjava.tjbot.commands.componentids.Lifespan; import java.util.List; /** - * Represents a feature that can interact with users. The most important implementation is - * {@link SlashCommand}. + * Represents a feature that can interact with users. The most used implementation is + * {@link SlashCommand}, {@link UserContextCommand} and {@link MessageContextCommand}. *

- * An interactor must have a unique name and can react to button clicks and selection menu actions. + * An interactor can react to button clicks and selection menu actions. This is done based on the + * given {@link #getName()}, because of this names have to be unique. But, names can be complicated + * if their type is different, all the types can be seen in {@link UserInteractorPrefix} */ public interface UserInteractor extends Feature { /** * Gets the name of the interactor. *

- * Requirements for this are documented in - * {@link net.dv8tion.jda.api.interactions.commands.build.Commands#slash(String, String)}. - *

+ * You cannot start the name with any of the prefixes found in {@link UserInteractorPrefix} *

* After registration of the interactor, the name must not change anymore. * @@ -32,15 +34,12 @@ public interface UserInteractor extends Feature { * Triggered by the core system when a button corresponding to this implementation (based on * {@link #getName()}) has been clicked. *

- * This method may be called multi-threaded. In particular, there are no guarantees that it will + * This method may be called multithreaded. In particular, there are no guarantees that it will * be executed on the same thread repeatedly or on the same thread that other event methods have * been called on. *

* Details are available in the given event and the event also enables implementations to * respond to it. - *

- * This method will be called in a multi-threaded context and the event may not be hold valid - * forever. * * @param event the event that triggered this * @param args the arguments transported with the button, see @@ -53,15 +52,12 @@ public interface UserInteractor extends Feature { * Triggered by the core system when a selection menu corresponding to this implementation * (based on {@link #getName()}) has been clicked. *

- * This method may be called multi-threaded. In particular, there are no guarantees that it will + * This method may be called multithreaded. In particular, there are no guarantees that it will * be executed on the same thread repeatedly or on the same thread that other event methods have * been called on. *

* Details are available in the given event and the event also enables implementations to * respond to it. - *

- * This method will be called in a multi-threaded context and the event may not be hold valid - * forever. * * @param event the event that triggered this * @param args the arguments transported with the selection menu, see @@ -71,11 +67,25 @@ public interface UserInteractor extends Feature { void onSelectionMenu(SelectMenuInteractionEvent event, List args); /** - * Triggered by the core system during its setup phase. It will provide the interactor a - * component id generator through this method, which can be used to generate component ids, as - * used for button or selection menus. See - * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)} for details on how to use - * this. + * Triggered by the core system during its setup phase. It will provide the command a component + * id generator through this method, which can be used to generate component ids, as used for + * button or selection menus. + * + *

+ * The component ID has to be a UUID-string (see {@link java.util.UUID}), which is associated to + * a specific database entry, containing meta information about the command being executed. Such + * a database entry can be created and a UUID be obtained by using + * {@link ComponentIdGenerator#generate(ComponentId, Lifespan)}, as provided by the instance + * given to this method during system setup. The required {@link ComponentId} instance accepts + * optional extra arguments, which, if provided, can be picked up during the corresponding event + * (see {@link #onButtonClick(ButtonInteractionEvent, List)}, + * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)}). + *

+ * Alternatively, if {@link BotCommandAdapter} has been extended, it also offers a handy + * {@link BotCommandAdapter#generateComponentId(String...)} method to ease the flow. + *

+ * See Component-IDs on + * our Wiki for more details and examples of how to use component IDs. * * @param generator the provided component id generator */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractorPrefix.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractorPrefix.java new file mode 100644 index 0000000000..e4537853e7 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractorPrefix.java @@ -0,0 +1,102 @@ +package org.togetherjava.tjbot.commands; + +import org.jetbrains.annotations.Contract; + +/** + * Contains the prefixes for the UserInteractor's. + *

+ * This is used for separate interactors with the same name, by command type (and possibly more in + * the future). Our system doesn't allow multiple interactors with the same name, while having a + * slash-command and a message-context-command with the same name can be really useful. + */ +public enum UserInteractorPrefix { + /* + * Implementations that are none of the following have no dedicated prefix + */ + + SLASH_COMMAND(SlashCommand.class, "s-"), + MESSAGE_CONTEXT_COMMAND(MessageContextCommand.class, "mc-"), + USER_CONTEXT_COMMAND(UserContextCommand.class, "uc-"); + + + private final Class classType; + private final String prefix; + + UserInteractorPrefix(Class classType, final String prefix) { + this.classType = classType; + this.prefix = prefix; + } + + /** + * The prefix for the command + * + * @return the command's prefix + */ + public String getPrefix() { + return prefix; + } + + /** + * The class type that should receive the prefix + * + * @return a {@link Class} instance of the type + */ + public Class getClassType() { + return classType; + } + + /** + * Checks what enum value the given instance collaborates to. + *

+ * This returns the name of the interactor, and adds the designated prefix to the name. As + * example, a slash-command with the name "help" becomes "s-help". + * + * @param instance an instance to type check for a prefix + * @param the type of the instance + * @return the interactor's name, with its prefix + */ + public static String getPrefixedNameFromInstance(final T instance) { + String name = instance.getName(); + + for (UserInteractorPrefix value : values()) { + Class valueClassType = value.getClassType(); + + if (valueClassType.isInstance(instance)) { + return value.getPrefix() + name; + } + } + + return name; + } + + /** + * Checks what enum value the given instance collaborates to. + *

+ * This combines the given name, with the interactor's prefix. As example, a slash-command with + * the name "help" becomes "s-help". + * + * @param clazz the class to get the prefix from + * @param name the name of the instance + * @param the type of the instance + * @return the prefixed {@link String} + */ + public static String getPrefixedNameFromClass(final Class clazz, + final String name) { + + for (UserInteractorPrefix value : values()) { + Class valueClassType = value.getClassType(); + + if (valueClassType.isAssignableFrom(clazz)) { + return value.getPrefix() + name; + } + } + + return name; + } + + @Override + @Contract(pure = true) + public String toString() { + return "UserInteractorPrefix{" + "prefix='" + prefix + '\'' + '}'; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/basic/PingCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/basic/PingCommand.java index fdaba47f5b..fd5afa121a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/basic/PingCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/basic/PingCommand.java @@ -1,8 +1,8 @@ package org.togetherjava.tjbot.commands.basic; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; /** * Implementation of an example command to illustrate how to respond to a user. @@ -14,7 +14,7 @@ public final class PingCommand extends SlashCommandAdapter { * Creates an instance of the ping pong command. */ public PingCommand() { - super("ping", "Bot responds with 'Pong!'", SlashCommandVisibility.GUILD); + super("ping", "Bot responds with 'Pong!'", CommandVisibility.GUILD); } /** diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java index 6b0e1376c2..096bb3327a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java @@ -15,11 +15,12 @@ import org.jetbrains.annotations.Contract; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.commands.componentids.Lifespan; -import java.awt.Color; +import java.awt.*; +import java.util.List; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @@ -29,7 +30,7 @@ *

* The command works in two stages. First, a user sets up a role selection dialog by using the * command: - * + * *

  * {@code
  * /role-select
@@ -40,7 +41,7 @@
  *   selectable-role2: @Droid
  * }
  * 
- * + * * Afterwards, users can pick their roles in a menu, upon which the command adjusts their roles. */ public final class RoleSelectCommand extends SlashCommandAdapter { @@ -61,7 +62,7 @@ public final class RoleSelectCommand extends SlashCommandAdapter { public RoleSelectCommand() { super("role-select", "Creates a dialog that lets users pick roles, system roles are ignored when selected.", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); OptionData roleOption = new OptionData(OptionType.ROLE, ROLE_OPTION, "pick roles that users will then be able to select", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/basic/VcActivityCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/basic/VcActivityCommand.java index 33f97035b4..1322c62591 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/basic/VcActivityCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/basic/VcActivityCommand.java @@ -15,8 +15,8 @@ import org.jetbrains.annotations.Contract; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.util.List; @@ -121,7 +121,7 @@ public final class VcActivityCommand extends SlashCommandAdapter { public VcActivityCommand() { super("vc-activity", "Starts a VC activity (you need to be in an voice channel to run this command)", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); SubcommandData applicationSubCommand = new SubcommandData(APPLICATION_SUBCOMMAND, "Choose an application from our list") diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java index 451ba9d4bf..91ad35f2c0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java @@ -11,8 +11,8 @@ import net.dv8tion.jda.api.requests.RestAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import java.util.Optional; @@ -54,8 +54,7 @@ public final class AskCommand extends SlashCommandAdapter { * @param helper the helper to use */ public AskCommand(Config config, HelpSystemHelper helper) { - super("ask", "Ask a question - use this in the staging channel", - SlashCommandVisibility.GUILD); + super("ask", "Ask a question - use this in the staging channel", CommandVisibility.GUILD); OptionData title = new OptionData(OptionType.STRING, TITLE_OPTION, "short and to the point", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpCategoryCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpCategoryCommand.java index fd884591f8..9235ba053d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpCategoryCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpCategoryCommand.java @@ -11,8 +11,8 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.RestAction; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import java.time.Instant; @@ -48,7 +48,7 @@ public final class ChangeHelpCategoryCommand extends SlashCommandAdapter { */ public ChangeHelpCategoryCommand(Config config, HelpSystemHelper helper) { super("change-help-category", "changes the category of a help thread", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); OptionData category = new OptionData(OptionType.STRING, CATEGORY_OPTION, "select what describes the question the best", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpTitleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpTitleCommand.java index 8ea5288f25..1510d54f2b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpTitleCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/ChangeHelpTitleCommand.java @@ -6,8 +6,8 @@ import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.commands.OptionType; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -40,8 +40,7 @@ public final class ChangeHelpTitleCommand extends SlashCommandAdapter { * @param helper the helper to use */ public ChangeHelpTitleCommand(HelpSystemHelper helper) { - super("change-help-title", "changes the title of a help thread", - SlashCommandVisibility.GUILD); + super("change-help-title", "changes the title of a help thread", CommandVisibility.GUILD); getData().addOption(OptionType.STRING, TITLE_OPTION, "short and to the point", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/CloseCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/CloseCommand.java index 3b0e348e7e..c50b14d1a7 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/CloseCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/CloseCommand.java @@ -6,8 +6,8 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.ThreadChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -31,7 +31,7 @@ public final class CloseCommand extends SlashCommandAdapter { * Creates a new instance. */ public CloseCommand() { - super("close", "Close this question thread", SlashCommandVisibility.GUILD); + super("close", "Close this question thread", CommandVisibility.GUILD); helpThreadIdToLastClose = Caffeine.newBuilder() .maximumSize(1_000) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java index c81e1f7be6..cfbfe88632 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java @@ -11,12 +11,11 @@ import org.scilab.forge.jlatexmath.TeXFormula; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.imageio.ImageIO; -import java.awt.Color; -import java.awt.Image; +import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -55,7 +54,7 @@ public final class TeXCommand extends SlashCommandAdapter { */ public TeXCommand() { super("tex", "Renders LaTeX, also supports inline $-regions like 'see this $\frac{x}{2}$'.", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData().addOption(OptionType.STRING, LATEX_OPTION, "The latex which is rendered as an image", true); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/wolframalpha/WolframAlphaCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/wolframalpha/WolframAlphaCommand.java index 8c650b60dc..c599368bb0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/wolframalpha/WolframAlphaCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/wolframalpha/WolframAlphaCommand.java @@ -6,8 +6,8 @@ import net.dv8tion.jda.api.interactions.callbacks.IDeferrableCallback; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.restaction.WebhookMessageUpdateAction; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import java.net.http.HttpClient; @@ -40,7 +40,7 @@ public final class WolframAlphaCommand extends SlashCommandAdapter { */ public WolframAlphaCommand(Config config) { super("wolfram-alpha", "Renders mathematical queries using WolframAlpha", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData().addOption(OptionType.STRING, QUERY_OPTION, "the query to send to WolframAlpha", true); appId = config.getWolframAlphaAppId(); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 983ff7aa24..8fceb3adb6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -14,8 +14,8 @@ import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.TimeUtil; import net.dv8tion.jda.internal.requests.CompletedRestAction; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.time.Instant; @@ -46,7 +46,7 @@ public final class AuditCommand extends SlashCommandAdapter { */ public AuditCommand(ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Lists all moderation actions that have been taken against a user", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData().addOption(OptionType.USER, TARGET_OPTION, "The user who to retrieve actions for", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 52ee553f9b..d42838dc35 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -16,8 +16,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.time.Instant; @@ -52,7 +52,7 @@ public final class BanCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public BanCommand(ModerationActionsStore actionsStore) { - super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); + super(COMMAND_NAME, "Bans the given user from the server", CommandVisibility.GUILD); OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, "the duration of the ban, permanent or temporary", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java index cd83762c6d..04fa4d3184 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -14,8 +14,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.util.Objects; @@ -41,7 +41,7 @@ public final class KickCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public KickCommand(ModerationActionsStore actionsStore) { - super(COMMAND_NAME, "Kicks the given user from the server", SlashCommandVisibility.GUILD); + super(COMMAND_NAME, "Kicks the given user from the server", CommandVisibility.GUILD); getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to kick", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be kicked", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index 0b4e4628b8..e977196cc0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -11,8 +11,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -49,7 +49,7 @@ public final class MuteCommand extends SlashCommandAdapter { */ public MuteCommand(ModerationActionsStore actionsStore, Config config) { super(COMMAND_NAME, "Mutes the given user so that they can not send messages anymore", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, "the duration of the mute, permanent or temporary", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/NoteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/NoteCommand.java index 3d0cc9cf2e..fc5017d170 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/NoteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/NoteCommand.java @@ -7,8 +7,8 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.util.Objects; @@ -34,7 +34,7 @@ public final class NoteCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public NoteCommand(ModerationActionsStore actionsStore) { - super("note", "Writes a note about the given user", SlashCommandVisibility.GUILD); + super("note", "Writes a note about the given user", CommandVisibility.GUILD); getData() .addOption(OptionType.USER, USER_OPTION, "The user who you want to write a note about", diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index c54fab71c7..a75d73fdd2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -10,8 +10,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -43,7 +43,7 @@ public final class QuarantineCommand extends SlashCommandAdapter { public QuarantineCommand(ModerationActionsStore actionsStore, Config config) { super(COMMAND_NAME, "Puts the given user under quarantine. They can not interact with anyone anymore then.", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData() .addOption(OptionType.USER, TARGET_OPTION, "The user who you want to quarantine", true) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java index e9a6ad2bd6..3aea534970 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java @@ -9,8 +9,8 @@ import net.dv8tion.jda.api.requests.ErrorResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.util.Objects; @@ -32,7 +32,7 @@ public final class UnbanCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public UnbanCommand(ModerationActionsStore actionsStore) { - super(COMMAND_NAME, "Unbans the given user from the server", SlashCommandVisibility.GUILD); + super(COMMAND_NAME, "Unbans the given user from the server", CommandVisibility.GUILD); getData() .addOption(OptionType.USER, TARGET_OPTION, "The banned user who you want to unban", diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 72b691c8a2..48e61b86d1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -10,8 +10,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -42,7 +42,7 @@ public final class UnmuteCommand extends SlashCommandAdapter { public UnmuteCommand(ModerationActionsStore actionsStore, Config config) { super(COMMAND_NAME, "Unmutes the given already muted user so that they can send messages again", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to unmute", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be unmuted", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 87bad18f96..7736e9b87c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -10,8 +10,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -43,7 +43,7 @@ public final class UnquarantineCommand extends SlashCommandAdapter { public UnquarantineCommand(ModerationActionsStore actionsStore, Config config) { super(COMMAND_NAME, "Unquarantines the given already quarantined user so that they can interact again", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); getData() .addOption(OptionType.USER, TARGET_OPTION, "The user who you want to unquarantine", diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 05a6ae4fa1..e518e5c5da 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -9,8 +9,8 @@ import net.dv8tion.jda.api.utils.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import javax.annotation.Nullable; import java.util.Objects; @@ -35,7 +35,7 @@ public final class WarnCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public WarnCommand(ModerationActionsStore actionsStore) { - super("warn", "Warns the given user", SlashCommandVisibility.GUILD); + super("warn", "Warns the given user", CommandVisibility.GUILD); getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to warn", true) .addOption(OptionType.STRING, REASON_OPTION, "Why you want to warn the user", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WhoIsCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WhoIsCommand.java index f255ab08ef..fe7bfaad8e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WhoIsCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WhoIsCommand.java @@ -8,12 +8,12 @@ import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.commands.utils.DiscordClientAction; import javax.annotation.CheckReturnValue; -import java.awt.Color; +import java.awt.*; import java.time.Instant; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; @@ -39,7 +39,7 @@ public final class WhoIsCommand extends SlashCommandAdapter { * Creates an instance. */ public WhoIsCommand() { - super("whois", "Provides info about the given user", SlashCommandVisibility.GUILD); + super("whois", "Provides info about the given user", CommandVisibility.GUILD); getData().addOption(OptionType.USER, USER_OPTION, "the user to look up", true) .addOption(OptionType.BOOLEAN, SHOW_SERVER_INFO_OPTION, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java index 931b26e075..6e2a4795ec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java @@ -7,8 +7,8 @@ import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; import java.time.*; @@ -53,7 +53,7 @@ public final class RemindCommand extends SlashCommandAdapter { */ public RemindCommand(Database database) { super(COMMAND_NAME, "Reminds you after a given time period has passed (e.g. in 5 weeks)", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); // TODO As soon as JDA offers date/time selector input, this should also offer // "/remind at" next to "/remind in" and use subcommands then diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java index 51e9434eed..8c0d5cb0b4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java @@ -1,22 +1,18 @@ package org.togetherjava.tjbot.commands.system; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Channel; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; -import net.dv8tion.jda.api.exceptions.ErrorHandler; import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.components.ComponentInteraction; -import net.dv8tion.jda.api.requests.ErrorResponse; +import org.jetbrains.annotations.Unmodifiable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.CommandReloading; import org.togetherjava.tjbot.commands.*; import org.togetherjava.tjbot.commands.componentids.ComponentId; import org.togetherjava.tjbot.commands.componentids.ComponentIdParser; @@ -29,8 +25,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; +import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -47,19 +43,17 @@ * event listener, using {@link net.dv8tion.jda.api.JDA#addEventListener(Object...)}. Afterwards, * the system is ready and will correctly forward events to all commands. */ -public final class BotCore extends ListenerAdapter implements SlashCommandProvider { +public final class BotCore extends ListenerAdapter implements CommandProvider { private static final Logger logger = LoggerFactory.getLogger(BotCore.class); - private static final String RELOAD_COMMAND = "reload"; private static final ExecutorService COMMAND_SERVICE = Executors.newCachedThreadPool(); private static final ScheduledExecutorService ROUTINE_SERVICE = Executors.newScheduledThreadPool(5); private final Config config; - private final Map nameToInteractor; + private final Map prefixedNameToInteractor; private final List routines; private final ComponentIdParser componentIdParser; private final ComponentIdStore componentIdStore; private final Map channelNameToMessageReceiver = new HashMap<>(); - private final AtomicBoolean receivedOnReady = new AtomicBoolean(false); /** * Creates a new command system which uses the given database to allow commands to persist data. @@ -94,74 +88,112 @@ public BotCore(JDA jda, Database database, Config config) { .toList(); // User Interactors (e.g. slash commands) - nameToInteractor = features.stream() + prefixedNameToInteractor = features.stream() .filter(UserInteractor.class::isInstance) .map(UserInteractor.class::cast) - .collect(Collectors.toMap(UserInteractor::getName, Function.identity())); + .filter(validateInteractorPredicate()) + .collect(Collectors.toMap(UserInteractorPrefix::getPrefixedNameFromInstance, + Function.identity())); - // Reload Command - if (nameToInteractor.containsKey(RELOAD_COMMAND)) { - throw new IllegalStateException( - "The 'reload' command is a special reserved command that must not be used by other user interactors"); - } - nameToInteractor.put(RELOAD_COMMAND, new ReloadCommand(this)); // Component Id Store componentIdStore = new ComponentIdStore(database); componentIdStore.addComponentIdRemovedListener(BotCore::onComponentIdRemoved); componentIdParser = uuid -> componentIdStore.get(UUID.fromString(uuid)); - nameToInteractor.values() - .forEach(slashCommand -> slashCommand - .acceptComponentIdGenerator(((componentId, lifespan) -> { - UUID uuid = UUID.randomUUID(); - componentIdStore.putOrThrow(uuid, componentId, lifespan); - return uuid.toString(); - }))); + Collection interactors = getInteractors(); + + interactors.forEach(slashCommand -> slashCommand + .acceptComponentIdGenerator(((componentId, lifespan) -> { + UUID uuid = UUID.randomUUID(); + componentIdStore.putOrThrow(uuid, componentId, lifespan); + return uuid.toString(); + }))); if (logger.isInfoEnabled()) { - logger.info("Available user interactors: {}", nameToInteractor.keySet()); + logger.info("Available user interactors: {}", interactors); } + + + CommandReloading.reloadCommands(jda, this); + scheduleRoutines(jda); + } + + /** + * Returns a predicate which validates the given interactor + * + * @return A predicate which validates the given interactor + */ + private static Predicate validateInteractorPredicate() { + return interactor -> { + String name = interactor.getName(); + + if (name == null) { + logger.error("An interactor's name shouldn't be null! {}", interactor); + return false; + } + + for (UserInteractorPrefix value : UserInteractorPrefix.values()) { + String prefix = value.getPrefix(); + + if (name.startsWith(prefix)) { + throw new IllegalArgumentException( + "The interactor's name cannot start with any of the reserved prefixes. (" + + prefix + ")"); + } + } + + if (name.startsWith("s-") || name.startsWith("mc-") || name.startsWith("uc-")) { + throw new IllegalArgumentException( + "The interactor's name cannot start with any of the prefixes."); + } + + return true; + }; } @Override - public Collection getSlashCommands() { - return nameToInteractor.values() - .stream() - .filter(SlashCommand.class::isInstance) - .map(SlashCommand.class::cast) - .toList(); + @Unmodifiable + public Collection getInteractors() { + return prefixedNameToInteractor.values(); } @Override - public Optional getSlashCommand(String name) { - return Optional.ofNullable(nameToInteractor.get(name)) - .filter(SlashCommand.class::isInstance) - .map(SlashCommand.class::cast); + public Optional getInteractor(final String prefixedName) { + + return Optional.ofNullable(prefixedNameToInteractor.get(prefixedName)); } - /** - * Trigger once JDA is ready. Subsequent calls are ignored. - * - * @param jda the JDA instance to work with - */ - public void onReady(JDA jda) { - if (!receivedOnReady.compareAndSet(false, true)) { - // Ensures that we only enter the event once - return; - } + @Override + public Optional getInteractor(final String name, + final Class type) { + Objects.requireNonNull(type, "The given type cannot be null"); + + String prefixedName = UserInteractorPrefix.getPrefixedNameFromClass(type, name); + return Optional.ofNullable(prefixedNameToInteractor.get(prefixedName)) + .filter(type::isInstance) + .map(type::cast); + } - // Register reload on all guilds - logger.debug("JDA is ready, registering reload command"); - jda.getGuildCache() - .forEach(guild -> COMMAND_SERVICE.execute(() -> registerReloadCommand(guild))); - // NOTE We do not have to wait for reload to complete for the command system to be ready - // itself - logger.debug("Bot core is now ready"); + @Override + public List getInteractorsWithName(final String name) { + List localInteractors = new ArrayList<>(4); - scheduleRoutines(jda); + for (UserInteractorPrefix value : UserInteractorPrefix.values()) { + getInteractor(name, value.getClassType()).ifPresent(localInteractors::add); + } + + return localInteractors; } - private void scheduleRoutines(JDA jda) { + + /** + * Schedules the registered routines. + *

+ * This needs a ready {@link JDA} instance. + * + * @param jda a ready JDA instance + */ + public void scheduleRoutines(JDA jda) { routines.forEach(routine -> { Runnable command = () -> { String routineName = routine.getClass().getSimpleName(); @@ -234,23 +266,6 @@ public void onSelectMenuInteraction(SelectMenuInteractionEvent event) { .execute(() -> forwardComponentCommand(event, UserInteractor::onSelectionMenu)); } - private void registerReloadCommand(Guild guild) { - guild.retrieveCommands().queue(commands -> { - // Has it been registered already? - if (commands.stream().map(Command::getName).anyMatch(RELOAD_COMMAND::equals)) { - logger.debug("Command '{}' has already been registered for guild '{}'", - RELOAD_COMMAND, guild.getName()); - return; - } - - logger.debug("Register '{}' for guild '{}'", RELOAD_COMMAND, guild.getName()); - SlashCommand reloadCommand = requireSlashCommand(RELOAD_COMMAND); - guild.upsertCommand(reloadCommand.getData()) - .queue(command -> logger.debug("Registered '{}' for guild '{}'", RELOAD_COMMAND, - guild.getName())); - }, ex -> handleRegisterErrors(ex, guild)); - } - /** * Forwards the given component event to the associated user interactor. *

@@ -305,7 +320,7 @@ private void forwardComponentCommand(T event, * @throws NullPointerException if the command with the given name was not registered */ private SlashCommand requireSlashCommand(String name) { - return getSlashCommand(name).orElseThrow( + return getInteractor(name, SlashCommand.class).orElseThrow( () -> new NullPointerException("There is no slash command with name " + name)); } @@ -314,39 +329,12 @@ private SlashCommand requireSlashCommand(String name) { * * @param name the name of the user interactor to get * @return the user interactor with the given name - * @throws NullPointerException if the user interactor with the given name was not registered + * @throws NoSuchElementException if the user interactor with the given name was not registered */ - private UserInteractor requireUserInteractor(String name) { - return Objects.requireNonNull(nameToInteractor.get(name)); + private UserInteractor requireUserInteractor(final String name) { + return getInteractor(name).orElseThrow(); } - private void handleRegisterErrors(Throwable ex, Guild guild) { - new ErrorHandler().handle(ErrorResponse.MISSING_ACCESS, errorResponse -> { - // Find a channel that we have permissions to write to - // NOTE Unfortunately, there is no better accurate way to find a proper channel - // where we can report the setup problems other than simply iterating all of them. - Optional channelToReportTo = guild.getTextChannelCache() - .stream() - .filter(channel -> guild.getPublicRole() - .hasPermission(channel, Permission.MESSAGE_SEND)) - .findAny(); - - // Report the problem to the guild - channelToReportTo.ifPresent(textChannel -> textChannel - .sendMessage("I need the commands scope, please invite me correctly." - + " You can join '%s' or visit '%s' for more info, I will leave your guild now." - .formatted(config.getDiscordGuildInvite(), config.getProjectWebsite())) - .queue()); - - guild.leave().queue(); - - String unableToReportText = channelToReportTo.isPresent() ? "" - : " Did not find any public text channel to report the issue to, unable to inform the guild."; - logger.warn( - "Guild '{}' does not have the required command scope, unable to register, leaving it.{}", - guild.getName(), unableToReportText, ex); - }).accept(ex); - } @SuppressWarnings("EmptyMethod") private static void onComponentIdRemoved(ComponentId componentId) { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandProvider.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandProvider.java new file mode 100644 index 0000000000..639b7dbf6d --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandProvider.java @@ -0,0 +1,70 @@ +package org.togetherjava.tjbot.commands.system; + +import org.togetherjava.tjbot.commands.BotCommand; +import org.togetherjava.tjbot.commands.UserInteractor; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +/** + * Provides all registered commands. + */ +public interface CommandProvider { + /** + * Gets a list of all currently available and registered interactors. + * + * @return all interactors + */ + Collection getInteractors(); + + /** + * Gets a list of all currently available and registered bot commands. + * + * @return all bot commands + */ + default Collection getCommands() { + return getInteractors().stream() + .filter(BotCommand.class::isInstance) + .map(BotCommand.class::cast) + .toList(); + } + + /** + * Gets the interactor registered under the given name, if any. + *

+ * This command expects the name to include the prefix already, if you prefer using a + * {@link Class} instance of the command/type instead, use {@link #getInteractor(String, Class)} + * instead. + * + * @param prefixedName the name of the command (including its prefix, see + * {@link org.togetherjava.tjbot.commands.UserInteractorPrefix UserInteractorPrefix} + * @return the interactor registered under this name, if any + */ + Optional getInteractor(String prefixedName); + + /** + * Gets the interactor registered under the given name, if any. + *

+ * Unlike {@link #getInteractor(String)}, this command expects the name, without the prefix (see + * {@link org.togetherjava.tjbot.commands.UserInteractorPrefix UserInteractorPrefix}). Instead, + * this command expects a {@link Class} instance of the commands class. This can be + * {@link org.togetherjava.tjbot.commands.SlashCommand SlashCommand}, or even as specific as + * {@link org.togetherjava.tjbot.commands.basic.PingCommand PingCommand}. + * + * @param name the name of the command without prefix + * @param type the type of the command + * @return the interactor registered under this name, if any + */ + Optional getInteractor(String name, Class type); + + /** + * Gets any interactors with the given name. The name you give should be without prefix, these + * methods checks all prefixes themselves. If your name is with prefix, use + * {@link #getInteractor(String)} + * + * @param name the name of the command + * @return a list of commands with that name, can be empty if none match + */ + List getInteractorsWithName(final String name); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/LogLevelCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/LogLevelCommand.java index 2780f3f8ed..3e11f2f367 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/LogLevelCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/LogLevelCommand.java @@ -6,8 +6,8 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.util.stream.Stream; @@ -31,7 +31,7 @@ public final class LogLevelCommand extends SlashCommandAdapter { */ public LogLevelCommand() { super("set-log-level", "Changes the log level of the bot while it is running.", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); OptionData option = new OptionData(OptionType.STRING, LOG_LEVEL_OPTION, "the log level to set", true); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java deleted file mode 100644 index f061b98695..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.togetherjava.tjbot.commands.system; - -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.interactions.components.buttons.Button; -import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; -import net.dv8tion.jda.api.requests.RestAction; -import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.togetherjava.tjbot.commands.SlashCommand; -import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; -import org.togetherjava.tjbot.commands.utils.MessageUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; -import java.util.stream.Stream; - -/** - * The reload command is a meta command that updates all commands to Discord by using - * {@link CommandListUpdateAction} to push any changes through JDA. - *

- * Whenever a command has been added, removed or changed, the reload command has to be called for - * the changes to actually take effect in Discord. - *

- * This command is rate limited by Discord and may not be used too often. Be aware that it will - * reload all commands registered with this application, on all guilds. - */ -public final class ReloadCommand extends SlashCommandAdapter { - private static final Logger logger = LoggerFactory.getLogger(ReloadCommand.class); - private final SlashCommandProvider commandProvider; - - /** - * Creates the reload command, using the given provider as source of truth for the commands to - * reload - * - * @param commandProvider the provider of slash commands to reload when this command is - * triggered - */ - public ReloadCommand(SlashCommandProvider commandProvider) { - super("reload", - "Uploads all existing slash-commands to Discord so they are fully up-to-date.", - SlashCommandVisibility.GUILD); - this.commandProvider = commandProvider; - } - - @Override - public void onSlashCommand(SlashCommandInteractionEvent event) { - Member member = Objects.requireNonNull(event.getMember()); - - if (!member.hasPermission(Permission.MANAGE_SERVER)) { - logger.debug( - "Attempted reload but is missing permissions, triggered by user '{}' in guild '{}'", - member.getId(), event.getGuild()); - event.reply("You need the 'MANAGE_SERVER' permission to use this command.") - .setEphemeral(true) - .queue(); - return; - } - - event.reply( - "Are you sure? You can only reload commands a few times each day, so do not overdo this.") - .addActionRow(Button.success(generateComponentId(member.getId()), "Yes"), - Button.danger(generateComponentId(member.getId()), "No")) - .queue(); - } - - @Override - public void onButtonClick(ButtonInteractionEvent event, List args) { - // Ignore if another user clicked the button - String userId = args.get(0); - if (!userId.equals(Objects.requireNonNull(event.getMember()).getId())) { - event.reply("Sorry, but only the user who triggered the command can use these buttons.") - .setEphemeral(true) - .queue(); - return; - } - - ButtonStyle buttonStyle = Objects.requireNonNull(event.getButton()).getStyle(); - switch (buttonStyle) { - case DANGER -> event.reply("Okay, will not reload.").queue(); - case SUCCESS -> { - logger.info("Reloading commands, triggered by user '{}' in guild '{}'", userId, - event.getGuild()); - event.deferReply().queue(); - List actions = - Collections.synchronizedList(new ArrayList<>()); - - // Reload global commands - actions.add(updateCommandsIf( - command -> command.getVisibility() == SlashCommandVisibility.GLOBAL, - getGlobalUpdateAction(event.getJDA()))); - - // Reload guild commands (potentially many guilds) - // NOTE Storing the guild actions in a list is potentially dangerous since the - // bot might theoretically be part of so many guilds that it exceeds the max size of - // list. However, correctly reducing RestActions in a stream is not trivial. - getGuildUpdateActions(event.getJDA()) - .map(updateAction -> updateCommandsIf( - command -> command.getVisibility() == SlashCommandVisibility.GUILD, - updateAction)) - .forEach(actions::add); - logger.debug("Reloading commands over {} action-upstreams", actions.size()); - - // Send message when all are done - RestAction.allOf(actions) - .queue(updatedCommands -> event.getHook() - .editOriginal( - "Commands successfully reloaded! (global commands can take up to one hour to load)") - .queue()); - } - default -> throw new AssertionError("Unexpected button action clicked: " + buttonStyle); - } - - MessageUtils.disableButtons(event.getMessage()); - } - - /** - * Updates all commands given by the command provider which pass the given filter by pushing - * through the given action upstream. - * - * @param commandFilter filter that matches commands that should be uploaded - * @param updateAction the upstream to update commands - * @return the given upstream for chaining - */ - private CommandListUpdateAction updateCommandsIf(Predicate commandFilter, - CommandListUpdateAction updateAction) { - return commandProvider.getSlashCommands() - .stream() - .filter(commandFilter) - .map(SlashCommand::getData) - .reduce(updateAction, CommandListUpdateAction::addCommands, (x, y) -> x); - } - - private static CommandListUpdateAction getGlobalUpdateAction(JDA jda) { - return jda.updateCommands(); - } - - private static Stream getGuildUpdateActions(JDA jda) { - return jda.getGuildCache().stream().map(Guild::updateCommands); - } -} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/SlashCommandProvider.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/SlashCommandProvider.java deleted file mode 100644 index 64808d67f4..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/SlashCommandProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.togetherjava.tjbot.commands.system; - -import org.togetherjava.tjbot.commands.SlashCommand; - -import java.util.Collection; -import java.util.Optional; - -/** - * Provides all registered slash commands. - */ -public interface SlashCommandProvider { - /** - * Gets a list of all currently available and registered slash commands. - * - * @return all slash commands - */ - Collection getSlashCommands(); - - /** - * Gets the slash command registered under the given name, if any. - * - * @param name the name of the command - * @return the command registered under this name, if any - */ - Optional getSlashCommand(String name); -} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java index 615ee799ae..2e00048a18 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java @@ -5,8 +5,8 @@ import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.time.Instant; import java.util.Objects; @@ -30,7 +30,7 @@ public final class TagCommand extends SlashCommandAdapter { * @param tagSystem the system providing the actual tag data */ public TagCommand(TagSystem tagSystem) { - super("tag", "Display a tags content", SlashCommandVisibility.GUILD); + super("tag", "Display a tags content", CommandVisibility.GUILD); this.tagSystem = tagSystem; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java index c7b2602da2..f496ed104a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java @@ -12,8 +12,8 @@ import net.dv8tion.jda.api.requests.ErrorResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import javax.annotation.Nullable; @@ -68,7 +68,7 @@ public final class TagManageCommand extends SlashCommandAdapter { * @param modAuditLogWriter to log tag changes for audition */ public TagManageCommand(TagSystem tagSystem, ModAuditLogWriter modAuditLogWriter) { - super("tag-manage", "Provides commands to manage all tags", SlashCommandVisibility.GUILD); + super("tag-manage", "Provides commands to manage all tags", CommandVisibility.GUILD); this.tagSystem = tagSystem; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java index 3432720cb9..1d1bffd7b6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java @@ -6,8 +6,8 @@ import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import java.time.Instant; import java.util.Collection; @@ -42,7 +42,7 @@ public final class TagsCommand extends SlashCommandAdapter { * @param tagSystem the system providing the actual tag data */ public TagsCommand(TagSystem tagSystem) { - super("tags", "Displays all available tags", SlashCommandVisibility.GUILD); + super("tags", "Displays all available tags", CommandVisibility.GUILD); this.tagSystem = tagSystem; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersCommand.java index dd609826ea..1ce9b20b80 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersCommand.java @@ -14,8 +14,8 @@ import org.jooq.impl.DSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; import javax.annotation.Nullable; @@ -51,7 +51,7 @@ public final class TopHelpersCommand extends SlashCommandAdapter { */ public TopHelpersCommand(Database database) { super(COMMAND_NAME, "Lists top helpers for the last month, or a given month", - SlashCommandVisibility.GUILD); + CommandVisibility.GUILD); OptionData monthData = new OptionData(OptionType.STRING, MONTH_OPTION, "the month to compute for, by default the last month", false); diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/SlashCommandAdapterTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/SlashCommandAdapterTest.java index 4007feba5c..bc5b18ed7d 100644 --- a/application/src/test/java/org/togetherjava/tjbot/commands/SlashCommandAdapterTest.java +++ b/application/src/test/java/org/togetherjava/tjbot/commands/SlashCommandAdapterTest.java @@ -11,7 +11,7 @@ final class SlashCommandAdapterTest { private static final String NAME = "foo"; private static final String DESCRIPTION = "Foo command"; - private static final SlashCommandVisibility VISIBILITY = SlashCommandVisibility.GUILD; + private static final CommandVisibility VISIBILITY = CommandVisibility.GUILD; private static final int UNIQUE_ID_ITERATIONS = 20; static SlashCommandAdapter createAdapter() { diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java deleted file mode 100644 index 69ca4c9518..0000000000 --- a/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.togetherjava.tjbot.commands.system; - -import org.junit.jupiter.api.Test; -import org.togetherjava.tjbot.commands.SlashCommand; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -final class ReloadCommandTest { - @Test - void ReloadCommand() { - @SuppressWarnings({"AnonymousInnerClassWithTooManyMethods", "AnonymousInnerClass", - "AnonymousInnerClassMayBeStatic"}) - SlashCommandProvider slashCommandProvider = new SlashCommandProvider() { - @Override - public Collection getSlashCommands() { - return List.of(); - } - - @Override - public Optional getSlashCommand(String name) { - return Optional.empty(); - } - }; - - // Adjust this test if the command is supposed to be renamed; make sure to update it in all - // places. - assertEquals("reload", new ReloadCommand(slashCommandProvider).getName(), - "expected name of reload command to be 'reload', a name change can have severe consequences if not all sites that rely on this are updated."); - } -}