Search in sources :

Example 46 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack 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 47 with AudioTrack

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

the class DJ method removeStar.

public void removeStar(IMessage message, IUser user) throws CommandStateException, CommandPermissionException {
    if (message == null || user == null || !trackMessages.containsKey(message))
        throw new CommandStateException("That track can not be found.");
    AudioTrack track = trackMessages.get(message);
    Playlist playlist = MusicModule.getPlaylistManager().getSelectedPlaylist(user.getLongID());
    if (playlist == null)
        throw new CommandStateException("You must have a selected playlist to unsave a song!");
    playlist.removeSong(user, track);
}
Also used : Playlist(com.discordbolt.boltbot.modules.music.playlists.Playlist) CommandStateException(com.discordbolt.api.command.exceptions.CommandStateException) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Example 48 with AudioTrack

use of com.sedmelluq.discord.lavaplayer.track.AudioTrack 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 49 with AudioTrack

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

the class VoiceManager method reactionEvent.

/* Listeners */
@EventSubscriber
public void reactionEvent(ReactionAddEvent e) {
    if (e.getUser().equals(MusicModule.getClient().getOurUser()))
        return;
    DJ dj = getDJ(e.getGuild());
    IMessage message = e.getMessage();
    AudioTrack track = null;
    if (message.equals(dj.getNowPlayingMessage()))
        track = dj.getPlaying();
    else if (dj.getTrackMessages().containsKey(message))
        track = dj.getTrackMessages().get(message);
    if (track == null)
        return;
    switch(e.getReaction().getUnicodeEmoji().getAliases().get(0)) {
        case "black_right_pointing_double_triangle_with_vertical_bar":
            if (track.getIdentifier().equals(dj.getPlaying().getIdentifier())) {
                try {
                    skip(e.getGuild(), e.getUser(), false, 1);
                    ChannelUtil.sendMessage(e.getChannel(), e.getUser().getDisplayName(e.getGuild()) + " has voted to skip this track.");
                } catch (CommandException ex) {
                    ChannelUtil.sendMessage(e.getChannel(), ex.getMessage());
                }
            } else {
                ChannelUtil.sendMessage(e.getChannel(), e.getUser().getName() + ", You can only skip currently playing songs");
                return;
            }
            break;
        case "star":
            try {
                getDJ(e.getGuild()).starSong(track, e.getUser());
                ChannelUtil.sendMessage(e.getChannel(), e.getUser().getDisplayName(e.getGuild()) + ", successfully added the song to your selected playlist.");
            } catch (CommandException ex) {
                ChannelUtil.sendMessage(e.getChannel(), ex.getMessage());
            }
            break;
    }
}
Also used : IMessage(sx.blah.discord.handle.obj.IMessage) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) EventSubscriber(sx.blah.discord.api.events.EventSubscriber)

Example 50 with AudioTrack

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

the class YoutubeAPI method search.

/**
 * @param query         Search Youtube for this query
 * @param maxResults    Keep this as small as necessary, each of the videos needs to be looked up for more detailed info
 * @param sourceManager The source manager may be used by the tracks to look further information up
 * @return A playlist representing the search results; null if there was an exception
 */
// docs: https://developers.google.com/youtube/v3/docs/search/list
// theres a lot of room for tweaking the searches
public AudioPlaylist search(String query, int maxResults, YoutubeAudioSourceManager sourceManager) throws TrackSearcher.SearchingException {
    JSONObject data;
    String gkey = credentials.getRandomGoogleKey();
    Http.SimpleRequest request = BotController.Companion.getHTTP().get(YOUTUBE_SEARCH, Http.Params.of("key", gkey, "type", "video", "maxResults", Integer.toString(maxResults), "q", query));
    try {
        data = request.asJson();
    } catch (IOException e) {
        throw new TrackSearcher.SearchingException("Youtube API search failed", e);
    }
    // The search contains all values we need, except for the duration :feelsbadman:
    // so we need to do another query for each video.
    List<String> ids = new ArrayList<>(maxResults);
    try {
        JSONArray items = data.getJSONArray("items");
        for (int i = 0; i < items.length(); i++) {
            JSONObject item = items.getJSONObject(i);
            ids.add(item.getJSONObject("id").getString("videoId"));
        }
    } catch (JSONException e) {
        String message = String.format("Youtube search with API key ending on %s for query %s returned unexpected JSON:\n%s", gkey.substring(20), query, data.toString());
        throw new TrackSearcher.SearchingException(message, e);
    }
    List<AudioTrack> tracks = new ArrayList<>();
    for (String id : ids) {
        try {
            YoutubeVideo vid = getVideoFromID(id, true);
            tracks.add(sourceManager.buildTrackObject(id, vid.name, vid.channelTitle, vid.isStream, vid.getDurationInMillis()));
        } catch (RuntimeException e) {
            throw new TrackSearcher.SearchingException("Could not look up details for youtube video with id " + id, e);
        }
    }
    return new BasicAudioPlaylist("Search results for: " + query, tracks, null, true);
}
Also used : BasicAudioPlaylist(com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) 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