Search in sources :

Example 16 with CommandContext

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

the class CommandMonitoringInterceptor method performChained.

@Override
public void performChained(Command command) {
    CommandContext context = command.getContext();
    CommandExecutionTask task = command.getTask();
    if (task == null) {
        return;
    }
    Future<?> monitoring = DaemonThreadPool.submit((LoggingRunnable) () -> {
        Thread thread = Thread.currentThread();
        String oldName = thread.getName();
        thread.setName("command-monitoring-" + context);
        CompletableFuture<Message> stillLoadingMessage = null;
        CompletableFuture<Message> warningMessage = null;
        try {
            task.await(MESSAGE_AFTER_THRESHOLD);
            if (!task.isDone()) {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.setDescription("Still loading...");
                stillLoadingMessage = messageService.send(embedBuilder, context.getChannel());
                task.await(LOGGER_WARNING_AFTER_THRESHOLD);
                if (!task.isDone()) {
                    EmbedBuilder warningEmbed = new EmbedBuilder();
                    warningEmbed.setColor(Color.RED);
                    warningEmbed.setTitle("Command timeout");
                    warningEmbed.setDescription(String.format("Your command '%s' is taking very long to execute. " + "If the command is not responding, consider interrupting it using the abort command.", command.display()));
                    warningMessage = messageService.send(warningEmbed.build(), context.getChannel());
                    logger.warn(String.format("Command [%s] on guild %s has exceeded the warn limit for execution duration of %d millis.", command.display(), context.getGuild(), MESSAGE_AFTER_THRESHOLD + LOGGER_WARNING_AFTER_THRESHOLD));
                }
                task.await();
                deleteMessages(stillLoadingMessage, warningMessage);
            }
        } catch (InterruptedException e) {
            // CommandExecutionInterceptor interrupts monitoring in post command
            deleteMessages(stillLoadingMessage, warningMessage);
        } finally {
            thread.setName(oldName);
        }
    });
    context.registerMonitoring(monitoring);
}
Also used : CommandExecutionTask(net.robinfriedli.aiode.concurrent.CommandExecutionTask) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CommandContext(net.robinfriedli.aiode.command.CommandContext)

Example 17 with CommandContext

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

the class HistoryInterceptor method performChained.

@Override
public void performChained(Command command) {
    CommandContext context = command.getContext();
    CommandHistory history = new CommandHistory();
    long currentTimeMillis = System.currentTimeMillis();
    history.setStartMillis(currentTimeMillis);
    history.setTimestamp(LocalDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis), ZoneId.systemDefault()));
    history.setCommandContextId(command.getContext().getId());
    history.setCommandIdentifier(command.getIdentifier());
    history.setWidget(command instanceof AbstractWidgetAction);
    history.setCommandBody(command instanceof AbstractCommand ? ((AbstractCommand) command).getCommandInput() : command.getCommandBody());
    history.setInput(command instanceof AbstractCommand ? context.getMessage().getContentDisplay() : command.getCommandBody());
    history.setGuild(context.getGuild().getName());
    history.setGuildId(context.getGuild().getId());
    history.setUser(context.getUser().getName());
    history.setUserId(context.getUser().getId());
    context.setCommandHistory(history);
}
Also used : CommandHistory(net.robinfriedli.aiode.entities.CommandHistory) CommandContext(net.robinfriedli.aiode.command.CommandContext) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) AbstractWidgetAction(net.robinfriedli.aiode.command.widget.AbstractWidgetAction)

Example 18 with CommandContext

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

the class SecurityInterceptor method performChained.

@Override
public void performChained(Command command) {
    try {
        CommandContext context = command.getContext();
        if (securityManager.isAdmin(context.getUser())) {
            return;
        }
        if (command instanceof AbstractCommand && ((AbstractCommand) command).getCategory() == AbstractCommand.Category.SCRIPTING) {
            if (!springPropertiesConfig.requireApplicationProperty(Boolean.class, "aiode.preferences.enable_scripting")) {
                throw new InvalidCommandException("The bot hoster disabled scripting. None of the commands in the scripting category may be used.");
            }
            Session session = context.getSession();
            GuildSpecification specification = context.getGuildContext().getSpecification(session);
            boolean enableScripting = guildPropertyManager.getPropertyValueOptional("enableScripting", Boolean.class, specification).orElse(true);
            if (!enableScripting) {
                throw new InvalidCommandException("Scripting has been disabled for this guild. None of the commands in the scripting category may be used. " + "Toggle the enable scripting property using the property command to enable / disable scripting.");
            }
        }
        PermissionTarget permissionTarget = command.getPermissionTarget();
        Member member = context.getMember();
        securityManager.ensurePermission(permissionTarget, member);
        if (command instanceof AbstractCommand) {
            AbstractCommand textCommand = (AbstractCommand) command;
            Collection<ArgumentController.ArgumentUsage> argumentUsages = textCommand.getArgumentController().getUsedArguments().values();
            for (ArgumentController.ArgumentUsage argumentUsage : argumentUsages) {
                PermissionTarget argumentPermissionTarget = argumentUsage.getArgument().getPermissionTarget();
                if (argumentPermissionTarget != null) {
                    securityManager.ensurePermission(argumentPermissionTarget, member);
                }
            }
        }
    } catch (ForbiddenCommandException | InvalidCommandException e) {
        throw e;
    } catch (Exception e) {
        throw new SecurityException("Failed to verify command security due to an unexpected exception", e);
    }
}
Also used : CommandContext(net.robinfriedli.aiode.command.CommandContext) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) ForbiddenCommandException(net.robinfriedli.aiode.exceptions.ForbiddenCommandException) PermissionTarget(net.robinfriedli.aiode.command.PermissionTarget) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) ArgumentController(net.robinfriedli.aiode.command.argument.ArgumentController) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) ForbiddenCommandException(net.robinfriedli.aiode.exceptions.ForbiddenCommandException) Member(net.dv8tion.jda.api.entities.Member) Session(org.hibernate.Session)

Example 19 with CommandContext

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

the class WidgetListener method handleWidgetExecution.

private void handleWidgetExecution(GuildMessageReactionAddEvent event, AbstractWidget activeWidget) {
    TextChannel channel = event.getChannel();
    Guild guild = event.getGuild();
    Aiode aiode = Aiode.get();
    SpotifyApi.Builder spotifyApiBuilder = aiode.getSpotifyApiBuilder();
    GuildContext guildContext = aiode.getGuildManager().getContextForGuild(guild);
    String emojiUnicode = event.getReaction().getReactionEmote().getName();
    try {
        Message message = activeWidget.getMessage().retrieve();
        if (message == null) {
            throw new IllegalStateException("Message of widget could not be retrieved.");
        }
        CommandContext commandContext = new CommandContext(event, guildContext, message, hibernateComponent.getSessionFactory(), spotifyApiBuilder, emojiUnicode);
        activeWidget.handleReaction(event, commandContext);
    } catch (UserException e) {
        messageService.sendError(e.getMessage(), channel);
    } catch (InsufficientPermissionException e) {
        Permission permission = e.getPermission();
        messageService.send("Bot is missing permission: " + permission.getName(), channel);
        logger.warn(String.format("Missing permission %s on guild %s", permission, guild));
    } catch (Exception e) {
        logger.error("Exception while handling WidgetAction execution.", e);
    }
}
Also used : Message(net.dv8tion.jda.api.entities.Message) CommandContext(net.robinfriedli.aiode.command.CommandContext) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) UserException(net.robinfriedli.aiode.exceptions.UserException) TextChannel(net.dv8tion.jda.api.entities.TextChannel) GuildContext(net.robinfriedli.aiode.discord.GuildContext) SpotifyApi(se.michaelthelin.spotify.SpotifyApi) Permission(net.dv8tion.jda.api.Permission) UserException(net.robinfriedli.aiode.exceptions.UserException)

Example 20 with CommandContext

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

the class EvalCommand method doRun.

@Override
public void doRun() {
    CommandContext context = getContext();
    Aiode aiode = Aiode.get();
    SecurityManager securityManager = aiode.getSecurityManager();
    GroovySandboxComponent groovySandboxComponent = aiode.getGroovySandboxComponent();
    GroovyVariableManager groovyVariableManager = aiode.getGroovyVariableManager();
    SafeGroovyScriptRunner groovyScriptRunner = new SafeGroovyScriptRunner(context, groovySandboxComponent, groovyVariableManager, securityManager, argumentSet("privileged"));
    groovyScriptRunner.runAndSendResult(getCommandInput(), 10, TimeUnit.SECONDS);
}
Also used : CommandContext(net.robinfriedli.aiode.command.CommandContext) SecurityManager(net.robinfriedli.aiode.command.SecurityManager) SafeGroovyScriptRunner(net.robinfriedli.aiode.scripting.SafeGroovyScriptRunner) Aiode(net.robinfriedli.aiode.Aiode) GroovyVariableManager(net.robinfriedli.aiode.scripting.GroovyVariableManager) GroovySandboxComponent(net.robinfriedli.aiode.boot.configurations.GroovySandboxComponent)

Aggregations

CommandContext (net.robinfriedli.aiode.command.CommandContext)21 Session (org.hibernate.Session)9 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)8 Guild (net.dv8tion.jda.api.entities.Guild)7 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)6 Aiode (net.robinfriedli.aiode.Aiode)6 SecurityManager (net.robinfriedli.aiode.command.SecurityManager)6 AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)5 PermissionTarget (net.robinfriedli.aiode.command.PermissionTarget)5 CustomPermissionTarget (net.robinfriedli.aiode.entities.CustomPermissionTarget)5 StoredScript (net.robinfriedli.aiode.entities.StoredScript)3 List (java.util.List)2 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)2 Role (net.dv8tion.jda.api.entities.Role)2 User (net.dv8tion.jda.api.entities.User)2 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)2 AudioManager (net.robinfriedli.aiode.audio.AudioManager)2 ThreadExecutionQueue (net.robinfriedli.aiode.concurrent.ThreadExecutionQueue)2 AccessConfiguration (net.robinfriedli.aiode.entities.AccessConfiguration)2 GrantedRole (net.robinfriedli.aiode.entities.GrantedRole)2