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

The following examples show how to use net.dv8tion.jda.api.entities.Member. 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 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 #2
Source File: CheckOwnerQueueListener.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@RabbitListener(queues = RabbitConfiguration.QUEUE_CHECK_OWNER_REQUEST)
public boolean isAdministrator(CheckOwnerRequest request) {
    Guild guild = null;
    switch (request.getType()) {
        case TEXT:
            TextChannel textChannel = discordService.getTextChannelById(request.getChannelId());
            if (textChannel != null) {
                guild = textChannel.getGuild();
            }
            break;
        case VOICE:
            VoiceChannel voiceChannel = discordService.getVoiceChannelById(request.getChannelId());
            if (voiceChannel != null) {
                guild = voiceChannel.getGuild();
            }
            break;
    }
    if (guild == null) {
        return true;
    }
    Member member = guild.getMemberById(request.getUserId());
    if (member == null) {
        return false;
    }
    return member.isOwner() || member.hasPermission(Permission.ADMINISTRATOR);
}
 
Example #3
Source File: NicknameUpdater.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public void setNickname(Member member, OfflinePlayer offlinePlayer) {
    String nickname;
    if (offlinePlayer.isOnline()) {
        Player player = offlinePlayer.getPlayer();

        nickname = DiscordSRV.config().getString("NicknameSynchronizationFormat")
                .replace("%displayname%", player.getDisplayName() != null ? player.getDisplayName() : player.getName())
                .replace("%username%", player.getName());

        nickname = PlaceholderUtil.replacePlaceholders(nickname, player);
    } else {
        nickname = offlinePlayer.getName();
    }

    nickname = DiscordUtil.strip(nickname);
    DiscordUtil.setNickname(member, nickname);
}
 
Example #4
Source File: MemberCacheViewImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsByUsername(@Nonnull String name, boolean ignoreCase)
{
    Checks.notEmpty(name, "Name");
    if (isEmpty())
        return Collections.emptyList();
    List<Member> members = new ArrayList<>();
    forEach(member ->
    {
        final String nick = member.getUser().getName();
        if (equals(ignoreCase, nick, name))
            members.add(member);
    });
    return Collections.unmodifiableList(members);
}
 
Example #5
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Transactional
public VoiceChannel getDesiredChannel(Member member) {
    MusicConfig musicConfig = musicConfigService.get(member.getGuild());
    VoiceChannel channel = null;
    if (musicConfig != null) {
        if (musicConfig.isUserJoinEnabled()
                && member.getVoiceState() != null
                && member.getVoiceState().inVoiceChannel()) {
            channel = member.getVoiceState().getChannel();
        }
        if (channel == null && musicConfig.getChannelId() != null) {
            channel = member.getGuild().getVoiceChannelById(musicConfig.getChannelId());
        }
    }
    if (channel == null) {
        channel = discordService.getDefaultMusicChannel(member.getGuild().getIdLong());
    }
    return channel;
}
 
Example #6
Source File: AuditActionBuilder.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private Object getReferenceForObject(Object object) {
    if (object instanceof User) {
        return getReference((User) object);
    }
    if (object instanceof LocalUser) {
        return getReference((LocalUser) object);
    }
    if (object instanceof Member) {
        return getReference((Member) object);
    }
    if (object instanceof LocalMember) {
        return getReference((LocalMember) object);
    }
    if (object instanceof GuildChannel) {
        return getReference((GuildChannel) object);
    }
    return object;
}
 
Example #7
Source File: UUser.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the member corresponding to the given user input.
 * @param guild The guild.
 * @param input The input.
 * @return A Member object, or null if the input is invalid.
 */
public static Member getMember(Guild guild, String input) {
    if(ID_PATTERN.matcher(input).find()
            || MENTION_PATTERN.matcher(input).find()) {
        return guild.getMemberById(input.replaceAll("\\D", ""));
    } else if(NAME_PATTERN.matcher(input).find()) {
        String name = input.substring(0, input.indexOf("#"));
        String discriminator = input.substring(input.indexOf("#") + 1);
        return guild.getMembers().stream()
                .filter(user -> user.getUser().getName().equals(name)
                    && user.getUser().getDiscriminator().equals(discriminator))
                .findFirst()
                .orElse(null);
    } else {
        return null;
    }
}
 
Example #8
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 #9
Source File: AudioCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String content) throws DiscordException {
    Member member = message.getMember();
    if (member == null) {
        return false;
    }
    if (!featureSetService.isAvailable(message.getGuild())) {
        discordService.sendBonusMessage(message.getChannel().getIdLong());
        return false;
    }
    if (!playerService.hasAccess(member)) {
        throw new ValidationException("discord.command.audio.missingAccess");
    }
    if (isActiveOnly() && !playerService.isActive(message.getGuild())) {
        messageManager.onMessage(message.getChannel(), "discord.command.audio.notStarted");
        return false;
    }
    if (isChannelRestricted() && !playerService.isInChannel(member)) {
        VoiceChannel channel = playerService.getChannel(member);
        throw new ValidationException("discord.command.audio.joinChannel", channel != null ? channel.getName() : "unknown");
    }
    return doInternal(message, context, content);
}
 
Example #10
Source File: Network.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
public void connect(Player player) {
    players.add(player);

    Member member = VoiceModule.getMember(player);
    DiscordSRV.debug(player.getName() + "/" + member + " is connecting to " + getChannel());
    if (member != null && member.getVoiceState() != null && member.getVoiceState().inVoiceChannel()) {
        try {
            VoiceModule.getGuild().moveVoiceMember(member, getChannel()).complete();
            synchronized (VoiceModule.getMutedUsers()) {
                if (VoiceModule.getMutedUsers().contains(member.getId())) {
                    member.mute(false).queue();
                    VoiceModule.getMutedUsers().remove(member.getId());
                }
            }
        } catch (Exception e) {
            DiscordSRV.error("Failed to move member " + member + " into voice channel " + getChannel() + ": " + e.getMessage());
        }
    }
}
 
Example #11
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 #12
Source File: ImagingServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private BufferedImage getStatusLayer(Member member, OnlineStatus status) {
    if (member == null && status == null) {
        return null;
    }
    if (member != null) {
        if (member.getActivities().stream().anyMatch(e -> e.getType() == Activity.ActivityType.STREAMING)) {
            return getResourceImage("avatar-status-streaming.png");
        }
        status = member.getOnlineStatus();
    }
    return getResourceImage(String.format("avatar-status-%s.png", status.getKey()));
}
 
Example #13
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.Member Members}
 *
 * @return Immutable list of affected members
 */
@Nonnull
public List<Member> getChangedMembers()
{
    return changed.stream()
        .filter(it -> it instanceof Member)
        .map(Member.class::cast)
        .collect(Collectors.toList());
}
 
Example #14
Source File: EmbedJSON.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public MessageEmbed gen(Member member) {
    EmbedBuilder embedBuilder = new EmbedBuilder();
    if (title != null) embedBuilder.setTitle(title, titleUrl);
    if (description != null) embedBuilder.setDescription(description);
    if (author != null) embedBuilder.setAuthor(author, authorUrl, authorImg);
    if (footer != null) embedBuilder.setFooter(footer, footerImg);
    if (image != null) embedBuilder.setImage(image);
    if (thumbnail != null) embedBuilder.setThumbnail(thumbnail);
    if (color != null) {
        Color col = null;
        try {
            col = (Color) Color.class.getField(color).get(null);
        } catch (Exception ignored) {
            String colorLower = color.toLowerCase();
            if (colorLower.equals("member")) {
                if (member != null)
                    col = member.getColor();
            } else if (colorLower.matches("#?(0x)?[0123456789abcdef]{1,6}")) {
                try {
                    col = Color.decode(colorLower.startsWith("0x") ? colorLower : "0x" + colorLower);
                } catch (Exception ignored2) {
                }
            }
        }
        if (col != null) embedBuilder.setColor(col);
    }

    fields.forEach(f -> {
        if (f == null) {
            embedBuilder.addBlankField(false);
        } else if (f.value == null) {
            embedBuilder.addBlankField(f.inline);
        } else {
            embedBuilder.addField(f.name == null ? "" : f.name, f.value, f.inline);
        }
    });

    return embedBuilder.build();
}
 
Example #15
Source File: MemberCacheViewImpl.java    From JDA with 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 #16
Source File: GuildUpdateOwnerEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GuildUpdateOwnerEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nullable Member oldOwner,
                             long prevId, long nextId)
{
    super(api, responseNumber, guild, oldOwner, guild.getOwner(), IDENTIFIER);
    this.prevId = prevId;
    this.nextId = nextId;
}
 
Example #17
Source File: ImageCommandBase.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
protected String getImageFromCommand(CommandContext ctx) {
    final List<String> args = ctx.getArgs();
    String url = null;

    if (!ctx.getMessage().getAttachments().isEmpty()) {
        url = tryGetAttachment(ctx);
    }

    if (url == null && args.isEmpty()) {
        url = getAvatarUrl(ctx.getAuthor());
    }

    if (url == null && AirUtils.isURL(args.get(0))) {
        url = tryGetUrl(ctx, args.get(0));
    }

    if (url == null && !ctx.getMessage().getMentionedUsers().isEmpty()) {
        url = getAvatarUrl(ctx.getMessage().getMentionedUsers().get(0));
    }

    if (url  == null) {
        final List<Member> textMentions = FinderUtils.searchMembers(ctx.getArgsJoined(), ctx);

        if (!textMentions.isEmpty()) {
            url = getAvatarUrl(textMentions.get(0).getUser());
        }
    }

    if (url == null) {
        url = getAvatarUrl(ctx.getAuthor());
    }

    return url;
}
 
Example #18
Source File: VoiceActivityListener.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private void stopRecord(VoiceChannel channel, Member member) {
    GuildVoiceActivityTracker tracker = trackers.getIfPresent(channel.getGuild().getIdLong());
    if (tracker == null) {
        return;
    }
    MemberVoiceState state = tracker.remove(channel, member);
    if (state != null) {
        rankingService.addVoiceActivity(member, state);
    }
    if (tracker.isEmpty()) {
        trackers.invalidate(channel.getIdLong());
    }
}
 
Example #19
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
public ChunkRequest(BiConsumer<Boolean, List<Member>> handler, GuildImpl guild, DataObject request)
{
    this.handler = handler;
    this.guild = guild;
    this.nonce = ThreadLocalRandom.current().nextLong() & ~1;
    this.request = request.put("nonce", getNonce());
}
 
Example #20
Source File: UnMuteCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean doCommand(MemberReference reference, GuildMessageReceivedEvent event, BotContext context, String query) {
    Member violator = reference.getMember();
    if (violator == null) {
        messageService.onError(event.getChannel(), "discord.command.mod.unmute.mention");
        return false;
    }
    boolean unmuted = muteService.unmute(event.getMember(), event.getChannel(), violator);
    messageService.onEmbedMessage(event.getChannel(), unmuted
            ? "discord.command.mod.unmute.done" : "discord.command.mod.unmute.already", violator.getEffectiveName());
    return true;
}
 
Example #21
Source File: CurrencyCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void level(CommandRegistry cr) {
    cr.register("level", new SimpleCommand(CommandCategory.CURRENCY) {
        @Override
        protected void call(Context ctx, String content, String[] args) {
            Member member = Utils.findMember(ctx.getEvent(), ctx.getMember(), content);
            if (member == null)
                return;

            if (member.getUser().isBot()) {
                ctx.sendLocalized("commands.level.bot_notice", EmoteReference.ERROR);
                return;
            }

            Player player = MantaroData.db().getPlayer(member);
            long experienceNext = (long) (player.getLevel() * Math.log10(player.getLevel()) * 1000) + (50 * player.getLevel() / 2);

            if (member.getUser().getIdLong() == ctx.getAuthor().getIdLong()) {
                ctx.sendLocalized("commands.level.own_success",
                        EmoteReference.ZAP, player.getLevel(), player.getData().getExperience(), experienceNext
                );
            } else {
                ctx.sendLocalized("commands.level.success_other",
                        EmoteReference.ZAP, member.getUser().getAsTag(), player.getLevel(), player.getData().getExperience(), experienceNext
                );
            }
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder()
                    .setDescription("Checks your level or the level of another user.")
                    .setUsage("~>level [user]")
                    .addParameterOptional("user", "The user to check the id of. Can be a mention, tag or id.")
                    .build();
        }
    });
}
 
Example #22
Source File: GenericGuildMemberUpdateEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GenericGuildMemberUpdateEvent(
    @Nonnull JDA api, long responseNumber, @Nonnull Member member,
    @Nullable T previous, @Nullable T next, @Nonnull String identifier)
{
    super(api, responseNumber, member);
    this.previous = previous;
    this.next = next;
    this.identifier = identifier;
}
 
Example #23
Source File: UnifiedCacheViewImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsById(long id)
{
    return Collections.unmodifiableList(distinctStream()
        .map(view -> view.getElementById(id))
        .filter(Objects::nonNull)
        .collect(Collectors.toList()));
}
 
Example #24
Source File: ChoiceStateHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected void outPlayer(MafiaInstance instance, MafiaPlayer player) {
    player.out();
    TextChannel goonChannel = instance.getGoonChannel();
    if (player.getRole() == MafiaRole.GOON && goonChannel != null) {
        Member member = player.getMember();
        if (member != null) {
            PermissionOverride override = goonChannel.getPermissionOverride(player.getMember());
            override.delete().queue();
        }
    }
}
 
Example #25
Source File: MafiaPlayer.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public String getName() {
    Member member = getMember();
    if (member != null) {
        return member.getEffectiveName();
    }
    User user = jda.getUserById(memberId);
    return user != null ? user.getName() : String.valueOf(memberId);
}
 
Example #26
Source File: ModerationServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public boolean isModerator(Member member) {
    if (member == null) {
        return false;
    }
    if (member.hasPermission(Permission.ADMINISTRATOR) || member.isOwner()) {
        return true;
    }
    ModerationConfig config = moderationConfigService.get(member.getGuild());
    return config != null && CollectionUtils.isNotEmpty(config.getRoles())
            && member.getRoles().stream().anyMatch(e -> config.getRoles().contains(e.getIdLong()));
}
 
Example #27
Source File: MafiaInstance.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public String getGoonsMentions() {
    return getGoons().stream()
            .map(MafiaPlayer::getMember)
            .filter(Objects::nonNull)
            .map(Member::getAsMention)
            .collect(Collectors.joining(" "));
}
 
Example #28
Source File: SupportServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isModerator(@NonNull Member member) {
    Long moderatorRoleId = workerProperties.getSupport().getModeratorRoleId();
    if (moderatorRoleId == null) {
        return false;
    }
    Guild supportGuild = getSupportGuild();
    if (supportGuild == null || !supportGuild.equals(member.getGuild())) {
        return false;
    }
    Role moderatorRole = supportGuild.getRoleById(moderatorRoleId);
    return moderatorRole != null && member.getRoles().contains(moderatorRole);
}
 
Example #29
Source File: UnifiedCacheViewImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Member> getElementsWithRoles(@Nonnull Role... roles)
{
    return Collections.unmodifiableList(distinctStream()
        .flatMap(view -> view.getElementsWithRoles(roles).stream())
        .collect(Collectors.toList()));
}
 
Example #30
Source File: StoredPlaylistServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public void storeToPlaylist(PlaybackInstance instance, List<TrackRequest> requests) {
    if (CollectionUtils.isEmpty(requests)) {
        return;
    }
    Member member = requests.stream()
            .map(TrackRequest::getMember)
            .filter(Objects::nonNull)
            .findFirst()
            .orElse(null);
    if (member == null) {
        return;
    }
    LocalMember localMember = entityAccessor.getOrCreate(member);

    try {
        Playlist playlist = getPlaylist(instance);
        for (TrackRequest request : requests) {
            PlaylistItem item = createItem(request.getTrack(), localMember);
            item.setPlaylist(playlist);
            item.setData(getAudioPlayerManager().encodeTrack(request.getTrack()));
            playlist.getItems().add(item);
        }
        playlistRepository.save(playlist);
    } catch (Exception e) {
        log.warn("[store] Could not update playlist", e);
    }
}