net.dv8tion.jda.api.Permission Java Examples

The following examples show how to use net.dv8tion.jda.api.Permission. 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: AnnounceCommand.java    From SkyBot with GNU Affero General Public License v3.0 7 votes vote down vote up
public AnnounceCommand() {
    this.requiresArgs = true;
    this.requiredArgCount = 2;
    this.category = CommandCategory.ADMINISTRATION;
    this.name = "announce";
    this.aliases = new String[]{
        "announce1",
        "announce2",
        "announce3",
    };
    this.help = "Sends an announcement in the specified channel";
    this.usage = "<#channel> <message> [--noembed] [--thumbnail]";
    this.userPermissions = new Permission[]{
        Permission.MANAGE_SERVER,
    };
    this.flags = new Flag[]{
        new Flag(
            "noembed",
            "Displays the announcement as plain text instead of as embed"
        ),
        new Flag(
            "thumbnail",
            "Displays the image as thumbnail instead of a large image"
        ),
    };
}
 
Example #2
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 #3
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 #4
Source File: PermissionOverrideImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public PermissionOverrideAction getManager()
{
    if (!getGuild().getSelfMember().hasPermission(getChannel(), Permission.MANAGE_PERMISSIONS))
        throw new InsufficientPermissionException(getChannel(), Permission.MANAGE_PERMISSIONS);
    PermissionOverrideAction mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new PermissionOverrideActionImpl(this).setOverride(false);
            return manager;
        });
    }
    return mng.reset();
}
 
Example #5
Source File: VoiceModule.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
private static void checkMutedUser(VoiceChannel channel, Member member) {
    if (channel == null || member.getVoiceState() == null) {
        return;
    }
    boolean isLobby = channel.getId().equals(getLobbyChannel().getId());
    if (isLobby && !member.getVoiceState().isGuildMuted()) {
        PermissionOverride override = channel.getPermissionOverride(channel.getGuild().getPublicRole());
        if (override != null && override.getDenied().contains(Permission.VOICE_SPEAK)
                && member.hasPermission(channel, Permission.VOICE_SPEAK, Permission.VOICE_MUTE_OTHERS)
                && channel.getGuild().getSelfMember().hasPermission(channel, Permission.VOICE_MUTE_OTHERS)) {
            member.mute(true).queue();
            mutedUsers.add(member.getId());
        }
    } else if (!isLobby) {
        if (mutedUsers.remove(member.getId())) {
            member.mute(false).queue();
        }
    }
}
 
Example #6
Source File: MuteCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
public MuteCommand() {
    this.shouldLoadMembers = true;
    this.requiresArgs = true;
    this.name = "mute";
    this.help = "Mutes a user in the server";
    this.usage = "<@user> [-r reason]";
    this.botPermissions = new Permission[]{
        Permission.MANAGE_SERVER,
        Permission.MANAGE_ROLES,
    };
    this.flags = new Flag[]{
        new Flag(
            'r',
            "reason",
            "Sets the reason for this mute"
        ),
    };
}
 
Example #7
Source File: CommandUtils.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private static boolean shouldGuildBeConsideredPremium(@Nonnull Guild g) {
    final AtomicBoolean foundPatron = new AtomicBoolean(false);

    guildPatrons.forEach((userId) -> {
        // Check if we have the member in the guild and if they are an admin
        final Member m = g.getMemberById(userId);
        final boolean userInGuild = m != null && m.hasPermission(Permission.ADMINISTRATOR);

        // Only set if we found a patron
        if (userInGuild) {
            foundPatron.set(true);
        }

        // return false to stop looping
        return !userInGuild;
    });

    return foundPatron.get();
}
 
Example #8
Source File: ModerationUtils.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void kickUser(Guild guild, Member member, TextChannel channel, String cause, boolean sendMessages) {
    final Member self = guild.getSelfMember();

    if (!self.hasPermission(Permission.KICK_MEMBERS)) {
        if (sendMessages) {
            sendMsg(channel, "I don't have permissions for kicking a person. Please give me kick members permissions.");
        }
        return;
    }

    if (!self.canInteract(member)) {
        if (sendMessages) {
            sendMsg(channel, "I can not access the member.");
        }
        return;
    }
    final String reason = String.format("The member %#s was kicked for %s.", member.getUser(), cause);
    guild.kick(member, reason).reason(reason).queue();
}
 
Example #9
Source File: MessageListener.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean doAutoModChecks(@Nonnull GuildMessageReceivedEvent event, GuildSettings settings, String rw) {
    final Guild guild = event.getGuild();
    if (guild.getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)
        && !Objects.requireNonNull(event.getMember()).hasPermission(Permission.MESSAGE_MANAGE)) {

        checkMessageForInvites(guild, event, settings, rw);

        final Message messageToCheck = event.getMessage();
        final DunctebotGuild dbG = new DunctebotGuild(event.getGuild(), variables);

        if (blacklistedWordCheck(dbG, messageToCheck, event.getMember(), settings.getBlacklistedWords())) {
            return true;
        }

        if (checkSwearFilter(messageToCheck, event, dbG)) {
            return true;
        }

        checkSpamFilter(messageToCheck, event, settings, dbG);
    }

    return false;
}
 
Example #10
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<ListedEmote> retrieveEmoteById(@Nonnull String id)
{
    Checks.isSnowflake(id, "Emote ID");

    JDAImpl jda = getJDA();
    return new DeferredRestAction<>(jda, ListedEmote.class,
    () -> {
        Emote emote = getEmoteById(id);
        if (emote != null)
        {
            ListedEmote listedEmote = (ListedEmote) emote;
            if (listedEmote.hasUser() || !getSelfMember().hasPermission(Permission.MANAGE_EMOTES))
                return listedEmote;
        }
        return null;
    }, () -> {
        Route.CompiledRoute route = Route.Emotes.GET_EMOTE.compile(getId(), id);
        return new AuditableRestActionImpl<>(jda, route, (response, request) ->
        {
            EntityBuilder builder = GuildImpl.this.getJDA().getEntityBuilder();
            return builder.createEmote(GuildImpl.this, response.getObject(), true);
        });
    });
}
 
Example #11
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 #12
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public AuditableRestAction<Integer> prune(int days, boolean wait, @Nonnull Role... roles)
{
    checkPermission(Permission.KICK_MEMBERS);

    Checks.check(days >= 1 && days <= 30, "Provided %d days must be between 1 and 30.", days);
    Checks.notNull(roles, "Roles");

    Route.CompiledRoute route = Route.Guilds.PRUNE_MEMBERS.compile(getId());
    FormBody.Builder form = new FormBody.Builder();
    form.add("days", Integer.toString(days));
    if (!wait)
        form.add("compute_prune_count", "false");
    for (Role role : roles)
    {
        Checks.notNull(role, "Role");
        Checks.check(role.getGuild().equals(this), "Role is not from the same guild!");
        form.add("include_roles", role.getId());
    }
    return new AuditableRestActionImpl<>(getJDA(), route, form.build(), (response, request) -> response.getObject().getInt("pruned", 0));
}
 
Example #13
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 #14
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> unpinMessageById(@Nonnull String messageId)
{
    checkPermission(Permission.MESSAGE_READ, "You cannot unpin a message in a channel you can't access. (MESSAGE_READ)");
    checkPermission(Permission.MESSAGE_MANAGE, "You need MESSAGE_MANAGE to pin or unpin messages.");

    //Call MessageChannel's default method
    return TextChannel.super.unpinMessageById(messageId);
}
 
Example #15
Source File: MessageHistory.java    From JDA with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new MessageHistory object.
 *
 * @param  channel
 *         The {@link net.dv8tion.jda.api.entities.MessageChannel MessageChannel} to retrieval history from.
 */
public MessageHistory(@Nonnull MessageChannel channel)
{
    Checks.notNull(channel, "Channel");
    this.channel = channel;
    if (channel instanceof TextChannel)
    {
        TextChannel tc = (TextChannel) channel;
        if (!tc.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_HISTORY))
            throw new InsufficientPermissionException(tc, Permission.MESSAGE_HISTORY);
    }
}
 
Example #16
Source File: RoleImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasPermission(@Nonnull GuildChannel channel, @Nonnull Permission... permissions)
{
    long effectivePerms = PermissionUtil.getEffectivePermission(channel, this);
    for (Permission perm : permissions)
    {
        final long rawValue = perm.getRawValue();
        if ((effectivePerms & rawValue) != rawValue)
            return false;
    }
    return true;
}
 
Example #17
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public MessageAction sendFile(@Nonnull File file, @Nonnull String fileName, @Nonnull AttachmentOption... options)
{
    checkPermission(Permission.MESSAGE_READ);
    checkPermission(Permission.MESSAGE_WRITE);
    checkPermission(Permission.MESSAGE_ATTACH_FILES);

    final long maxSize = getGuild().getMaxFileSize();
    Checks.check(file == null || file.length() <= maxSize,
                "File may not exceed the maximum file length of %d bytes!", maxSize);

    //Call MessageChannel's default method
    return TextChannel.super.sendFile(file, fileName, options);
}
 
Example #18
Source File: GuildImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public AuditableRestAction<Void> modifyNickname(@Nonnull Member member, String nickname)
{
    Checks.notNull(member, "Member");
    checkGuild(member.getGuild(), "Member");

    if (member.equals(getSelfMember()))
    {
        if (!member.hasPermission(Permission.NICKNAME_CHANGE) && !member.hasPermission(Permission.NICKNAME_MANAGE))
            throw new InsufficientPermissionException(this, Permission.NICKNAME_CHANGE, "You neither have NICKNAME_CHANGE nor NICKNAME_MANAGE permission!");
    }
    else
    {
        checkPermission(Permission.NICKNAME_MANAGE);
        checkPosition(member);
    }

    JDAImpl jda = getJDA();
    return new DeferredRestAction<>(jda, () -> {
        DataObject body = DataObject.empty().put("nick", nickname == null ? "" : nickname);

        Route.CompiledRoute route;
        if (member.equals(getSelfMember()))
            route = Route.Guilds.MODIFY_SELF_NICK.compile(getId());
        else
            route = Route.Guilds.MODIFY_MEMBER.compile(getId(), member.getUser().getId());

        return new AuditableRestActionImpl<Void>(jda, route, body);
    }).setCacheCheck(() -> !Objects.equals(nickname, member.getNickname()));
}
 
Example #19
Source File: PurgeChannelCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public PurgeChannelCommand() {
    this.requiresArgs = true;
    this.name = "purgechannel";
    this.help = "Purges an entire text channel";
    this.usage = "<#channel>";
    this.userPermissions = new Permission[]{
        Permission.MESSAGE_MANAGE,
        Permission.MESSAGE_HISTORY,
    };
    this.botPermissions = new Permission[]{
        Permission.MANAGE_CHANNEL,
        Permission.MANAGE_SERVER,
    };
}
 
Example #20
Source File: GuildListener.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void handleVcAutoRole(Guild guild, Member member, VoiceChannel channel, boolean remove) {
    final Member self = guild.getSelfMember();
    final long guildId = guild.getIdLong();

    final TLongObjectMap<TLongLongMap> vcAutoRoleCache = variables.getVcAutoRoleCache();

    if (!vcAutoRoleCache.containsKey(guildId)) {
        return;
    }

    final TLongLongMap vcToRolePair = vcAutoRoleCache.get(guildId);

    if (vcToRolePair.get(channel.getIdLong()) > 0) {
        final Role role = guild.getRoleById(vcToRolePair.get(channel.getIdLong()));

        if (role != null && self.canInteract(member) && self.canInteract(role) && self.hasPermission(Permission.MANAGE_ROLES)) {
            if (remove) {
                guild
                    .removeRoleFromMember(member, role)
                    .reason("VC auto role removed")
                    .queue();
            } else {
                guild
                    .addRoleToMember(member, role)
                    .reason("VC auto role applied")
                    .queue();
            }
        }
    }
}
 
Example #21
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> addReactionById(@Nonnull String messageId, @Nonnull String unicode)
{
    checkPermission(Permission.MESSAGE_HISTORY);

    //Call MessageChannel's default method
    return TextChannel.super.addReactionById(messageId, unicode);
}
 
Example #22
Source File: SettingsBase.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public SettingsBase() {
    this.displayAliasesInHelp = true;
    this.category = CommandCategory.ADMINISTRATION;
    this.userPermissions = new Permission[]{
        Permission.MANAGE_SERVER,
    };
}
 
Example #23
Source File: VoiceModule.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
private void checkNetworkPermissions(Network network) {
    PermissionOverride override = network.getChannel().getPermissionOverride(getGuild().getPublicRole());
    if (override == null) {
        PermissionOverrideAction action = network.getChannel().createPermissionOverride(getGuild().getPublicRole());
        if (isVoiceActivationAllowed()) {
            action.setAllow(Permission.VOICE_SPEAK, Permission.VOICE_USE_VAD);
            action.setDeny(Permission.VOICE_CONNECT);
        } else {
            action.setAllow(Permission.VOICE_SPEAK);
            action.setDeny(Permission.VOICE_CONNECT, Permission.VOICE_USE_VAD);
        }
        action.queue(null, (throwable) ->
                DiscordSRV.error("Failed to create permission override for network " + network.getChannel().getName() + ": " + throwable.getMessage())
        );
    } else {
        List<Permission> allowed;
        List<Permission> denied;
        if (isVoiceActivationAllowed()) {
            allowed = Arrays.asList(Permission.VOICE_SPEAK, Permission.VOICE_USE_VAD);
            denied = Collections.singletonList(Permission.VOICE_CONNECT);
        } else {
            allowed = Collections.singletonList(Permission.VOICE_SPEAK);
            denied = Arrays.asList(Permission.VOICE_CONNECT, Permission.VOICE_USE_VAD);
        }

        boolean dirty = false;
        PermissionOverrideAction manager = override.getManager();
        if (!override.getAllowed().containsAll(allowed)) {
            manager.grant(allowed);
            dirty = true;
        }
        if (!override.getDenied().containsAll(denied)) {
            manager.deny(denied);
            dirty = true;
        }
        if (dirty) manager.complete();
    }
}
 
Example #24
Source File: JDAImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getInviteUrl(Collection<Permission> permissions)
{
    StringBuilder builder = buildBaseInviteUrl();
    if (permissions != null && !permissions.isEmpty())
        builder.append("&permissions=").append(Permission.getRaw(permissions));
    return builder.toString();
}
 
Example #25
Source File: DiscordGuildDetails.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static DiscordGuildDetails create(Map<Object, Object> map) {
    DiscordGuildDetails details = new DiscordGuildDetails();
    setValue(String.class, map, "id", details::setId);
    setValue(String.class, map, "name", details::setName);
    setValue(String.class, map, "icon", details::setIcon);
    setValue(Boolean.class, map, "owner", details::setOwner);
    Object permissions = map.get("permissions");
    if (permissions instanceof Number) {
        details.permissions = Permission.getPermissions(((Number) permissions).longValue());
    }
    return details;
}
 
Example #26
Source File: ChannelActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
protected void checkPermissions(Collection<Permission> permissions)
{
    if (permissions == null)
        return;
    for (Permission p : permissions)
        Checks.notNull(p, "Permissions");
}
 
Example #27
Source File: MessageActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public MessageActionImpl addFile(@Nonnull final InputStream data, @Nonnull String name, @Nonnull AttachmentOption... options)
{
    checkEdit();
    Checks.notNull(data, "Data");
    Checks.notBlank(name, "Name");
    Checks.noneNull(options, "Options");
    checkFileAmount();
    checkPermission(Permission.MESSAGE_ATTACH_FILES);
    name = applyOptions(name, options);
    files.put(name, data);
    return this;
}
 
Example #28
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canTalk(@Nonnull Member member)
{
    if (!getGuild().equals(member.getGuild()))
        throw new IllegalArgumentException("Provided Member is not from the Guild that this TextChannel is part of.");

    return member.hasPermission(this, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE);
}
 
Example #29
Source File: GuildImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public AuditableRestAction<Void> unban(@Nonnull String userId)
{
    Checks.isSnowflake(userId, "User ID");
    checkPermission(Permission.BAN_MEMBERS);

    Route.CompiledRoute route = Route.Guilds.UNBAN.compile(getId(), userId);
    return new AuditableRestActionImpl<>(getJDA(), route);
}
 
Example #30
Source File: DiscordUtils.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static Role getHighestRole(Member member, Permission... permission) {
    if (member == null || CollectionUtils.isEmpty(member.getRoles())) {
        return null;
    }
    return member.getRoles().stream()
            .sorted(Comparator.comparingInt(Role::getPosition).reversed())
            .filter(e -> permission == null || permission.length == 0 || e.hasPermission(permission))
            .findFirst().orElse(null);
}