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();
}
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⃣");
}
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.");
}
});
}
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);
}
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!"));
}
});
}
Aggregations