Search in sources :

Example 1 with MessageService

use of net.robinfriedli.aiode.discord.MessageService in project aiode by robinfriedli.

the class PermissionExceptionHandler method handleException.

@Override
public Result handleException(Throwable uncaughtException, PermissionException exceptionToHandle) {
    if (Aiode.isInitialised()) {
        Aiode aiode = Aiode.get();
        ExecutionContext executionContext = ExecutionContext.Current.get();
        if (executionContext != null) {
            MessageService messageService = aiode.getMessageService();
            Permission permission = exceptionToHandle.getPermission();
            TextChannel channel = executionContext.getChannel();
            Guild guild = executionContext.getGuild();
            Aiode.LOGGER.warn(String.format("Bot is missing permission %s on guild %s", permission, guild));
            messageService.send("Bot is missing permission: " + permission.getName(), channel);
            return Result.HANDLED;
        }
    }
    return Result.UNHANDLED;
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) ExecutionContext(net.robinfriedli.aiode.concurrent.ExecutionContext) Permission(net.dv8tion.jda.api.Permission) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) MessageService(net.robinfriedli.aiode.discord.MessageService)

Example 2 with MessageService

use of net.robinfriedli.aiode.discord.MessageService in project aiode by robinfriedli.

the class ExceptionUtils method handleTrackLoadingException.

public static void handleTrackLoadingException(Throwable e, Logger logger, @Nullable ExecutionContext executionContext, @Nullable MessageChannel messageChannel) {
    if (e instanceof InterruptedException || ExceptionUtils.getRootCause(e) instanceof InterruptedException) {
        logger.warn("Suppressed InterruptedException " + e + " while loading tracks.");
        return;
    }
    String commandContextSuffix = executionContext != null ? " (started by command: " + executionContext.getId() + ")" : "";
    String msg = "Exception while loading tracks" + commandContextSuffix;
    if (Aiode.isShuttingDown()) {
        logger.warn(String.format("Suppressed error because it happened during shutdown: %s: %s", msg, e));
        return;
    }
    logger.error(msg, e);
    if (messageChannel != null) {
        EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(e);
        embedBuilder.setDescription("There has been an error while loading some tracks. Please try again.");
        if (executionContext != null) {
            embedBuilder.addField("CommandContext ID", executionContext.getId(), false);
        }
        MessageService messageService = Aiode.get().getMessageService();
        messageService.send(embedBuilder.build(), messageChannel);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageService(net.robinfriedli.aiode.discord.MessageService)

Example 3 with MessageService

use of net.robinfriedli.aiode.discord.MessageService in project aiode by robinfriedli.

the class QueueWidget method reset.

@Override
public void reset() {
    MessageService messageService = Aiode.get().getMessageService();
    Guild guild = getGuild().get();
    MessageChannel channel = getChannel().get();
    DiscordEntity.Message message = getMessage();
    EmbedBuilder embedBuilder = audioPlayback.getAudioQueue().buildMessageEmbed(audioPlayback, guild);
    MessageEmbed messageEmbed = messageService.buildEmbed(embedBuilder);
    messageService.executeMessageAction(channel, c -> c.editMessageById(message.getId(), messageEmbed), Permission.MESSAGE_EMBED_LINKS);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) Guild(net.dv8tion.jda.api.entities.Guild) MessageService(net.robinfriedli.aiode.discord.MessageService) DiscordEntity(net.robinfriedli.aiode.discord.DiscordEntity)

Example 4 with MessageService

use of net.robinfriedli.aiode.discord.MessageService in project aiode by robinfriedli.

the class ConnectCommand method awaitPrivateMessage.

private void awaitPrivateMessage(ClientSession clientSession, long userId, Guild guild, User user, int attemptNumber) {
    CompletableFuture<PrivateMessageReceivedEvent> futurePrivateMessage = getManager().getEventWaiter().awaitEvent(PrivateMessageReceivedEvent.class, event -> event.getAuthor().getIdLong() == userId).orTimeout(1, TimeUnit.MINUTES);
    CompletableFutures.handleWhenComplete(futurePrivateMessage, (event, error) -> {
        try {
            MessageService messageService = getMessageService();
            if (event != null) {
                String token = event.getMessage().getContentRaw();
                UUID sessionId;
                try {
                    sessionId = UUID.fromString(token);
                } catch (IllegalArgumentException e) {
                    String message = String.format("'%s' is not a valid token. ", token);
                    if (attemptNumber >= RETRY_COUNT) {
                        messageService.sendError(message + "Maximum retry count reached.", user);
                    } else {
                        messageService.sendError(message + String.format("Attempt %d / %d", attemptNumber, RETRY_COUNT), user);
                        awaitPrivateMessage(clientSession, userId, guild, user, attemptNumber + 1);
                    }
                    return;
                }
                QueryBuilderFactory queryBuilderFactory = getQueryBuilderFactory();
                MutexSyncMode<UUID> mutexSyncMode = new MutexSyncMode<>(sessionId, TOKEN_SYNC);
                HibernateInvoker.create().invokeConsumer(Mode.create().with(mutexSyncMode), session -> {
                    Optional<GeneratedToken> foundGeneratedToken = queryBuilderFactory.find(GeneratedToken.class).where((cb, root) -> cb.equal(root.get("token"), sessionId)).build(session).uniqueResultOptional();
                    if (foundGeneratedToken.isEmpty()) {
                        String message = "Token is invalid. Make sure it matches the token generated by your web client. Tokens may not be shared or reused. ";
                        if (attemptNumber >= RETRY_COUNT) {
                            messageService.sendError(message + "Maximum retry count reached.", user);
                        } else {
                            messageService.sendError(message + String.format("Attempt %d / %d", attemptNumber, RETRY_COUNT), user);
                            awaitPrivateMessage(clientSession, userId, guild, user, attemptNumber + 1);
                        }
                        return;
                    }
                    GeneratedToken generatedToken = foundGeneratedToken.get();
                    Long existingSessionCount = queryBuilderFactory.select(ClientSession.class, (from, cb) -> cb.count(from.get("pk")), Long.class).where((cb, root) -> cb.equal(root.get("sessionId"), sessionId)).build(session).uniqueResult();
                    if (existingSessionCount > 0) {
                        messageService.sendError("A session with this ID already exists. You are probably already signed in, try reloading your web client. If your client still can't sign in try generating a new token using the reload button and then try the connect command again.", user);
                        return;
                    }
                    clientSession.setLastRefresh(LocalDateTime.now());
                    clientSession.setSessionId(sessionId);
                    clientSession.setIpAddress(generatedToken.getIp());
                    session.persist(clientSession);
                    session.delete(generatedToken);
                    messageService.sendSuccess(String.format("Okay, a session connected to guild '%s' " + "has been prepared. You may return to the web client to complete the setup. The client should " + "connect automatically, else you can continue manually.", guild.getName()), user);
                });
            } else if (error != null) {
                if (error instanceof TimeoutException) {
                    messageService.sendError("Your connection attempt timed out", user);
                } else {
                    EmbedBuilder exceptionEmbed = ExceptionUtils.buildErrorEmbed(error);
                    exceptionEmbed.setTitle("Exception");
                    exceptionEmbed.setDescription("There has been an error awaiting private message to establish connection");
                    LoggerFactory.getLogger(getClass()).error("unexpected exception while awaiting private message", error);
                    sendMessage(exceptionEmbed.build());
                }
                setFailed(true);
            }
        } finally {
            USERS_WITH_PENDING_CONNECTION.remove(userId);
        }
    }, e -> {
        LoggerFactory.getLogger(getClass()).error("Unexpected error in whenComplete of event handler", e);
        EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(e).setTitle("Exception").setDescription("There has been an unexpected exception while trying to establish the connection");
        getMessageService().send(embedBuilder.build(), user);
    });
}
Also used : LocalDateTime(java.time.LocalDateTime) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) MutexSync(net.robinfriedli.exec.MutexSync) User(net.dv8tion.jda.api.entities.User) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) Guild(net.dv8tion.jda.api.entities.Guild) Map(java.util.Map) CompletableFutures(net.robinfriedli.aiode.concurrent.CompletableFutures) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) ClientSession(net.robinfriedli.aiode.entities.ClientSession) CommandManager(net.robinfriedli.aiode.command.CommandManager) Mode(net.robinfriedli.exec.Mode) MessageService(net.robinfriedli.aiode.discord.MessageService) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PrivateMessageReceivedEvent(net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent) UUID(java.util.UUID) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) HibernateInvoker(net.robinfriedli.aiode.function.HibernateInvoker) TimeUnit(java.util.concurrent.TimeUnit) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) CommandContext(net.robinfriedli.aiode.command.CommandContext) GeneratedToken(net.robinfriedli.aiode.entities.GeneratedToken) Optional(java.util.Optional) MutexSyncMode(net.robinfriedli.exec.modes.MutexSyncMode) ExceptionUtils(net.robinfriedli.aiode.exceptions.ExceptionUtils) PrivateMessageReceivedEvent(net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent) MessageService(net.robinfriedli.aiode.discord.MessageService) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MutexSyncMode(net.robinfriedli.exec.modes.MutexSyncMode) GeneratedToken(net.robinfriedli.aiode.entities.GeneratedToken) ClientSession(net.robinfriedli.aiode.entities.ClientSession) UUID(java.util.UUID) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with MessageService

use of net.robinfriedli.aiode.discord.MessageService in project aiode by robinfriedli.

the class AbstractPaginationWidget method prepareInitialMessage.

@Override
public CompletableFuture<Message> prepareInitialMessage() {
    EmbedBuilder embedBuilder = prepareEmbedBuilderForPage();
    MessageService messageService = Aiode.get().getMessageService();
    return messageService.send(embedBuilder, getChannel().get());
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageService(net.robinfriedli.aiode.discord.MessageService)

Aggregations

MessageService (net.robinfriedli.aiode.discord.MessageService)11 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 Guild (net.dv8tion.jda.api.entities.Guild)5 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)3 CompletableFuture (java.util.concurrent.CompletableFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)2 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)2 Aiode (net.robinfriedli.aiode.Aiode)2 CommandContext (net.robinfriedli.aiode.command.CommandContext)2 ExecutionContext (net.robinfriedli.aiode.concurrent.ExecutionContext)2 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)2 GroovyShell (groovy.lang.GroovyShell)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 LocalDateTime (java.time.LocalDateTime)1 Map (java.util.Map)1 Optional (java.util.Optional)1 UUID (java.util.UUID)1