Search in sources :

Example 91 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class MuteCommand method list.

@Command(value = "list", description = "Lists all the currently muted users in the server")
@CommandId(343)
@Redirects({ "muted list" })
@Examples({ "mute list" })
public void list(Sx4CommandEvent event) {
    List<Document> mutes = event.getMongo().getMutes(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("unmuteAt", "userId")).into(new ArrayList<>());
    if (mutes.isEmpty()) {
        event.replyFailure("There is no one muted in this server").queue();
        return;
    }
    mutes.sort(Comparator.comparingLong(d -> d.getLong("unmuteAt")));
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), mutes).setAuthor("Muted Users", null, event.getGuild().getIconUrl()).setIndexed(false).setSelect().setDisplayFunction(data -> {
        User user = event.getShardManager().getUserById(data.getLong("userId"));
        return (user == null ? "Anonymous#0000" : user.getAsTag()) + " - " + TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("unmuteAt") - Clock.systemUTC().instant().getEpochSecond());
    });
    paged.execute(event);
}
Also used : Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) ModAction(com.sx4.bot.entities.mod.action.ModAction) Member(net.dv8tion.jda.api.entities.Member) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Redirects(com.sx4.bot.annotations.command.Redirects) Alternative(com.sx4.bot.entities.argument.Alternative) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) Option(com.jockie.bot.core.option.Option) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Reason(com.sx4.bot.entities.mod.Reason) com.mongodb.client.model(com.mongodb.client.model) Argument(com.jockie.bot.core.argument.Argument) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) ModUtility(com.sx4.bot.utility.ModUtility) EnumOptions(com.sx4.bot.annotations.argument.EnumOptions) CompletionException(java.util.concurrent.CompletionException) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Comparator(java.util.Comparator) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) Redirects(com.sx4.bot.annotations.command.Redirects) 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 92 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class OffencesCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    Bson filter = Filters.eq("guildId", event.getGuild().getIdLong());
    if (member != null) {
        filter = Filters.and(filter, Filters.eq("targetId", member.getIdLong()));
    }
    event.getMongo().getOffences(filter, Sorts.descending("_id")).whenComplete((iterable, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        try {
            List<Document> data = iterable.into(new ArrayList<>());
            if (data.isEmpty()) {
                event.replyFailure((member == null ? "This server" : "**" + member.getUser().getAsTag() + "**") + " has no offences").queue();
                return;
            }
            User user = member == null ? null : member.getUser();
            PagedResult<Document> paged = new PagedResult<>(event.getBot(), data).setPerPage(6).setCustomFunction(page -> {
                EmbedBuilder embed = new EmbedBuilder().setAuthor("Offences", null, member == null ? event.getGuild().getIconUrl() : user.getEffectiveAvatarUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
                page.forEach((offence, index) -> {
                    Action action = Action.fromData(offence.get("action", Document.class));
                    ObjectId id = offence.getObjectId("_id");
                    OffsetDateTime time = OffsetDateTime.ofInstant(Instant.ofEpochSecond(id.getTimestamp()), ZoneOffset.UTC);
                    long targetId = offence.getLong("targetId");
                    User target = member == null ? event.getShardManager().getUserById(targetId) : user;
                    String targetContent = target == null ? "Anonymous#0000 (" + targetId + ")" : target.getAsTag();
                    long moderatorId = offence.getLong("moderatorId");
                    User moderator = event.getShardManager().getUserById(moderatorId);
                    String moderatorContent = moderator == null ? "Anonymous#0000 (" + moderatorId + ")" : moderator.getAsTag();
                    embed.addField(action.toString(), String.format("Target: %s\nModerator: %s\nReason: %s\nTime: %s", targetContent, moderatorContent, offence.get("reason", "None Given"), time.format(this.formatter)), true);
                });
                return new MessageBuilder().setEmbeds(embed.build());
            });
            paged.execute(event);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    });
}
Also used : Action(com.sx4.bot.entities.mod.action.Action) User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) OffsetDateTime(java.time.OffsetDateTime) PagedResult(com.sx4.bot.paged.PagedResult)

Example 93 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class RoleCommand method add.

@Command(value = "add", description = "Add a role to a member")
@CommandId(250)
@Redirects({ "addrole", "add role", "ar" })
@Examples({ "role add @Shea#6653 Role", "role add Shea 345718366373150720", "role add @Role" })
@AuthorPermissions(permissions = { Permission.MANAGE_ROLES })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void add(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) @AlternativeOptions("all") Alternative<Member> option, @Argument(value = "role", endless = true) Role role) {
    if (role.isManaged()) {
        event.replyFailure("I cannot give managed roles").queue();
        return;
    }
    if (role.isPublicRole()) {
        event.replyFailure("I cannot give the @everyone role").queue();
        return;
    }
    if (!event.getMember().canInteract(role)) {
        event.replyFailure("You cannot give a role higher or equal than your top role").queue();
        return;
    }
    if (!event.getSelfMember().canInteract(role)) {
        event.replyFailure("I cannot give a role higher or equal than my top role").queue();
        return;
    }
    if (option != null && option.isAlternative()) {
        List<Member> members = event.getGuild().getMemberCache().applyStream(stream -> stream.filter(member -> !member.getRoles().contains(role)).collect(Collectors.toList()));
        if (members.size() == 0) {
            event.replyFailure("All users already have that role").queue();
            return;
        }
        if (!this.pending.add(event.getGuild().getIdLong())) {
            event.replyFailure("You can only have 1 concurrent role being added to all users").queue();
            return;
        }
        event.replyFormat("Adding %s to **%,d** user%s, another message will be sent once this is done %s", role.getAsMention(), members.size(), members.size() == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        for (Member member : members) {
            futures.add(event.getGuild().addRoleToMember(member, role).submit().handle((result, exception) -> exception == null ? 1 : 0));
        }
        FutureUtility.allOf(futures).whenComplete((completed, exception) -> {
            this.pending.remove(event.getGuild().getIdLong());
            int count = completed.stream().reduce(0, Integer::sum);
            event.replyFormat("Successfully added the role %s to **%,d/%,d** user%s %s", role.getAsMention(), count, members.size(), count == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
        });
    } else {
        Member effectiveMember = option == null ? event.getMember() : option.getValue();
        event.getGuild().addRoleToMember(effectiveMember, role).flatMap($ -> event.replySuccess(role.getAsMention() + " has been added to **" + effectiveMember.getUser().getAsTag() + "**")).queue();
    }
}
Also used : Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Set(java.util.Set) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) Colour(com.sx4.bot.annotations.argument.Colour) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ModuleCategory(com.sx4.bot.category.ModuleCategory) Alternative(com.sx4.bot.entities.argument.Alternative) PermissionUtility(com.sx4.bot.utility.PermissionUtility) List(java.util.List) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) FutureUtility(com.sx4.bot.utility.FutureUtility) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) PermissionUtil(net.dv8tion.jda.internal.utils.PermissionUtil) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) Member(net.dv8tion.jda.api.entities.Member) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 94 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class InvitesCommand method leaderboard.

@Command(value = "leaderboard", aliases = { "lb" }, description = "View a leaderboard of all invites in the server sorted by user")
@CommandId(266)
@Redirects({ "lb invites", "leaderboard invites" })
@Examples({ "invites leaderboard" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event) {
    event.getGuild().retrieveInvites().queue(invites -> {
        if (invites.isEmpty()) {
            event.replyFailure("There are no invites in this server").queue();
            return;
        }
        Map<Long, Integer> count = new HashMap<>();
        AtomicInteger total = new AtomicInteger(0);
        for (Invite invite : invites) {
            User inviter = invite.getInviter();
            if (inviter != null) {
                count.compute(inviter.getIdLong(), (key, value) -> value == null ? invite.getUses() : value + invite.getUses());
            }
            total.addAndGet(invite.getUses());
        }
        List<Map.Entry<Long, Integer>> sortedCount = new ArrayList<>(count.entrySet());
        sortedCount.sort(Collections.reverseOrder(Comparator.comparingInt(Map.Entry::getValue)));
        PagedResult<Map.Entry<Long, Integer>> paged = new PagedResult<>(event.getBot(), sortedCount).setIncreasedIndex(true).setAuthor("Invites Leaderboard", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
            int percentInvited = Math.round(((float) data.getValue() / total.get()) * 100);
            String percent = percentInvited >= 1 ? String.valueOf(percentInvited) : "<1";
            Member member = event.getGuild().getMemberById(data.getKey());
            String memberString = member == null ? String.valueOf(data.getKey()) : member.getUser().getAsTag();
            return String.format("`%s` - %,d %s (%s%%)", memberString, data.getValue(), data.getValue() == 1 ? "invite" : "invites", percent);
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Member(net.dv8tion.jda.api.entities.Member) Invite(net.dv8tion.jda.api.entities.Invite) Redirects(com.sx4.bot.annotations.command.Redirects) 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 95 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent 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();
    });
}
Also used : Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) ImageError(com.sx4.bot.entities.image.ImageError) Permission(net.dv8tion.jda.api.Permission) ModuleCategory(com.sx4.bot.category.ModuleCategory) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)255 Command (com.jockie.bot.core.command.Command)181 Document (org.bson.Document)153 ModuleCategory (com.sx4.bot.category.ModuleCategory)130 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)130 CommandId (com.sx4.bot.annotations.command.CommandId)121 Argument (com.jockie.bot.core.argument.Argument)119 Examples (com.sx4.bot.annotations.command.Examples)119 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)119 Permission (net.dv8tion.jda.api.Permission)119 Bson (org.bson.conversions.Bson)111 PagedResult (com.sx4.bot.paged.PagedResult)90 HttpCallback (com.sx4.bot.http.HttpCallback)69 Request (okhttp3.Request)68 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)60 User (net.dv8tion.jda.api.entities.User)57 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)55 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)54 Operators (com.sx4.bot.database.mongo.model.Operators)50 List (java.util.List)50