Search in sources :

Example 1 with CommandRuntimeException

use of net.robinfriedli.aiode.exceptions.CommandRuntimeException 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)

Example 2 with CommandRuntimeException

use of net.robinfriedli.aiode.exceptions.CommandRuntimeException in project aiode by robinfriedli.

the class CommandExecutionInterceptor method performChained.

@Override
public void performChained(Command command) {
    boolean completedSuccessfully = false;
    boolean failedManually = false;
    String errorMessage = null;
    boolean unexpectedException = false;
    boolean aborted = false;
    try {
        try {
            if (command.isAborted()) {
                aborted = true;
                return;
            }
            command.doRun();
        } catch (Exception e) {
            if ((command.getTask() != null && command.getTask().isTerminated()) || Thread.currentThread().isInterrupted()) {
                logger.warn(String.format("Suppressed '%s' because command execution was interrupted.", e));
                return;
            }
            try {
                command.onFailure();
            } catch (Exception e1) {
                logger.error("Exception thrown in onFailure of command, logging this error and throwing the exception that caused the command to fail.", e1);
            }
            throw e;
        }
        if (!command.isFailed()) {
            command.onSuccess();
            completedSuccessfully = true;
        } else {
            command.onFailure();
            failedManually = true;
        }
    } catch (AmbiguousCommandException e) {
        if (command instanceof AbstractCommand) {
            ((AbstractCommand) command).askQuestion(e.getOptions(), e.getDisplayFunc());
        } else {
            throw e;
        }
    } catch (CommandFailure e) {
        throw e;
    } catch (NoLoginException e) {
        MessageChannel channel = command.getContext().getChannel();
        User user = command.getContext().getUser();
        String message = "User " + user.getName() + " is not logged in to Spotify";
        messageService.sendError(message, channel);
        errorMessage = message;
        throw new CommandFailure(e);
    } catch (UserException e) {
        messageService.sendTemporary(e.buildEmbed().build(), command.getContext().getChannel());
        errorMessage = e.getMessage();
        throw new CommandFailure(e);
    } catch (FriendlyException e) {
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setTitle("Could not load track");
        if (e.getMessage() != null) {
            embedBuilder.setDescription("Message returned by source: " + e.getMessage());
        }
        embedBuilder.setColor(Color.RED);
        messageService.sendTemporary(embedBuilder.build(), command.getContext().getChannel());
        throw new CommandFailure(e);
    } catch (UnauthorizedException e) {
        String message = "Unauthorized: " + e.getMessage();
        messageService.sendException(message, command.getContext().getChannel());
        logger.warn("Unauthorized Spotify API operation", e);
        errorMessage = message;
        unexpectedException = true;
        throw new CommandFailure(e);
    } catch (TooManyRequestsException e) {
        String message = "Executing too many Spotify requests at the moment, please try again later.";
        messageService.sendException(message, command.getContext().getChannel());
        logger.warn("Executing too many Spotify requests", e);
        errorMessage = message;
        unexpectedException = true;
        throw new CommandFailure(e);
    } catch (GoogleJsonResponseException e) {
        String message = e.getDetails().getMessage();
        StringBuilder responseBuilder = new StringBuilder("Error occurred when requesting data from YouTube.");
        if (!Strings.isNullOrEmpty(message)) {
            responseBuilder.append(" Error response: ").append(message);
        }
        messageService.sendException(responseBuilder.toString(), command.getContext().getChannel());
        logger.error("Exception during YouTube request", e);
        errorMessage = message;
        unexpectedException = true;
        throw new CommandFailure(e);
    } catch (ErrorResponseException e) {
        messageService.sendException(String.format("Discord returned error (code: %d): %s", e.getErrorCode(), e.getMeaning()), command.getContext().getChannel());
        logger.error("Blocking Discord request returned error", e);
        throw new CommandFailure(e);
    } catch (CommandRuntimeException e) {
        if (e.getCause() != null) {
            errorMessage = e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage();
        } else {
            errorMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
        }
        unexpectedException = true;
        throw e;
    } catch (Exception e) {
        errorMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
        unexpectedException = true;
        throw new CommandRuntimeException(e);
    } finally {
        postCommand(command, completedSuccessfully, failedManually, errorMessage, unexpectedException, aborted);
    }
}
Also used : AmbiguousCommandException(net.robinfriedli.aiode.exceptions.AmbiguousCommandException) User(net.dv8tion.jda.api.entities.User) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) UnauthorizedException(se.michaelthelin.spotify.exceptions.detailed.UnauthorizedException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) UserException(net.robinfriedli.aiode.exceptions.UserException) NoLoginException(net.robinfriedli.aiode.exceptions.NoLoginException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) AmbiguousCommandException(net.robinfriedli.aiode.exceptions.AmbiguousCommandException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) TooManyRequestsException(se.michaelthelin.spotify.exceptions.detailed.TooManyRequestsException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) TooManyRequestsException(se.michaelthelin.spotify.exceptions.detailed.TooManyRequestsException) NoLoginException(net.robinfriedli.aiode.exceptions.NoLoginException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) UnauthorizedException(se.michaelthelin.spotify.exceptions.detailed.UnauthorizedException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) CommandFailure(net.robinfriedli.aiode.exceptions.CommandFailure) UserException(net.robinfriedli.aiode.exceptions.UserException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException)

Example 3 with CommandRuntimeException

use of net.robinfriedli.aiode.exceptions.CommandRuntimeException in project aiode by robinfriedli.

the class Invoker method invoke.

/**
 * Invoke a callable in a hibernate transaction. There is one Invoker per guild and this method runs synchronised,
 * making sure the same guild can not run this method concurrently. This is to counteract the
 * spamming of a command that uses this method, e.g. spamming the add command concurrently could evade the playlist
 * size limit.
 *
 * @param session  the target hibernate session, individual for each command execution
 * @param callable tho callable to run
 * @param <E>      the return type
 * @return the value the callable returns, often void
 */
public synchronized <E> E invoke(Session session, Callable<E> callable) {
    boolean isNested = false;
    if (session.getTransaction() == null || !session.getTransaction().isActive()) {
        session.beginTransaction();
    } else {
        isNested = true;
    }
    if (isNested) {
        try {
            return callable.call();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new CommandRuntimeException(e);
        }
    }
    E retVal;
    try {
        retVal = callable.call();
        session.getTransaction().commit();
    } catch (UserException e) {
        session.getTransaction().rollback();
        throw e;
    } catch (Exception e) {
        session.getTransaction().rollback();
        throw new RuntimeException("Exception in invoked callable. Transaction rolled back.", e);
    }
    return retVal;
}
Also used : CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) UserException(net.robinfriedli.aiode.exceptions.UserException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) UserException(net.robinfriedli.aiode.exceptions.UserException) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException)

Aggregations

CommandRuntimeException (net.robinfriedli.aiode.exceptions.CommandRuntimeException)3 AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)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 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)1 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)1 User (net.dv8tion.jda.api.entities.User)1 ErrorResponseException (net.dv8tion.jda.api.exceptions.ErrorResponseException)1 AmbiguousCommandException (net.robinfriedli.aiode.exceptions.AmbiguousCommandException)1 CommandFailure (net.robinfriedli.aiode.exceptions.CommandFailure)1 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)1 NoLoginException (net.robinfriedli.aiode.exceptions.NoLoginException)1 TooManyRequestsException (se.michaelthelin.spotify.exceptions.detailed.TooManyRequestsException)1 UnauthorizedException (se.michaelthelin.spotify.exceptions.detailed.UnauthorizedException)1