Search in sources :

Example 6 with AudioChannel

use of net.dv8tion.jda.api.entities.AudioChannel in project JDA by DV8FromTheWorld.

the class AudioWebSocket method close.

protected void close(final ConnectionStatus closeStatus) {
    // Makes sure we don't run this method again after the socket.close(1000) call fires onDisconnect
    if (shutdown)
        return;
    locked((manager) -> {
        if (shutdown)
            return;
        ConnectionStatus status = closeStatus;
        ready = false;
        shutdown = true;
        stopKeepAlive();
        if (audioConnection.udpSocket != null)
            audioConnection.udpSocket.close();
        if (socket != null)
            socket.sendClose();
        audioConnection.shutdown();
        AudioChannel disconnectedChannel = manager.getConnectedChannel();
        manager.setAudioConnection(null);
        // Verify that it is actually a lost of connection and not due the connected channel being deleted.
        JDAImpl api = getJDA();
        if (status == ConnectionStatus.DISCONNECTED_KICKED_FROM_CHANNEL && (!api.getClient().isSession() || !api.getClient().isConnected())) {
            LOG.debug("Connection was closed due to session invalidate!");
            status = ConnectionStatus.ERROR_CANNOT_RESUME;
        } else if (status == ConnectionStatus.ERROR_LOST_CONNECTION || status == ConnectionStatus.DISCONNECTED_KICKED_FROM_CHANNEL) {
            // Get guild from JDA, don't use [guild] field to make sure that we don't have
            // a problem of an out of date guild stored in [guild] during a possible mWS invalidate.
            Guild connGuild = api.getGuildById(guild.getIdLong());
            if (connGuild != null) {
                AudioChannel channel = (AudioChannel) connGuild.getGuildChannelById(audioConnection.getChannel().getIdLong());
                if (channel == null)
                    status = ConnectionStatus.DISCONNECTED_CHANNEL_DELETED;
            }
        }
        changeStatus(status);
        // decide if we reconnect.
        if (shouldReconnect && // indicated that the connection was purposely closed. don't reconnect.
        status.shouldReconnect() && // Already handled.
        status != ConnectionStatus.AUDIO_REGION_CHANGE) {
            if (disconnectedChannel == null) {
                LOG.debug("Cannot reconnect due to null audio channel");
                return;
            }
            api.getDirectAudioController().reconnect(disconnectedChannel);
        } else if (status == ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD) {
            // Remove audio manager as we are no longer in the guild
            api.getAudioManagersView().remove(guild.getIdLong());
        } else if (status != ConnectionStatus.AUDIO_REGION_CHANGE && status != ConnectionStatus.DISCONNECTED_KICKED_FROM_CHANNEL) {
            api.getDirectAudioController().disconnect(guild);
        }
    });
}
Also used : AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) JDAImpl(net.dv8tion.jda.internal.JDAImpl) ConnectionStatus(net.dv8tion.jda.api.audio.hooks.ConnectionStatus) Guild(net.dv8tion.jda.api.entities.Guild)

Example 7 with AudioChannel

use of net.dv8tion.jda.api.entities.AudioChannel in project JDA by DV8FromTheWorld.

the class GuildMemberRemoveHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    final long id = content.getLong("guild_id");
    boolean setup = getJDA().getGuildSetupController().onRemoveMember(id, content);
    if (setup)
        return null;
    GuildImpl guild = (GuildImpl) getJDA().getGuildsView().get(id);
    if (guild == null) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    final long userId = content.getObject("user").getUnsignedLong("id");
    if (userId == getJDA().getSelfUser().getIdLong()) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    // Update the memberCount
    guild.onMemberRemove();
    CacheView.SimpleCacheView<MemberPresenceImpl> presences = guild.getPresenceView();
    if (presences != null)
        presences.remove(userId);
    User user = api.getEntityBuilder().createUser(content.getObject("user"));
    MemberImpl member = (MemberImpl) guild.getMembersView().remove(userId);
    if (member == null) {
        // WebSocketClient.LOG.debug("Received GUILD_MEMBER_REMOVE for a Member that does not exist in the specified Guild. UserId: {} GuildId: {}", userId, id);
        // Remove user from voice channel if applicable
        guild.getVoiceChannelsView().forEachUnordered((channel) -> {
            VoiceChannelImpl impl = (VoiceChannelImpl) channel;
            Member connected = impl.getConnectedMembersMap().remove(userId);
            if (// user left channel!
            connected != null) {
                getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, connected, channel));
            }
        });
        // Fire cache independent event, we can still inform the library user about the member removal
        getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, null));
        return null;
    }
    GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
    if (// If this user was in an AudioChannel, fire VoiceLeaveEvent.
    voiceState != null && voiceState.inAudioChannel()) {
        AudioChannel channel = voiceState.getChannel();
        voiceState.setConnectedChannel(null);
        ((AudioChannelMixin<?>) channel).getConnectedMembersMap().remove(userId);
        getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, member, channel));
    }
    // The user is not in a different guild that we share
    SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
    try (UnlockHook hook = userView.writeLock()) {
        if (// don't remove selfUser from cache
        userId != getJDA().getSelfUser().getIdLong() && getJDA().getGuildsView().stream().noneMatch(g -> g.getMemberById(userId) != null)) {
            userView.remove(userId);
            getJDA().getEventCache().clear(EventCache.Type.USER, userId);
        }
    }
    // Cache independent event
    getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, member));
    return null;
}
Also used : GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) net.dv8tion.jda.internal.entities(net.dv8tion.jda.internal.entities) JDAImpl(net.dv8tion.jda.internal.JDAImpl) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) Member(net.dv8tion.jda.api.entities.Member) DataObject(net.dv8tion.jda.api.utils.data.DataObject) User(net.dv8tion.jda.api.entities.User) AudioChannelMixin(net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) User(net.dv8tion.jda.api.entities.User) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) Member(net.dv8tion.jda.api.entities.Member)

Example 8 with AudioChannel

use of net.dv8tion.jda.api.entities.AudioChannel in project JDA by DV8FromTheWorld.

the class WebSocketClient method getNextAudioConnectRequest.

protected ConnectionRequest getNextAudioConnectRequest() {
    // Don't try to setup audio connections before JDA has finished loading.
    if (sessionId == null)
        return null;
    long now = System.currentTimeMillis();
    AtomicReference<ConnectionRequest> request = new AtomicReference<>();
    queuedAudioConnections.retainEntries((// we use this because it locks the mutex
    guildId, // we use this because it locks the mutex
    audioRequest) -> {
        if (audioRequest.getNextAttemptEpoch() < now) {
            // Check if the guild is ready
            Guild guild = api.getGuildById(guildId);
            if (guild == null) {
                // Not yet ready, check if the guild is known to this shard
                GuildSetupController controller = api.getGuildSetupController();
                if (!controller.isKnown(guildId)) {
                    // The guild is not tracked anymore -> we can't connect the audio channel
                    LOG.debug("Removing audio connection request because the guild has been removed. {}", audioRequest);
                    return false;
                }
                return true;
            }
            ConnectionListener listener = guild.getAudioManager().getConnectionListener();
            if (audioRequest.getStage() != ConnectionStage.DISCONNECT) {
                // Check if we can connect to the target channel
                AudioChannel channel = (AudioChannel) guild.getGuildChannelById(audioRequest.getChannelId());
                if (channel == null) {
                    if (listener != null)
                        listener.onStatusChange(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
                    return false;
                }
                IPermissionContainer permChannel = (IPermissionContainer) channel;
                if (!guild.getSelfMember().hasPermission(permChannel, Permission.VOICE_CONNECT)) {
                    if (listener != null)
                        listener.onStatusChange(ConnectionStatus.DISCONNECTED_LOST_PERMISSION);
                    return false;
                }
            }
            // This will take the first result
            request.compareAndSet(null, audioRequest);
        }
        return true;
    });
    return request.get();
}
Also used : ConnectionRequest(net.dv8tion.jda.internal.audio.ConnectionRequest) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConnectionListener(net.dv8tion.jda.api.audio.hooks.ConnectionListener) Guild(net.dv8tion.jda.api.entities.Guild) IPermissionContainer(net.dv8tion.jda.api.entities.IPermissionContainer)

Example 9 with AudioChannel

use of net.dv8tion.jda.api.entities.AudioChannel in project discord-bot-reddit-java by Glaxier0.

the class PlayCommand method playMusic.

private void playMusic(SlashCommandInteractionEvent event, List<String> youtubeLinks) {
    AudioChannel userChannel = event.getMember().getVoiceState().getChannel();
    AudioChannel botChannel = event.getGuild().getSelfMember().getVoiceState().getChannel();
    boolean isUserInVoiceChannel = event.getMember().getVoiceState().inAudioChannel();
    boolean isBotInVoiceChannel = event.getGuild().getSelfMember().getVoiceState().inAudioChannel();
    if (isUserInVoiceChannel && !youtubeLinks.isEmpty()) {
        if (!isBotInVoiceChannel) {
            GuildMusicManager musicManager = PlayerManager.getInstance().getMusicManager(event);
            musicManager.scheduler.player.destroy();
            musicManager.scheduler.queue.clear();
            event.getGuild().getAudioManager().openAudioConnection(userChannel);
            botChannel = userChannel;
        }
        if (botChannel.equals(userChannel)) {
            int trackSize = youtubeLinks.size();
            if (trackSize > 1) {
                PlayerManager.getInstance().loadMultipleAndPlay(event, youtubeLinks);
            } else if (trackSize == 1) {
                PlayerManager.getInstance().loadAndPlay(event, youtubeLinks.get(0));
            }
        }
    }
}
Also used : AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) GuildMusicManager(com.discord.bot.audioplayer.GuildMusicManager)

Example 10 with AudioChannel

use of net.dv8tion.jda.api.entities.AudioChannel in project Bean by Xirado.

the class JoinCommand method executeCommand.

@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
    Member member = event.getMember();
    GuildVoiceState voiceState = member.getVoiceState();
    if (voiceState.getChannel() == null) {
        event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in a voice channel to run this command!")).queue();
        return;
    }
    GuildVoiceState state = event.getGuild().getSelfMember().getVoiceState();
    if (state.getChannel() != null) {
        AudioChannel channel = state.getChannel();
        if (voiceState.getChannel().getIdLong() == channel.getIdLong()) {
            event.replyEmbeds(EmbedUtil.errorEmbed("I already joined this channel!")).queue();
            return;
        }
        if (Util.getListeningUsers(channel) > 0) {
            event.replyEmbeds(EmbedUtil.errorEmbed("I am already playing music in **" + channel.getName() + "**!")).queue();
            return;
        }
    }
    GuildAudioPlayer audioPlayer = Bean.getInstance().getAudioManager().getAudioPlayer(event.getGuild().getIdLong());
    try {
        audioPlayer.getLink().connect(voiceState.getChannel());
    } catch (PermissionException exception) {
        event.replyEmbeds(EmbedUtil.errorEmbed("I do not have permission to join this channel!")).queue();
        return;
    }
    event.replyEmbeds(EmbedUtil.successEmbed("Joined <#" + voiceState.getChannel().getIdLong() + ">!")).setEphemeral(true).queue();
    audioPlayer.playerSetup((GuildMessageChannel) event.getChannel(), (s) -> {
    }, e -> {
    });
}
Also used : PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) GuildAudioPlayer(at.xirado.bean.music.GuildAudioPlayer) Member(net.dv8tion.jda.api.entities.Member)

Aggregations

AudioChannel (net.dv8tion.jda.api.entities.AudioChannel)10 Guild (net.dv8tion.jda.api.entities.Guild)4 DataObject (net.dv8tion.jda.api.utils.data.DataObject)3 GuildVoiceState (net.dv8tion.jda.api.entities.GuildVoiceState)2 Member (net.dv8tion.jda.api.entities.Member)2 VoiceDispatchInterceptor (net.dv8tion.jda.api.hooks.VoiceDispatchInterceptor)2 JDAImpl (net.dv8tion.jda.internal.JDAImpl)2 AudioChannelMixin (net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin)2 AudioManagerImpl (net.dv8tion.jda.internal.managers.AudioManagerImpl)2 GuildMusicManager (Core.Music.GuildMusicManager)1 CommandFlag (at.xirado.bean.command.CommandFlag)1 SlashCommand (at.xirado.bean.command.SlashCommand)1 SlashCommandContext (at.xirado.bean.command.SlashCommandContext)1 EmbedUtil (at.xirado.bean.misc.EmbedUtil)1 GuildAudioPlayer (at.xirado.bean.music.GuildAudioPlayer)1 GuildMusicManager (com.discord.bot.audioplayer.GuildMusicManager)1 OffsetDateTime (java.time.OffsetDateTime)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Permission (net.dv8tion.jda.api.Permission)1 ConnectionListener (net.dv8tion.jda.api.audio.hooks.ConnectionListener)1