Search in sources :

Example 1 with Permission

use of net.dv8tion.jda.api.Permission in project MantaroBot by Mantaro.

the class MessageCmds method prune.

@Subscribe
public void prune(CommandRegistry cr) {
    var pruneCmd = cr.register("prune", new TreeCommand(CommandCategory.MODERATION) {

        @Override
        public Command defaultTrigger(Context context, String mainCommand, String commandName) {
            return new SubCommand() {

                @Override
                protected void call(Context ctx, I18nContext languageContext, String content) {
                    var args = ctx.getArguments();
                    if (content.isEmpty()) {
                        ctx.sendLocalized("commands.prune.no_messages_specified", EmoteReference.ERROR);
                        return;
                    }
                    var mentionedUsers = ctx.getMentionedUsers();
                    var amount = 5;
                    if (args.length > 0) {
                        try {
                            amount = Integer.parseInt(args[0]);
                            if (amount < 3) {
                                amount = 3;
                            }
                        } catch (Exception e) {
                            ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
                            return;
                        }
                    }
                    if (!mentionedUsers.isEmpty()) {
                        List<Long> users = mentionedUsers.stream().map(User::getIdLong).collect(Collectors.toList());
                        final var finalAmount = amount;
                        ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.mention_no_messages", message -> users.contains(message.getAuthor().getIdLong())), error -> ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage()));
                        return;
                    }
                    ctx.getChannel().getHistory().retrievePast(Math.min(amount, 100)).queue(messageHistory -> prune(ctx, messageHistory), error -> {
                        ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
                        error.printStackTrace();
                    });
                }
            };
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Prunes X amount of messages from a channel. Requires Message Manage permission.").setUsage("`~>prune <messages> [@user...]`").addParameter("messages", "Number of messages from 4 to 100.").addParameterOptional("@user...", "Prunes messages only from mentioned users.").build();
        }
    });
    pruneCmd.setPredicate(ctx -> {
        if (!ctx.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
            ctx.sendLocalized("commands.prune.no_permissions_user", EmoteReference.ERROR);
            return false;
        }
        if (!ctx.getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) {
            ctx.sendLocalized("commands.prune.no_permissions", EmoteReference.ERROR);
            return false;
        }
        return true;
    });
    pruneCmd.addSubCommand("bot", new SubCommand() {

        @Override
        public String description() {
            return "Prune bot messages. It takes the number of messages as an argument.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var args = ctx.getArguments();
            var amount = 100;
            if (args.length >= 1) {
                try {
                    amount = Integer.parseInt(args[0]);
                    if (amount < 3) {
                        amount = 3;
                    }
                } catch (Exception e) {
                    ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
                    return;
                }
            }
            final var finalAmount = amount;
            ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> {
                String prefix = MantaroData.db().getGuild(ctx.getGuild()).getData().getGuildCustomPrefix();
                getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.bots_no_messages", message -> message.getAuthor().isBot() || message.getContentRaw().startsWith(prefix == null ? "~>" : prefix));
            }, error -> {
                ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
                error.printStackTrace();
            });
        }
    });
    pruneCmd.addSubCommand("nopins", new SubCommand() {

        @Override
        public String description() {
            return "Prune messages that aren't pinned. It takes the number of messages as an argument.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var args = ctx.getArguments();
            var amount = 100;
            if (args.length >= 1) {
                try {
                    amount = Integer.parseInt(args[0]);
                    if (amount < 3) {
                        amount = 3;
                    }
                } catch (Exception e) {
                    ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
                    return;
                }
            }
            final var finalAmount = amount;
            ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.no_pins_no_messages", message -> !message.isPinned()), error -> {
                ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
                error.printStackTrace();
            });
        }
    });
}
Also used : I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) Message(net.dv8tion.jda.api.entities.Message) Module(net.kodehawa.mantarobot.core.modules.Module) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Predicate(java.util.function.Predicate) Permission(net.dv8tion.jda.api.Permission) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) ModLog(net.kodehawa.mantarobot.commands.moderation.ModLog) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) User(net.dv8tion.jda.api.entities.User) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) List(java.util.List) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with Permission

use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.

the class EventsCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    // process any optional channel arguments
    List<String> channelIds = new ArrayList<>();
    for (String arg : args) {
        channelIds.add(arg.replaceAll("[^\\d]", ""));
    }
    Guild guild = event.getGuild();
    List<String> scheduleIds = Main.getScheduleManager().getSchedulesForGuild(guild.getId());
    if (!channelIds.isEmpty()) {
        // filter the list of schedules
        scheduleIds = scheduleIds.stream().filter(channelIds::contains).collect(Collectors.toList());
    }
    // build the embed body content
    StringBuilder content = new StringBuilder();
    String title = "Events on " + guild.getName(), footer = "(events list continued on next page)";
    // total number of events
    int count = 0;
    // get the caller's guild member information
    Member caller = event.getGuild().getMember(event.getAuthor());
    if (// hide all events if null
    caller != null) {
        // list events by their schedule
        for (String sId : scheduleIds) {
            // only show users events that are on schedules they can view
            TextChannel sChannel = event.getGuild().getTextChannelById(sId);
            Collection<Permission> permissions = sChannel != null ? caller.getPermissions(sChannel) : new ArrayList();
            if (true || (sChannel != null && permissions != null && permissions.contains(Permission.MESSAGE_READ))) {
                if (content.length() > 1400) {
                    sendEventsMessage(footer, title, content, event.getTextChannel());
                    // adjust title and footer to reflect future messages are a continuation
                    title = "Events on " + guild.getName() + " (continued)";
                    footer = "(events list continued on next page)";
                    content = new StringBuilder();
                }
                // for each schedule, generate a list of events scheduled
                Collection<ScheduleEntry> entries = Main.getEntryManager().getEntriesFromChannel(sId);
                if (!entries.isEmpty()) {
                    // start a new schedule list
                    content.append("<#").append(sId).append("> ...\n");
                    while (!entries.isEmpty()) {
                        if (content.length() > 1800) {
                            sendEventsMessage(footer, title, content, event.getTextChannel());
                            // adjust title and footer to reflect future messages are a continuation
                            title = "Events on " + guild.getName() + " (continued)";
                            footer = "(events list continued on next page)";
                            content = new StringBuilder();
                        }
                        // find and remove the next earliest occurring event
                        ScheduleEntry top = entries.toArray(new ScheduleEntry[entries.size()])[0];
                        for (ScheduleEntry se : entries) {
                            if (se.getStart().isBefore(top.getStart()))
                                top = se;
                        }
                        entries.remove(top);
                        // determine time until the event begins/ends
                        long timeTil = ZonedDateTime.now().until(top.getStart(), ChronoUnit.MINUTES);
                        String status = "begins";
                        if (// adjust if event is ending
                        timeTil < 0) {
                            timeTil = ZonedDateTime.now().until(top.getEnd(), ChronoUnit.MINUTES);
                            status = "ends";
                        }
                        // add the event as a single line in the content
                        content.append(":id:``").append(ParsingUtilities.intToEncodedID(top.getId())).append("`` ~ **").append(top.getTitle()).append("** ").append(status).append(" in *");
                        ParsingUtilities.addTimeGap(content, timeTil, false, 3);
                        content.append("*\n");
                        // iterate event counter
                        count++;
                    }
                    // end a schedule list
                    content.append("\n");
                }
            }
        }
    }
    // final footer shows count
    footer = count + " event(s)";
    sendEventsMessage(footer, title, content, event.getTextChannel());
}
Also used : ArrayList(java.util.ArrayList) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Permission(net.dv8tion.jda.api.Permission)

Example 3 with Permission

use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.

the class ScheduleManager method createSchedule.

/**
 * Create a new schedule and it's associated schedule channel, if the bot cannot create the
 * new channel no schedule will be created
 * @param gId (String) guild ID
 * @param optional (String) optional name of schedule channel
 */
public void createSchedule(String gId, String optional) {
    JDA jda = Main.getShardManager().getJDA(gId);
    // bot self permissions
    Collection<Permission> channelPerms = Stream.of(Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES).collect(Collectors.toList());
    // create channel and get ID
    String cId;
    try {
        Guild guild = jda.getGuildById(gId);
        cId = guild.createTextChannel(optional != null ? optional : "new_schedule").addPermissionOverride(// allow self permissions
        guild.getMember(jda.getSelfUser()), channelPerms, new ArrayList<>()).addPermissionOverride(// disable @everyone message write
        guild.getPublicRole(), // disable @everyone message write
        new ArrayList<>(), Collections.singletonList(Permission.MESSAGE_WRITE)).complete().getId();
    } catch (PermissionException e) {
        String m = e.getMessage() + ": Guild ID " + gId;
        Logging.warn(this.getClass(), m);
        return;
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
        return;
    }
    // create the schedule database entry
    createNewSchedule(cId, gId);
}
Also used : PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) JDA(net.dv8tion.jda.api.JDA) Permission(net.dv8tion.jda.api.Permission) Guild(net.dv8tion.jda.api.entities.Guild) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException)

Example 4 with Permission

use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.

the class ScheduleManager method createSchedule.

/**
 * Convert a pre-existing discord channel to a new saber schedule channel
 * @param channel (TextChannel) a pre-existing channel to convert to a schedule
 */
public void createSchedule(TextChannel channel) {
    JDA jda = Main.getShardManager().getJDA(channel.getGuild().getId());
    // bot self permissions
    Collection<Permission> channelPerms = Stream.of(Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES).collect(Collectors.toList());
    // attempt to set the channel permissions
    try {
        // self perms
        channel.createPermissionOverride(channel.getGuild().getMember(jda.getSelfUser())).setAllow(channelPerms).queue();
        // @everyone perms
        channel.createPermissionOverride(channel.getGuild().getPublicRole()).setDeny(Collections.singleton(Permission.MESSAGE_WRITE)).queue();
    } catch (PermissionException e) {
        String m = e.getMessage() + ": Guild ID " + channel.getGuild().getId();
        Logging.warn(this.getClass(), m);
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    }
    // create the schedule database entry
    createNewSchedule(channel.getId(), channel.getGuild().getId());
}
Also used : PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) JDA(net.dv8tion.jda.api.JDA) Permission(net.dv8tion.jda.api.Permission) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException)

Aggregations

Permission (net.dv8tion.jda.api.Permission)4 PermissionException (net.dv8tion.jda.api.exceptions.PermissionException)3 JDA (net.dv8tion.jda.api.JDA)2 Subscribe (com.google.common.eventbus.Subscribe)1 OffsetDateTime (java.time.OffsetDateTime)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Predicate (java.util.function.Predicate)1 Collectors (java.util.stream.Collectors)1 Guild (net.dv8tion.jda.api.entities.Guild)1 Message (net.dv8tion.jda.api.entities.Message)1 User (net.dv8tion.jda.api.entities.User)1 ModLog (net.kodehawa.mantarobot.commands.moderation.ModLog)1 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)1 Module (net.kodehawa.mantarobot.core.modules.Module)1 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)1 TreeCommand (net.kodehawa.mantarobot.core.modules.commands.TreeCommand)1 Command (net.kodehawa.mantarobot.core.modules.commands.base.Command)1 CommandCategory (net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory)1 Context (net.kodehawa.mantarobot.core.modules.commands.base.Context)1