Search in sources :

Example 11 with AudioPlaylist

use of com.sedmelluq.discord.lavaplayer.track.AudioPlaylist in project MantaroBot by Mantaro.

the class AudioRequester method playlistLoaded.

@Override
public void playlistLoaded(AudioPlaylist playlist) {
    if (playlist.isSearchResult()) {
        if (!skipSelection)
            onSearchResult(playlist);
        else
            loadSingle(playlist.getTracks().get(0), false);
        return;
    }
    int i = 0;
    for (AudioTrack track : playlist.getTracks()) {
        if (MantaroData.db().getGuild(event.getGuild()).getData().getMusicQueueSizeLimit() != null) {
            if (i < MantaroData.db().getGuild(event.getGuild()).getData().getMusicQueueSizeLimit()) {
                loadSingle(track, true);
            } else {
                event.getChannel().sendMessage(String.format(":warning: The queue you added had more than %d songs, so we added songs until this limit and ignored the rest.", MantaroData.db().getGuild(event.getGuild()).getData().getMusicQueueSizeLimit())).queue();
                break;
            }
        } else {
            if (i < MAX_QUEUE_LENGTH) {
                loadSingle(track, true);
            } else {
                event.getChannel().sendMessage(":warning: The queue you added had more than 300 songs, so we added songs until this limit and ignored the rest.").queue();
                break;
            }
        }
        i++;
    }
    event.getChannel().sendMessage(String.format("Added **%d songs** to queue on playlist: **%s** *(%s)*", i, playlist.getName(), Utils.getDurationMinutes(playlist.getTracks().stream().mapToLong(temp -> temp.getInfo().length).sum()))).queue();
}
Also used : FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) Color(java.awt.Color) Utils(net.kodehawa.mantarobot.utils.Utils) IntConsumer(java.util.function.IntConsumer) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) YoutubeAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Example 12 with AudioPlaylist

use of com.sedmelluq.discord.lavaplayer.track.AudioPlaylist in project MantaroBot by Mantaro.

the class AudioRequester method onSearchResult.

private void onSearchResult(AudioPlaylist playlist) {
    EmbedBuilder builder = new EmbedBuilder().setColor(Color.CYAN).setTitle("Song selection." + (MantaroData.db().getGuild(event.getGuild()).getData().isReactionMenus() ? "React to the desired number to select a song." : "Type the song number to continue."), null).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").setFooter("This timeouts in 10 seconds.", null);
    java.util.List<AudioTrack> tracks = playlist.getTracks();
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < 4 && i < tracks.size(); i++) {
        AudioTrack at = tracks.get(i);
        b.append(i + 1).append(".** [").append(at.getInfo().title).append("](").append(at.getInfo().uri).append(")**" + " (").append(Utils.getDurationMinutes(at.getInfo().length)).append(")").append("\n");
    }
    builder.setDescription(b);
    if (!event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION) || !MantaroData.db().getGuild(event.getGuild()).getData().isReactionMenus()) {
        event.getChannel().sendMessage(builder.setDescription(b.toString()).build()).queue();
        IntConsumer consumer = (c) -> loadSingle(playlist.getTracks().get(c - 1), false);
        DiscordUtils.selectInt(event, 5, consumer);
        return;
    }
    //just in case someone else uses play before timing out
    long id = event.getAuthor().getIdLong();
    ReactionOperations.create(event.getChannel().sendMessage(builder.build()).complete(), 15, (e) -> {
        if (e.getUser().getIdLong() != id)
            return false;
        int i = e.getReactionEmote().getName().charAt(0) - '0';
        if (i < 1 || i > 4)
            return false;
        loadSingle(playlist.getTracks().get(i - 1), false);
        event.getChannel().getMessageById(e.getMessageIdLong()).queue(m -> m.clearReactions().queue());
        return true;
    }, "1⃣", "2⃣", "3⃣", "4⃣");
}
Also used : FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) Color(java.awt.Color) Utils(net.kodehawa.mantarobot.utils.Utils) IntConsumer(java.util.function.IntConsumer) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) YoutubeAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) IntConsumer(java.util.function.IntConsumer)

Example 13 with AudioPlaylist

use of com.sedmelluq.discord.lavaplayer.track.AudioPlaylist in project BoltBot by DiscordBolt.

the class VoiceManager method queue.

public void queue(IGuild guild, IUser requester, String songID) throws CommandPermissionException, CommandRuntimeException, CommandStateException {
    if (songID.toLowerCase().contains("twitch.tv") && !MusicModule.hasAdminPermissions(requester, guild))
        throw new CommandPermissionException("You must be a \"" + MusicModule.ADMIN_ROLE + "\" to add Twitch.tv live streams!");
    if (requester.getVoiceStateForGuild(guild).getChannel() == null)
        throw new CommandStateException("You must be connected to a voice channel to execute this command!");
    if (getDJ(guild).getVoiceChannel() != null && !requester.getVoiceStateForGuild(guild).getChannel().equals(getDJ(guild).getVoiceChannel()))
        throw new CommandStateException("You must be in my voice channel to control the music!");
    DJ dj = getDJ(guild);
    if ((dj.getPlaying() != null && songID.contains(dj.getPlaying().getIdentifier())) || dj.getQueue().stream().anyMatch(t -> songID.contains(t.getIdentifier()))) {
        throw new CommandStateException("That song is already in the queue!");
    }
    playerManager.loadItemOrdered(dj, songID, new AudioLoadResultHandler() {

        @Override
        public void trackLoaded(AudioTrack track) {
            dj.queue(requester, track);
        }

        @Override
        public void playlistLoaded(AudioPlaylist playlist) {
            for (AudioTrack track : playlist.getTracks()) {
                dj.queue(requester, track);
            }
        }

        @Override
        public void noMatches() {
            throw new CommandRuntimeException("Sorry, I was unable to find the song you specified.");
        }

        @Override
        public void loadFailed(FriendlyException exception) {
            if (exception.severity == FriendlyException.Severity.COMMON)
                throw new CommandRuntimeException(exception.getMessage());
            throw new CommandRuntimeException("Sorry, an error occurred while loading your song. Please try again later.");
        }
    });
}
Also used : ExceptionMessage(com.discordbolt.boltbot.utils.ExceptionMessage) com.discordbolt.api.command.exceptions(com.discordbolt.api.command.exceptions) HashMap(java.util.HashMap) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) ReactionRemoveEvent(sx.blah.discord.handle.impl.events.guild.channel.message.reaction.ReactionRemoveEvent) IVoiceChannel(sx.blah.discord.handle.obj.IVoiceChannel) IMessage(sx.blah.discord.handle.obj.IMessage) IUser(sx.blah.discord.handle.obj.IUser) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) DefaultAudioPlayerManager(com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager) Semaphore(java.util.concurrent.Semaphore) ReactionAddEvent(sx.blah.discord.handle.impl.events.guild.channel.message.reaction.ReactionAddEvent) EventSubscriber(sx.blah.discord.api.events.EventSubscriber) Playlist(com.discordbolt.boltbot.modules.music.playlists.Playlist) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) AudioConfiguration(com.sedmelluq.discord.lavaplayer.player.AudioConfiguration) AudioPlayerManager(com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager) ChannelUtil(com.discordbolt.boltbot.utils.ChannelUtil) IGuild(sx.blah.discord.handle.obj.IGuild) List(java.util.List) MusicModule(com.discordbolt.boltbot.modules.music.MusicModule) AudioSourceManagers(com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) StandardAudioDataFormats(com.sedmelluq.discord.lavaplayer.format.StandardAudioDataFormats) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Example 14 with AudioPlaylist

use of com.sedmelluq.discord.lavaplayer.track.AudioPlaylist in project FredBoat by Frederikam.

the class TrackSearcher method searchForTracks.

/**
 * @param query         The search term
 * @param cacheMaxAge   Age of acceptable results from cache.
 * @param timeoutMillis How long to wait for each lavaplayer search to answer
 * @param providers     Providers that shall be used for the search. They will be used in the order they are provided, the
 *                      result of the first successful one will be returned
 * @return The result of the search, or an empty list.
 * @throws SearchingException If none of the search providers could give us a result, and there was at least one SearchingException thrown by them
 */
public AudioPlaylist searchForTracks(String query, long cacheMaxAge, int timeoutMillis, List<SearchProvider> providers) throws SearchingException {
    Metrics.searchRequests.inc();
    List<SearchProvider> provs = new ArrayList<>();
    if (providers == null || providers.isEmpty()) {
        log.warn("No search provider provided, defaulting to youtube -> soundcloud.");
        provs.add(SearchProvider.YOUTUBE);
        provs.add(SearchProvider.SOUNDCLOUD);
    } else {
        provs.addAll(providers);
    }
    SearchingException searchingException = null;
    for (SearchProvider provider : provs) {
        // 1. cache
        AudioPlaylist cacheResult = fromCache(provider, query, cacheMaxAge);
        if (cacheResult != null && !cacheResult.getTracks().isEmpty()) {
            log.debug("Loaded search result {} {} from cache", provider, query);
            Metrics.searchHits.labels("cache").inc();
            return cacheResult;
        }
        // 2. lavaplayer todo break up this beautiful construction of ifs and exception handling in a better readable one?
        if (provider != SearchProvider.YOUTUBE || System.currentTimeMillis() > youtubeCooldownUntil) {
            try {
                AudioPlaylist lavaplayerResult = new SearchResultHandler().searchSync(audioPlayerManager, provider, query, timeoutMillis);
                if (!lavaplayerResult.getTracks().isEmpty()) {
                    log.debug("Loaded search result {} {} from lavaplayer", provider, query);
                    // got a search result? cache and return it
                    executor.execute(() -> searchResultService.mergeSearchResult(new SearchResult(audioPlayerManager, provider, query, lavaplayerResult)));
                    Metrics.searchHits.labels("lavaplayer-" + provider.name().toLowerCase()).inc();
                    return lavaplayerResult;
                }
            } catch (Http503Exception e) {
                if (provider == SearchProvider.YOUTUBE) {
                    log.warn("Got a 503 from Youtube. Not hitting it with searches it for {} minutes", TimeUnit.MILLISECONDS.toMinutes(DEFAULT_YOUTUBE_COOLDOWN));
                    youtubeCooldownUntil = System.currentTimeMillis() + DEFAULT_YOUTUBE_COOLDOWN;
                }
                searchingException = e;
            } catch (SearchingException e) {
                searchingException = e;
            }
        }
        // 3. optional: youtube api
        if (provider == SearchProvider.YOUTUBE && (appConfig.isPatronDistribution() || appConfig.isDevDistribution())) {
            try {
                AudioPlaylist youtubeApiResult = youtubeAPI.search(query, MAX_RESULTS, audioPlayerManager.source(YoutubeAudioSourceManager.class));
                if (!youtubeApiResult.getTracks().isEmpty()) {
                    log.debug("Loaded search result {} {} from Youtube API", provider, query);
                    // got a search result? cache and return it
                    executor.execute(() -> searchResultService.mergeSearchResult(new SearchResult(audioPlayerManager, provider, query, youtubeApiResult)));
                    Metrics.searchHits.labels("youtube-api").inc();
                    return youtubeApiResult;
                }
            } catch (SearchingException e) {
                searchingException = e;
            }
        }
    }
    // did we run into searching exceptions that made us end up here?
    if (searchingException != null) {
        Metrics.searchHits.labels("exception").inc();
        throw searchingException;
    }
    // no result with any of the search providers
    Metrics.searchHits.labels("empty").inc();
    return new BasicAudioPlaylist("Search result for: " + query, Collections.emptyList(), null, true);
}
Also used : BasicAudioPlaylist(com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist) YoutubeAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager) ArrayList(java.util.ArrayList) SearchProvider(fredboat.definitions.SearchProvider) SearchResult(fredboat.db.transfer.SearchResult) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) BasicAudioPlaylist(com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist)

Example 15 with AudioPlaylist

use of com.sedmelluq.discord.lavaplayer.track.AudioPlaylist in project SkyBot by duncte123.

the class AudioUtils method loadAndPlay.

/**
 * Loads a track and plays it if the bot isn't playing
 *
 * @param mng         The {@link GuildMusicManager MusicManager} for the guild
 * @param channel     The {@link net.dv8tion.jda.core.entities.MessageChannel channel} that the bot needs to send the messages to
 * @param trackUrlRaw The url from the track to play
 * @param addPlayList If the url is a playlist
 */
public void loadAndPlay(GuildMusicManager mng, final TextChannel channel, final String trackUrlRaw, final boolean addPlayList) {
    final String trackUrl;
    // Strip <>'s that prevent discord from embedding link resources
    if (trackUrlRaw.startsWith("<") && trackUrlRaw.endsWith(">")) {
        trackUrl = trackUrlRaw.substring(1, trackUrlRaw.length() - 1);
    } else {
        trackUrl = trackUrlRaw;
    }
    playerManager.loadItemOrdered(mng, trackUrl, new AudioLoadResultHandler() {

        @Override
        public void trackLoaded(AudioTrack track) {
            String title = track.getInfo().title;
            if (track.getInfo().isStream) {
                Optional<RadioStream> stream = ((RadioCommand) AirUtils.COMMAND_MANAGER.getCommand("radio")).getRadioStreams().stream().filter(s -> s.getUrl().equals(track.getInfo().uri)).findFirst();
                if (stream.isPresent())
                    title = stream.get().getName();
            }
            String msg = "Adding to queue: " + title;
            if (mng.player.getPlayingTrack() == null) {
                msg += "\nand the Player has started playing;";
            }
            mng.scheduler.queue(track);
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, msg));
        }

        @Override
        public void playlistLoaded(AudioPlaylist playlist) {
            AudioTrack firstTrack = playlist.getSelectedTrack();
            List<AudioTrack> tracks = playlist.getTracks();
            if (tracks.size() == 0) {
                MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Error: This playlist is empty."));
                return;
            } else if (firstTrack == null) {
                firstTrack = playlist.getTracks().get(0);
            }
            String msg;
            if (addPlayList) {
                msg = "Adding **" + playlist.getTracks().size() + "** tracks to queue from playlist: " + playlist.getName();
                if (mng.player.getPlayingTrack() == null) {
                    msg += "\nand the Player has started playing;";
                }
                tracks.forEach(mng.scheduler::queue);
            } else {
                msg = "Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")";
                if (mng.player.getPlayingTrack() == null) {
                    msg += "\nand the Player has started playing;";
                }
                mng.scheduler.queue(firstTrack);
            }
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, msg));
        }

        @Override
        public void noMatches() {
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Nothing found by _" + trackUrl + "_"));
        }

        @Override
        public void loadFailed(FriendlyException exception) {
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Could not play: " + exception.getMessage() + "\nIf this happens often try another link or join our [support guild](https://discord.gg/NKM9Xtk) for more!"));
        }
    });
}
Also used : AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) RadioCommand(ml.duncte123.skybot.commands.music.RadioCommand) Optional(java.util.Optional) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) List(java.util.List) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Aggregations

AudioPlaylist (com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)18 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)17 AudioLoadResultHandler (com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler)14 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)14 List (java.util.List)8 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)7 YoutubeAudioSourceManager (com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager)5 AudioTrackInfo (com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo)5 Optional (java.util.Optional)4 TimeUnit (java.util.concurrent.TimeUnit)4 Permission (net.dv8tion.jda.core.Permission)4 Color (java.awt.Color)3 ArrayList (java.util.ArrayList)3 Slf4j (lombok.extern.slf4j.Slf4j)3 MessageBuilder (net.dv8tion.jda.core.MessageBuilder)3 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)3 AudioPlayer (com.sedmelluq.discord.lavaplayer.player.AudioPlayer)2 AudioPlayerManager (com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager)2 DefaultAudioPlayerManager (com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager)2 AudioSourceManager (com.sedmelluq.discord.lavaplayer.source.AudioSourceManager)2