Search in sources :

Example 1 with Range

use of com.sx4.bot.entities.argument.Range in project Sx4 by sx4-discord-bot.

the class GuessTheNumberCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member, @Option(value = "min", description = "Choose the minimum number of the range") @Limit(min = 1) @DefaultNumber(1) int min, @Option(value = "max", description = "Choose the maximum number of the range") @Limit(min = 2) @DefaultNumber(50) int max) {
    User opponent = member.getUser();
    if (opponent.isBot()) {
        event.replyFailure("You cannot play against bots").queue();
        return;
    }
    if (opponent.getIdLong() == event.getAuthor().getIdLong()) {
        event.replyFailure("You cannot play against yourself").queue();
        return;
    }
    List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
    event.reply(opponent.getAsMention() + ", do you want to play guess the number with **" + event.getAuthor().getName() + "**?").allowedMentions(EnumSet.of(Message.MentionType.USER)).setActionRow(buttons).submit().thenCompose(message -> {
        return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, opponent)).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, opponent)).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
    }).whenComplete((confirmEvent, confirmException) -> {
        Throwable confirmCause = confirmException instanceof CompletionException ? confirmException.getCause() : confirmException;
        if (confirmCause instanceof CancelException) {
            GenericEvent cancelEvent = ((CancelException) confirmCause).getEvent();
            if (cancelEvent != null) {
                ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
            }
            return;
        } else if (confirmCause instanceof TimeoutException) {
            event.reply("Timed out :stopwatch:").queue();
            return;
        }
        confirmEvent.deferEdit().queue();
        CompletableFuture<MessageReceivedEvent> authorFuture = event.getAuthor().openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
            return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
                int number;
                try {
                    number = Integer.parseInt(e.getMessage().getContentRaw());
                } catch (NumberFormatException exception) {
                    return false;
                }
                return number >= min && number <= max;
            }).start();
        });
        CompletableFuture<MessageReceivedEvent> opponentFuture = opponent.openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
            return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(opponent.getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
                int number;
                try {
                    number = Integer.parseInt(e.getMessage().getContentRaw());
                } catch (NumberFormatException exception) {
                    return false;
                }
                return number >= min && number <= max;
            }).start();
        });
        authorFuture.whenComplete((messageEvent, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                opponentFuture.cancel(true);
                if (((CancelException) cause).getType() == CancelType.USER) {
                    event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
                }
                event.replyFailure("**" + event.getAuthor().getAsTag() + "** cancelled their response").queue();
                return;
            } else if (cause instanceof TimeoutException) {
                opponentFuture.cancel(true);
                event.replyFailure("**" + event.getAuthor().getAsTag() + "** took too long to respond").queue();
                return;
            } else if (cause instanceof ErrorResponseException) {
                opponentFuture.cancel(true);
                event.replyFailure("I could not send a message to **" + event.getAuthor().getAsTag() + "**").queue();
                return;
            }
            messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
        });
        opponentFuture.whenComplete((messageEvent, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                authorFuture.cancel(true);
                if (((CancelException) cause).getType() == CancelType.USER) {
                    opponent.openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
                }
                event.replyFailure("**" + opponent.getAsTag() + "** cancelled their response").queue();
                return;
            } else if (cause instanceof TimeoutException) {
                authorFuture.cancel(true);
                event.replyFailure("**" + opponent.getAsTag() + "** took too long to respond").queue();
                return;
            } else if (cause instanceof ErrorResponseException) {
                authorFuture.cancel(true);
                event.replyFailure("I could not send a message to **" + opponent.getAsTag() + "**").queue();
                return;
            }
            messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
        });
        CompletableFuture.allOf(authorFuture, opponentFuture).whenComplete((result, exception) -> {
            if (exception != null) {
                return;
            }
            MessageReceivedEvent authorEvent = authorFuture.join(), opponentEvent = opponentFuture.join();
            ObjectId gameId = ObjectId.get();
            int authorNumber = Integer.parseInt(authorEvent.getMessage().getContentRaw());
            int opponentNumber = Integer.parseInt(opponentEvent.getMessage().getContentRaw());
            int randomNumber = event.getRandom().nextInt(max) + 1;
            Document authorData = new Document("userId", event.getAuthor().getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
            Document opponentData = new Document("userId", opponent.getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
            int authorDifference = Math.abs(authorNumber - randomNumber), opponentDifference = Math.abs(opponentNumber - randomNumber);
            StringBuilder content = new StringBuilder("The random number was **" + randomNumber + "**\n" + opponent.getName() + "'s number was **" + opponentNumber + "**\n" + event.getAuthor().getName() + "'s number was **" + authorNumber + "**\n\n");
            if (authorDifference == opponentDifference) {
                content.append("You both guessed the same number, It was a draw!");
                authorData.append("state", GameState.DRAW.getId());
                opponentData.append("state", GameState.DRAW.getId());
            } else if (authorDifference > opponentDifference) {
                content.append(opponent.getName()).append(" won! They were the closest to ").append(randomNumber);
                authorData.append("state", GameState.LOSS.getId());
                opponentData.append("state", GameState.WIN.getId());
            } else {
                content.append(event.getAuthor().getName()).append(" won! They were the closest to ").append(randomNumber);
                authorData.append("state", GameState.WIN.getId());
                opponentData.append("state", GameState.LOSS.getId());
            }
            event.reply(content.toString()).queue();
            event.getMongo().insertManyGames(List.of(authorData, opponentData)).whenComplete(MongoDatabase.exceptionally());
        });
    });
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Option(com.jockie.bot.core.option.Option) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) GameState(com.sx4.bot.entities.games.GameState) EnumSet(java.util.EnumSet) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) CancelType(com.sx4.bot.waiter.Waiter.CancelType) Message(net.dv8tion.jda.api.entities.Message) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) GameType(com.sx4.bot.entities.games.GameType) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) ObjectId(org.bson.types.ObjectId) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException)

Example 2 with Range

use of com.sx4.bot.entities.argument.Range in project Sx4 by sx4-discord-bot.

the class ModLogCommand method case_.

@Command(value = "case", description = "Edit the reason of a mod log case")
@CommandId(68)
@Examples({ "modlog case 5e45ce6d3688b30ee75201ae Spamming", "modlog case 5fc24ea34854845b7c74e7f4-5fc24ea64854845b7c74e7f6 template:tos", "modlog case 5e45ce6d3688b30ee75201ae,5e45ce6d3688b30ee75201ab t:tos and Spamming" })
public void case_(Sx4CommandEvent event, @Argument(value = "id(s)") Range<ObjectId> range, @Argument(value = "reason", endless = true) Reason reason) {
    List<Bson> or = new ArrayList<>();
    for (Pair<ObjectId, ObjectId> r : range.getRanges()) {
        or.add(Operators.and(Operators.gte(Operators.objectIdToEpochSecond("$_id"), r.getLeft().getTimestamp()), Operators.lte(Operators.objectIdToEpochSecond("$_id"), r.getRight().getTimestamp())));
    }
    for (ObjectId r : range.getObjects()) {
        or.add(Operators.eq("$_id", r));
    }
    long authorId = event.getAuthor().getIdLong();
    List<Bson> update = List.of(Operators.set("reason", Operators.cond(Operators.and(Operators.or(Operators.eq("$moderatorId", authorId), event.hasPermission(event.getMember(), Permission.ADMINISTRATOR)), Operators.or(or)), reason.getParsed(), "$reason")));
    event.getMongo().updateManyModLogs(Filters.eq("guildId", event.getGuild().getIdLong()), update).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        long modified = result.getModifiedCount();
        if (modified == 0) {
            event.replyFailure("You were unable to update any of those mod logs or you provided an invalid range").queue();
            return;
        }
        event.replyFormat("Updated **%d** case%s %s", modified, modified == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)2 ObjectId (org.bson.types.ObjectId)2 Argument (com.jockie.bot.core.argument.Argument)1 Command (com.jockie.bot.core.command.Command)1 Option (com.jockie.bot.core.option.Option)1 DefaultNumber (com.sx4.bot.annotations.argument.DefaultNumber)1 Limit (com.sx4.bot.annotations.argument.Limit)1 CommandId (com.sx4.bot.annotations.command.CommandId)1 Examples (com.sx4.bot.annotations.command.Examples)1 ModuleCategory (com.sx4.bot.category.ModuleCategory)1 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)1 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)1 GameState (com.sx4.bot.entities.games.GameState)1 GameType (com.sx4.bot.entities.games.GameType)1 ButtonUtility (com.sx4.bot.utility.ButtonUtility)1 Waiter (com.sx4.bot.waiter.Waiter)1 CancelType (com.sx4.bot.waiter.Waiter.CancelType)1 CancelException (com.sx4.bot.waiter.exception.CancelException)1 TimeoutException (com.sx4.bot.waiter.exception.TimeoutException)1 ArrayList (java.util.ArrayList)1