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

The following examples show how to use net.dv8tion.jda.api.entities.Role. 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: SkyBot   Source File: SettingsBase.java    License: 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 2
@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 3
@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
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 5
Source Project: SkyBot   Source File: TagCommand.java    License: 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 Project: JuniperBot   Source File: MemberListener.java    License: 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 7
Source Project: JuniperBot   Source File: VoiceLinkListener.java    License: 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 8
Source Project: JDA   Source File: EmoteManagerImpl.java    License: 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 9
Source Project: JDA   Source File: GuildRoleCreateHandler.java    License: 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 10
Source Project: Arraybot   Source File: ManagerMethods.java    License: 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 11
Source Project: JDA   Source File: MemberActionImpl.java    License: 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 12
Source Project: Arraybot   Source File: PunishmentListener.java    License: 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 13
Source Project: Arraybot   Source File: MemberListener.java    License: 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 14
Source Project: JDA   Source File: RoleImpl.java    License: 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 15
Source Project: Arraybot   Source File: UPunishment.java    License: 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 16
Source Project: JDA   Source File: MemberActionImpl.java    License: 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 17
Source Project: DiscordSRV   Source File: LuckPermsHook.java    License: 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 18
Source Project: JDA   Source File: EmbedBuilder.java    License: 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 19
Source Project: JDA   Source File: GuildMemberUpdateHandler.java    License: 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 20
@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 21
@Override
public void execute(@Nonnull CommandContext ctx) {
    final List<String> args = ctx.getArgs();

    if (rolePermCheck(ctx)) {
        return;
    }

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


    final DunctebotGuild guild = ctx.getGuild();
    final GuildSettings settings = guild.getSettings();

    if ("disable".equals(args.get(0))) {
        sendMsg(ctx, "SpamRole feature & SpamFilter has been disabled");
        //Never clean the role's id so activating the filter wont cause issues.
        //GuildSettingsUtils.updateGuildSettings(guild, settings.setMuteRoleId(0L));
        guild.setSettings(settings.setEnableSpamFilter(false));
        return;
    }

    final Role foundRole = getFoundRoleOrNull(ctx);

    if (foundRole == null) {
        return;
    }

    guild.setSettings(settings.setMuteRoleId(foundRole.getIdLong()));

    sendMsg(ctx, "SpamRole has been set to " + foundRole.getName());
}
 
Example 22
@Override
public void execute(@Nonnull CommandContext ctx) {
    final DunctebotGuild guild = ctx.getGuild();
    final GuildSettings settings = guild.getSettings();
    final TextChannel logChan = AirUtils.getLogChannel(settings.getLogChannel(), guild);
    final TextChannel welcomeLeaveChannel = AirUtils.getLogChannel(settings.getWelcomeLeaveChannel(), guild);
    final Role autoRole = guild.getRoleById(settings.getAutoroleRole());
    final Role muteRole = guild.getRoleById(settings.getMuteRoleId());

    final EmbedBuilder message = EmbedUtils.embedMessage("Here are the settings from this guild.\n" +
        "**Show join/leave messages:** " + toEmoji(settings.isEnableJoinMessage()) + "\n" +
        "**Swearword filter:** " + toEmoji(settings.isEnableSwearFilter()) + "\n" +
        "**Announce next track:** " + toEmoji(settings.isAnnounceTracks()) + "\n" +
        "**Auto de-hoist:** " + toEmoji(settings.isAutoDeHoist()) + "\n" +
        "**Filter Discord invites:** " + toEmoji(settings.isFilterInvites()) + "\n" +
        "**Spamfilter:** " + toEmoji(settings.isEnableSpamFilter()) + "\n" +
        "**Kick Mode:** " + (settings.getKickState() ? "Kick Members" : "Mute members") + "\n" +

        "**MuteRole:** " + (settings.getMuteRoleId() <= 0
        ? "Not Set" : (muteRole == null ? "Not set" : muteRole.getAsMention())) + "\n" +

        "**Join message:** " + settings.getCustomJoinMessage() + "\n" +
        "**Leave message:** " + settings.getCustomLeaveMessage() + "\n" +

        "**AutoRole:** " + (settings.getAutoroleRole() <= 0
        ? "Not Set" : (autoRole == null ? "Not Set" : autoRole.getAsMention())) + "\n" +

        "**Current prefix:** " + settings.getCustomPrefix() + "\n" +
        "**Modlog Channel:** " + (logChan == null ? "Not set" : logChan.getAsMention()) + "\n" +
        "**Welcome/Leave channel:** " + (welcomeLeaveChannel == null ? "Not set" : welcomeLeaveChannel.getAsMention()) + "\n" +
        "**Embed color code:** " + guild.getHexColor()
    );

    sendEmbed(ctx.getEvent(), message);
}
 
Example 23
@Override
public void execute(@Nonnull CommandContext ctx) {
    final List<String> args = ctx.getArgs();
    final DunctebotGuild guild = ctx.getGuild();
    final GuildSettings settings = guild.getSettings();

    if (rolePermCheck(ctx)) {
        return;
    }

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

    if ("disable".equals(args.get(0))) {
        sendMsg(ctx, "AutoRole feature has been disabled");
        guild.setSettings(settings.setAutoroleRole(0L));
        return;
    }

    final Role foundRole = getFoundRoleOrNull(ctx);

    if (foundRole == null) {
        return;
    }

    guild.setSettings(settings.setAutoroleRole(foundRole.getIdLong()));

    sendMsg(ctx, "AutoRole has been set to " + foundRole.getName());
}
 
Example 24
Source Project: JDA   Source File: MemberCacheViewImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsWithRoles(@Nonnull Role... roles)
{
    Checks.notNull(roles, "Roles");
    return getElementsWithRoles(Arrays.asList(roles));
}
 
Example 25
Source Project: JuniperBot   Source File: WarnCommand.java    License: GNU General Public License v3.0 5 votes vote down vote up
private List<Role> getRoles(Guild guild, List<Long> roleIds) {
    if (CollectionUtils.isEmpty(roleIds)) {
        return Collections.emptyList();
    }
    return roleIds.stream()
            .map(guild::getRoleById)
            .filter(e -> e != null && guild.getSelfMember().canInteract(e))
            .collect(Collectors.toList());
}
 
Example 26
Source Project: JuniperBot   Source File: VoiceLinkListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
    GuildConfig config = getApplicableConfig(event);
    if (config == null) {
        return;
    }
    Role role = getRole(config, event.getChannelJoined());
    if (role != null) {
        event.getGuild().addRoleToMember(event.getMember(), role).queue();
    }
}
 
Example 27
Source Project: JuniperBot   Source File: VoiceLinkListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Role getRole(GuildConfig config, VoiceChannel channel) {
    if (channel == null) {
        return null;
    }
    Guild guild = channel.getGuild();
    return config.getVoiceLinks()
            .stream()
            .filter(e -> channel.getId().equals(e.getChannelId()))
            .findFirst()
            .map(e -> guild.getRoleById(e.getRoleId()))
            .filter(e -> guild.getSelfMember().canInteract(e))
            .orElse(null);
}
 
Example 28
Source Project: JDA   Source File: RoleManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new RoleManager instance
 *
 * @param role
 *        {@link net.dv8tion.jda.api.entities.Role Role} that should be modified
 */
public RoleManagerImpl(Role role)
{
    super(role.getJDA(), Route.Roles.MODIFY_ROLE.compile(role.getGuild().getId(), role.getId()));
    JDA api = role.getJDA();
    this.role = new SnowflakeReference<>(role, api::getRoleById);
    if (isPermissionChecksEnabled())
        checkPermissions();
}
 
Example 29
Source Project: JDA   Source File: EmoteImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Role> getRoles()
{
    if (!canProvideRoles())
        throw new IllegalStateException("Unable to return roles because this emote is fake. (We do not know the origin Guild of this emote)");
    return Collections.unmodifiableList(new LinkedList<>(roles));
}
 
Example 30
@Override
public Role getDonatorRole() {
    Long donatorRoleId = workerProperties.getSupport().getDonatorRoleId();
    if (donatorRoleId == null) {
        return null;
    }
    Guild guild = getSupportGuild();
    return guild != null ? guild.getRoleById(donatorRoleId) : null;
}