Search in sources :

Example 16 with PermissionException

use of net.dv8tion.jda.core.exceptions.PermissionException in project Ardent by adamint.

the class Prune method noArgs.

@Override
public void noArgs(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
    if (args.length == 1) {
        sendTranslatedMessage("Prune\n" + "Prune users who have been inactive a certain amount of days\n" + "\n" + "Syntax: {0}prune [amount of days]\n" + "Example usage: {0}prune 4".replace("{0}", GuildUtils.getPrefix(guild) + args[0]), channel, user);
    } else {
        if (guild.getMember(user).hasPermission(Permission.MANAGE_SERVER)) {
            try {
                int day = Integer.parseInt(args[1]);
                if (day <= 0) {
                    sendTranslatedMessage("Your number has to be at least 1!", channel, user);
                    return;
                }
                guild.getController().prune(day).queue(integer -> {
                    try {
                        sendTranslatedMessage("Successfully pruned{0} users.".replace("{0}", String.valueOf(integer)), channel, user);
                    } catch (Exception e) {
                        new BotException(e);
                    }
                });
            } catch (NumberFormatException ex) {
                sendTranslatedMessage("You did not supply a whole number.", channel, user);
            } catch (PermissionException ex) {
                sendTranslatedMessage("I don't have permissions to kick users", channel, user);
            }
        } else
            sendTranslatedMessage("You don't have permission to kick users.", channel, user);
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) BotException(tk.ardentbot.core.misc.logging.BotException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) BotException(tk.ardentbot.core.misc.logging.BotException)

Example 17 with PermissionException

use of net.dv8tion.jda.core.exceptions.PermissionException in project MantaroBot by Mantaro.

the class MantaroListener method logDelete.

private void logDelete(GuildMessageDeleteEvent event) {
    try {
        String hour = df.format(new Date(System.currentTimeMillis()));
        String logChannel = MantaroData.db().getGuild(event.getGuild()).getData().getGuildLogChannel();
        if (logChannel != null) {
            TextChannel tc = event.getGuild().getTextChannelById(logChannel);
            if (tc == null)
                return;
            CachedMessage deletedMessage = CommandListener.getMessageCache().get(event.getMessageId(), Optional::empty).orElse(null);
            if (deletedMessage != null && !deletedMessage.getContent().isEmpty() && !event.getChannel().getId().equals(logChannel) && !deletedMessage.getAuthor().getId().equals(event.getJDA().getSelfUser().getId())) {
                if (MantaroData.db().getGuild(event.getGuild()).getData().getModlogBlacklistedPeople().contains(deletedMessage.getAuthor().getId())) {
                    return;
                }
                if (MantaroData.db().getGuild(event.getGuild()).getData().getLogExcludedChannels().contains(event.getChannel().getId())) {
                    return;
                }
                logTotal++;
                tc.sendMessage(String.format(EmoteReference.WARNING + "`[%s]` Message created by **%s#%s** in channel **%s** was deleted.\n" + "```diff\n-%s```", hour, deletedMessage.getAuthor().getName(), deletedMessage.getAuthor().getDiscriminator(), event.getChannel().getName(), deletedMessage.getContent().replace("```", ""))).queue();
            }
        }
    } catch (Exception e) {
        if (!(e instanceof IllegalArgumentException) && !(e instanceof NullPointerException) && !(e instanceof CacheLoader.InvalidCacheLoadException) && !(e instanceof PermissionException)) {
            log.warn("Unexpected exception while logging a deleted message.", e);
        }
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) CacheLoader(com.google.common.cache.CacheLoader) Date(java.util.Date) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) ExecutionException(java.util.concurrent.ExecutionException) CachedMessage(net.kodehawa.mantarobot.core.listeners.entities.CachedMessage)

Example 18 with PermissionException

use of net.dv8tion.jda.core.exceptions.PermissionException in project MantaroBot by Mantaro.

the class CommandListener method onCommand.

private void onCommand(GuildMessageReceivedEvent event) {
    try {
        Member self = event.getGuild().getSelfMember();
        if (!self.getPermissions(event.getChannel()).contains(Permission.MESSAGE_WRITE) && !self.hasPermission(Permission.ADMINISTRATOR))
            return;
        if (commandProcessor.run(event)) {
            commandTotal++;
        } else {
            // Only run experience if no command has been executed, avoids weird race conditions when saving player status.
            try {
                // Only run experience if the user is not rate limited (clears every 30 seconds)
                if (random.nextInt(15) > 7 && !event.getAuthor().isBot() && experienceRatelimiter.process(event.getAuthor())) {
                    if (event.getMember() == null)
                        return;
                    // some nasty race conditions involving player save.
                    if (InteractiveOperations.get(event.getChannel()) != null)
                        return;
                    Player player = MantaroData.db().getPlayer(event.getAuthor());
                    PlayerData data = player.getData();
                    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
                    GuildData guildData = dbGuild.getData();
                    if (player.isLocked())
                        return;
                    // Set level to 1 if level is zero.
                    if (player.getLevel() == 0)
                        player.setLevel(1);
                    // Set player experience to a random number between 1 and 5.
                    data.setExperience(data.getExperience() + Math.round(random.nextInt(5)));
                    // Apply some black magic.
                    if (data.getExperience() > (player.getLevel() * Math.log10(player.getLevel()) * 1000) + (50 * player.getLevel() / 2)) {
                        player.setLevel(player.getLevel() + 1);
                        // Check if the member is not null, just to be sure it happened in-between.
                        if (player.getLevel() > 1 && event.getGuild().getMemberById(player.getUserId()) != null) {
                            if (guildData.isEnabledLevelUpMessages()) {
                                String levelUpChannel = guildData.getLevelUpChannel();
                                String levelUpMessage = guildData.getLevelUpMessage();
                                // Player has leveled up!
                                if (levelUpMessage != null && levelUpChannel != null) {
                                    processMessage(String.valueOf(player.getLevel()), levelUpMessage, levelUpChannel, event);
                                }
                            }
                        }
                    }
                    // This time, actually remember to save the player so you don't have to restart 102 shards to fix it.
                    player.saveAsync();
                }
            } catch (Exception ignored) {
            }
        }
    } catch (IndexOutOfBoundsException e) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Your query returned no results or you used the incorrect arguments, seemingly. Just in case, check command help!").queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            event.getChannel().sendMessage(String.format("%sI don't have permission to do this :<, I need the permission: **%s**%s", EmoteReference.ERROR, e.getPermission().getName(), e.getMessage() != null ? String.format(" | Message: %s", e.getMessage()) : "")).queue();
        } else {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot perform this action due to the lack of permission! Is the role I might be trying to assign" + " higher than my role? Do I have the correct permissions/hierarchy to perform this action?").queue();
        }
    } catch (IllegalArgumentException e) {
        // NumberFormatException == IllegalArgumentException
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        event.getChannel().sendMessage(String.format("%sI think you forgot something on the floor. (Maybe we threw it there? [Error ID: %s]... I hope we didn't)\n" + "- Incorrect type arguments or the message I'm trying to send exceeds 2048 characters, Just in case, check command help!", EmoteReference.ERROR, id)).queue();
        log.warn("Exception caught and alternate message sent. We should look into this, anyway (ID: {})", id, e);
    } catch (ReqlError e) {
        // So much just went wrong...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Database");
    } catch (RedisException e) {
        // So much just went wrong but on another side of the db...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Redis Database");
    } catch (Exception e) {
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        Player player = MantaroData.db().getPlayer(event.getAuthor());
        event.getChannel().sendMessage(String.format("%s%s\n(Error ID: `%s`)\n" + "If you want, join our **support guild** (Link on `~>about`), or check out our GitHub page (/Mantaro/MantaroBot). " + "Please tell them to quit exploding me and please don't forget the Error ID when reporting!", EmoteReference.ERROR, boomQuotes[rand.nextInt(boomQuotes.length)], id)).queue();
        if (player.getData().addBadgeIfAbsent(Badge.FIRE))
            player.saveAsync();
        SentryHelper.captureException(String.format("Unexpected Exception on Command: %s | (Error ID: ``%s``)", event.getMessage().getContentRaw(), id), e, this.getClass());
        log.error("Error happened with id: {} (Error ID: {})", event.getMessage().getContentRaw(), id, e);
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) ReqlError(com.rethinkdb.gen.exc.ReqlError) RedisException(org.redisson.client.RedisException) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) RedisException(org.redisson.client.RedisException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException)

Example 19 with PermissionException

use of net.dv8tion.jda.core.exceptions.PermissionException in project MantaroBot by Mantaro.

the class MessageCmds method prune.

private void prune(GuildMessageReceivedEvent event, List<Message> messageHistory) {
    messageHistory = messageHistory.stream().filter(message -> !message.getCreationTime().isBefore(OffsetDateTime.now().minusWeeks(2))).collect(Collectors.toList());
    TextChannel channel = event.getChannel();
    if (messageHistory.isEmpty()) {
        channel.sendMessage(EmoteReference.ERROR + "There are no messages newer than 2 weeks old, discord won't let me delete them.").queue();
        return;
    }
    final int size = messageHistory.size();
    if (messageHistory.size() < 3) {
        channel.sendMessage(EmoteReference.ERROR + "Too few messages to prune!").queue();
        return;
    }
    channel.deleteMessages(messageHistory).queue(success -> {
        channel.sendMessage(EmoteReference.PENCIL + "Successfully pruned " + size + " messages from this channel!").queue(message -> message.delete().queueAfter(15, TimeUnit.SECONDS));
        DBGuild db = MantaroData.db().getGuild(event.getGuild());
        db.getData().setCases(db.getData().getCases() + 1);
        db.saveAsync();
        ModLog.log(event.getMember(), null, "Pruned Messages", ModLog.ModAction.PRUNE, db.getData().getCases());
    }, error -> {
        if (error instanceof PermissionException) {
            PermissionException pe = (PermissionException) error;
            channel.sendMessage(String.format("%sLack of permission while pruning messages(No permission provided: %s)", EmoteReference.ERROR, pe.getPermission())).queue();
        } else {
            channel.sendMessage(String.format("%sUnknown error while pruning messages<%s>: %s", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage())).queue();
            error.printStackTrace();
        }
    });
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) TextChannel(net.dv8tion.jda.core.entities.TextChannel) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild)

Example 20 with PermissionException

use of net.dv8tion.jda.core.exceptions.PermissionException in project MantaroBot by Mantaro.

the class MiscCmds method iamFunction.

protected static void iamFunction(String autoroleName, GuildMessageReceivedEvent event) {
    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
    Map<String, String> autoroles = dbGuild.getData().getAutoroles();
    if (autoroles.containsKey(autoroleName)) {
        Role role = event.getGuild().getRoleById(autoroles.get(autoroleName));
        if (role == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "The role that this autorole corresponded to has been deleted").queue();
            // delete the non-existent autorole.
            dbGuild.getData().getAutoroles().remove(autoroleName);
            dbGuild.saveAsync();
        } else {
            if (event.getMember().getRoles().stream().filter(r1 -> r1.getId().equals(role.getId())).collect(Collectors.toList()).size() > 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You already have this role, silly!").queue();
                return;
            }
            try {
                event.getGuild().getController().addSingleRoleToMember(event.getMember(), role).reason("Auto-assignable roles assigner (~>iam)").queue(aVoid -> event.getChannel().sendMessage(String.format("%s%s, you've been given the **%s** role", EmoteReference.OK, event.getMember().getEffectiveName(), role.getName())).queue());
            } catch (PermissionException pex) {
                event.getChannel().sendMessage(String.format("%sI couldn't take from you **%s. Make sure that I have permission to add roles and that my role is above **%s**", EmoteReference.ERROR, role.getName(), role.getName())).queue();
            }
        }
    } else {
        event.getChannel().sendMessage(EmoteReference.ERROR + "There isn't an autorole with the name ``" + autoroleName + "``!").queue();
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) IntStream(java.util.stream.IntStream) Poll(net.kodehawa.mantarobot.commands.interaction.polls.Poll) Module(net.kodehawa.mantarobot.core.modules.Module) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) Utils(net.kodehawa.mantarobot.utils.Utils) Random(java.util.Random) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) Message(net.dv8tion.jda.core.entities.Message) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) JSONObject(org.json.JSONObject) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Map(java.util.Map) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) SimpleFileDataManager(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Role(net.dv8tion.jda.core.entities.Role) PollBuilder(net.kodehawa.mantarobot.commands.interaction.polls.PollBuilder) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Slf4j(lombok.extern.slf4j.Slf4j) DataManager(net.kodehawa.mantarobot.utils.data.DataManager) URLEncoder(java.net.URLEncoder) List(java.util.List) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild)

Aggregations

PermissionException (net.dv8tion.jda.core.exceptions.PermissionException)21 Permission (net.dv8tion.jda.core.Permission)8 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)8 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)7 Slf4j (lombok.extern.slf4j.Slf4j)6 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)6 BotException (tk.ardentbot.core.misc.logging.BotException)6 Subscribe (com.google.common.eventbus.Subscribe)5 Random (java.util.Random)5 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)5 MantaroData (net.kodehawa.mantarobot.data.MantaroData)5 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)5 List (java.util.List)4 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)4 Module (net.kodehawa.mantarobot.core.modules.Module)4 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)4 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)4 Utils (net.kodehawa.mantarobot.utils.Utils)4 Date (java.util.Date)3 Message (net.dv8tion.jda.core.entities.Message)3