Search in sources :

Example 1 with PrivateMessageReceivedEvent

use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project Emolga by TecToast.

the class NominateCommand method process.

@Override
public void process(PrivateMessageReceivedEvent e) {
    JSONObject nds = getEmolgaJSON().getJSONObject("drafts").getJSONObject("NDS");
    JSONObject nom = nds.getJSONObject("nominations");
    int currentDay = nom.getInt("currentDay");
    if (!nom.has(currentDay))
        nom.put(currentDay, new JSONObject());
    if (nom.getJSONObject(String.valueOf(currentDay)).has(e.getAuthor().getId())) {
        e.getChannel().sendMessage("Du hast für diesen Spieltag dein Team bereits nominiert!").queue();
        return;
    }
    JSONArray arr = nds.getJSONObject("picks").getJSONArray(e.getAuthor().getId());
    List<JSONObject> list = arr.toJSONList();
    list.sort(tiercomparator);
    List<String> b = list.stream().map(o -> o.getString("name")).collect(Collectors.toList());
    Nominate n = new Nominate(list);
    e.getChannel().sendMessageEmbeds(new EmbedBuilder().setTitle("Nominierungen").setColor(Color.CYAN).setDescription(n.generateDescription()).build()).setActionRows(addAndReturn(getActionRows(b, s -> Button.primary("nominate;" + s, s)), ActionRow.of(Button.success("nominate;FINISH", Emoji.fromUnicode("✅"))))).queue(m -> nominateButtons.put(m.getIdLong(), n));
}
Also used : JSONObject(org.jsolf.JSONObject) Arrays(java.util.Arrays) PrivateMessageReceivedEvent(net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Emoji(net.dv8tion.jda.api.entities.Emoji) PrivateCommand(de.tectoast.emolga.commands.PrivateCommand) Collectors(java.util.stream.Collectors) java.awt(java.awt) Command(de.tectoast.emolga.commands.Command) List(java.util.List) Nominate(de.tectoast.emolga.buttons.buttonsaves.Nominate) JSONArray(org.jsolf.JSONArray) Button(net.dv8tion.jda.api.interactions.components.Button) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) Comparator(java.util.Comparator) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) JSONObject(org.jsolf.JSONObject) JSONArray(org.jsolf.JSONArray) Nominate(de.tectoast.emolga.buttons.buttonsaves.Nominate)

Example 2 with PrivateMessageReceivedEvent

use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent 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 3 with PrivateMessageReceivedEvent

use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project ExciteBot by TheGameCommunity.

the class Commands method handleCommand.

public void handleCommand(PrivateMessageReceivedEvent e) {
    MessageContext<PrivateMessageReceivedEvent> context = new MessageContext<PrivateMessageReceivedEvent>(e);
    String message = e.getMessage().getContentRaw();
    try {
        DiscordUser sender = DiscordUser.getDiscordUser(ConsoleContext.INSTANCE, e.getAuthor().getIdLong());
        if (!sender.isBanned()) {
            if (!sender.isBanned()) {
                CommandAudit.addCommandAudit(context, message);
                this.dispatcher.execute(message, context);
            }
        }
    } catch (CommandSyntaxException ex) {
        context.sendMessage(ex.getMessage());
    } catch (Throwable t) {
        context.sendMessage(StacktraceUtil.getStackTrace(t));
        if (!context.isConsoleMessage()) {
            t.printStackTrace();
        }
        if (t instanceof Error) {
            throw t;
        }
    }
}
Also used : DiscordUser(com.gamebuster19901.excite.bot.user.DiscordUser) PrivateMessageReceivedEvent(net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException)

Example 4 with PrivateMessageReceivedEvent

use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project Robertify-Bot by bombies.

the class ReportsEvents method onPrivateMessageReceived.

@Override
public void onPrivateMessageReceived(@NotNull PrivateMessageReceivedEvent event) {
    if (!ReportsCommand.activeReports.contains(event.getAuthor().getIdLong()))
        return;
    final var user = event.getAuthor();
    final var channel = event.getChannel();
    try {
        final var response = event.getMessage().getContentRaw();
        if (response.chars().count() > 1024) {
            channel.sendMessageEmbeds(EmbedUtils.embedMessageWithTitle("Bug reports", "Your response cannot be more than 1024 characters!").build()).queue();
            return;
        }
        final var nextPage = getNextPage(user.getIdLong());
        var responseList = responses.get(user.getIdLong());
        responseList.add(response);
        responses.put(user.getIdLong(), responseList);
        event.getChannel().sendMessageEmbeds(nextPage.getEmbed()).queue();
    } catch (IllegalStateException e) {
        var responseList = responses.get(user.getIdLong());
        responseList.add(event.getMessage().getContentRaw());
        responses.put(user.getIdLong(), responseList);
        final var collectedResponses = responses.get(user.getIdLong());
        responses.remove(user.getIdLong());
        final var config = BotBDCache.getInstance();
        final var openedReportsChannel = Robertify.shardManager.getTextChannelById(config.getReportsID(BotBDCache.ReportsConfigField.CHANNEL));
        if (openedReportsChannel == null) {
            channel.sendMessageEmbeds(EmbedUtils.embedMessage("Could not send your report!\n" + "Please contact a developer in our [support server](https://discord.gg/VbjmtfJDvU).").build()).queue();
            return;
        }
        openedReportsChannel.sendMessageEmbeds(new EmbedBuilder().setTitle("Bug Report from " + user.getName()).setThumbnail(user.getEffectiveAvatarUrl()).addField("Reporter", user.getAsMention(), false).addField("Command/Feature Origin", collectedResponses.get(0), false).addField("Reproduction of Bug", collectedResponses.get(1), false).addField("Additional Comments", collectedResponses.get(2), false).setColor(new Color(255, 106, 0)).build()).queue(success -> {
            ReportsCommand.activeReports.remove(user.getIdLong());
            channel.sendMessageEmbeds(EmbedUtils.embedMessageWithTitle("Bug Reports", "You have submitted your bug report. \nThank you for answering all the questions!" + " Be on the lookout for a response from us!").build()).queue();
            currentQuestionForUser.remove(user.getIdLong());
        });
    }
}
Also used : EmbedUtils(me.duncte123.botcommons.messaging.EmbedUtils) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) PrivateMessageReceivedEvent(net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent) HashMap(java.util.HashMap) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CategoryDeleteEvent(net.dv8tion.jda.api.events.channel.category.CategoryDeleteEvent) Instant(java.time.Instant) ArrayList(java.util.ArrayList) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Robertify(main.main.Robertify) List(java.util.List) MessagePage(main.utils.pagination.MessagePage) BotBDCache(main.utils.database.mongodb.cache.BotBDCache) BotConstants(main.constants.BotConstants) NotNull(org.jetbrains.annotations.NotNull) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder)

Aggregations

PrivateMessageReceivedEvent (net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent)4 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 java.awt (java.awt)2 List (java.util.List)2 TimeUnit (java.util.concurrent.TimeUnit)2 DiscordUser (com.gamebuster19901.excite.bot.user.DiscordUser)1 CommandSyntaxException (com.mojang.brigadier.exceptions.CommandSyntaxException)1 Nominate (de.tectoast.emolga.buttons.buttonsaves.Nominate)1 Command (de.tectoast.emolga.commands.Command)1 PrivateCommand (de.tectoast.emolga.commands.PrivateCommand)1 Instant (java.time.Instant)1 LocalDateTime (java.time.LocalDateTime)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Optional (java.util.Optional)1 UUID (java.util.UUID)1 CompletableFuture (java.util.concurrent.CompletableFuture)1