[AB-66] adding mines game

fixing suggestion evaluation job not getting the correct parameters
adding feature dependent parameters
This commit is contained in:
Sheldan
2022-12-02 01:33:38 +01:00
parent 96c38763b1
commit 0d6182c5d5
38 changed files with 992 additions and 29 deletions

View File

@@ -10,6 +10,7 @@ import dev.sheldan.abstracto.core.command.exception.InsufficientParametersExcept
import dev.sheldan.abstracto.core.command.execution.*;
import dev.sheldan.abstracto.core.command.handler.CommandParameterHandler;
import dev.sheldan.abstracto.core.command.handler.CommandParameterIterators;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.interaction.button.CommandConfirmationModel;
import dev.sheldan.abstracto.core.interaction.button.CommandConfirmationPayload;
import dev.sheldan.abstracto.core.command.service.CommandManager;
@@ -109,6 +110,12 @@ public class CommandReceivedHandler extends ListenerAdapter {
@Autowired
private MessageService messageService;
@Autowired
private FeatureConfigService featureConfigService;
@Autowired
private FeatureFlagService featureFlagService;
public static final String COMMAND_CONFIRMATION_ORIGIN = "commandConfirmation";
public static final String COMMAND_CONFIRMATION_MESSAGE_TEMPLATE_KEY = "command_confirmation_message";
public static final String COMMAND_PROCESSED = "command.processed";
@@ -260,7 +267,7 @@ public class CommandReceivedHandler extends ListenerAdapter {
.message(event.getMessage())
.jda(event.getJDA())
.userInitiatedContext(userInitiatedContext);
validateCommandParameters(parsedParameters, foundCommand);
validateCommandParameters(parsedParameters, foundCommand, event.getGuild().getIdLong());
CommandContext commandContext = commandContextBuilder.parameters(parsedParameters).build();
CompletableFuture<ConditionResult> conditionResultFuture = commandService.isCommandExecutable(foundCommand, commandContext);
conditionResultFuture.thenAccept(conditionResult -> {
@@ -347,7 +354,7 @@ public class CommandReceivedHandler extends ListenerAdapter {
reportException(event.getMessage(), event.getChannel(), event.getMember(), foundCommand, throwable, s);
}
private void validateCommandParameters(Parameters parameters, Command foundCommand) {
private void validateCommandParameters(Parameters parameters, Command foundCommand, Long serverId) {
CommandConfiguration commandConfiguration = foundCommand.getConfiguration();
List<Parameter> parameterList = commandConfiguration.getParameters();
// we iterate only over the actually found parameters, that way we dont have to consider the optional parameters
@@ -362,8 +369,9 @@ public class CommandReceivedHandler extends ListenerAdapter {
}
}
}
if (commandConfiguration.getNecessaryParameterCount() > parameters.getParameters().size()) {
String nextParameterName = commandConfiguration.getParameters().get(commandConfiguration.getNecessaryParameterCount() - 1).getName();
long necessaryParameters = commandManager.getParameterCountForCommandConfig(commandConfiguration, serverId);
if (necessaryParameters > parameters.getParameters().size()) {
String nextParameterName = commandConfiguration.getParameters().get((int)necessaryParameters - 1).getName();
throw new InsufficientParametersException(foundCommand, nextParameterName);
}
}
@@ -438,6 +446,22 @@ public class CommandReceivedHandler extends ListenerAdapter {
} else {
break;
}
if(!param.getDependentFeatures().isEmpty()) {
List<FeatureDefinition> featureDefinitions = param
.getDependentFeatures()
.stream()
.map(s -> featureConfigService.getFeatureEnum(s))
.collect(Collectors.toList());
boolean parameterActiveForFeatures = false;
for (FeatureDefinition featureDefinition : featureDefinitions) {
if(featureFlagService.getFeatureFlagValue(featureDefinition, message.getGuild().getIdLong())) {
parameterActiveForFeatures = true;
}
}
if(!parameterActiveForFeatures) {
break;
}
}
UnparsedCommandParameterPiece value = unParsedCommandParameter.getParameters().get(i);
// TODO might be able to do this without iterating, if we directly associated the handler required for each parameter
for (CommandParameterHandler handler : usedParameterHandler) {

View File

@@ -4,13 +4,17 @@ import dev.sheldan.abstracto.core.command.Command;
import dev.sheldan.abstracto.core.command.CommandReceivedHandler;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.ModuleDefinition;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.exception.CommandNotFoundException;
import dev.sheldan.abstracto.core.command.exception.InsufficientParametersException;
import dev.sheldan.abstracto.core.command.execution.UnParsedCommandParameter;
import dev.sheldan.abstracto.core.command.model.database.ACommandInAServer;
import dev.sheldan.abstracto.core.command.model.database.ACommandInServerAlias;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.metric.service.MetricService;
import dev.sheldan.abstracto.core.service.ConfigService;
import dev.sheldan.abstracto.core.service.FeatureConfigService;
import dev.sheldan.abstracto.core.service.FeatureFlagService;
import dev.sheldan.abstracto.core.service.management.DefaultConfigManagementService;
import net.dv8tion.jda.api.entities.Message;
import org.springframework.beans.factory.annotation.Autowired;
@@ -20,6 +24,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Service
public class CommandManager implements CommandRegistry {
@@ -40,9 +45,15 @@ public class CommandManager implements CommandRegistry {
@Autowired
private CommandInServerAliasService commandInServerAliasService;
@Autowired
private FeatureFlagService featureFlagService;
@Autowired
private FeatureConfigService featureConfigService;
@Override
public Optional<Command> findCommandByParameters(String name, UnParsedCommandParameter unParsedCommandParameter, Long serverId) {
Optional<Command> commandOptional = commands.stream().filter(getCommandByNameAndParameterPredicate(name, unParsedCommandParameter)).findFirst();
Optional<Command> commandOptional = commands.stream().filter(getCommandByNameAndParameterPredicate(name, unParsedCommandParameter, serverId)).findFirst();
if(!commandOptional.isPresent()) {
commandOptional = getCommandViaAliasAndParameter(name, unParsedCommandParameter, serverId);
}
@@ -55,7 +66,7 @@ public class CommandManager implements CommandRegistry {
// if its present, retrieve the original command
ACommandInAServer command = aliasOptional.get().getCommandInAServer();
// and find the command based on the newly found name
return commands.stream().filter(getCommandByNameAndParameterPredicate(command.getCommandReference().getName(), unParsedCommandParameter)).findFirst();
return commands.stream().filter(getCommandByNameAndParameterPredicate(command.getCommandReference().getName(), unParsedCommandParameter, serverId)).findFirst();
}
return Optional.empty();
}
@@ -71,7 +82,7 @@ public class CommandManager implements CommandRegistry {
return Optional.empty();
}
private Predicate<Command> getCommandByNameAndParameterPredicate(String name, UnParsedCommandParameter unParsedCommandParameter) {
private Predicate<Command> getCommandByNameAndParameterPredicate(String name, UnParsedCommandParameter unParsedCommandParameter, Long serverId) {
return (Command commandObj) -> {
CommandConfiguration commandConfiguration = commandObj.getConfiguration();
if (commandConfiguration == null) {
@@ -80,7 +91,7 @@ public class CommandManager implements CommandRegistry {
if (!commandNameOrAliasMatches(name, commandConfiguration)) {
return false;
}
return verifyCommandConfiguration(unParsedCommandParameter, commandObj, commandConfiguration);
return verifyCommandConfiguration(unParsedCommandParameter, commandObj, commandConfiguration, serverId);
};
}
@@ -94,15 +105,47 @@ public class CommandManager implements CommandRegistry {
};
}
private boolean verifyCommandConfiguration(UnParsedCommandParameter unParsedCommandParameter, Command command, CommandConfiguration commandConfiguration) {
if(commandConfiguration.getParameters() != null && commandConfiguration.getNecessaryParameterCount() > unParsedCommandParameter.getParameters().size()){
String nextParameterName = commandConfiguration.getParameters().get(commandConfiguration.getNecessaryParameterCount() - 1).getName();
metricService.incrementCounter(CommandReceivedHandler.COMMANDS_WRONG_PARAMETER_COUNTER);
throw new InsufficientParametersException(command, nextParameterName);
private boolean verifyCommandConfiguration(UnParsedCommandParameter unParsedCommandParameter, Command command, CommandConfiguration commandConfiguration, Long serverId) {
if(commandConfiguration.getParameters() != null) {
long necessaryParameterCount = getParameterCountForCommandConfig(commandConfiguration, serverId);
if(necessaryParameterCount > unParsedCommandParameter.getParameters().size()){
String nextParameterName = commandConfiguration.getParameters().get((int) necessaryParameterCount - 1).getName();
metricService.incrementCounter(CommandReceivedHandler.COMMANDS_WRONG_PARAMETER_COUNTER);
throw new InsufficientParametersException(command, nextParameterName);
}
}
return true;
}
public long getParameterCountForCommandConfig(CommandConfiguration commandConfiguration, Long serverId) {
if(commandConfiguration.getParameters() == null || commandConfiguration.getParameters().isEmpty()) {
return 0;
}
return commandConfiguration
.getParameters()
.stream().filter(parameter -> isParameterRequired(parameter, serverId))
.count();
}
private boolean isParameterRequired(Parameter parameter, Long serverId) {
if(parameter.getDependentFeatures().isEmpty() || parameter.isOptional()) {
return !parameter.isOptional();
} else {
List<FeatureDefinition> featureDefinitions = parameter
.getDependentFeatures()
.stream()
.map(s -> featureConfigService.getFeatureEnum(s))
.collect(Collectors.toList());
boolean required = false;
for (FeatureDefinition featureDefinition : featureDefinitions) {
if(featureFlagService.getFeatureFlagValue(featureDefinition, serverId)) {
required = true;
}
}
return required;
}
}
private boolean commandNameOrAliasMatches(String name, CommandConfiguration commandConfiguration) {
return commandConfiguration.getName().equalsIgnoreCase(name) ||
commandConfiguration.getAliases() != null && commandConfiguration.getAliases().stream().anyMatch(s -> s.equalsIgnoreCase(name));

View File

@@ -92,7 +92,7 @@ public class CommandLoaderListener implements AsyncStartupListener {
return;
}
log.info("Updating slash command {} in guild {}.", command.getConfiguration().getName(), guild.getId());
slashCommandService.convertCommandConfigToCommandData(command.getConfiguration(), slashCommandsToUpdate);
slashCommandService.convertCommandConfigToCommandData(command.getConfiguration(), slashCommandsToUpdate, guild.getIdLong());
});
log.info("Updating context commands for guild {}.", guild.getIdLong());

View File

@@ -25,6 +25,12 @@ public class ComponentPayloadServiceBean implements ComponentPayloadService {
return componentPayloadManagementService.createPayload(componentId, json, payload.getClass(), origin, server, ComponentType.BUTTON);
}
@Override
public void updateButtonPayload(String componentId, ButtonPayload payload) {
String json = gson.toJson(payload);
componentPayloadManagementService.updatePayload(componentId, json);
}
@Override
public ComponentPayload createSelectionPayload(String componentId, ButtonPayload payload, String origin, AServer server) {
String json = gson.toJson(payload);

View File

@@ -1,11 +1,15 @@
package dev.sheldan.abstracto.core.interaction.slash;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.model.database.ACommand;
import dev.sheldan.abstracto.core.command.model.database.ACommandInAServer;
import dev.sheldan.abstracto.core.command.service.management.CommandInServerManagementService;
import dev.sheldan.abstracto.core.command.service.management.CommandManagementService;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.interaction.slash.parameter.SlashCommandParameterService;
import dev.sheldan.abstracto.core.service.FeatureConfigService;
import dev.sheldan.abstracto.core.service.FeatureFlagService;
import dev.sheldan.abstracto.core.templating.service.TemplateService;
import dev.sheldan.abstracto.core.utils.CompletableFutureList;
import net.dv8tion.jda.api.entities.Guild;
@@ -42,8 +46,14 @@ public class SlashCommandServiceBean implements SlashCommandService {
@Autowired
private SlashCommandServiceBean self;
@Autowired
private FeatureConfigService featureConfigService;
@Autowired
private FeatureFlagService featureFlagService;
@Override
public void convertCommandConfigToCommandData(CommandConfiguration commandConfiguration, List<Pair<List<CommandConfiguration>, SlashCommandData>> existingCommands) {
public void convertCommandConfigToCommandData(CommandConfiguration commandConfiguration, List<Pair<List<CommandConfiguration>, SlashCommandData>> existingCommands, Long serverId) {
boolean isTemplated = commandConfiguration.isTemplated();
SlashCommandConfig slashConfig = commandConfiguration.getSlashCommandConfig();
String description;
@@ -76,10 +86,10 @@ public class SlashCommandServiceBean implements SlashCommandService {
groupData.addSubcommands(slashCommand);
rootCommand.addSubcommandGroups(groupData);
}
List<OptionData> requiredParameters = getParameters(commandConfiguration, isTemplated, internalCommandName);
List<OptionData> requiredParameters = getParameters(commandConfiguration, isTemplated, internalCommandName, serverId);
slashCommand.addOptions(requiredParameters);
} else {
List<OptionData> requiredParameters = getParameters(commandConfiguration, isTemplated, internalCommandName);
List<OptionData> requiredParameters = getParameters(commandConfiguration, isTemplated, internalCommandName, serverId);
rootCommand.addOptions(requiredParameters);
}
if(!existingRootCommand.isPresent()) {
@@ -95,10 +105,18 @@ public class SlashCommandServiceBean implements SlashCommandService {
}
}
private List<OptionData> getParameters(CommandConfiguration commandConfiguration, boolean isTemplated, String internalCommandName) {
@Override
public void convertCommandConfigToCommandData(CommandConfiguration commandConfiguration, List<Pair<List<CommandConfiguration>, SlashCommandData>> existingCommands) {
convertCommandConfigToCommandData(commandConfiguration, existingCommands, null);
}
private List<OptionData> getParameters(CommandConfiguration commandConfiguration, boolean isTemplated, String internalCommandName, Long serverId) {
List<OptionData> requiredParameters = new ArrayList<>();
List<OptionData> optionalParameters = new ArrayList<>();
commandConfiguration.getParameters().forEach(parameter -> {
if(!shouldParameterBeCreated(parameter, serverId)) {
return;
}
List<OptionType> types = slashCommandParameterService.getTypesFromParameter(parameter.getType());
if(types.size() > 1) {
if(parameter.isListParam()) {
@@ -132,6 +150,25 @@ public class SlashCommandServiceBean implements SlashCommandService {
return requiredParameters;
}
private boolean shouldParameterBeCreated(Parameter parameter, Long serverId) {
if(parameter.getDependentFeatures().isEmpty()) {
return true;
} else {
List<FeatureDefinition> featureDefinitions = parameter
.getDependentFeatures()
.stream()
.map(s -> featureConfigService.getFeatureEnum(s))
.collect(Collectors.toList());
for (FeatureDefinition featureDefinition : featureDefinitions) {
if(!featureFlagService.getFeatureFlagValue(featureDefinition, serverId)) {
return false;
}
}
return true;
}
}
@Override
public CompletableFuture<List<Command>> updateGuildSlashCommand(Guild guild, List<Pair<List<CommandConfiguration>, SlashCommandData>> commandData) {

View File

@@ -55,7 +55,7 @@ public class SlashCommandFeatureActivationListener implements FeatureActivationL
return;
}
log.info("Updating slash command {} in guild {}.", command.getConfiguration().getName(), guild.getId());
slashCommandService.convertCommandConfigToCommandData(command.getConfiguration(), commandsToUpDate);
slashCommandService.convertCommandConfigToCommandData(command.getConfiguration(), commandsToUpDate, model.getServerId());
});
slashCommandService.addGuildSlashCommands(guild, commandsToUpDate)
.thenAccept(commands1 -> log.info("Updating {} slash commands in guild {}.", commandsToUpDate.size(), guild.getIdLong()));

View File

@@ -42,6 +42,11 @@ public class ComponentPayloadManagementServiceBean implements ComponentPayloadMa
return repository.save(componentPayload);
}
@Override
public void updatePayload(String id, String payload) {
findPayload(id).ifPresent(componentPayload -> componentPayload.setPayload(payload));
}
@Override
public ComponentPayload createButtonPayload(ButtonConfigModel buttonConfigModel, AServer server) {
String payload = gson.toJson(buttonConfigModel.getButtonPayload());

View File

@@ -100,7 +100,6 @@ public class CommandManagerTest {
commands.add(firstCommand);
when(commandConfiguration.getName()).thenReturn(COMMAND_NAME);
when(firstCommand.getConfiguration()).thenReturn(commandConfiguration);
when(commandConfiguration.getNecessaryParameterCount()).thenReturn(0);
when(parsedCommandParameter.getParameters()).thenReturn(new ArrayList<>());
Optional<Command> foundCommand = testUnit.findCommandByParameters(COMMAND_NAME, parsedCommandParameter, SERVER_ID);
Assert.assertEquals(firstCommand, foundCommand.get());
@@ -132,7 +131,6 @@ public class CommandManagerTest {
when(commandConfiguration.getName()).thenReturn(COMMAND_NAME_2);
when(commandConfiguration.getAliases()).thenReturn(Arrays.asList(COMMAND_NAME));
when(firstCommand.getConfiguration()).thenReturn(commandConfiguration);
when(commandConfiguration.getNecessaryParameterCount()).thenReturn(0);
when(parsedCommandParameter.getParameters()).thenReturn(new ArrayList<>());
Optional<Command> foundCommand = testUnit.findCommandByParameters(COMMAND_NAME, parsedCommandParameter, SERVER_ID);
Assert.assertEquals(firstCommand, foundCommand.get());
@@ -144,7 +142,6 @@ public class CommandManagerTest {
when(commandConfiguration.getParameters()).thenReturn(Arrays.asList(parameter));
when(firstCommand.getConfiguration()).thenReturn(commandConfiguration);
when(commandConfiguration.getName()).thenReturn(COMMAND_NAME);
when(commandConfiguration.getNecessaryParameterCount()).thenReturn(1);
when(parsedCommandParameter.getParameters()).thenReturn(new ArrayList<>());
testUnit.findCommandByParameters(COMMAND_NAME, parsedCommandParameter, SERVER_ID);
}
@@ -154,7 +151,6 @@ public class CommandManagerTest {
commands.add(firstCommand);
when(commandConfiguration.getName()).thenReturn(COMMAND_NAME);
when(firstCommand.getConfiguration()).thenReturn(commandConfiguration);
when(commandConfiguration.getNecessaryParameterCount()).thenReturn(0);
when(parsedCommandParameter.getParameters()).thenReturn(new ArrayList<>());
setupAliasTest();
Optional<Command> foundCommand = testUnit.findCommandByParameters(ALIAS_NAME, parsedCommandParameter, SERVER_ID);

View File

@@ -50,7 +50,4 @@ public class CommandConfiguration {
.enabled(false)
.build();
public int getNecessaryParameterCount(){
return (int) parameters.stream().filter(parameter -> !parameter.isOptional()).count();
}
}

View File

@@ -34,6 +34,9 @@ public class Parameter implements Serializable {
private List<ParameterValidator> validators = new ArrayList<>();
@Builder.Default
private Map<String, Object> additionalInfo = new HashMap<>();
// these are the features which potentially require this parameter
@Builder.Default
private List<String> dependentFeatures = new ArrayList<>();
public String getSlashCompatibleName() {
return name.toLowerCase(Locale.ROOT);

View File

@@ -38,6 +38,13 @@ public class MaxIntegerValueValidator implements ParameterValidator {
return Arrays.asList(param);
}
public static MaxIntegerValueValidator max(Long number) {
return MaxIntegerValueValidator
.builder()
.maxValue(number)
.build();
}
@Override
public String getExceptionTemplateName() {
return "command_parameter_validation_value_too_large";

View File

@@ -2,6 +2,7 @@ package dev.sheldan.abstracto.core.command.service;
import dev.sheldan.abstracto.core.command.Command;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.ModuleDefinition;
import dev.sheldan.abstracto.core.command.execution.UnParsedCommandParameter;
import net.dv8tion.jda.api.entities.Message;
@@ -19,4 +20,5 @@ public interface CommandRegistry {
Command getCommandByName(String name, boolean searchAliases, Long serverId);
Optional<Command> getCommandByNameOptional(String name, boolean searchAliases, Long serverId);
String getCommandName(String input, Long serverId);
long getParameterCountForCommandConfig(CommandConfiguration commandConfiguration, Long serverId);
}

View File

@@ -11,6 +11,7 @@ import java.util.Optional;
public interface ComponentPayloadManagementService {
ComponentPayload createPayload(String id, String payload, Class payloadType, String buttonOrigin, AServer server, ComponentType type);
void updatePayload(String id, String payload);
ComponentPayload createButtonPayload(ButtonConfigModel buttonConfigModel, AServer server);
ComponentPayload createButtonPayload(ButtonConfigModel buttonConfigModel, Long serverId);
ComponentPayload createModalPayload(ModalConfigPayload payloadConfig, Long serverId);

View File

@@ -6,5 +6,6 @@ import dev.sheldan.abstracto.core.interaction.button.ButtonPayload;
public interface ComponentPayloadService {
ComponentPayload createButtonPayload(String componentId, ButtonPayload payload, String origin, AServer server);
void updateButtonPayload(String componentId, ButtonPayload payload);
ComponentPayload createSelectionPayload(String componentId, ButtonPayload payload, String origin, AServer server);
}

View File

@@ -10,6 +10,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
public interface SlashCommandService {
void convertCommandConfigToCommandData(CommandConfiguration commandConfiguration, List<Pair<List<CommandConfiguration>, SlashCommandData>> existingCommands, Long serverId);
void convertCommandConfigToCommandData(CommandConfiguration commandConfiguration, List<Pair<List<CommandConfiguration>, SlashCommandData>> existingCommands);
CompletableFuture<List<Command>> updateGuildSlashCommand(Guild guild, List<Pair<List<CommandConfiguration>, SlashCommandData>> commandData);
CompletableFuture<Void> deleteGuildSlashCommands(Guild guild, List<Long> slashCommandId, List<Long> commandInServerIdsToUnset);