Search in sources :

Example 6 with MessageArgument

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

the class GiveawayCommand method delete.

@Command(value = "delete", aliases = { "remove" }, description = "Deletes a giveaway")
@CommandId(51)
@Examples({ "giveaway delete 727224132202397726", "giveaway delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "message id | all") @AlternativeOptions("all") Alternative<MessageArgument> option) {
    if (option.isAlternative()) {
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** giveaways in this server?").setActionRow(buttons).submit().thenCompose(message -> {
            return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
        }).whenComplete((e, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                GenericEvent cancelEvent = ((CancelException) cause).getEvent();
                if (cancelEvent != null) {
                    ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
                }
                return;
            } else if (cause instanceof TimeoutException) {
                event.reply("Timed out :stopwatch:").queue();
                return;
            } else if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            event.getMongo().deleteManyGiveaways(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("There are no giveaways in this server " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All giveaways in this server have been deleted " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        long messageId = option.getValue().getMessageId();
        event.getMongo().deleteGiveawayById(messageId).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getDeletedCount() == 0) {
                event.replyFailure("There was no giveaway with that id").queue();
                return;
            }
            event.replySuccess("That giveaway has been deleted").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.sx4.bot.utility(com.sx4.bot.utility) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Sx4Command(com.sx4.bot.core.Sx4Command) ReturnDocument(com.mongodb.client.model.ReturnDocument) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) Clock(java.time.Clock) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Collections(java.util.Collections) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)

Example 7 with MessageArgument

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

the class GiveawayCommand method restart.

@Command(value = "restart", description = "Restarts a giveaway")
@CommandId(48)
@Examples({ "giveaway restart 727224132202397726" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void restart(Sx4CommandEvent event, @Argument(value = "message id") MessageArgument messageArgument, @Argument(value = "duration", endless = true, nullDefault = true) Duration duration) {
    long timeNow = Clock.systemUTC().instant().getEpochSecond();
    List<Bson> update = List.of(Operators.set("endAt", Operators.cond(Operators.exists("$winners"), duration == null ? Operators.add(timeNow, "$duration") : duration.toSeconds() + timeNow, "$endAt")), Operators.set("duration", Operators.cond(Operators.exists("$winners"), duration == null ? "$duration" : duration.toSeconds(), "$duration")), Operators.unset("winners"));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.exclude("winners"));
    event.getMongo().findAndUpdateGiveawayById(messageArgument.getMessageId(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("There is no giveaway with that id").queue();
            return;
        }
        if (data.getLong("endAt") - timeNow > 0) {
            event.replyFailure("That giveaway has not ended yet").queue();
            return;
        }
        long seconds = duration == null ? data.getLong("duration") : duration.toSeconds();
        TextChannel channel = event.getGuild().getTextChannelById(data.getLong("channelId"));
        if (channel == null) {
            event.replyFailure("That giveaway no longer exists").queue();
            return;
        }
        channel.editMessageEmbedsById(data.getLong("messageId"), this.getEmbed(data.getInteger("winnersAmount"), seconds, data.getString("item"))).queue();
        event.getBot().getGiveawayManager().putGiveaway(data, seconds);
        event.replySuccess("That giveaway has been restarted").queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)

Example 8 with MessageArgument

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

the class TranslateCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "to") Locale to, @Argument(value = "query | message id", endless = true, acceptEmpty = true) Or<MessageArgument, String> option, @Option(value = "from", description = "Choose what language to translate from") Locale from) {
    String toTag = to.getLanguage(), fromTag = from == null ? "auto" : from.getLanguage();
    this.getQuery(option).whenComplete((query, exception) -> {
        if (query.length() > 1000) {
            event.replyFailure("Query length cannot be any more than **1000** characters").queue();
            return;
        }
        FormBody requestBody = new FormBody.Builder().addEncoded("f.req", "%5B%5B%5B%22MkEWBc%22%2C%22%5B%5B%5C%22" + URLEncoder.encode(query, StandardCharsets.UTF_8).replace("%0A", "\n") + "%5C%22%2C%5C%22" + fromTag + "%5C%22%2C%5C%22" + toTag + "%5C%22%2Ctrue%5D%2C%5Bnull%5D%5D%22%2Cnull%2C%22generic%22%5D%5D%5D").build();
        Request request = new Request.Builder().url("https://translate.google.com/_/TranslateWebserverUi/data/batchexecute").post(requestBody).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> event.reply(this.getEmbed(response.body().string(), query, from, to)).queue());
    });
}
Also used : TextNode(org.jsoup.nodes.TextNode) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) CompletableFuture(java.util.concurrent.CompletableFuture) FormBody(okhttp3.FormBody) JSONObject(org.json.JSONObject) Locale(java.util.Locale) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Element(org.jsoup.nodes.Element) Option(com.jockie.bot.core.option.Option) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) SearchUtility(com.sx4.bot.utility.SearchUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Document(org.jsoup.nodes.Document) StringJoiner(java.util.StringJoiner) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) JSONArray(org.json.JSONArray) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) FormBody(okhttp3.FormBody) Request(okhttp3.Request)

Example 9 with MessageArgument

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

the class SuggestionCommand method set.

@Command(value = "set", description = "Sets a suggestion to a specified state")
@CommandId(86)
@Examples({ "suggestion set 5e45ce6d3688b30ee75201ae pending Need some time to think about this", "suggestion set 5e45ce6d3688b30ee75201ae accepted I think this is a great idea", "suggestion 5e45ce6d3688b30ee75201ae set denied Not possible" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "id | message", acceptEmpty = true) Or<ObjectId, MessageArgument> argument, @Argument(value = "state") String stateName, @Argument(value = "reason", endless = true, nullDefault = true) String reason) {
    Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("suggestion.states", "suggestion.webhook")).get("suggestion", MongoDatabase.EMPTY_DOCUMENT);
    List<Document> states = data.getList("states", Document.class, SuggestionState.DEFAULT_STATES);
    Document state = states.stream().filter(stateData -> stateData.getString("dataName").equalsIgnoreCase(stateName)).findFirst().orElse(null);
    if (state == null) {
        event.replyFailure("You do not have a suggestion state with that name").queue();
        return;
    }
    String stateData = state.getString("dataName");
    Bson update = Updates.combine(reason == null ? Updates.unset("reason") : Updates.set("reason", reason), Updates.set("state", stateData), Updates.set("moderatorId", event.getAuthor().getIdLong()));
    Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("_id", argument.getFirst()) : Filters.eq("messageId", argument.getSecond().getMessageId()), Filters.eq("guildId", event.getGuild().getIdLong()));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("channelId", "authorId", "reason", "state", "suggestion", "messageId", "image"));
    event.getMongo().findAndUpdateSuggestion(filter, update, options).whenComplete((suggestionData, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (suggestionData == null) {
            event.replyFailure("There is no suggestion with that id").queue();
            return;
        }
        String reasonData = suggestionData.getString("reason");
        boolean reasonMatch = reasonData == null && reason == null || (reasonData != null && reasonData.equals(reason));
        if (suggestionData.getString("state").equals(stateData) && reasonMatch) {
            event.replyFailure("That suggestion is already in that state and has the same reason").queue();
            return;
        }
        TextChannel channel = event.getGuild().getTextChannelById(suggestionData.getLong("channelId"));
        if (channel == null) {
            event.replyFailure("The channel for that suggestion no longer exists").queue();
            return;
        }
        User author = event.getShardManager().getUserById(suggestionData.getLong("authorId"));
        long messageId = suggestionData.getLong("messageId");
        if (author != null) {
            author.openPrivateChannel().flatMap(privateChannel -> privateChannel.sendMessage("Your suggestion has been updated by a moderator, click the message link to view it\nhttps://discord.com/channels/" + event.getGuild().getIdLong() + "/" + channel.getIdLong() + "/" + messageId)).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
        }
        WebhookEmbed embed = Suggestion.getWebhookEmbed(suggestionData.getObjectId("_id"), event.getAuthor(), author, suggestionData.getString("suggestion"), suggestionData.getString("image"), reason, new SuggestionState(state));
        event.getBot().getSuggestionManager().editSuggestion(messageId, channel.getIdLong(), data.get("webhook", MongoDatabase.EMPTY_DOCUMENT), embed);
        event.replySuccess("That suggestion has been set to the `" + stateData + "` state").queue();
    });
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Suggestion(com.sx4.bot.entities.management.Suggestion) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) ButtonUtility(com.sx4.bot.utility.ButtonUtility) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Operators(com.sx4.bot.database.mongo.model.Operators) 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) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Collections(java.util.Collections) TextChannel(net.dv8tion.jda.api.entities.TextChannel) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) User(net.dv8tion.jda.api.entities.User) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)9 Command (com.jockie.bot.core.command.Command)7 Document (org.bson.Document)7 Argument (com.jockie.bot.core.argument.Argument)5 ModuleCategory (com.sx4.bot.category.ModuleCategory)5 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)5 MessageArgument (com.sx4.bot.entities.argument.MessageArgument)5 Permission (net.dv8tion.jda.api.Permission)5 Bson (org.bson.conversions.Bson)5 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)4 CommandId (com.sx4.bot.annotations.command.CommandId)4 Examples (com.sx4.bot.annotations.command.Examples)4 Or (com.sx4.bot.entities.argument.Or)4 PagedResult (com.sx4.bot.paged.PagedResult)4 TextChannel (net.dv8tion.jda.api.entities.TextChannel)4 User (net.dv8tion.jda.api.entities.User)4 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)3 Operators (com.sx4.bot.database.mongo.model.Operators)3 Alternative (com.sx4.bot.entities.argument.Alternative)3 Waiter (com.sx4.bot.waiter.Waiter)3