Search in sources :

Example 56 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack in project FlareBot by FlareBot.

the class YouTubeExtractor method process.

@Override
public void process(String input, Player player, Message message, User user) throws Exception {
    AudioItem item;
    try {
        item = GeneralUtils.resolveItem(player, input);
    } catch (IllegalArgumentException e) {
        MessageUtils.editMessage(null, MessageUtils.getEmbed(user).setDescription("Could not get that video/playlist! Make sure the URL is correct!").setColor(Color.RED), message);
        return;
    } catch (IllegalStateException e) {
        if (e.getMessage().contains("Vevo")) {
            MessageUtils.editMessage(null, MessageUtils.getEmbed(user).setDescription("We are blocked from playing this video as it is from Vevo! " + "Sorry for any inconvenience.").setColor(Color.RED), message);
            return;
        }
        MessageUtils.editMessage(null, MessageUtils.getEmbed(user).setDescription("There was a problem with that video!\n" + "If the error continues, join our support discord: " + Constants.INVITE_URL + "\n" + "Input: " + input + "\n" + "Error Message: " + e.getMessage() + "\n" + "Stacktrace: " + MessageUtils.paste(GeneralUtils.getStackTrace(e))).setColor(Color.RED), message);
        return;
    }
    List<AudioTrack> audioTracks = new ArrayList<>();
    String name;
    if (item instanceof AudioPlaylist) {
        AudioPlaylist audioPlaylist = (AudioPlaylist) item;
        audioTracks.addAll(audioPlaylist.getTracks());
        name = audioPlaylist.getName();
    } else {
        AudioTrack track = (AudioTrack) item;
        /*if (track.getInfo().length == 0 || track.getInfo().isStream) {
                EmbedBuilder builder = MessageUtils.getEmbed(user).setDescription("Cannot queue a livestream!");
                MessageUtils.editMessage(null, builder, message);
                return;
            }*/
        audioTracks.add(track);
        name = track.getInfo().title;
        if (track.getInfo().identifier.equals("dQw4w9WgXcQ") && (random.nextInt(1000) + 1) == 1000) {
            GeneralUtils.sendImage("https://flarebot.stream/img/rick_roll.jpg", "rick_roll.jpg", user);
            Constants.logEG("You can't rick roll me!", null, message.getGuild(), user);
        }
    }
    if (name != null) {
        List<Track> tracks = audioTracks.stream().map(Track::new).peek(track -> {
            track.getMeta().put("requester", user.getId());
            track.getMeta().put("guildId", player.getGuildId());
        }).collect(Collectors.toList());
        if (tracks.size() > 1) {
            // Double `if` https://giphy.com/gifs/ng1xAzwIkDgfm
            Playlist p = new Playlist(tracks);
            player.queue(p);
        } else {
            player.queue(tracks.get(0));
        }
        EmbedBuilder builder = MessageUtils.getEmbed(user);
        builder.setDescription(String.format("%s added the %s [`%s`](%s)", user.getAsMention(), audioTracks.size() == 1 ? "song" : "playlist", name.replace("`", "'"), input));
        if (audioTracks.size() > 1)
            builder.addField("Song count:", String.valueOf(audioTracks.size()), true);
        MessageUtils.editMessage(null, builder, message);
    }
}
Also used : Color(java.awt.Color) Track(com.arsenarsen.lavaplayerbridge.player.Track) Player(com.arsenarsen.lavaplayerbridge.player.Player) Random(java.util.Random) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) GeneralUtils(stream.flarebot.flarebot.util.general.GeneralUtils) Collectors(java.util.stream.Collectors) Message(net.dv8tion.jda.core.entities.Message) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) Playlist(com.arsenarsen.lavaplayerbridge.player.Playlist) List(java.util.List) User(net.dv8tion.jda.core.entities.User) YoutubeAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager) AudioSourceManager(com.sedmelluq.discord.lavaplayer.source.AudioSourceManager) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) Constants(stream.flarebot.flarebot.util.Constants) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) ArrayList(java.util.ArrayList) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) Playlist(com.arsenarsen.lavaplayerbridge.player.Playlist) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) Track(com.arsenarsen.lavaplayerbridge.player.Track) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)

Example 57 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack in project FlareBot by FlareBot.

the class SavedPlaylistExtractor method process.

@Override
public void process(String input, Player player, Message message, User user) throws Exception {
    input = input.substring(input.indexOf('\u200B') + 1).replaceAll("\\[? ?]?", "");
    int i = 0;
    ArrayList<Track> playlist = new ArrayList<>();
    for (String s : input.split(",")) {
        String url = YouTubeExtractor.WATCH_URL + s;
        Document doc;
        try {
            doc = Jsoup.connect(url).get();
        } catch (Exception e) {
            continue;
        }
        if (!doc.title().endsWith("YouTube") || doc.title().equals("YouTube")) {
            continue;
        }
        try {
            Track track = new Track((AudioTrack) player.resolve(url));
            track.getMeta().put("requester", user.getId());
            track.getMeta().put("guildId", player.getGuildId());
            playlist.add(track);
            if (playlist.size() == 10) {
                player.queue(new Playlist(playlist));
                playlist.clear();
            }
            i++;
        } catch (FriendlyException ignored) {
        }
    }
    if (!playlist.isEmpty()) {
        player.queue(new Playlist(playlist));
    }
    MessageUtils.editMessage(null, MessageUtils.getEmbed(user).setDescription(String.format("*Loaded %s songs!*", i)), message);
}
Also used : Playlist(com.arsenarsen.lavaplayerbridge.player.Playlist) ArrayList(java.util.ArrayList) Document(org.jsoup.nodes.Document) Track(com.arsenarsen.lavaplayerbridge.player.Track) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Example 58 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack in project FlareBot by FlareBot.

the class PlayerListener method onTrackStart.

@Override
public void onTrackStart(AudioPlayer aplayer, AudioTrack atrack) {
    FlareBotManager.instance().getLastActive().remove(Long.parseLong(player.getGuildId()));
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(player.getGuildId());
    if (wrapper.getMusicAnnounceChannelId() != null) {
        TextChannel c = Getters.getChannelById(wrapper.getMusicAnnounceChannelId());
        if (c != null) {
            if (c.getGuild().getSelfMember().hasPermission(c, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE)) {
                Track track = player.getPlayingTrack();
                Queue<Track> playlist = player.getPlaylist();
                c.sendMessage(MessageUtils.getEmbed().addField("Now Playing", SongCommand.getLink(track), false).addField("Duration", FormatUtils.formatDuration(track.getTrack().getDuration()), false).addField("Requested by", String.format("<@!%s>", track.getMeta().get("requester")), false).addField("Next up", playlist.isEmpty() ? "Nothing" : SongCommand.getLink(playlist.peek()), false).setImage("https://img.youtube.com/vi/" + track.getTrack().getIdentifier() + "/hqdefault.jpg").build()).queue();
            } else {
                wrapper.setMusicAnnounceChannelId(null);
            }
        } else {
            wrapper.setMusicAnnounceChannelId(null);
        }
    }
    if (wrapper.isSongnickEnabled()) {
        Guild c = wrapper.getGuild();
        if (c == null || !GuildUtils.canChangeNick(player.getGuildId())) {
            if (!GuildUtils.canChangeNick(player.getGuildId())) {
                wrapper.setSongnick(false);
                MessageUtils.sendPM(wrapper.getGuild().getOwner().getUser(), "FlareBot can't change it's nickname so SongNick has been disabled!");
            }
        } else {
            Track track = player.getPlayingTrack();
            String str = null;
            if (track != null) {
                str = track.getTrack().getInfo().title;
                if (str.length() > 32)
                    str = str.substring(0, 32);
                str = str.substring(0, str.lastIndexOf(' ') + 1);
            }
            // Even I couldn't make this a one-liner
            c.getController().setNickname(c.getSelfMember(), str).queue();
        }
    }
}
Also used : GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Guild(net.dv8tion.jda.core.entities.Guild) Track(com.arsenarsen.lavaplayerbridge.player.Track) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Example 59 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack in project DiscLoader by R3alCl0ud.

the class Main method runVoiceChannelTest.

public static void runVoiceChannelTest() throws Exception {
    CompletableFuture<VoiceConnection> future = new CompletableFuture<>();
    IGuildVoiceChannel channel = guild.getVoiceChannelByName("General");
    VoiceConnection voiceconnection = channel.join().get();
    voiceconnection.addListener(new VoiceEventAdapter() {

        @Override
        public void end(AudioTrack track, AudioTrackEndReason endReason) {
            if (endReason == AudioTrackEndReason.LOAD_FAILED) {
                logger.severe("Test Failed\nFailed to load the audio track.");
            } else {
                logger.info("Track Finished Playing");
            }
            CompletableFuture<VoiceConnection> f16 = voiceconnection.disconnect();
            f16.exceptionally(ex -> {
                future.completeExceptionally(ex);
                return null;
            });
            f16.thenAcceptAsync(vc -> {
                logger.config("Disconnected From VC");
                future.complete(vc);
            });
        }
    });
    voiceconnection.play("https://soundcloud.com/r3alcl0ud/guardians-of-animus");
    future.get();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Options(io.discloader.discloader.common.start.Options) Gson(com.google.gson.Gson) RichEmbed(io.discloader.discloader.core.entity.message.embed.RichEmbed) DiscLoader(io.discloader.discloader.common.DiscLoader) DLLogger(io.discloader.discloader.common.logger.DLLogger) AudioTrackEndReason(com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason) IGuild(io.discloader.discloader.entity.guild.IGuild) IGuildVoiceChannel(io.discloader.discloader.entity.channel.IGuildVoiceChannel) IUser(io.discloader.discloader.entity.user.IUser) Files(java.nio.file.Files) VoiceEventAdapter(io.discloader.discloader.entity.voice.VoiceEventAdapter) VoiceConnection(io.discloader.discloader.entity.voice.VoiceConnection) IOException(java.io.IOException) Logger(java.util.logging.Logger) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) IGuildTextChannel(io.discloader.discloader.entity.channel.IGuildTextChannel) Paths(java.nio.file.Paths) CommandRegistry(io.discloader.discloader.common.registry.CommandRegistry) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) UnauthorizedException(io.discloader.discloader.common.exceptions.UnauthorizedException) IChannelCategory(io.discloader.discloader.entity.channel.IChannelCategory) IMessage(io.discloader.discloader.entity.message.IMessage) DLOptions(io.discloader.discloader.common.DLOptions) VoiceConnection(io.discloader.discloader.entity.voice.VoiceConnection) CompletableFuture(java.util.concurrent.CompletableFuture) AudioTrackEndReason(com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason) VoiceEventAdapter(io.discloader.discloader.entity.voice.VoiceEventAdapter) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) IGuildVoiceChannel(io.discloader.discloader.entity.channel.IGuildVoiceChannel)

Example 60 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack in project Shadbot by Shadorc.

the class AudioLoadResultListener method playlistLoaded.

@Override
public void playlistLoaded(AudioPlaylist playlist) {
    List<AudioTrack> tracks = playlist.getTracks();
    // SoundCloud returns an empty playlist when it has not found any results
    if (tracks.isEmpty()) {
        this.onNoMatches();
        return;
    }
    if (identifier.startsWith(YT_SEARCH) || identifier.startsWith(SC_SEARCH)) {
        guildMusic.setDj(userDj);
        guildMusic.setWaiting(true);
        String choices = FormatUtils.numberedList(5, tracks.size(), count -> String.format("\t**%d.** %s", count, FormatUtils.formatTrackName(tracks.get(count - 1).getInfo())));
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Music results").withAuthorIcon(guildMusic.getDj().getAvatarURL()).withThumbnail("http://icons.iconarchive.com/icons/dtafalonso/yosemite-flat/512/Music-icon.png").appendDescription("**Select a music by typing the corresponding number.**" + "\nYou can choose several musics by separating them with a comma." + "\nExample: 1,3,4" + "\n\n" + choices).withFooterText(String.format("Use %scancel to cancel the selection (Automatically canceled in %ds).", Database.getDBGuild(guildMusic.getChannel().getGuild()).getPrefix(), CHOICE_DURATION));
        BotUtils.sendMessage(embed.build(), guildMusic.getChannel());
        stopWaitingTask = Shadbot.getScheduler().schedule(() -> this.stopWaiting(), CHOICE_DURATION, TimeUnit.SECONDS);
        resultsTracks = new ArrayList<>(tracks);
        MessageManager.addListener(guildMusic.getChannel(), this);
        return;
    }
    guildMusic.joinVoiceChannel(userVoiceChannel);
    int musicsAdded = 0;
    for (AudioTrack track : tracks) {
        guildMusic.getScheduler().startOrQueue(track, putFirst);
        musicsAdded++;
        if (guildMusic.getScheduler().getPlaylist().size() >= Config.MAX_PLAYLIST_SIZE - 1 && !PremiumManager.isPremium(guildMusic.getChannel().getGuild(), userDj)) {
            BotUtils.sendMessage(TextUtils.PLAYLIST_LIMIT_REACHED, guildMusic.getChannel());
            break;
        }
    }
    BotUtils.sendMessage(String.format(Emoji.MUSICAL_NOTE + " %d musics have been added to the playlist.", musicsAdded), guildMusic.getChannel());
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Aggregations

AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)85 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)26 ArrayList (java.util.ArrayList)23 AudioPlaylist (com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)21 AudioLoadResultHandler (com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler)18 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)17 AudioTrackInfo (com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo)11 List (java.util.List)10 JsonBrowser (com.sedmelluq.discord.lavaplayer.tools.JsonBrowser)9 IOException (java.io.IOException)9 BasicAudioPlaylist (com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist)8 TimeUnit (java.util.concurrent.TimeUnit)7 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)7 YoutubeAudioSourceManager (com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager)6 Optional (java.util.Optional)6 MessageBuilder (net.dv8tion.jda.core.MessageBuilder)6 Permission (net.dv8tion.jda.core.Permission)6 AudioPlayer (com.sedmelluq.discord.lavaplayer.player.AudioPlayer)5 InternalAudioTrack (com.sedmelluq.discord.lavaplayer.track.InternalAudioTrack)5 Slf4j (lombok.extern.slf4j.Slf4j)5