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

The following examples show how to use net.dv8tion.jda.api.entities.Member. 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
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 2
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 3
Source Project: JuniperBot   Source File: AudioCommand.java    License: 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 4
Source Project: DiscordSRV   Source File: NicknameUpdater.java    License: 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 5
Source Project: JDA   Source File: MemberCacheViewImpl.java    License: 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 6
Source Project: JuniperBot   Source File: PlayerServiceImpl.java    License: 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 7
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 8
Source Project: DiscordSRV   Source File: Network.java    License: 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 9
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 10
@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 11
Source Project: Arraybot   Source File: UUser.java    License: 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 12
@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 13
Source Project: JDA   Source File: MemberChunkManager.java    License: Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Void> chunkGuild(GuildImpl guild, String query, int limit, BiConsumer<Boolean, List<Member>> handler)
{
    init();
    DataObject request = DataObject.empty()
            .put("guild_id", guild.getId())
            .put("limit", Math.min(100, Math.max(1, limit)))
            .put("query", query);

    ChunkRequest chunkRequest = new ChunkRequest(handler, guild, request);
    makeRequest(chunkRequest);
    return chunkRequest;
}
 
Example 14
Source Project: MantaroBot   Source File: EmbedJSON.java    License: 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 Project: JDA   Source File: CategoryUpdatePermissionsEvent.java    License: 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 16
Source Project: JDA   Source File: GenericGuildMemberUpdateEvent.java    License: 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 17
Source Project: JDA   Source File: UnifiedCacheViewImpl.java    License: 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 18
@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 19
@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);
    }
}
 
Example 20
Source Project: JDA   Source File: UnifiedCacheViewImpl.java    License: 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 21
Source Project: JuniperBot   Source File: MafiaInstance.java    License: 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 22
@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 23
Source Project: JuniperBot   Source File: MafiaPlayer.java    License: 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 24
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 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 26
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 27
Source Project: MantaroBot   Source File: CurrencyCmds.java    License: 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 28
Source Project: JDA   Source File: GuildUpdateOwnerEvent.java    License: 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 29
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 30
Source Project: JDA   Source File: MemberChunkManager.java    License: 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());
}