Search in sources :

Example 31 with Or

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

the class SteamCommand method game.

@Command(value = "profile", description = "Look up information about a steam profile")
@CommandId(212)
@Examples({ "steam profile dog", "steam profile https://steamcommunity.com/id/dog" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query) {
    List<Document> profiles;
    if (query == null) {
        List<Document> connections = event.getMongo().getUserById(event.getAuthor().getIdLong(), Projections.include("connections.steam")).getEmbedded(List.of("connections", "steam"), Collections.emptyList());
        if (connections.isEmpty()) {
            event.replyFailure("You do not have a steam account linked, use `steam connect` to link an account or provide an argument to search").queue();
            return;
        }
        profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id"))).collect(Collectors.toList());
    } else {
        profiles = List.of(new Document("url", this.getProfileUrl(query)));
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), profiles).setAutoSelect(true).setAuthor("Steam Profiles", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setDisplayFunction(data -> "[" + data.getString("name") + "](" + data.getString("url") + ")");
    paged.onSelect(select -> {
        String url = select.getSelected().getString("url");
        Request request = new Request.Builder().url(url + "?xml=1").build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            JSONObject json = XML.toJSONObject(response.body().string());
            if (json.has("response")) {
                event.replyFailure("I could not find that steam user").queue();
                return;
            }
            JSONObject profile = json.getJSONObject("profile");
            if (profile.getInt("visibilityState") == 1) {
                event.replyFailure("That profile is private").queue();
                return;
            }
            JSONObject mostPlayedGames = profile.optJSONObject("mostPlayedGames");
            JSONArray gamesArray = mostPlayedGames == null ? new JSONArray() : mostPlayedGames.optJSONArray("mostPlayedGame");
            if (gamesArray == null) {
                gamesArray = new JSONArray().put(mostPlayedGames.getJSONObject("mostPlayedGame"));
            }
            double hours = 0D;
            StringBuilder gamesString = new StringBuilder();
            for (int i = 0; i < gamesArray.length(); i++) {
                JSONObject game = gamesArray.getJSONObject(i);
                hours += game.getDouble("hoursPlayed");
                gamesString.append(String.format("[%s](%s) - **%.1f** hours\n", game.getString("gameName"), game.getString("gameLink"), game.getDouble("hoursPlayed")));
            }
            String stateMessage = profile.getString("stateMessage");
            String location = profile.getString("location");
            String realName = profile.getString("realname");
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(profile.getString("steamID"), url, profile.getString("avatarFull"));
            embed.setDescription(Jsoup.parse(profile.getString("summary")).text());
            embed.setFooter("ID: " + profile.getLong("steamID64"));
            embed.setThumbnail(profile.getString("avatarFull"));
            embed.addField("Real Name", realName.isBlank() ? "None Given" : realName, true);
            embed.addField("Created At", LocalDate.parse(profile.getString("memberSince"), DateTimeFormatter.ofPattern("LLLL d, yyyy")).format(this.formatter), true);
            embed.addField("Status", StringUtility.title(profile.getString("onlineState")), true);
            embed.addField("State Message", Jsoup.parse(stateMessage).text(), true);
            embed.addField("Vac Bans", String.valueOf(profile.getInt("vacBanned")), true);
            if (!location.isBlank()) {
                embed.addField("Location", location, true);
            }
            if (hours != 0) {
                gamesString.append(String.format("\nTotal - **%.1f** hours", hours));
                embed.addField("Games Played (2 Weeks)", gamesString.toString(), false);
            }
            event.reply(embed.build()).queue();
        });
    });
    paged.execute(event);
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CommandId(com.sx4.bot.annotations.command.CommandId) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) EmbedType(net.dv8tion.jda.api.entities.EmbedType) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Role(net.dv8tion.jda.api.entities.Role) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Examples(com.sx4.bot.annotations.command.Examples) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) InvalidKeyException(java.security.InvalidKeyException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Pattern(java.util.regex.Pattern) StringUtility(com.sx4.bot.utility.StringUtility) JSONArray(org.json.JSONArray) SteamGameCache(com.sx4.bot.cache.SteamGameCache) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) JSONObject(org.json.JSONObject) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) JSONArray(org.json.JSONArray) Document(org.bson.Document) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 32 with Or

use of com.sx4.bot.entities.argument.Or 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 33 with Or

use of com.sx4.bot.entities.argument.Or 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)

Example 34 with Or

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

the class WelcomerCommand method preview.

@Command(value = "preview", description = "Preview your welcomer message")
@CommandId(99)
@Examples({ "welcomer preview" })
public void preview(Sx4CommandEvent event) {
    Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("welcomer.message", "welcomer.image", "welcomer.enabled", "premium.endAt"));
    Document welcomer = data.get("welcomer", MongoDatabase.EMPTY_DOCUMENT);
    Document image = welcomer.get("image", MongoDatabase.EMPTY_DOCUMENT);
    boolean messageEnabled = welcomer.get("enabled", false), imageEnabled = image.get("enabled", false);
    if (!messageEnabled && !imageEnabled) {
        event.replyFailure("Neither welcomer or image welcomer is enabled").queue();
        return;
    }
    boolean gif = data.getEmbedded(List.of("premium", "endAt"), 0L) >= Clock.systemUTC().instant().getEpochSecond();
    WelcomerUtility.getWelcomerMessage(event.getHttpClient(), messageEnabled ? welcomer.get("message", WelcomerManager.DEFAULT_MESSAGE) : null, image.getString("bannerId"), event.getMember(), event.getConfig().isCanary(), imageEnabled, gif, (builder, exception) -> {
        if (exception instanceof IllegalArgumentException) {
            event.replyFailure(exception.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        MessageUtility.fromWebhookMessage(event.getTextChannel(), builder.build()).queue();
    });
}
Also used : Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 35 with Or

use of com.sx4.bot.entities.argument.Or 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)36 Command (com.jockie.bot.core.command.Command)25 Document (org.bson.Document)25 Argument (com.jockie.bot.core.argument.Argument)19 ModuleCategory (com.sx4.bot.category.ModuleCategory)19 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)19 Bson (org.bson.conversions.Bson)17 CommandId (com.sx4.bot.annotations.command.CommandId)16 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)16 Examples (com.sx4.bot.annotations.command.Examples)15 PagedResult (com.sx4.bot.paged.PagedResult)15 Permission (net.dv8tion.jda.api.Permission)15 Member (net.dv8tion.jda.api.entities.Member)13 List (java.util.List)12 CompletionException (java.util.concurrent.CompletionException)10 Option (com.jockie.bot.core.option.Option)8 Collectors (java.util.stream.Collectors)8 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)8 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)7 Operators (com.sx4.bot.database.mongo.model.Operators)7