Java Code Examples for net.dv8tion.jda.api.Permission

The following examples show how to use net.dv8tion.jda.api.Permission. These examples are extracted from open source projects. 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 Project: JDA   Source File: PermissionOverrideImpl.java    License: 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 2
Source Project: DiscordSRV   Source File: DiscordUtil.java    License: 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 3
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 4
Source Project: DiscordSRV   Source File: VoiceModule.java    License: 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 5
Source Project: SkyBot   Source File: MuteCommand.java    License: 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 6
Source Project: SkyBot   Source File: CommandUtils.java    License: 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 7
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 8
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 9
Source Project: JDA   Source File: GuildImpl.java    License: 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 10
Source Project: DiscordSRV   Source File: DiscordUtil.java    License: 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 11
Source Project: JDA   Source File: GuildImpl.java    License: 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 12
Source Project: JDA   Source File: ChannelOrderActionImpl.java    License: 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 13
Source Project: DiscordSRV   Source File: DiscordUtil.java    License: 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 14
Source Project: JDA   Source File: TextChannelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Message> retrieveMessageById(@Nonnull String messageId)
{
    checkPermission(Permission.MESSAGE_READ);
    checkPermission(Permission.MESSAGE_HISTORY);

    //Call MessageChannel's default method
    return TextChannel.super.retrieveMessageById(messageId);
}
 
Example 15
Source Project: SkyBot   Source File: SettingsBase.java    License: 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 16
Source Project: JDA   Source File: ChannelActionImpl.java    License: Apache License 2.0 5 votes vote down vote up
private ChannelActionImpl<T> addOverride(long targetId, int type, long allow, long deny)
{
    Checks.notNegative(allow, "Granted permissions value");
    Checks.notNegative(deny, "Denied permissions value");
    Checks.check(allow <= Permission.ALL_PERMISSIONS, "Specified allow value may not be greater than a full permission set");
    Checks.check(deny <= Permission.ALL_PERMISSIONS, "Specified deny value may not be greater than a full permission set");

    overrides.add(new PermOverrideData(type, targetId, allow, deny));
    return this;
}
 
Example 17
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 18
Source Project: JDA   Source File: TextChannelImpl.java    License: 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 19
public PurgeUserCommand() {
    this.shouldLoadMembers = true;
    this.requiresArgs = true;
    this.name = "purgeuser";
    this.help = "Purges the last " + DEL_COUNT + " messages of a user";
    this.usage = "<@user>";
    this.userPermissions = new Permission[]{
        Permission.MESSAGE_MANAGE,
        Permission.MESSAGE_HISTORY,
    };
    this.botPermissions = new Permission[]{
        Permission.MESSAGE_MANAGE,
        Permission.MESSAGE_HISTORY,
    };
}
 
Example 20
@Override
public void execute(@Nonnull CommandContext ctx) {
    final Guild g = ctx.getJDAGuild();

        // If the guild has the VANITY_URL feature enabled or the vanityCode is not null the guild has a vanity url
        // We do this check before fetching the invites so that we can display the vanity url if they have one
        if (g.getFeatures().contains("VANITY_URL") || g.getVanityCode() != null) {
            sendGuildInfoEmbed(ctx, String.format(INVITE_STRING_TEMPLATE, g.getVanityCode()));
            return;
        }

        // Check if the selfuser has the manage server permissions
        // We can only fetch the invites when we have those permissions
        if (g.getSelfMember().hasPermission(Permission.MANAGE_SERVER)) {
            // Fetch the invites for the guild
            g.retrieveInvites().queue((invites) -> {

                // If there are no invites we will put give an empty string
                if (invites.isEmpty()) {
                    sendGuildInfoEmbed(ctx, null);
                    return;
                }

                // Get the first invite and format that with the code
                final Invite invite = invites.get(0);
                sendGuildInfoEmbed(ctx, String.format(INVITE_STRING_TEMPLATE, invite.getCode()));
            });

            return;
        }

        // If there is no vanity url and we are not allowed to fetch invites
        // we will default to the empty string for the invite so that we don't crash
        sendGuildInfoEmbed(ctx, "");
}
 
Example 21
Source Project: JDA   Source File: TextChannelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public ReactionPaginationAction retrieveReactionUsersById(@Nonnull String messageId, @Nonnull Emote emote)
{
    Checks.isSnowflake(messageId, "Message ID");
    Checks.notNull(emote, "Emote");

    checkPermission(Permission.MESSAGE_HISTORY);

    return new ReactionPaginationActionImpl(this, messageId, String.format("%s:%s", emote, emote.getId()));
}
 
Example 22
Source Project: JDA   Source File: MessageHistory.java    License: 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 23
Source Project: JDA   Source File: TextChannelImpl.java    License: 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 24
Source Project: JDA   Source File: GuildImpl.java    License: 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 25
Source Project: SkyBot   Source File: GuildListener.java    License: 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 26
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 27
Source Project: JDA   Source File: ChannelActionImpl.java    License: 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 28
Source Project: JDA   Source File: MessageActionImpl.java    License: 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 29
Source Project: JDA   Source File: TextChannelImpl.java    License: 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 30
Source Project: JDA   Source File: GuildImpl.java    License: 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);
}