net.dv8tion.jda.api.exceptions.PermissionException Java Examples

The following examples show how to use net.dv8tion.jda.api.exceptions.PermissionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MemberListener.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the autorole to the specified member.
 * @param member The member.
 */
private void assignAutoRole(Member member) {
    Guild guild = member.getGuild();
    long guildId = guild.getIdLong();
    GuildEntry entry = (GuildEntry) Category.GUILD.getEntry();
    boolean apply = Boolean.valueOf(entry.fetch(entry.getField(GuildEntry.Fields.AUTOROLE_ENABLED), guildId, null));
    if(!apply) {
        return;
    }
    String roleId = entry.fetch(entry.getField(GuildEntry.Fields.AUTOROLE_ROLE), guildId, null);
    Role role = guild.getRoleById(roleId);
    if(role == null) {
        return;
    }
    try {
        guild.addRoleToMember(member, role).queue();
    } catch(PermissionException exception) {
        logger.warn("Could not apply the autorole in the guild {} due to a permission error.", guildId);
    }
}
 
Example #2
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public AuditableRestAction<Void> transferOwnership(@Nonnull Member newOwner)
{
    Checks.notNull(newOwner, "Member");
    checkGuild(newOwner.getGuild(), "Member");
    if (!getSelfMember().isOwner())
        throw new PermissionException("The logged in account must be the owner of this Guild to be able to transfer ownership");

    Checks.check(!getSelfMember().equals(newOwner),
                 "The member provided as the newOwner is the currently logged in account. Provide a different member to give ownership to.");

    Checks.check(!newOwner.getUser().isBot(), "Cannot transfer ownership of a Guild to a Bot!");

    DataObject body = DataObject.empty().put("owner_id", newOwner.getUser().getId());
    Route.CompiledRoute route = Route.Guilds.MODIFY_GUILD.compile(getId());
    return new AuditableRestActionImpl<>(getJDA(), route, body);
}
 
Example #3
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> delete(String mfaCode)
{
    if (!getSelfMember().isOwner())
        throw new PermissionException("Cannot delete a guild that you do not own!");

    DataObject mfaBody = null;
    if (!getJDA().getSelfUser().isBot() && getJDA().getSelfUser().isMfaEnabled())
    {
        Checks.notEmpty(mfaCode, "Provided MultiFactor Auth code");
        mfaBody = DataObject.empty().put("code", mfaCode);
    }

    Route.CompiledRoute route = Route.Guilds.DELETE_GUILD.compile(getId());
    return new RestActionImpl<>(getJDA(), route, mfaBody);
}
 
Example #4
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public static void banMember(Member member, int daysOfMessagesToDelete) {
    if (member == null) {
        DiscordSRV.debug("Attempted to ban null member");
        return;
    }

    daysOfMessagesToDelete = Math.abs(daysOfMessagesToDelete);

    try {
        member.ban(daysOfMessagesToDelete).queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Failed to ban " + member + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Failed to ban " + member + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #5
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public static void setNickname(Member member, String nickname) {
    if (member == null) {
        DiscordSRV.debug("Can't set nickname of null member");
        return;
    }

    if (!member.getGuild().getSelfMember().canInteract(member)) {
        DiscordSRV.debug("Not setting " + member + "'s nickname because we can't interact with them");
        return;
    }

    if (nickname != null && nickname.equals(member.getNickname())) {
        DiscordSRV.debug("Not setting " + member + "'s nickname because it wouldn't change");
        return;
    }

    try {
        member.modifyNickname(nickname).queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not set nickname for " + member + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not set nickname for " + member + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #6
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public static void removeRolesFromMember(Member member, Role... roles) {
    if (member == null) {
        DiscordSRV.debug("Can't remove roles from null member");
        return;
    }

    List<Role> rolesToRemove = Arrays.stream(roles)
            .filter(role -> !role.isManaged())
            .filter(role -> !role.getGuild().getPublicRole().getId().equals(role.getId()))
            .collect(Collectors.toList());

    try {
        member.getGuild().modifyMemberRoles(member, Collections.emptySet(), rolesToRemove).queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not demote " + member + " from role(s) " + rolesToRemove + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not demote " + member + " from role(s) " + rolesToRemove + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #7
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public static void addRolesToMember(Member member, Role... roles) {
    if (member == null) {
        DiscordSRV.debug("Can't add roles to null member");
        return;
    }

    List<Role> rolesToAdd = Arrays.stream(roles)
            .filter(role -> !role.isManaged())
            .filter(role -> !role.getGuild().getPublicRole().getId().equals(role.getId()))
            .collect(Collectors.toList());

    try {
        member.getGuild().modifyMemberRoles(member, rolesToAdd, Collections.emptySet()).queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not add " + member + " to role(s) " + rolesToAdd + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not add " + member + " to role(s) " + rolesToAdd + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #8
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public static void addRoleToMember(Member member, Role role) {
    if (member == null) {
        DiscordSRV.debug("Can't add role to null member");
        return;
    }

    try {
        member.getGuild().addRoleToMember(member, role).queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not add " + member + " to role " + role + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not add " + member + " to role " + role + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #9
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Set the topic message of the given channel
 * @param channel The channel to set the topic of
 * @param topic The new topic to be set
 */
public static void setTextChannelTopic(TextChannel channel, String topic) {
    if (channel == null) {
        DiscordSRV.debug("Attempted to set status of null channel");
        return;
    }

    try {
        channel.getManager().setTopic(topic).queue();
    } catch (Exception e) {
        if (e instanceof PermissionException) {
            PermissionException pe = (PermissionException) e;
            if (pe.getPermission() != Permission.UNKNOWN) {
                DiscordSRV.warning("Could not set topic of channel " + channel + " because the bot does not have the \"" + pe.getPermission().getName() + "\" permission");
            }
        } else {
            DiscordSRV.warning("Could not set topic of channel " + channel + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #10
Source File: UPunishment.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Applies or removes the muted role to the specified user.
 * This method is used to permanently mute.
 * @param guild The guild.
 * @param punishedId The ID of the muted user.
 * @param apply True: adds role, false: removes role.
 * @return A pair of success and whether the punishment needs to be revoked.
 */
private static Pair<Boolean, Boolean> manageMute(Guild guild, long punishedId, boolean apply) {
    GuildEntry entry = (GuildEntry) Category.GUILD.getEntry();
    String mutedRoleId = entry.fetch(entry.getField(GuildEntry.Fields.MUTE_ROLE), guild.getIdLong(), null);
    Member muted = guild.getMemberById(punishedId);
    Role mutedRole = guild.getRoleById(mutedRoleId);
    if(muted == null
            || mutedRole == null) {
        return new Pair<>(false, false);
    }
    try {
        if(apply) {
            guild.addRoleToMember(muted, mutedRole).queue();
        } else {
            guild.removeRoleFromMember(muted, mutedRole).queue();
        }
        return new Pair<>(true, false);
    } catch(PermissionException exception) {
        return new Pair<>(false, false);
    }
}
 
Example #11
Source File: MiscCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void iamFunction(String autoroleName, Context ctx, String message) {
    DBGuild dbGuild = ctx.getDBGuild();
    Map<String, String> autoroles = dbGuild.getData().getAutoroles();

    if (autoroles.containsKey(autoroleName)) {
        Role role = ctx.getGuild().getRoleById(autoroles.get(autoroleName));
        if (role == null) {
            ctx.sendLocalized("commands.iam.deleted_role", EmoteReference.ERROR);

            //delete the non-existent autorole.
            dbGuild.getData().getAutoroles().remove(autoroleName);
            dbGuild.saveAsync();
        } else {
            if (ctx.getMember().getRoles().stream().anyMatch(r1 -> r1.getId().equals(role.getId()))) {
                ctx.sendLocalized("commands.iam.already_assigned", EmoteReference.ERROR);
                return;
            }
            try {
                ctx.getGuild().addRoleToMember(ctx.getMember(), role)
                        //don't translate the reason!
                        .reason("Auto-assignable roles assigner (~>iam)")
                        .queue(aVoid -> {
                            if (message == null || message.isEmpty())
                                ctx.sendLocalized("commands.iam.success", EmoteReference.OK, ctx.getAuthor().getName(), role.getName());
                            else
                                //Simple stuff for custom commands. (iamcustom:)
                                ctx.sendStripped(message);
                        });
            } catch (PermissionException pex) {
                ctx.sendLocalized("commands.iam.error", EmoteReference.ERROR, role.getName());
            }
        }
    } else {
        ctx.sendStrippedLocalized("commands.iam.no_role", EmoteReference.ERROR, autoroleName);
    }
}
 
Example #12
Source File: MiscCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void iamnotFunction(String autoroleName, Context ctx, String message) {
    DBGuild dbGuild = ctx.getDBGuild();
    Map<String, String> autoroles = dbGuild.getData().getAutoroles();

    if (autoroles.containsKey(autoroleName)) {
        Role role = ctx.getGuild().getRoleById(autoroles.get(autoroleName));
        if (role == null) {
            ctx.sendLocalized("commands.iam.deleted_role", EmoteReference.ERROR);

            //delete the non-existent autorole.
            dbGuild.getData().getAutoroles().remove(autoroleName);
            dbGuild.saveAsync();
        } else {
            if (ctx.getMember().getRoles().stream().noneMatch(r1 -> r1.getId().equals(role.getId()))) {
                ctx.sendLocalized("commands.iamnot.not_assigned", EmoteReference.ERROR);
                return;
            }

            try {
                ctx.getGuild().removeRoleFromMember(ctx.getMember(), role)
                        .queue(aVoid -> {
                            if (message == null || message.isEmpty())
                                ctx.sendLocalized("commands.iamnot.success", EmoteReference.OK, ctx.getAuthor().getName(), role.getName());
                            else
                                ctx.sendStrippedLocalized(message);
                        });
            } catch (PermissionException pex) {
                ctx.sendLocalized("commands.iam.error", EmoteReference.ERROR, role.getName());
            }
        }
    } else {
        ctx.sendStrippedLocalized("commands.iam.no_role", EmoteReference.ERROR, autoroleName);
    }
}
 
Example #13
Source File: MessageCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private void prune(Context ctx, List<Message> messageHistory) {
    messageHistory = messageHistory.stream().filter(message -> !message.getTimeCreated()
            .isBefore(OffsetDateTime.now().minusWeeks(2)))
            .collect(Collectors.toList());

    if (messageHistory.isEmpty()) {
        ctx.sendLocalized("commands.prune.messages_too_old", EmoteReference.ERROR);
        return;
    }

    final int size = messageHistory.size();

    if (messageHistory.size() < 3) {
        ctx.sendLocalized("commands.prune.too_few_messages", EmoteReference.ERROR);
        return;
    }

    ctx.getChannel().deleteMessages(messageHistory).queue(
            success -> {
                ctx.sendLocalized("commands.prune.success", EmoteReference.PENCIL, size);

                DBGuild db = ctx.getDBGuild();
                db.getData().setCases(db.getData().getCases() + 1);
                db.saveAsync();
                ModLog.log(ctx.getMember(), null, "Pruned Messages",
                        ctx.getChannel().getName(), ModLog.ModAction.PRUNE, db.getData().getCases(), size
                );
            },
            error -> {
                if (error instanceof PermissionException) {
                    PermissionException pe = (PermissionException) error;
                    ctx.sendLocalized("commands.prune.lack_perms", EmoteReference.ERROR, pe.getPermission());
                } else {
                    ctx.sendLocalized("commands.prune.error_deleting", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
                    error.printStackTrace();
                }
            }
    );
}
 
Example #14
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Send the given message to the given channel, blocking the thread's execution until it's successfully sent then returning it
 * @param channel The channel to send the message to
 * @param message The message to send to the channel
 * @return The sent message
 */
public static Message sendMessageBlocking(TextChannel channel, Message message) {
    if (getJda() == null) {
        DiscordSRV.debug("Tried sending a message when JDA was null");
        return null;
    }

    if (channel == null) {
        DiscordSRV.debug("Tried sending a message to a null channel");
        return null;
    }

    if (message == null || StringUtils.isBlank(message.getContentRaw())) {
        DiscordSRV.debug("Tried sending a null or blank message");
        return null;
    }

    Message sentMessage;
    try {
        sentMessage = channel.sendMessage(message).complete();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not send message in channel " + channel + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not send message in channel " + channel + " because \"" + e.getMessage() + "\"");
        }
        return null;
    }
    DiscordSRV.api.callEvent(new DiscordGuildMessageSentEvent(getJda(), sentMessage));

    return sentMessage;
}
 
Example #15
Source File: DiscordUtil.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Delete the given message, given the bot has permission to
 * @param message The message to delete
 */
public static void deleteMessage(Message message) {
    if (message.isFromType(ChannelType.PRIVATE)) return;

    try {
        message.delete().queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            DiscordSRV.warning("Could not delete message in channel " + message.getTextChannel() + " because the bot does not have the \"" + e.getPermission().getName() + "\" permission");
        } else {
            DiscordSRV.warning("Could not delete message in channel " + message.getTextChannel() + " because \"" + e.getMessage() + "\"");
        }
    }
}
 
Example #16
Source File: UPunishment.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Unbans a user.
 * @param guild The guild.
 * @param punishedId The ID of the punished user.
 * @return True if the unban was successful, false otherwise.
 */
public static boolean unban(Guild guild, long punishedId) {
    if(!isBan(guild, punishedId)) {
        return true;
    }
    try {
        guild.unban(String.valueOf(punishedId)).queue();
        return true;
    } catch(PermissionException exception) {
        return false;
    }
}
 
Example #17
Source File: UPunishment.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Bans a user.
 * @param guild The guild.
 * @param punishedId The ID of the punished user.
 * @param reason The reason for the ban.
 * @return A pair of success and whether the punishment needs to be revoked.
 */
public static Pair<Boolean, Boolean> ban(Guild guild, long punishedId, String reason) {
    try {
        guild.ban(String.valueOf(punishedId), 0, reason).queue();
        return new Pair<>(true, false);
    } catch(PermissionException exception) {
        return new Pair<>(false, false);
    }
}
 
Example #18
Source File: KickPunishment.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Kicks the user.
 * @param guild The guild where the punishment is to occur.
 * @param punishedId The ID of the punished user.
 * @param reason The reason for the punishment.
 * @return A pair of success and whether the punishment needs to be revoked.
 */
@Override
public Pair<Boolean, Boolean> punish(Guild guild, long punishedId, String reason) {
    try {
        guild.kick(String.valueOf(punishedId), reason).queue();
        return new Pair<>(true, false);
    } catch(PermissionException | IllegalArgumentException exception) {
        return new Pair<>(false, false);
    }
}
 
Example #19
Source File: ChatSoundBoardListener.java    From DiscordSoundboard with Apache License 2.0 5 votes vote down vote up
private void deleteMessage(MessageReceivedEvent event) {
    if (!event.isFromType(ChannelType.PRIVATE)) {
        try {
            event.getMessage().delete().queue();
        } catch (PermissionException e) {
            LOG.warn("Unable to delete message");
        }
    }
}
 
Example #20
Source File: SoftBanPunishment.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Softbans the user.
 * @param guild The guild where the punishment is to occur.
 * @param punishedId The ID of the punished user.
 * @param reason The reason for the punishment.
 * @return A pair of success and whether the punishment needs to be revoked.
 */
@Override
public Pair<Boolean, Boolean> punish(Guild guild, long punishedId, String reason) {
    try {
        String id = String.valueOf(punishedId);
        guild.ban(id, 1, reason).queue(done -> guild.unban(id).queue());
        return new Pair<>(true, false);
    } catch(PermissionException | IllegalArgumentException exception) {
        return new Pair<>(false, false);
    }
}
 
Example #21
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> void sendMessageSilentQueue(Function<T, RestAction<Message>> action, T embed,
                                       Consumer<Message> messageConsumer) {
    try {
        action.apply(embed).queue(messageConsumer);
    } catch (PermissionException e) {
        // we don't care about it, this is why it is silent
    }
}
 
Example #22
Source File: MantaroListener.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
private void logDelete(GuildMessageDeleteEvent event) {
    try {
        String hour = df.format(new Date(System.currentTimeMillis()));
        final ManagedDatabase db = MantaroData.db();

        final DBGuild dbGuild = db.getGuild(event.getGuild());
        final GuildData data = dbGuild.getData();

        String logChannel = data.getGuildLogChannel();
        if (logChannel != null) {
            TextChannel tc = event.getGuild().getTextChannelById(logChannel);
            if (tc == null)
                return;

            CachedMessage deletedMessage = messageCache.get(event.getMessageIdLong(), Optional::empty).orElse(null);
            if (deletedMessage != null && !deletedMessage.getContent().isEmpty() && !event.getChannel().getId().equals(logChannel) && !deletedMessage.getAuthor().getId().equals(event.getJDA().getSelfUser().getId())) {
                if (data.getModlogBlacklistedPeople().contains(deletedMessage.getAuthor().getId())) {
                    return;
                }

                if (data.getLogExcludedChannels().contains(event.getChannel().getId())) {
                    return;
                }

                if (!data.getModLogBlacklistWords().isEmpty()) {
                    //This is not efficient at all I'm pretty sure, is there a better way?
                    List<String> splitMessage = Arrays.asList(deletedMessage.getContent().split("\\s+"));
                    if (data.getModLogBlacklistWords().stream().anyMatch(splitMessage::contains)) {
                        return;
                    }
                }

                String message;
                if (data.getDeleteMessageLog() != null) {
                    message = new DynamicModifiers()
                            .set("hour", hour)
                            .set("content", deletedMessage.getContent().replace("```", ""))
                            .mapEvent("event", event)
                            .mapChannel("event.channel", event.getChannel())
                            .mapUser("event.user", deletedMessage.getAuthor())
                            .set("event.message.id", event.getMessageId())
                            .resolve(data.getDeleteMessageLog());
                } else {
                    message = String.format(EmoteReference.WARNING + "`[%s]` Message (ID: %s) created by **%s#%s** (ID: %s) in channel **%s** was deleted.\n" +
                            "```diff\n-%s```", hour, event.getMessageId(), deletedMessage.getAuthor().getName(), deletedMessage.getAuthor().getDiscriminator(), deletedMessage.getAuthor().getId(), event.getChannel().getName(), deletedMessage.getContent().replace("```", ""));
                }

                logTotal++;
                tc.sendMessage(message).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);
        }
    }
}
 
Example #23
Source File: MantaroListener.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
private void logEdit(GuildMessageUpdateEvent event) {
    try {
        String hour = df.format(new Date(System.currentTimeMillis()));
        final ManagedDatabase db = MantaroData.db();
        final GuildData guildData = db.getGuild(event.getGuild()).getData();
        String logChannel = guildData.getGuildLogChannel();

        if (logChannel != null) {
            TextChannel tc = event.getGuild().getTextChannelById(logChannel);
            if (tc == null)
                return;

            User author = event.getAuthor();
            CachedMessage editedMessage = messageCache.get(event.getMessage().getIdLong(), Optional::empty).orElse(null);

            if (editedMessage != null && !editedMessage.getContent().isEmpty() && !event.getChannel().getId().equals(logChannel)) {
                //Update message in cache in any case.
                messageCache.put(event.getMessage().getIdLong(), Optional.of(new CachedMessage(event.getAuthor().getIdLong(), event.getMessage().getContentDisplay())));

                if (guildData.getLogExcludedChannels().contains(event.getChannel().getId())) {
                    return;
                }

                if (guildData.getModlogBlacklistedPeople().contains(editedMessage.getAuthor().getId())) {
                    return;
                }

                //Don't log if content is equal but update in cache (cc: message is still relevant).
                if (event.getMessage().getContentDisplay().equals(editedMessage.getContent()))
                    return;

                if (!guildData.getModLogBlacklistWords().isEmpty()) {
                    //This is not efficient at all I'm pretty sure, is there a better way?
                    List<String> splitMessage = Arrays.asList(editedMessage.getContent().split("\\s+"));
                    if (guildData.getModLogBlacklistWords().stream().anyMatch(splitMessage::contains)) {
                        return;
                    }
                }

                String message;
                if (guildData.getEditMessageLog() != null) {
                    message = new DynamicModifiers()
                            .set("hour", hour)
                            .set("old", editedMessage.getContent().replace("```", ""))
                            .set("new", event.getMessage().getContentDisplay().replace("```", ""))
                            .mapEvent("event", event)
                            .mapChannel("event.channel", event.getChannel())
                            .mapUser("event.user", editedMessage.getAuthor())
                            .mapMessage("event.message", event.getMessage())
                            .resolve(guildData.getEditMessageLog());
                } else {
                    message = String.format(EmoteReference.WARNING + "`[%s]` Message (ID: %s) created by **%s#%s** in channel **%s** was modified.\n```diff\n-%s\n+%s```",
                            hour, event.getMessage().getId(), author.getName(), author.getDiscriminator(), event.getChannel().getName(), editedMessage.getContent().replace("```", ""), event.getMessage().getContentDisplay().replace("```", ""));
                }

                tc.sendMessage(message).queue();

                logTotal++;
            }
        }
    } catch (Exception e) {
        if (!(e instanceof NullPointerException) && !(e instanceof IllegalArgumentException) && !(e instanceof CacheLoader.InvalidCacheLoadException) && !(e instanceof PermissionException)) {
            log.warn("Unexpected error while logging a edit.", e);
        }
    }
}
 
Example #24
Source File: ModerationCmds.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void kick(CommandRegistry cr) {
    cr.register("kick", new SimpleCommand(CommandCategory.MODERATION) {
        @Override
        protected void call(Context ctx, String content, String[] args) {
            Guild guild = ctx.getGuild();
            User author = ctx.getAuthor();

            Message receivedMessage = ctx.getMessage();
            String reason = content;

            if (args.length == 0) {
                ctx.sendLocalized("commands.kick.no_users", EmoteReference.ERROR);
                return;
            }

            if (!ctx.getMember().hasPermission(Permission.KICK_MEMBERS)) {
                ctx.sendLocalized("commands.kick.no_permission", EmoteReference.ERROR2);
                return;
            }

            Member selfMember = guild.getSelfMember();

            if (!selfMember.hasPermission(Permission.KICK_MEMBERS)) {
                ctx.sendLocalized("commands.kick.no_permission_self", EmoteReference.ERROR2);
                return;
            }

            if (args.length > 1) {
                reason = StringUtils.splitArgs(content, 2)[1];
            }

            if (reason.isEmpty()) {
                reason = "Reason not specified";
            }

            final String finalReason = String.format("Kicked by %#s: %s", ctx.getAuthor(), reason);
            Member member = Utils.findMember(ctx.getEvent(), ctx.getMember(), args[0]);
            if (member == null)
                return;

            User user = member.getUser();

            if (!ctx.getMember().canInteract(member)) {
                ctx.sendLocalized("commands.kick.hierarchy_conflict", EmoteReference.ERROR);
                return;
            }

            if (ctx.getAuthor().getId().equals(user.getId())) {
                ctx.sendLocalized("commands.kick.yourself_note", EmoteReference.ERROR);
                return;
            }

            //If one of them is in a higher hierarchy than the bot, cannot kick.
            if (!selfMember.canInteract(member)) {
                ctx.sendLocalized("commands.kick.self_hierarchy_conflict", EmoteReference.ERROR2, user.getName());
                return;
            }
            final DBGuild db = MantaroData.db().getGuild(ctx.getGuild());

            guild.kick(member).reason(finalReason).queue(
                    success -> {
                        if (!user.isBot()) {
                            user.openPrivateChannel()
                                    .flatMap(privateChannel ->
                                            privateChannel.sendMessage(String.format("%sYou were **kicked** by %s#%s with reason: %s on server **%s**.",
                                            EmoteReference.MEGA, ctx.getAuthor().getName(), ctx.getAuthor().getDiscriminator(), finalReason, ctx.getGuild().getName()))
                                    ).queue();
                        }

                        db.getData().setCases(db.getData().getCases() + 1);
                        db.saveAsync();

                        ctx.sendLocalized("commands.kick.success", EmoteReference.ZAP, ctx.getLanguageContext().get("general.mod_quotes"), user.getName());
                        ModLog.log(ctx.getMember(), user, finalReason, ctx.getChannel().getName(), ModLog.ModAction.KICK, db.getData().getCases());
                        TextChannelGround.of(ctx.getEvent()).dropItemWithChance(2, 2);
                    },
                    error -> {
                        if (error instanceof PermissionException) {
                            ctx.sendLocalized("commands.kick.error", EmoteReference.ERROR, user.getName(), ((PermissionException) error).getPermission().getName());
                        } else {
                            ctx.sendLocalized("commands.kick.unknown_error", EmoteReference.ERROR, user.getName());
                            log.warn("Unexpected error while kicking someone.", error);
                        }
                    }
            );
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder()
                    .setDescription("Kicks the mentioned user.")
                    .setUsage("`~>kick <@user> [reason]`")
                    .addParameter("@user", "The user to kick.")
                    .addParameter("reason", "The reason of the kick. This is optional.")
                    .build();
        }
    });
}
 
Example #25
Source File: UPunishment.java    From Arraybot with Apache License 2.0 2 votes vote down vote up
/**
 * Checks whether the specified member is banned in the guild.
 * @param guild The guild.
 * @param user The user.
 * @return True if they are, false otherwise.
 * @throws PermissionException If the bot has no permissions.
 */
public static boolean isBan(Guild guild, long user)
        throws PermissionException {
    return PermissionUtil.checkPermission(guild.getSelfMember(), Permission.BAN_MEMBERS) && guild.retrieveBanList().complete().stream().anyMatch(ban -> ban.getUser().getIdLong() == user);
}