lavalink.client.io.Link Java Examples

The following examples show how to use lavalink.client.io.Link. 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: JDAVoiceInterceptor.java    From Lavalink-Client with MIT License 6 votes vote down vote up
@Override
public boolean onVoiceStateUpdate(@Nonnull VoiceStateUpdate update) {

    VoiceChannel channel = update.getChannel();
    JdaLink link = lavalink.getLink(update.getGuildId());

    if (channel == null) {
        // Null channel means disconnected
        if (link.getState() != Link.State.DESTROYED) {
            link.onDisconnected();
        }
    } else {
        link.setChannel(channel.getId()); // Change expected channel
    }

    return link.getState() == Link.State.CONNECTED;
}
 
Example #2
Source File: LavalinkTest.java    From Lavalink-Client with MIT License 6 votes vote down vote up
private static void ensureConnected(JdaLavalink lavalink, VoiceChannel voiceChannel) {
    JdaLink link = lavalink.getLink(voiceChannel.getGuild());
    link.connect(voiceChannel);
    long started = System.currentTimeMillis();
    while (link.getState() != Link.State.CONNECTED
            && System.currentTimeMillis() - started < 10000 //wait 10 sec max
            && !Thread.currentThread().isInterrupted()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        link.connect(voiceChannel);
    }

    assertEquals(Link.State.CONNECTED, link.getState(), "Failed to connect to voice channel in a reasonable amount of time");
}
 
Example #3
Source File: LavalinkTest.java    From Lavalink-Client with MIT License 6 votes vote down vote up
private static void ensureNotConnected(JdaLavalink lavalink, VoiceChannel voiceChannel) {
    Link link = lavalink.getLink(voiceChannel.getGuild());
    link.disconnect();
    long started = System.currentTimeMillis();
    while (link.getState() != Link.State.NOT_CONNECTED && link.getState() != Link.State.DISCONNECTING
            && System.currentTimeMillis() - started < 10000 //wait 10 sec max
            && !Thread.currentThread().isInterrupted()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        link.disconnect();
    }

    assertTrue(link.getState() == Link.State.NOT_CONNECTED
            || link.getState() == Link.State.DISCONNECTING, "Failed to disconnect from voice channel in a reasonable amount of time");
}
 
Example #4
Source File: DefaultAudioServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void closeConnection(Guild guild) {
    if (lavaLink != null) {
        Link link = lavaLink.getExistingLink(guild);
        if (link != null
                && link.getState() != Link.State.DESTROYED
                && link.getState() != Link.State.DESTROYING) {
            link.destroy();

            // Sometimes JDA thinks that bot is connected to channel,
            // we should manually clear this state to let Lavalink connect to it again
            if (guild.getSelfMember().getVoiceState() instanceof GuildVoiceStateImpl) {
                GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) guild.getSelfMember().getVoiceState();
                voiceState.setConnectedChannel(null);
            }
        }
    } else {
        guild.getAudioManager().closeAudioConnection();
    }
}
 
Example #5
Source File: LavalinkTest.java    From Lavalink-Client with MIT License 5 votes vote down vote up
@Test
void vcJoinTest() {
    VoiceChannel vc = fetchVoiceChannel(jda, getTestVoiceChannelId());
    ensureConnected(lavalink, vc);
    assertEquals(Link.State.CONNECTED, lavalink.getLink(vc.getGuild()).getState(), "Failed to connect to voice channel");
    ensureNotConnected(lavalink, vc);
}
 
Example #6
Source File: DefaultAudioServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isConnected(Guild guild) {
    if (lavaLink != null) {
        Link link = lavaLink.getLink(guild);
        return link.getState() == Link.State.CONNECTED || link.getState() == Link.State.CONNECTING;
    } else {
        AudioManager audioManager = guild.getAudioManager();
        return audioManager != null && (audioManager.isConnected() || audioManager.isAttemptingToConnect());
    }
}
 
Example #7
Source File: TrackScheduler.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public TrackScheduler(Link player, String guildId) {
    this.audioPlayer = player;
    this.queue = new ConcurrentLinkedDeque<>();
    this.guildId = guildId;
    this.voteSkips = new ArrayList<>();
    this.voteStop = new ArrayList<>();

    //Only take guild language settings into consideration for announcement messages.
    this.language = I18n.of(guildId);
}
 
Example #8
Source File: TrackScheduler.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public Link getAudioPlayer() {
    if (audioPlayer == null) {
        audioPlayer = MantaroBot.getInstance().getLavaLink().getLink(guildId);
    }

    return audioPlayer;
}
 
Example #9
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 4 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public Link getLink() {
    return link;
}
 
Example #10
Source File: LavalinkManager.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean isConnected(Guild g) {
    return isEnabled() ?
        lavalink.getLink(g).getState() == Link.State.CONNECTED :
        g.getAudioManager().isConnected();
}
 
Example #11
Source File: AudioMessageManager.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
private EmbedBuilder getPlayMessage(TrackRequest request) {
    EmbedBuilder builder = getBasicMessage(request);
    builder.setDescription(null);

    AudioTrackInfo info = request.getTrack().getInfo();
    PlaybackInstance instance = TrackData.get(request.getTrack()).getInstance();
    boolean refreshable = isRefreshable(instance.getGuildId());

    String durationText;
    if (request.getEndReason() != null) {
        StringBuilder reasonBuilder = new StringBuilder();

        boolean hasDuration = !info.isStream && info.length > 0;
        if (hasDuration) {
            reasonBuilder.append(CommonUtils.formatDuration(request.getTrack().getDuration())).append(" (");
        }
        reasonBuilder.append(messageService.getEnumTitle(request.getEndReason()));

        String endMember = getMemberName(request, true);
        if (StringUtils.isNotBlank(endMember)) {
            reasonBuilder
                    .append(" - **")
                    .append(endMember)
                    .append("**");
        }
        if (hasDuration) {
            reasonBuilder.append(")");
        }
        reasonBuilder.append(CommonUtils.EMPTY_SYMBOL);
        durationText = reasonBuilder.toString();
    } else {
        durationText = getTextProgress(instance, request.getTrack(), refreshable);
    }

    if (instance.getPlaylistUuid() != null) {
        builder.setDescription(messageService.getMessage("discord.command.audio.panel.playlist",
                commonProperties.getBranding().getWebsiteUrl(), instance.getPlaylistUuid()));
    }

    int size = instance.getQueue().size();
    if (request.getEndReason() == null && size > 1) {
        MusicConfig config = musicConfigService.getByGuildId(instance.getGuildId());
        if (config != null && config.isShowQueue()) {
            List<TrackRequest> next = instance.getQueue().subList(1, Math.min(size, MAX_SHORT_QUEUE + 1));
            addQueue(builder, instance, next, 2 + instance.getCursor(), true);
        }
    }

    if (request.getTrack().getInfo().isStream || !refreshable) {
        builder.addField(messageService.getMessage("discord.command.audio.panel.duration"),
                durationText, true);
        builder.addField(messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false), true);
    } else {
        String requestedBy = String.format("%s: %s",
                messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false));
        builder.addField(requestedBy, durationText, true);
    }

    if (request.getEndReason() == null) {
        IPlayer player = instance.getPlayer();
        if (player.getVolume() != 100) {
            int volume = player.getVolume();
            builder.addField(messageService.getMessage("discord.command.audio.panel.volume"),
                    String.format("%d%% %s", volume, CommonUtils.getVolumeIcon(volume)), true);
        }
        if (!RepeatMode.NONE.equals(instance.getMode())) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.repeatMode"),
                    instance.getMode().getEmoji(), true);
        }
        if (player.isPaused()) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.paused"),
                    "\u23F8", true);
        }

        if (player instanceof LavalinkPlayer) {
            LavalinkPlayer lavalinkPlayer = (LavalinkPlayer) player;
            Link link = lavalinkPlayer.getLink();
            if (link != null) {
                LavalinkSocket socket = link.getNode(false);
                if (socket != null) {
                    StringBuilder statsBuilder = new StringBuilder(messageService
                            .getMessage("discord.command.audio.panel.poweredBy", socket.getName()));
                    if (refreshable && socket.getStats() != null) {
                        long load = Math.round(socket.getStats().getSystemLoad() * 100);
                        if (load < 0) load = 0;
                        if (load > 100) load = 100;
                        statsBuilder
                                .append(" ")
                                .append(messageService.getMessage("discord.command.audio.panel.load", load));
                    }
                    builder.setFooter(statsBuilder.toString(), null);
                }
            }
        }
    }
    return builder;
}
 
Example #12
Source File: AudioCmdUtils.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public static CompletionStage<Boolean> connectToVoiceChannel(GuildMessageReceivedEvent event, I18nContext lang) {
    VoiceChannel userChannel = event.getMember().getVoiceState().getChannel();
    Guild guild = event.getGuild();
    TextChannel textChannel = event.getChannel();

    //I can't see you in any VC here?
    if (userChannel == null) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.user_no_vc"), EmoteReference.ERROR).queue();
        return completedFuture(false);
    }

    //Can't connect to this channel
    if (!guild.getSelfMember().hasPermission(userChannel, Permission.VOICE_CONNECT)) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.missing_permissions_connect"), EmoteReference.ERROR, lang.get("discord_permissions.voice_connect")).queue();
        return completedFuture(false);
    }

    //Can't speak on this channel
    if (!guild.getSelfMember().hasPermission(userChannel, Permission.VOICE_SPEAK)) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.missing_permission_speak"), EmoteReference.ERROR, lang.get("discord_permissions.voice_speak")).queue();
        return completedFuture(false);
    }

    //Set the custom guild music channel from the db value
    VoiceChannel guildMusicChannel = null;
    if (MantaroData.db().getGuild(guild).getData().getMusicChannel() != null)
        guildMusicChannel = guild.getVoiceChannelById(MantaroData.db().getGuild(guild).getData().getMusicChannel());

    //This is where we call LL.
    JdaLink link = MantaroBot.getInstance().getAudioManager().getMusicManager(guild).getLavaLink();
    if (guildMusicChannel != null) {
        //If the channel is not the set one, reject this connect.
        if (!userChannel.equals(guildMusicChannel)) {
            textChannel.sendMessageFormat(lang.get("commands.music_general.connect.channel_locked"), EmoteReference.ERROR, guildMusicChannel.getName()).queue();
            return completedFuture(false);
        }

        //If the link is not currently connected or connecting, accept connection and call openAudioConnection
        if (link.getState() != Link.State.CONNECTED && link.getState() != Link.State.CONNECTING) {
            log.debug("Connected to channel {}. Reason: Link is not CONNECTED or CONNECTING and we requested a connection from connectToVoiceChannel (custom music channel)", userChannel.getId());
            return openAudioConnection(event, link, userChannel, lang).thenApply(__ -> true);
        }

        //Nothing to connect to, but pass true so we can load the song (for example, it's already connected)
        return completedFuture(true);
    }

    //Assume last channel it's the one it was attempting to connect to? (on the one below this too)
    //If the link is CONNECTED and the lastChannel is not the one it's already connected to, reject connection
    if (link.getState() == Link.State.CONNECTED && link.getLastChannel() != null && !link.getLastChannel().equals(userChannel.getId())) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.already_connected"), EmoteReference.WARNING, guild.getVoiceChannelById(link.getLastChannel()).getName()).queue();
        return completedFuture(false);
    }

    //If the link is CONNECTING and the lastChannel is not the one it's already connected to, reject connection
    if (link.getState() == Link.State.CONNECTING && link.getLastChannel() != null && !link.getLastChannel().equals(userChannel.getId())) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.attempting_to_connect"), EmoteReference.ERROR, guild.getVoiceChannelById(link.getLastChannel()).getName()).queue();
        return completedFuture(false);
    }

    //If the link is not currently connected or connecting, accept connection and call openAudioConnection
    if (link.getState() != Link.State.CONNECTED && link.getState() != Link.State.CONNECTING) {
        log.debug("Connected to voice channel {}. Reason: Link is not CONNECTED or CONNECTING and we requested a connection from connectToVoiceChannel", userChannel.getId());
        return openAudioConnection(event, link, userChannel, lang).thenApply(__ -> true);
    }

    //Nothing to connect to, but pass true so we can load the song (for example, it's already connected)
    return completedFuture(true);
}
 
Example #13
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 2 votes vote down vote up
/**
 * Constructor only for internal use
 *
 * @param link the parent link
 */
public LavalinkPlayer(Link link) {
    this.link = link;
    addListener(new LavalinkInternalPlayerEventHandler());
}