net.dv8tion.jda.api.entities.Role Java Examples

The following examples show how to use net.dv8tion.jda.api.entities.Role. 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 JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Transactional
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
    if (event.getMember().getUser().isBot()) {
        return;
    }
    LocalMember member = entityAccessor.getOrCreate(event.getMember());
    member.setLastKnownRoles(event.getMember().getRoles().stream()
            .map(Role::getIdLong).collect(Collectors.toList()));
    memberService.save(member);

    if (!actionsHolderService.isLeaveNotified(event.getGuild().getIdLong(), event.getUser().getIdLong())) {
        getAuditService().log(event.getGuild(), AuditActionType.MEMBER_LEAVE)
                .withUser(member)
                .save();
    }
}
 
Example #2
Source File: TempMuteCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
static boolean canNotProceed(@Nonnull CommandContext ctx, GuildMessageReceivedEvent event, Member mod, Member toMute, Role role, Member self) {
    if (role == null) {
        sendMsg(event, "The current mute role does not exist on this server, please contact your server administrator about this.");

        return true;
    }

    if (!canInteract(mod, toMute, "mute", ctx.getChannel())) {
        return true;
    }

    if (!self.canInteract(role)) {
        sendMsg(event, "I cannot mute this member, is the mute role above mine?");

        return true;
    }

    return false;
}
 
Example #3
Source File: AutoRoleCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Nullable
static Role getFoundRoleOrNull(CommandContext ctx) {
    final List<Role> mentionedRoles = ctx.getMessage().getMentionedRoles();

    final Role foundRole;

    if (mentionedRoles.isEmpty()) {
        foundRole = FinderUtil.findRoles(ctx.getArgsRaw(), ctx.getGuild())
            .stream()
            .filter((role) -> ctx.getSelfMember().canInteract(role))
            .findFirst()
            .orElse(null);
    } else {
        foundRole = mentionedRoles.get(0);
    }

    if (foundRole == null) {
        sendMsg(ctx, "I'm sorry but I could not find any roles for your input, " +
            "make sure that the target role is below my role.");
        return null;
    }

    return foundRole;
}
 
Example #4
Source File: ToggleSpamFilterCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final DunctebotGuild guild = ctx.getGuild();
    final GuildSettings settings = guild.getSettings();

    final long muteRoleId = settings.getMuteRoleId();

    if (muteRoleId <= 0) {
        sendMsg(ctx.getEvent(), "**__Please set a spam/mute role first!__**");
        return;
    }

    final boolean spamState = !settings.isEnableSpamFilter();
    guild.setSettings(settings.setEnableSpamFilter(spamState));
    String message = String.format("Spamfilter **%s**!", (spamState ? "activated" : "disabled"));

    final Role r = guild.getRoleById(muteRoleId);
    message += "\nThe spam role is " + ((r == null) ? "deleted. Please update it." : r.getName() + ". Change it if it's outdated.");

    sendMsg(ctx.getEvent(), message);
}
 
Example #5
Source File: TagCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean isTagPatron(Member member) {
    final User u = member.getUser();

    if (isUserTagPatron(u)) {
        return true;
    }

    if (member.getGuild().getIdLong() != Settings.SUPPORT_GUILD_ID) {
        return false;
    }

    final boolean hasRole = member.getRoles()
        .stream()
        .map(Role::getIdLong)
        .anyMatch((it) -> it == Settings.TAG_PATRONS_ROLE);

    if (hasRole) {
        tagPatrons.add(u.getIdLong());
    }

    return hasRole;
}
 
Example #6
Source File: GuildMemberUpdateHandler.java    From JDA with Apache License 2.0 6 votes vote down vote up
private List<Role> toRolesList(GuildImpl guild, DataArray array)
{
    LinkedList<Role> roles = new LinkedList<>();
    for(int i = 0; i < array.length(); i++)
    {
        final long id = array.getLong(i);
        Role r = guild.getRolesView().get(id);
        if (r != null)
        {
            roles.add(r);
        }
        else
        {
            getJDA().getEventCache().cache(EventCache.Type.ROLE, id, responseNumber, allContent, this::handle);
            EventCache.LOG.debug("Got GuildMember update but one of the Roles for the Member is not yet cached.");
            return null;
        }
    }
    return roles;
}
 
Example #7
Source File: SettingsBase.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
boolean rolePermCheck(CommandContext ctx) {
    if (!ctx.getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
        sendMsg(ctx, "I need the _Manage Roles_ permission in order for this feature to work.");

        return true;
    }

    final List<Role> selfRoles = ctx.getSelfMember().getRoles();

    if (selfRoles.isEmpty()) {
        sendMsg(ctx, "I need a role above the specified role in order for this feature to work.");

        return true;
    }

    return false;
}
 
Example #8
Source File: EmbedBuilder.java    From JDA with Apache License 2.0 6 votes vote down vote up
/**
 * Resets this builder to default state.
 * <br>All parts will be either empty or null after this method has returned.
 *
 * @return The current EmbedBuilder with default values
 */
@Nonnull
public EmbedBuilder clear()
{
    description.setLength(0);
    fields.clear();
    url = null;
    title = null;
    timestamp = null;
    color = Role.DEFAULT_COLOR_RAW;
    thumbnail = null;
    author = null;
    footer = null;
    image = null;
    return this;
}
 
Example #9
Source File: VoiceLinkListener.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onGuildVoiceMove(GuildVoiceMoveEvent event) {
    GuildConfig config = getApplicableConfig(event);
    if (config == null) {
        return;
    }
    Guild guild = event.getGuild();
    Member member = event.getMember();
    Role roleToAdd = getRole(config, event.getChannelJoined());
    Role roleToRemove = getRole(config, event.getChannelLeft());

    if (Objects.equals(roleToAdd, roleToRemove)) {
        return;
    }
    if (roleToAdd != null && roleToRemove != null) {
        guild.modifyMemberRoles(member, Collections.singleton(roleToAdd), Collections.singleton(roleToRemove)).queue();
    } else if (roleToAdd != null) {
        guild.addRoleToMember(member, roleToAdd).queue();
    } else if (roleToRemove != null) {
        guild.removeRoleFromMember(member, roleToRemove).queue();
    }
}
 
Example #10
Source File: LuckPermsHook.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    ImmutableContextSet.Builder builder = ImmutableContextSet.builder();

    builder.add(CONTEXT_LINKED, "true");
    builder.add(CONTEXT_LINKED, "false");

    builder.add(CONTEXT_BOOSTING, "true");
    builder.add(CONTEXT_BOOSTING, "false");

    Guild mainGuild = DiscordSRV.getPlugin().getMainGuild();
    if (mainGuild != null) {
        for (Role role : mainGuild.getRoles()) {
            builder.add(CONTEXT_ROLE, role.getName());
        }
    }

    return builder.build();
}
 
Example #11
Source File: EmoteManagerImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public EmoteManagerImpl setRoles(Set<Role> roles)
{
    if (roles == null)
    {
        withLock(this.roles, List::clear);
    }
    else
    {
        Checks.notNull(roles, "Roles");
        roles.forEach((role) ->
        {
            Checks.notNull(role, "Roles");
            Checks.check(role.getGuild().equals(getGuild()), "Roles must all be from the same guild");
        });
        withLock(this.roles, (list) ->
        {
            list.clear();
            roles.stream().map(Role::getId).forEach(list::add);
        });
    }
    set |= ROLES;
    return this;
}
 
Example #12
Source File: MemberActionImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public MemberActionImpl setRoles(Role... roles)
{
    if (roles == null)
    {
        this.roles = null;
        return this;
    }
    Set<Role> newRoles = new HashSet<>(roles.length);
    for (Role role : roles)
        checkAndAdd(newRoles, role);
    this.roles = newRoles;
    return this;
}
 
Example #13
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 #14
Source File: GuildRoleCreateHandler.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    final long guildId = content.getLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;

    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild == null)
    {
        getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);
        EventCache.LOG.debug("GUILD_ROLE_CREATE was received for a Guild that is not yet cached: {}", content);
        return null;
    }

    Role newRole = getJDA().getEntityBuilder().createRole(guild, content.getObject("role"), guild.getIdLong());
    getJDA().handleEvent(
        new RoleCreateEvent(
            getJDA(), responseNumber,
            newRole));
    return null;
}
 
Example #15
Source File: ManagerMethods.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Manages the roles of a user.
 * @param user The user.
 * @param role The role.
 * @param add True = add, false = remove.
 * @return True if successful, false otherwise.
 */
private synchronized boolean manageRole(ScriptUser user, ScriptRole role, boolean add) {
    try {
        Guild guild = environment.getGuild();
        Member member = environment.getGuild().getMemberById(user.getID());
        Role rank = environment.getGuild().getRoleById(role.getID());
        if(member != null
                && rank != null) {
            if(add) {
                guild.addRoleToMember(member, rank).complete();
            } else {
                guild.removeRoleFromMember(member, rank).complete();
            }
        }
        return true;
    } catch(Exception exception) {
        return false;
    }
}
 
Example #16
Source File: RoleImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public int compareTo(@Nonnull Role r)
{
    if (this == r)
        return 0;
    if (!(r instanceof RoleImpl))
        throw new IllegalArgumentException("Cannot compare different role implementations");
    RoleImpl impl = (RoleImpl) r;

    if (this.guild.getIdLong() != impl.guild.getIdLong())
        throw new IllegalArgumentException("Cannot compare roles that aren't from the same guild!");

    if (this.getPositionRaw() != r.getPositionRaw())
        return this.getPositionRaw() - r.getPositionRaw();

    OffsetDateTime thisTime = this.getTimeCreated();
    OffsetDateTime rTime = r.getTimeCreated();

    //We compare the provided role's time to this's time instead of the reverse as one would expect due to how
    // discord deals with hierarchy. The more recent a role was created, the lower its hierarchy ranking when
    // it shares the same position as another role.
    return rTime.compareTo(thisTime);
}
 
Example #17
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 #18
Source File: MemberActionImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public MemberActionImpl setRoles(Collection<Role> roles)
{
    if (roles == null)
    {
        this.roles = null;
        return this;
    }
    Set<Role> newRoles = new HashSet<>(roles.size());
    for (Role role : roles)
        checkAndAdd(newRoles, role);
    this.roles = newRoles;
    return this;
}
 
Example #19
Source File: PunishmentListener.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Whether or not the latest audit log shows that it is a punishment.
 * @param entry The audit log entry.
 * @param user The user.
 * @param type The punishment type.
 * @param roles The roles involved in the event, should be null unless it is a mute.
 * @return True if it is, false otherwise.
 */
private boolean isPunishment(AuditLogEntry entry, long user, PunishmentType type, Role[] roles) {
    if(entry.getTargetIdLong() != user) {
        return false;
    }
    if(entry.getType() != type.getAuditType()
            && entry.getType() != type.getUndoAuditType()) {
        return false;
    }
    if(type == PunishmentType.MUTE) {
        String mutedRole = UPunishment.getMutedRole(entry.getGuild());
        for(Role role : roles) {
            if(role.getId().equals(mutedRole)) {
                return true;
            }
        }
        return false;
    }
    return true;
}
 
Example #20
Source File: DiscordAccountLinkListener.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
    // add linked role back to people when they rejoin the server
    UUID uuid = DiscordSRV.getPlugin().getAccountLinkManager().getUuid(event.getUser().getId());
    if (uuid != null) {
        Role roleToAdd = DiscordUtil.getRoleByName(event.getMember().getGuild(), DiscordSRV.config().getString("MinecraftDiscordAccountLinkedRoleNameToAddUserTo"));
        if (roleToAdd != null) DiscordUtil.addRoleToMember(event.getMember(), roleToAdd);
        else DiscordSRV.debug("Couldn't add user to null role");
    }
}
 
Example #21
Source File: MemberActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestBody finalizeData()
{
    DataObject obj = DataObject.empty();
    obj.put("access_token", accessToken);
    if (nick != null)
        obj.put("nick", nick);
    if (roles != null && !roles.isEmpty())
        obj.put("roles", roles.stream().map(Role::getId).collect(Collectors.toList()));
    obj.put("mute", mute);
    obj.put("deaf", deaf);
    return getRequestBody(obj);
}
 
Example #22
Source File: DiscordChatListener.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
private String replacePlaceholders(String input, GuildMessageReceivedEvent event, List<Role> selectedRoles, String message) {
    return input.replace("%message%", message)
            .replace("%channelname%", event.getChannel().getName())
            .replace("%name%", DiscordUtil.strip(event.getMember().getEffectiveName()))
            .replace("%username%", DiscordUtil.strip(event.getMember().getUser().getName()))
            .replace("%toprole%", DiscordUtil.getRoleName(!selectedRoles.isEmpty() ? selectedRoles.get(0) : null))
            .replace("%toproleinitial%", !selectedRoles.isEmpty() ? DiscordUtil.getRoleName(selectedRoles.get(0)).substring(0, 1) : "")
            .replace("%toprolecolor%", DiscordUtil.convertRoleToMinecraftColor(!selectedRoles.isEmpty() ? selectedRoles.get(0) : null))
            .replace("%allroles%", DiscordUtil.getFormattedRoles(selectedRoles))
            .replace("\\~", "~") // get rid of badly escaped characters
            .replace("\\*", "") // get rid of badly escaped characters
            .replace("\\_", "_"); // get rid of badly escaped characters
}
 
Example #23
Source File: RoleImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o)
{
    if (o == this)
        return true;
    if (!(o instanceof Role))
        return false;
    Role oRole = (Role) o;
    return this.getIdLong() == oRole.getIdLong();
}
 
Example #24
Source File: CategoryUpdatePermissionsEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
/**
 * Filtered list of affected {@link net.dv8tion.jda.api.entities.Role Roles}
 *
 * @return Immutable list of affected roles
 */
@Nonnull
public List<Role> getChangedRoles()
{
    return changed.stream()
        .filter(it -> it instanceof Role)
        .map(Role.class::cast)
        .collect(Collectors.toList());
}
 
Example #25
Source File: MemberCacheViewImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsWithRoles(@Nonnull Collection<Role> roles)
{
    Checks.noneNull(roles, "Roles");
    if (isEmpty())
        return Collections.emptyList();
    List<Member> members = new ArrayList<>();
    forEach(member ->
    {
        if (member.getRoles().containsAll(roles))
            members.add(member);
    });
    return members;
}
 
Example #26
Source File: UPunishment.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Whether or not a member is muted.
 * @param member The member.
 * @return True if they are, false otherwise.
 */
public static boolean isMute(Member member) {
    String mutedRole = getMutedRole(member.getGuild());
    for(Role role : member.getRoles()) {
        if(role.getId().equals(mutedRole)) {
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: RoleManagerImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public RoleManagerImpl reset(long fields)
{
    super.reset(fields);
    if ((fields & NAME) == NAME)
        this.name = null;
    if ((fields & COLOR) == COLOR)
        this.color = Role.DEFAULT_COLOR_RAW;
    return this;
}
 
Example #28
Source File: LockEmoteCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {

    final GuildMessageReceivedEvent event = ctx.getEvent();
    final Message message = ctx.getMessage();

    if (ctx.getArgs().isEmpty()) {
        this.sendUsageInstructions(ctx);
        return;
    }

    final List<Emote> mentionedEmotes = message.getEmotes();
    final List<Role> mentionedRoles = new ArrayList<>(message.getMentionedRoles());

    if (mentionedRoles.isEmpty()) {
        // Loop over the args and check if there are roles found in text
        ctx.getArgs().forEach(
            (arg) -> mentionedRoles.addAll(FinderUtil.findRoles(arg, ctx.getGuild()))
        );
    }

    if (mentionedEmotes.isEmpty() || mentionedRoles.isEmpty()) {
        this.sendUsageInstructions(ctx);
        return;
    }

    final Emote emote = mentionedEmotes.get(0);

    if (cannotInteractWithEmote(event, emote)) return;

    emote.getManager().setRoles(new HashSet<>(mentionedRoles)).queue();
    sendSuccess(message);
    final List<String> roleNames = mentionedRoles.stream().map(Role::getName).collect(Collectors.toList());

    sendMsg(event, "The emote " + emote.getAsMention() + " has been locked to users that have the " +
        "following roles: `" + String.join("`, `", roleNames) + "`");
}
 
Example #29
Source File: EmbedBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the given embed is empty. Empty embeds will throw an exception if built
 *
 * @return true if the embed is empty and cannot be built
 */
public boolean isEmpty()
{
    return title == null
        && timestamp == null
        && thumbnail == null
        && author == null
        && footer == null
        && image == null
        && color == Role.DEFAULT_COLOR_RAW
        && description.length() == 0
        && fields.isEmpty();
}
 
Example #30
Source File: UnifiedCacheViewImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsWithRoles(@Nonnull Collection<Role> roles)
{
    return Collections.unmodifiableList(distinctStream()
        .flatMap(view -> view.getElementsWithRoles(roles).stream())
        .collect(Collectors.toList()));
}