use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class ResizeCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "image url") @ImageUrl String imageUrl, @Argument(value = "width") @Limit(min = 0, max = 5000) double width, @Argument(value = "height") @Limit(min = 0, max = 5000) @DefaultNumber(1) double height) {
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("resize")).addQuery("w", width).addQuery("h", height).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
ImageUtility.getImageMessage(event, response, (body, error) -> {
if (error == ImageError.INVALID_QUERY_VALUE) {
return event.replyFailure(body.getString("message"));
}
return null;
}).queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class AntiRegexCommand method add.
@Command(value = "add", description = "Add a custom regex to be checked on every message")
@CommandId(125)
@Examples({ "anti regex add [0-9]+", "anti regex add https://discord\\.com/channels/([0-9]+)/([0-9]+)/?" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "regex", endless = true) Pattern pattern) {
List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())));
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false), Filters.eq("type", RegexType.REGEX.getId()))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(10), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
event.getMongo().aggregateRegexes(pipeline).thenCompose(documents -> {
Document counter = documents.isEmpty() ? null : documents.get(0);
int count = counter == null ? 0 : counter.getInteger("count");
if (count >= 3 && !counter.getBoolean("premium")) {
throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled anti regexes, you can get premium at <https://www.patreon.com/Sx4>");
}
if (count == 10) {
throw new IllegalArgumentException("You cannot have any more than 10 anti regexes");
}
Document patternData = new Document("guildId", event.getGuild().getIdLong()).append("type", RegexType.REGEX.getId()).append("pattern", pattern.pattern());
return event.getMongo().insertRegex(patternData);
}).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have that anti regex setup in this server").queue();
return;
} else if (cause instanceof IllegalArgumentException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class AntiRegexCommand method add.
@Command(value = "add", description = "Add a regex from `anti regex template list` to be checked on every message")
@CommandId(106)
@Examples({ "anti regex add 5f023782ef9eba03390a740c" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
Document regex = event.getMongo().getRegexTemplateById(id, Projections.include("pattern", "title", "type"));
if (regex == null) {
event.replyFailure("I could not find that regex template").queue();
return;
}
List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())));
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false), Filters.eq("type", RegexType.REGEX.getId()))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(10), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
event.getMongo().aggregateRegexes(pipeline).thenCompose(documents -> {
Document counter = documents.isEmpty() ? null : documents.get(0);
int count = counter == null ? 0 : counter.getInteger("count");
if (count >= 3 && !counter.getBoolean("premium")) {
throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled anti regexes, you can get premium at <https://www.patreon.com/Sx4>");
}
if (count == 10) {
throw new IllegalArgumentException("You cannot have any more than 10 anti regexes");
}
Document pattern = new Document("regexId", id).append("guildId", event.getGuild().getIdLong()).append("type", regex.getInteger("type", RegexType.REGEX.getId())).append("pattern", regex.getString("pattern"));
return event.getMongo().insertRegex(pattern);
}).thenCompose(result -> {
event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
return event.getMongo().updateRegexTemplateById(id, Updates.inc("uses", 1L));
}).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have that anti regex setup in this server").queue();
return;
} else if (cause instanceof IllegalArgumentException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
ExceptionUtility.sendExceptionally(event, exception);
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class BlacklistCommand method list.
@Command(value = "list", description = "Lists the commands roles/users blacklisted from using in a specific channel")
@CommandId(182)
@Examples({ "blacklist list", "blacklist list #channel" })
public void list(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) TextChannel channel) {
List<TextChannel> channels = channel == null ? event.getGuild().getTextChannels() : List.of(channel);
PagedResult<TextChannel> channelPaged = new PagedResult<>(event.getBot(), channels).setAutoSelect(true).setAuthor("Channels", null, event.getGuild().getIconUrl()).setDisplayFunction(TextChannel::getAsMention);
channelPaged.onSelect(channelSelect -> {
TextChannel selectedChannel = channelSelect.getSelected();
Document blacklist = event.getMongo().getBlacklist(Filters.eq("channelId", selectedChannel.getIdLong()), Projections.include("holders"));
if (blacklist == null) {
event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
return;
}
List<Document> holders = blacklist.getList("holders", Document.class).stream().filter(holder -> !holder.getList("blacklisted", Long.class, Collections.emptyList()).isEmpty()).sorted(Comparator.comparingInt(a -> a.getInteger("type"))).collect(Collectors.toList());
if (holders.isEmpty()) {
event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
return;
}
PagedResult<Document> holderPaged = new PagedResult<>(event.getBot(), holders).setAuthor("Users/Roles", null, event.getGuild().getIconUrl()).setDisplayFunction(holder -> {
long id = holder.getLong("id");
int type = holder.getInteger("type");
if (type == HolderType.ROLE.getType()) {
Role role = event.getGuild().getRoleById(id);
return role == null ? "Deleted Role (" + id + ")" : role.getAsMention();
} else {
User user = event.getShardManager().getUserById(id);
return user == null ? "Unknown User (" + id + ")" : user.getAsTag();
}
});
holderPaged.onSelect(holderSelect -> {
Document holder = holderSelect.getSelected();
List<Long> blacklisted = holder.getList("blacklisted", Long.class, Collections.emptyList());
BitSet bitSet = BitSet.valueOf(blacklisted.stream().mapToLong(l -> l).toArray());
List<Sx4Command> commands = event.getCommandListener().getAllCommands().stream().map(Sx4Command.class::cast).filter(command -> bitSet.get(command.getId())).collect(Collectors.toList());
PagedResult<Sx4Command> commandPaged = new PagedResult<>(event.getBot(), commands).setAuthor("Blacklisted Commands", null, event.getGuild().getIconUrl()).setDisplayFunction(Sx4Command::getCommandTrigger).setSelect().setIndexed(false);
commandPaged.execute(event);
});
holderPaged.execute(event);
});
channelPaged.execute(event);
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class DiscordBotCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "bot", endless = true, nullDefault = true) String query) {
CompletableFuture<String> future = new CompletableFuture<>();
if (query == null) {
future.complete("440996323156819968");
} else {
Matcher mentionMatch = SearchUtility.USER_MENTION.matcher(query);
if (NumberUtility.isNumber(query)) {
future.complete(query);
} else if (mentionMatch.matches()) {
future.complete(mentionMatch.group(1));
} else if (query.length() <= 32) {
Request request = new Request.Builder().url("https://top.gg/api/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&type=bot").build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
PagedResult<Document> paged = new PagedResult<>(event.getBot(), data.getList("results", Document.class)).setAutoSelect(true).setDisplayFunction(d -> d.getString("name") + " (" + d.getString("id") + ")");
paged.onSelect(select -> future.complete(select.getSelected().getString("id")));
paged.execute(event);
});
} else {
event.replyFailure("I could not find that bot").queue();
return;
}
}
future.whenComplete((id, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Request request = new Request.Builder().url("https://top.gg/api/bots/" + id).addHeader("Authorization", event.getConfig().getTopGG()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (response.code() == 404) {
event.replyFailure("I could not find that bot").queue();
return;
}
Document bot = Document.parse(response.body().string());
String botAvatarUrl = "https://cdn.discordapp.com/avatars/" + bot.getString("id") + "/" + bot.getString("avatar");
String botInviteUrl = !bot.getString("invite").isEmpty() ? bot.getString("invite") : "https://discord.com/oauth2/authorize?client_id=" + bot.getString("id") + "&scope=bot";
String guildCount = bot.containsKey("server_count") ? String.format("%,d", bot.getInteger("server_count")) : "N/A";
String ownerId = bot.getList("owners", String.class).get(0);
User owner = event.getShardManager().getUserById(ownerId);
EmbedBuilder embed = new EmbedBuilder().setAuthor(bot.getString("username") + "#" + bot.getString("discriminator"), "https://top.gg/bot/" + bot.getString("id"), botAvatarUrl).setThumbnail(botAvatarUrl).setDescription((bot.getBoolean("certifiedBot") ? "<:certified:438392214545235978> | " : "") + bot.getString("shortdesc")).addField("Guilds", guildCount, true).addField("Prefix", bot.getString("prefix"), true).addField("Library", bot.getString("lib"), true).addField("Approval Date", OffsetDateTime.parse(bot.getString("date")).format(this.formatter), true).addField("Monthly Votes", String.format("%,d :thumbsup:", bot.getInteger("monthlyPoints")), true).addField("Total Votes", String.format("%,d :thumbsup:", bot.getInteger("points")), true).addField("Invite", "**[Invite " + bot.getString("username") + " to your server](" + botInviteUrl + ")**", true);
if (owner == null) {
embed.setFooter("Primary Owner ID: " + ownerId, null);
} else {
embed.setFooter("Primary Owner: " + owner.getAsTag(), owner.getEffectiveAvatarUrl());
}
event.reply(embed.build()).queue();
});
});
}
Aggregations