Java Code Examples for net.dv8tion.jda.api.entities.Member#hasPermission()

The following examples show how to use net.dv8tion.jda.api.entities.Member#hasPermission() . 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: CheckOwnerQueueListener.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@RabbitListener(queues = RabbitConfiguration.QUEUE_CHECK_OWNER_REQUEST)
public boolean isAdministrator(CheckOwnerRequest request) {
    Guild guild = null;
    switch (request.getType()) {
        case TEXT:
            TextChannel textChannel = discordService.getTextChannelById(request.getChannelId());
            if (textChannel != null) {
                guild = textChannel.getGuild();
            }
            break;
        case VOICE:
            VoiceChannel voiceChannel = discordService.getVoiceChannelById(request.getChannelId());
            if (voiceChannel != null) {
                guild = voiceChannel.getGuild();
            }
            break;
    }
    if (guild == null) {
        return true;
    }
    Member member = guild.getMemberById(request.getUserId());
    if (member == null) {
        return false;
    }
    return member.isOwner() || member.hasPermission(Permission.ADMINISTRATOR);
}
 
Example 2
Source File: ChannelOrderActionImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody finalizeData()
{
    final Member self = guild.getSelfMember();
    if (!self.hasPermission(Permission.MANAGE_CHANNEL))
        throw new InsufficientPermissionException(guild, Permission.MANAGE_CHANNEL);
    DataArray array = DataArray.empty();
    for (int i = 0; i < orderList.size(); i++)
    {
        GuildChannel chan = orderList.get(i);
        array.add(DataObject.empty()
                .put("id", chan.getId())
                .put("position", i));
    }

    return getRequestBody(array);
}
 
Example 3
Source File: JdaLink.java    From Lavalink-Client with MIT License 5 votes vote down vote up
/**
 * Eventually connect to a channel. Takes care of disconnecting from an existing connection
 *
 * @param channel Channel to connect to
 */
@SuppressWarnings("WeakerAccess")
void connect(VoiceChannel channel, boolean checkChannel) {
    if (!channel.getGuild().equals(getJda().getGuildById(guild)))
        throw new IllegalArgumentException("The provided VoiceChannel is not a part of the Guild that this AudioManager handles." +
                "Please provide a VoiceChannel from the proper Guild");
    if (channel.getJDA().isUnavailable(channel.getGuild().getIdLong()))
        throw new GuildUnavailableException("Cannot open an Audio Connection with an unavailable guild. " +
                "Please wait until this Guild is available to open a connection.");
    final Member self = channel.getGuild().getSelfMember();
    if (!self.hasPermission(channel, Permission.VOICE_CONNECT) && !self.hasPermission(channel, Permission.VOICE_MOVE_OTHERS))
        throw new InsufficientPermissionException(channel, Permission.VOICE_CONNECT);

    //If we are already connected to this VoiceChannel, then do nothing.
    if (checkChannel && channel.equals(channel.getGuild().getSelfMember().getVoiceState().getChannel()))
        return;

    if (channel.getGuild().getSelfMember().getVoiceState().inVoiceChannel()) {
        final int userLimit = channel.getUserLimit(); // userLimit is 0 if no limit is set!
        if (!self.isOwner() && !self.hasPermission(Permission.ADMINISTRATOR)) {
            if (userLimit > 0                                                      // If there is a userlimit
                    && userLimit <= channel.getMembers().size()                    // if that userlimit is reached
                    && !self.hasPermission(channel, Permission.VOICE_MOVE_OTHERS)) // If we don't have voice move others permissions
                throw new InsufficientPermissionException(channel, Permission.VOICE_MOVE_OTHERS, // then throw exception!
                        "Unable to connect to VoiceChannel due to userlimit! Requires permission VOICE_MOVE_OTHERS to bypass");
        }
    }

    setState(State.CONNECTING);
    queueAudioConnect(channel.getIdLong());
}
 
Example 4
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public boolean hasAccess(Member member) {
    MusicConfig config = musicConfigService.get(member.getGuild());
    return config == null
            || CollectionUtils.isEmpty(config.getRoles())
            || member.isOwner()
            || member.hasPermission(Permission.ADMINISTRATOR)
            || member.getRoles().stream().anyMatch(e -> config.getRoles().contains(e.getIdLong()));
}
 
Example 5
Source File: MafiaFilter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void doInternal(GuildMessageReceivedEvent event, FilterChain<GuildMessageReceivedEvent> chain) {
    MafiaInstance instance = mafiaService.getRelatedInstance(event.getChannel().getIdLong());
    if (instance != null && !instance.isInState(MafiaState.FINISH)) {
        boolean isPlayer = instance.isPlayer(event.getAuthor());
        if (isPlayer) {
            instance.tick();
        }

        Member selfMember = event.getGuild().getSelfMember();
        if (!event.getMember().equals(selfMember)
                && !instance.isInState(MafiaState.CHOOSING)
                && !Objects.equals(event.getChannel().getIdLong(), instance.getGoonChannelId())
                && selfMember.hasPermission(event.getChannel(), Permission.MESSAGE_MANAGE)) {
            if (instance.isInState(MafiaState.DAY)) {
                if (!isPlayer) {
                    messageService.delete(event.getMessage());
                    return;
                }
            } else {
                messageService.delete(event.getMessage());
                return;
            }
        }
    }
    chain.doFilter(event);
}
 
Example 6
Source File: ModerationServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public boolean isModerator(Member member) {
    if (member == null) {
        return false;
    }
    if (member.hasPermission(Permission.ADMINISTRATOR) || member.isOwner()) {
        return true;
    }
    ModerationConfig config = moderationConfigService.get(member.getGuild());
    return config != null && CollectionUtils.isNotEmpty(config.getRoles())
            && member.getRoles().stream().anyMatch(e -> config.getRoles().contains(e.getIdLong()));
}
 
Example 7
Source File: RoleManagerImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean checkPermissions()
{
    Member selfMember = getGuild().getSelfMember();
    if (!selfMember.hasPermission(Permission.MANAGE_ROLES))
        throw new InsufficientPermissionException(getGuild(), Permission.MANAGE_ROLES);
    if (!selfMember.canInteract(getRole()))
        throw new HierarchyException("Cannot modify a role that is higher or equal in hierarchy");
    return super.checkPermissions();
}
 
Example 8
Source File: RoleOrderActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestBody finalizeData()
{
    final Member self = guild.getSelfMember();
    final boolean isOwner = self.isOwner();

    if (!isOwner)
    {
        if (self.getRoles().isEmpty())
            throw new IllegalStateException("Cannot move roles above your highest role unless you are the guild owner");
        if (!self.hasPermission(Permission.MANAGE_ROLES))
            throw new InsufficientPermissionException(guild, Permission.MANAGE_ROLES);
    }

    DataArray array = DataArray.empty();
    List<Role> ordering = new ArrayList<>(orderList);

    //If not in normal discord order, reverse.
    // Normal order is descending, not ascending.
    if (ascendingOrder)
        Collections.reverse(ordering);

    for (int i = 0; i < ordering.size(); i++)
    {
        Role role = ordering.get(i);
        final int initialPos = role.getPosition();
        if (initialPos != i && !isOwner && !self.canInteract(role))
            // If the current role was moved, we are not owner and we can't interact with the role then throw a PermissionException
            throw new IllegalStateException("Cannot change order: One of the roles could not be moved due to hierarchical power!");

        array.add(DataObject.empty()
                .put("id", role.getId())
                .put("position", i + 1)); //plus 1 because position 0 is the @everyone position.
    }

    return getRequestBody(array);
}
 
Example 9
Source File: CommandReactionListener.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onGenericGuildMessageReaction(@Nonnull GenericGuildMessageReactionEvent event) {
    Guild guild = event.getGuild();
    Member self = guild.getSelfMember();

    if (event.getUser().isBot()
            || !self.hasPermission(Permission.MANAGE_ROLES)
            || !featureSetService.isAvailable(guild)) {
        return;
    }

    CommandReaction reaction = reactionRepository.findByMessageId(event.getMessageIdLong());
    if (reaction == null) {
        return;
    }
    CustomCommand customCommand = reaction.getCommand();
    if (CollectionUtils.isEmpty(customCommand.getEmojiRoles())) {
        return;
    }

    EmojiRole emojiRole = customCommand.getEmojiRoles().stream()
            .filter(e -> {
                if (StringUtils.isEmpty(e.getEmoji()) || StringUtils.isEmpty(e.getRoleId())) {
                    return false;
                }
                return e.getEmoji().equals(event.getReactionEmote().isEmoji()
                        ? event.getReactionEmote().getName()
                        : event.getReactionEmote().getId());
            })
            .findFirst()
            .orElse(null);

    if (emojiRole == null) {
        return;
    }

    Role targetRole = guild.getRoleById(emojiRole.getRoleId());
    if (targetRole == null || !self.canInteract(targetRole)) {
        return;
    }

    Member issuer = guild.getMember(event.getUser());
    if (issuer == null) {
        return; // FIXME for some reason member can be null here
    }
    if (event instanceof GuildMessageReactionAddEvent) {
        guild.addRoleToMember(issuer, targetRole).queue();
    } else {
        guild.removeRoleFromMember(issuer, targetRole).queue();
    }
}
 
Example 10
Source File: LoggingAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
public void send(AuditConfig config, AuditAction action, Map<String, byte[]> attachments) {
    Class<?> clazz = this.getClass();
    if (config.getForwardChannelId() == null
            || !config.isForwardEnabled()
            || CollectionUtils.isEmpty(config.getForwardActions())
            || !config.getForwardActions().contains(action.getActionType())
            || !clazz.isAnnotationPresent(ForwardProvider.class)
            || clazz.getAnnotation(ForwardProvider.class).value() != action.getActionType()) {
        return;
    }
    if (!discordService.isConnected(action.getGuildId())) {
        return;
    }
    Guild guild = discordService.getGuildById(action.getGuildId());
    if (guild == null) {
        return;
    }
    Member self = guild.getSelfMember();
    TextChannel channel = guild.getTextChannelById(config.getForwardChannelId());
    if (channel == null || !self.hasPermission(channel, Permission.MESSAGE_WRITE, Permission.MESSAGE_EMBED_LINKS)) {
        return;
    }

    contextService.withContext(guild, () -> {
        EmbedBuilder embedBuilder = messageService.getBaseEmbed();
        MessageBuilder messageBuilder = new MessageBuilder();
        build(action, messageBuilder, embedBuilder);
        if (!embedBuilder.isEmpty()) {
            embedBuilder.setTimestamp(Instant.now());
            if (action.getActionType().getColor() != null) {
                embedBuilder.setColor(action.getActionType().getColor());
            }
            messageBuilder.setEmbed(embedBuilder.build());
        }
        if (!messageBuilder.isEmpty()) {
            MessageAction messageAction = channel.sendMessage(messageBuilder.build());
            if (attachments != null && self.hasPermission(channel, Permission.MESSAGE_ATTACH_FILES)) {
                for (Map.Entry<String, byte[]> entry : attachments.entrySet()) {
                    messageAction.addFile(entry.getValue(), entry.getKey());
                }
            }
            messageAction.queue();
        }
    });
}
 
Example 11
Source File: ModerationServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
public boolean performAction(ModerationActionRequest request) {
    Guild guild = request.getGuild();
    String guildId = guild.getId();
    Member self = guild.getSelfMember();
    if (request.getModerator() != null) {
        String memberKey = DiscordUtils.getMemberKey(guild, request.getViolatorId());
        lastActionCache.put(memberKey, request);
    }
    switch (request.getType()) {
        case MUTE:
            // to prevent circular injection. Yeah bad practice but still we need this
            return applicationContext.getBean(MuteService.class).mute(request);
        case BAN:
            if (!self.hasPermission(Permission.BAN_MEMBERS)) {
                return false;
            }
            final int delDays = request.getDelDays() != null ? request.getDelDays() : 0;
            if (request.getViolator() != null) {
                if (self.canInteract(request.getViolator())) {
                    notifyUserAction(e -> {
                        e.getGuild().ban(e, delDays, request.getReason()).queue(e2 ->
                                scheduleUnBan(guildId, request.getViolatorId(), request.getDurationDate()));
                    }, request.getViolator(), "discord.command.mod.action.message.ban", request.getReason(),
                            request.getDuration());
                    return true;
                }
            } else if (request.getViolatorId() != null) {
                guild.ban(request.getViolatorId(), delDays, request.getReason()).queue(e2 ->
                        scheduleUnBan(guildId, request.getViolatorId(), request.getDurationDate()));
                return true;
            }
            return false;
        case KICK:
            if (!self.hasPermission(Permission.KICK_MEMBERS) || !self.canInteract(request.getViolator())) {
                return false;
            }
            AuditActionBuilder actionBuilder = auditService
                    .log(self.getGuild(), AuditActionType.MEMBER_KICK)
                    .withUser(request.getModerator())
                    .withTargetUser(request.getViolator())
                    .withAttribute(REASON_ATTR, request.getReason());

            notifyUserAction(e -> {
                actionBuilder.save();
                actionsHolderService.setLeaveNotified(e.getGuild().getIdLong(), e.getUser().getIdLong());
                e.getGuild().kick(e, request.getReason()).queue();
            }, request.getViolator(), "discord.command.mod.action.message.kick", request.getReason(), null);
            return true;

        case CHANGE_ROLES:
            if (!self.hasPermission(Permission.MANAGE_ROLES) || !self.canInteract(request.getViolator())) {
                return false;
            }
            List<Role> currentRoles = new ArrayList<>(request.getViolator().getRoles());
            List<Role> rolesToAssign = Collections.emptyList();
            if (CollectionUtils.isNotEmpty(request.getAssignRoles())) {
                rolesToAssign = request.getAssignRoles().stream()
                        .map(guild::getRoleById)
                        .filter(e -> e != null && !e.isManaged() && self.canInteract(e) && !currentRoles.contains(e))
                        .collect(Collectors.toList());
            }

            List<Role> rolesToRevoke = Collections.emptyList();
            if (CollectionUtils.isNotEmpty(request.getRevokeRoles())) {
                rolesToRevoke = request.getRevokeRoles().stream()
                        .map(guild::getRoleById)
                        .filter(e -> e != null && !e.isManaged() && self.canInteract(e) && currentRoles.contains(e))
                        .collect(Collectors.toList());
            }

            if (CollectionUtils.isEmpty(rolesToAssign) && CollectionUtils.isEmpty(rolesToRevoke)) {
                return false;
            }

            guild.modifyMemberRoles(request.getViolator(), rolesToAssign, rolesToRevoke).queue();
            return true;
    }
    return false;
}