Search in sources :

Example 1 with AbstractCommand

use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.

the class GuildPropertyInterceptor method updatePresets.

private void updatePresets(AbstractGuildProperty argumentPrefixProperty, Character oldArgumentPrefix, char newArgumentPrefix, Session session) {
    List<Preset> presets = queryBuilderFactory.find(Preset.class).build(session).getResultList();
    String defaultValue = argumentPrefixProperty.getDefaultValue();
    char[] chars = defaultValue.toCharArray();
    char defaultArgPrefix;
    if (chars.length == 1) {
        defaultArgPrefix = chars[0];
    } else {
        defaultArgPrefix = ArgumentPrefixProperty.DEFAULT_FALLBACK;
    }
    char argPrefix = oldArgumentPrefix != null ? oldArgumentPrefix : defaultArgPrefix;
    ArgumentPrefixProperty.Config argumentPrefixConfig = new ArgumentPrefixProperty.Config(argPrefix, defaultArgPrefix);
    for (Preset preset : presets) {
        Aiode aiode = Aiode.get();
        AbstractCommand command = preset.instantiateCommand(aiode.getCommandManager(), commandContext, preset.getName());
        String oldPreset = preset.getPreset();
        StringBuilder newPresetBuilder = new StringBuilder(oldPreset);
        List<Integer> oldPrefixOccurrences = Lists.newArrayList();
        CommandParser commandParser = new CommandParser(command, argumentPrefixConfig, new CommandParseListener() {

            @Override
            public void onModeSwitch(CommandParser.Mode previousMode, CommandParser.Mode newMode, int index, char character) {
                // they are in fact argument prefixes
                if (newMode instanceof ArgumentBuildingMode) {
                    oldPrefixOccurrences.add(index);
                }
            }
        });
        commandParser.parse(oldPreset);
        for (int oldPrefixOccurrence : oldPrefixOccurrences) {
            newPresetBuilder.setCharAt(oldPrefixOccurrence, newArgumentPrefix);
        }
        String newPreset = newPresetBuilder.toString();
        if (!oldPreset.equals(newPreset)) {
            preset.setPreset(newPreset);
        }
    }
}
Also used : Preset(net.robinfriedli.aiode.entities.Preset) ArgumentPrefixProperty(net.robinfriedli.aiode.discord.property.properties.ArgumentPrefixProperty) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) ArgumentBuildingMode(net.robinfriedli.aiode.command.parser.ArgumentBuildingMode) Aiode(net.robinfriedli.aiode.Aiode) CommandParser(net.robinfriedli.aiode.command.parser.CommandParser) CommandParseListener(net.robinfriedli.aiode.command.parser.CommandParseListener)

Example 2 with AbstractCommand

use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.

the class CommandListener method startCommandExecution.

private void startCommandExecution(String namePrefix, Message message, Guild guild, GuildContext guildContext, Session session, GuildMessageReceivedEvent event) {
    ThreadExecutionQueue queue = executionQueueManager.getForGuild(guild);
    String commandBody = message.getContentDisplay().substring(namePrefix.length()).trim();
    CommandContext commandContext = new CommandContext(event, guildContext, hibernateComponent.getSessionFactory(), spotifyApiBuilder, commandBody);
    ExecutionContext.Current.set(commandContext.fork());
    try {
        Optional<AbstractCommand> commandInstance = commandManager.instantiateCommandForContext(commandContext, session);
        commandInstance.ifPresent(command -> commandManager.runCommand(command, queue));
    } catch (UserException e) {
        EmbedBuilder embedBuilder = e.buildEmbed();
        messageService.sendTemporary(embedBuilder.build(), commandContext.getChannel());
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CommandContext(net.robinfriedli.aiode.command.CommandContext) ThreadExecutionQueue(net.robinfriedli.aiode.concurrent.ThreadExecutionQueue) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) UserException(net.robinfriedli.aiode.exceptions.UserException)

Example 3 with AbstractCommand

use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.

the class PresetCommand method doRun.

@Override
public void doRun() {
    Session session = getContext().getSession();
    if (argumentSet("delete")) {
        Preset preset = SearchEngine.searchPreset(session, getCommandInput());
        if (preset == null) {
            throw new InvalidCommandException(String.format("No preset found for '%s'", getCommandInput()));
        }
        invoke(() -> session.delete(preset));
    } else if (getCommandInput().isBlank()) {
        List<Preset> presets = getQueryBuilderFactory().find(Preset.class).build(session).getResultList();
        EmbedBuilder embedBuilder = new EmbedBuilder();
        if (presets.isEmpty()) {
            embedBuilder.setDescription("No presets saved");
        } else {
            EmbedTable table = new EmbedTable(embedBuilder);
            table.addColumn("Name", presets, Preset::getName);
            table.addColumn("Preset", presets, Preset::getPreset);
            table.build();
        }
        sendMessage(embedBuilder);
    } else {
        String presetString = getCommandInput();
        String name = getArgumentValue("as");
        Preset existingPreset = SearchEngine.searchPreset(getContext().getSession(), name);
        if (existingPreset != null) {
            throw new InvalidCommandException("Preset " + name + " already exists");
        }
        Preset preset = new Preset(name, presetString, getContext().getGuild(), getContext().getUser());
        String testString = presetString.contains("%s") ? name + " test" : name;
        AbstractCommand abstractCommand = preset.instantiateCommand(getManager(), getContext(), testString);
        CommandParser commandParser = new CommandParser(abstractCommand, ArgumentPrefixProperty.getForCurrentContext());
        commandParser.parse();
        abstractCommand.verify();
        invoke(() -> session.persist(preset));
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) Preset(net.robinfriedli.aiode.entities.Preset) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) List(java.util.List) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) Session(org.hibernate.Session) CommandParser(net.robinfriedli.aiode.command.parser.CommandParser)

Example 4 with AbstractCommand

use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.

the class ScriptCommandInterceptor method performChained.

@Override
public void performChained(Command command) {
    if (command instanceof AbstractCommand) {
        AbstractCommand abstractCommand = (AbstractCommand) command;
        if (abstractCommand.getArgumentController().argumentSet("skipInterceptors") || abstractCommand.getCommandContribution().isDisableScriptInterceptors()) {
            return;
        }
    } else {
        return;
    }
    CommandContext context = command.getContext();
    Session session = context.getSession();
    GuildSpecification specification = context.getGuildContext().getSpecification(session);
    boolean enableScripting = guildPropertyManager.getPropertyValueOptional("enableScripting", Boolean.class, specification).orElse(true);
    if (!enableScripting) {
        return;
    }
    String usageId = getUsageId();
    List<StoredScript> scriptInterceptors = queryBuilderFactory.find(StoredScript.class).where((cb, root, subQueryFactory) -> cb.and(cb.isTrue(root.get("active")), cb.equal(root.get("scriptUsage"), subQueryFactory.createUncorrelatedSubQuery(StoredScript.ScriptUsage.class, "pk").where((cb1, root1) -> cb1.equal(root1.get("uniqueId"), usageId)).build(session)))).build(session).getResultList();
    if (scriptInterceptors.isEmpty()) {
        return;
    }
    Aiode aiode = Aiode.get();
    SafeGroovyScriptRunner scriptRunner = new SafeGroovyScriptRunner(context, groovySandboxComponent, aiode.getGroovyVariableManager(), aiode.getSecurityManager(), false);
    AtomicReference<StoredScript> currentScriptReference = new AtomicReference<>();
    try {
        scriptRunner.runScripts(scriptInterceptors, currentScriptReference, 5, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
        Throwable error = e.getCause() != null ? e.getCause() : e;
        if (error instanceof CommandFailure) {
            messageService.sendError(String.format("Executing command %1$ss failed due to an error in %1$s '%2$s'", usageId, currentScriptReference.get().getIdentifier()), context.getChannel());
        } else {
            EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(error);
            StoredScript currentScript = currentScriptReference.get();
            embedBuilder.setTitle(String.format("Error occurred while executing custom command %s%s", usageId, currentScript.getIdentifier() != null ? ": " + currentScript.getIdentifier() : ""));
            messageService.sendTemporary(embedBuilder.build(), context.getChannel());
        }
    } catch (TimeoutException e) {
        StoredScript currentScript = currentScriptReference.get();
        messageService.sendError(String.format("Execution of script command %ss stopped because script%s has run into a timeout", usageId, currentScript != null ? String.format(" '%s'", currentScript.getIdentifier()) : ""), context.getChannel());
    }
}
Also used : CommandContext(net.robinfriedli.aiode.command.CommandContext) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) AtomicReference(java.util.concurrent.atomic.AtomicReference) Aiode(net.robinfriedli.aiode.Aiode) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SafeGroovyScriptRunner(net.robinfriedli.aiode.scripting.SafeGroovyScriptRunner) StoredScript(net.robinfriedli.aiode.entities.StoredScript) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) CommandFailure(net.robinfriedli.aiode.exceptions.CommandFailure) ExecutionException(java.util.concurrent.ExecutionException) Session(org.hibernate.Session) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with AbstractCommand

use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.

the class AnswerCommand method doRun.

@Override
public void doRun() {
    getContext().getGuildContext().getClientQuestionEventManager().getQuestion(getContext()).ifPresentOrElse(question -> {
        AbstractCommand sourceCommand = question.getSourceCommand();
        String commandInput = getCommandInput();
        Splitter commaSplitter = Splitter.on(",").trimResults().omitEmptyStrings();
        List<String> options = commaSplitter.splitToList(commandInput);
        Object option;
        if (options.size() == 1) {
            option = question.get(options.get(0));
        } else {
            Set<Object> chosenOptions = new LinkedHashSet<>();
            for (String o : options) {
                Object chosen = question.get(o);
                if (chosen instanceof Collection) {
                    chosenOptions.addAll((Collection<?>) chosen);
                } else {
                    chosenOptions.add(chosen);
                }
            }
            option = chosenOptions;
        }
        try {
            targetCommand = sourceCommand.fork(getContext());
            targetCommand.withUserResponse(option);
            question.destroy();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new CommandRuntimeException(e);
        }
    }, () -> {
        throw new InvalidCommandException("I don't remember asking you anything " + getContext().getUser().getName());
    });
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Splitter(com.google.common.base.Splitter) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) Collection(java.util.Collection) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException)

Aggregations

AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)9 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)4 CommandContext (net.robinfriedli.aiode.command.CommandContext)4 CommandParser (net.robinfriedli.aiode.command.parser.CommandParser)3 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)3 Session (org.hibernate.Session)3 Aiode (net.robinfriedli.aiode.Aiode)2 GuildSpecification (net.robinfriedli.aiode.entities.GuildSpecification)2 Preset (net.robinfriedli.aiode.entities.Preset)2 CommandFailure (net.robinfriedli.aiode.exceptions.CommandFailure)2 CommandRuntimeException (net.robinfriedli.aiode.exceptions.CommandRuntimeException)2 UserException (net.robinfriedli.aiode.exceptions.UserException)2 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)1 Splitter (com.google.common.base.Splitter)1 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)1 Collection (java.util.Collection)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1