diff --git a/app/src/main/java/musicbot/Listeners.java b/app/src/main/java/musicbot/Listeners.java index b17dd83..f883724 100644 --- a/app/src/main/java/musicbot/Listeners.java +++ b/app/src/main/java/musicbot/Listeners.java @@ -9,57 +9,57 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import org.jetbrains.annotations.NotNull; public class Listeners extends ListenerAdapter { - @Override - public void onReady(@NotNull final ReadyEvent event) { - //final JDA jda = event.getJDA().getGuildById(1197770092243599431L).getJDA(); - final JDA jda = event.getJDA(); + @Override + public void onReady(@NotNull final ReadyEvent event) { + //final JDA jda = event.getJDA().getGuildById(1197770092243599431L).getJDA(); + final JDA jda = event.getJDA(); - jda.upsertCommand("music", "find music to play").addOptions( - new OptionData( - OptionType.STRING, - "title", - "The name of the song", - true), - new OptionData( - OptionType.STRING, - "artist", - "The artist of the song", - true) - ).queue(); + jda.upsertCommand("music", "find music to play").addOptions( + new OptionData( + OptionType.STRING, + "title", + "The name of the song", + true), + new OptionData( + OptionType.STRING, + "artist", + "The artist of the song", + true) + ).queue(); - jda.upsertCommand("recommend", "find recommendations for music").addOptions( - new OptionData( - OptionType.STRING, - "artist", - "Find other songs and artists based on an artist you like" - ), - new OptionData( - OptionType.STRING, - "genre", - "Find other songs and artists based on a genre you like" - ) - ).queue(); + jda.upsertCommand("recommend", "find recommendations for music").addOptions( + new OptionData( + OptionType.STRING, + "artist", + "Find other songs and artists based on an artist you like" + ), + new OptionData( + OptionType.STRING, + "genre", + "Find other songs and artists based on a genre you like" + ) + ).queue(); - jda.upsertCommand("artist", "find songs by artist").addOptions( - new OptionData( - OptionType.STRING, - "name", - "Find tracks by an artist.", - true - ) - ).queue(); + jda.upsertCommand("artist", "find songs by artist").addOptions( + new OptionData( + OptionType.STRING, + "name", + "Find tracks by an artist.", + true + ) + ).queue(); - jda.upsertCommand("genres", "find supported genres").queue(); - } + jda.upsertCommand("genres", "find supported genres").queue(); + } - @Override - public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { - final String artist = event.getComponent().getId(); - final String title = event.getComponent().getLabel(); + @Override + public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { + final String artist = event.getComponent().getId(); + final String title = event.getComponent().getLabel(); - final YoutubeSearch youtubeSearch = new YoutubeSearch(); - final String result = youtubeSearch.searchForMusic(title, artist); + final YoutubeSearch youtubeSearch = new YoutubeSearch(); + final String result = youtubeSearch.searchForMusic(title, artist); - event.reply(result).queue(); - } + event.reply(result).queue(); + } } diff --git a/app/src/main/java/musicbot/Main.java b/app/src/main/java/musicbot/Main.java index bb295cb..ef5bb9c 100644 --- a/app/src/main/java/musicbot/Main.java +++ b/app/src/main/java/musicbot/Main.java @@ -8,14 +8,14 @@ import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; public class Main { - public static void main(final String[] args) { - final JDA jda = JDABuilder - .createDefault(Token.TOKEN) - .build(); - jda.addEventListener(new Listeners()); - jda.addEventListener(new MusicVideo()); - jda.addEventListener(new Recommend()); - jda.addEventListener(new Genres()); - jda.addEventListener(new Artist()); - } + public static void main(final String[] args) { + final JDA jda = JDABuilder + .createDefault(Token.TOKEN) + .build(); + jda.addEventListener(new Listeners()); + jda.addEventListener(new MusicVideo()); + jda.addEventListener(new Recommend()); + jda.addEventListener(new Genres()); + jda.addEventListener(new Artist()); + } } diff --git a/app/src/main/java/musicbot/SpotifyClient.java b/app/src/main/java/musicbot/SpotifyClient.java index 751447e..cbd5d80 100644 --- a/app/src/main/java/musicbot/SpotifyClient.java +++ b/app/src/main/java/musicbot/SpotifyClient.java @@ -23,94 +23,94 @@ import java.util.Optional; import java.util.stream.Collectors; public class SpotifyClient { - private static final SpotifyApi SPOTIFY_API = new SpotifyApi.Builder() - .setClientId(Token.SPOTIFY_CLIENT_ID) - .setClientSecret(Token.SPOTIFY_CLIENT_SECRET) - .build(); - - private static final ClientCredentialsRequest CLIENT_CREDENTIALS_REQUEST = SPOTIFY_API - .clientCredentials() - .build(); - - public SpotifyClient() { - clientCredentialsSync(); + private static final SpotifyApi SPOTIFY_API = new SpotifyApi.Builder() + .setClientId(Token.SPOTIFY_CLIENT_ID) + .setClientSecret(Token.SPOTIFY_CLIENT_SECRET) + .build(); + + private static final ClientCredentialsRequest CLIENT_CREDENTIALS_REQUEST = SPOTIFY_API + .clientCredentials() + .build(); + + public SpotifyClient() { + clientCredentialsSync(); + } + + public Optional findArtist(final String artist) { + try { + final SearchArtistsRequest searchArtistsRequest = SPOTIFY_API.searchArtists(artist) + .limit(1) + .build(); + + final Paging artists = searchArtistsRequest.execute(); + + return Arrays.stream(artists.getItems()).findFirst(); + } catch (SpotifyWebApiException | ParseException | IOException exception) { + return Optional.empty(); } + } - public Optional findArtist(final String artist) { - try { - final SearchArtistsRequest searchArtistsRequest = SPOTIFY_API.searchArtists(artist) - .limit(1) - .build(); + public List findTracks(final String query) { + try { + final SearchTracksRequest searchTracksRequest = SPOTIFY_API.searchTracks(query).limit(10).build(); - final Paging artists = searchArtistsRequest.execute(); + final Paging tracks = searchTracksRequest.execute(); - return Arrays.stream(artists.getItems()).findFirst(); - } catch (SpotifyWebApiException | ParseException | IOException exception) { - return Optional.empty(); - } + return Arrays.stream(tracks.getItems()).collect(Collectors.toList()); + } catch (SpotifyWebApiException | ParseException | IOException exception) { + return List.of(); } + } - public List findTracks(final String query) { - try { - final SearchTracksRequest searchTracksRequest = SPOTIFY_API.searchTracks(query).limit(10).build(); - - final Paging tracks = searchTracksRequest.execute(); + public List findRecommendations(final String artistId, final String genres) { + final GetRecommendationsRequest.Builder recommendationsRequestBuilder = SPOTIFY_API.getRecommendations() + .limit(5); - return Arrays.stream(tracks.getItems()).collect(Collectors.toList()); - } catch (SpotifyWebApiException | ParseException | IOException exception) { - return List.of(); - } + if (!artistId.isEmpty()) { + recommendationsRequestBuilder + .seed_artists(artistId); } - public List findRecommendations(final String artistId, final String genres) { - final GetRecommendationsRequest.Builder recommendationsRequestBuilder = SPOTIFY_API.getRecommendations() - .limit(5); - - if (!artistId.isEmpty()) { - recommendationsRequestBuilder - .seed_artists(artistId); - } - - if (!genres.isEmpty()) { - recommendationsRequestBuilder - .seed_genres(genres); - } + if (!genres.isEmpty()) { + recommendationsRequestBuilder + .seed_genres(genres); + } - final GetRecommendationsRequest recommendationsRequest = recommendationsRequestBuilder.build(); + final GetRecommendationsRequest recommendationsRequest = recommendationsRequestBuilder.build(); - try { - final Recommendations recommendations = recommendationsRequest.execute(); - System.out.println("Length: " + recommendations.getTracks().length); + try { + final Recommendations recommendations = recommendationsRequest.execute(); + System.out.println("Length: " + recommendations.getTracks().length); - return Arrays.stream(recommendations.getTracks()).collect(Collectors.toList()); - } catch (IOException | SpotifyWebApiException | ParseException e) { - System.out.println("Error: " + e.getMessage()); - return ImmutableList.of(); - } + return Arrays.stream(recommendations.getTracks()).collect(Collectors.toList()); + } catch (IOException | SpotifyWebApiException | ParseException e) { + System.out.println("Error: " + e.getMessage()); + return ImmutableList.of(); } + } - public List findGenres() { - final GetAvailableGenreSeedsRequest request = SPOTIFY_API.getAvailableGenreSeeds().build(); + public List findGenres() { + final GetAvailableGenreSeedsRequest request = SPOTIFY_API.getAvailableGenreSeeds().build(); - try { - final String[] genres = request.execute(); - return Arrays.stream(genres).collect(Collectors.toList()); - } catch (IOException | SpotifyWebApiException | ParseException e) { - System.out.println("Error: " + e.getMessage()); - return ImmutableList.of(); - } + try { + final String[] genres = request.execute(); + return Arrays.stream(genres).collect(Collectors.toList()); + } catch (IOException | SpotifyWebApiException | ParseException e) { + System.out.println("Error: " + e.getMessage()); + return ImmutableList.of(); } + } - private static void clientCredentialsSync() { - try { - final ClientCredentials clientCredentials = CLIENT_CREDENTIALS_REQUEST.execute(); + private static void clientCredentialsSync() { + try { + final ClientCredentials clientCredentials = CLIENT_CREDENTIALS_REQUEST.execute(); - // Set access token for further "spotifyApi" object usage - SPOTIFY_API.setAccessToken(clientCredentials.getAccessToken()); + // Set access token for further "spotifyApi" object usage + SPOTIFY_API.setAccessToken(clientCredentials.getAccessToken()); - System.out.println("Expires in: " + clientCredentials.getExpiresIn()); - } catch (final IOException | SpotifyWebApiException | ParseException e) { - System.out.println("Error: " + e.getMessage()); - } + System.out.println("Expires in: " + clientCredentials.getExpiresIn()); + } catch (final IOException | SpotifyWebApiException | ParseException e) { + System.out.println("Error: " + e.getMessage()); } + } } diff --git a/app/src/main/java/musicbot/YoutubeSearch.java b/app/src/main/java/musicbot/YoutubeSearch.java index 827ec74..e9664c7 100644 --- a/app/src/main/java/musicbot/YoutubeSearch.java +++ b/app/src/main/java/musicbot/YoutubeSearch.java @@ -1,4 +1,5 @@ package musicbot; + import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.http.HttpRequest; @@ -18,71 +19,72 @@ import java.util.Optional; import java.util.Properties; public class YoutubeSearch { - private static final String PROPERTIES_FILENAME = "youtube.properties"; - - private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); - - private static final JsonFactory JSON_FACTORY = new JacksonFactory(); - - private static final long NUMBER_VIDEOS_RETURNED = 1; - - private static YouTube _youtube; - - public String searchForMusic(final String title, final String artist) { - _youtube = get_youtube(); - - final List searchResults = doSearch(title, artist); - - final Optional maybeResult = searchResults.stream().findFirst(); - searchResults.stream().forEach(result -> { - System.out.println("result ID = " + result.getId()); - }); - - return maybeResult.map(result -> "http://www.youtube.com/watch?v=" + result.getId().getVideoId()) - .orElse("No videos found."); - } - - private YouTube get_youtube() { - return new YouTube.Builder( - HTTP_TRANSPORT, - JSON_FACTORY, - createRequestInitializer() - ).setApplicationName("discord-musicbot").build(); - } - - private HttpRequestInitializer createRequestInitializer() { - final HttpRequestInitializer initializer = new HttpRequestInitializer() { - public void initialize(HttpRequest request) throws IOException {} - }; - - return initializer; - } - - private List doSearch(final String title, final String artist) { - try { - final String apiKey = Token.YOUTUBE_API_KEY; - - final String query = title + " by " + artist; - - final YouTube.Search.List search = _youtube.search().list("id,snippet") - .setKey(apiKey) - .setType("video") - .setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)") - .setMaxResults(NUMBER_VIDEOS_RETURNED) - .setQ(query); - - final SearchListResponse response = search.execute(); - return response.getItems(); - } catch (GoogleJsonResponseException e) { - System.err.println("There was a service error: " + e.getDetails().getCode() + " : " - + e.getDetails().getMessage()); - return ImmutableList.of(); - } catch (IOException e) { - System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); - return ImmutableList.of(); - } catch (Throwable t) { - t.printStackTrace(); - return ImmutableList.of(); - } + private static final String PROPERTIES_FILENAME = "youtube.properties"; + + private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); + + private static final JsonFactory JSON_FACTORY = new JacksonFactory(); + + private static final long NUMBER_VIDEOS_RETURNED = 1; + + private static YouTube _youtube; + + public String searchForMusic(final String title, final String artist) { + _youtube = get_youtube(); + + final List searchResults = doSearch(title, artist); + + final Optional maybeResult = searchResults.stream().findFirst(); + searchResults.stream().forEach(result -> { + System.out.println("result ID = " + result.getId()); + }); + + return maybeResult.map(result -> "http://www.youtube.com/watch?v=" + result.getId().getVideoId()) + .orElse("No videos found."); + } + + private YouTube get_youtube() { + return new YouTube.Builder( + HTTP_TRANSPORT, + JSON_FACTORY, + createRequestInitializer() + ).setApplicationName("discord-musicbot").build(); + } + + private HttpRequestInitializer createRequestInitializer() { + final HttpRequestInitializer initializer = new HttpRequestInitializer() { + public void initialize(HttpRequest request) throws IOException { + } + }; + + return initializer; + } + + private List doSearch(final String title, final String artist) { + try { + final String apiKey = Token.YOUTUBE_API_KEY; + + final String query = title + " by " + artist; + + final YouTube.Search.List search = _youtube.search().list("id,snippet") + .setKey(apiKey) + .setType("video") + .setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)") + .setMaxResults(NUMBER_VIDEOS_RETURNED) + .setQ(query); + + final SearchListResponse response = search.execute(); + return response.getItems(); + } catch (GoogleJsonResponseException e) { + System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + + e.getDetails().getMessage()); + return ImmutableList.of(); + } catch (IOException e) { + System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); + return ImmutableList.of(); + } catch (Throwable t) { + t.printStackTrace(); + return ImmutableList.of(); } + } } diff --git a/app/src/main/java/musicbot/commands/Artist.java b/app/src/main/java/musicbot/commands/Artist.java index 24116a7..c21afef 100644 --- a/app/src/main/java/musicbot/commands/Artist.java +++ b/app/src/main/java/musicbot/commands/Artist.java @@ -14,28 +14,27 @@ import java.util.List; public class Artist extends ListenerAdapter { - @Override - public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { - if (!event.getName().equals("artist")) return; + @Override + public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { + if (!event.getName().equals("artist")) return; - event.deferReply().queue(); + event.deferReply().queue(); - final String artist = event.getOption("name").getAsString(); - System.out.print("hey!"); + final String artist = event.getOption("name").getAsString(); - final SpotifyClient spotifyClient = new SpotifyClient(); - final List tracks = spotifyClient.findTracks("artist:"+artist); + final SpotifyClient spotifyClient = new SpotifyClient(); + final List tracks = spotifyClient.findTracks("artist:" + artist); - final EmbedBuilder eb = new EmbedBuilder(); - eb - .setTitle("Some tracks by " + artist); + final EmbedBuilder eb = new EmbedBuilder(); + eb + .setTitle("Some tracks by " + artist); - tracks.forEach(track -> { - eb.addField(track.getName(), "", false); - }); + tracks.forEach(track -> { + eb.addField(track.getName(), "", false); + }); - final MessageEmbed embed = eb.build(); + final MessageEmbed embed = eb.build(); - event.getHook().sendMessageEmbeds(embed).queue(); - } + event.getHook().sendMessageEmbeds(embed).queue(); + } } diff --git a/app/src/main/java/musicbot/commands/Genres.java b/app/src/main/java/musicbot/commands/Genres.java index a0a7ee9..d9bc786 100644 --- a/app/src/main/java/musicbot/commands/Genres.java +++ b/app/src/main/java/musicbot/commands/Genres.java @@ -12,21 +12,21 @@ import java.util.List; import java.util.stream.Collectors; public class Genres extends ListenerAdapter { - @Override - public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { - if (!event.getName().equals("genres")) return; + @Override + public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { + if (!event.getName().equals("genres")) return; - final SpotifyClient spotifyClient = new SpotifyClient(); - final List genres = spotifyClient.findGenres(); + final SpotifyClient spotifyClient = new SpotifyClient(); + final List genres = spotifyClient.findGenres(); - final List> batches = Lists.partition(genres, 20); + final List> batches = Lists.partition(genres, 20); - final List embeds = batches.stream().map(genresList -> { - final EmbedBuilder eb = new EmbedBuilder(); - genresList.forEach(genre -> eb.addField(genre, "", false)); - return eb.build(); - }).collect(Collectors.toList()); + final List embeds = batches.stream().map(genresList -> { + final EmbedBuilder eb = new EmbedBuilder(); + genresList.forEach(genre -> eb.addField(genre, "", false)); + return eb.build(); + }).collect(Collectors.toList()); - event.getChannel().sendMessageEmbeds(embeds).queue(); - } + event.getChannel().sendMessageEmbeds(embeds).queue(); + } } diff --git a/app/src/main/java/musicbot/commands/MusicVideo.java b/app/src/main/java/musicbot/commands/MusicVideo.java index 49420fc..f7db80f 100644 --- a/app/src/main/java/musicbot/commands/MusicVideo.java +++ b/app/src/main/java/musicbot/commands/MusicVideo.java @@ -8,16 +8,16 @@ import org.jetbrains.annotations.NotNull; import java.util.Objects; public class MusicVideo extends ListenerAdapter { - @Override - public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { - if (!event.getName().equals("music")) return; + @Override + public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { + if (!event.getName().equals("music")) return; - final String title = Objects.requireNonNull(event.getOption("title")).getAsString(); - final String artist = Objects.requireNonNull(event.getOption("artist")).getAsString(); + final String title = Objects.requireNonNull(event.getOption("title")).getAsString(); + final String artist = Objects.requireNonNull(event.getOption("artist")).getAsString(); - final YoutubeSearch youtubeSearch = new YoutubeSearch(); - final String result = youtubeSearch.searchForMusic(title, artist); + final YoutubeSearch youtubeSearch = new YoutubeSearch(); + final String result = youtubeSearch.searchForMusic(title, artist); - event.reply(result).queue(); - } + event.reply(result).queue(); + } } diff --git a/app/src/main/java/musicbot/commands/Recommend.java b/app/src/main/java/musicbot/commands/Recommend.java index 3912a25..7285630 100644 --- a/app/src/main/java/musicbot/commands/Recommend.java +++ b/app/src/main/java/musicbot/commands/Recommend.java @@ -19,72 +19,72 @@ import java.util.stream.Collectors; public class Recommend extends ListenerAdapter { - @Override - public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { - if (!event.getName().equals("recommend")) return; + @Override + public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { + if (!event.getName().equals("recommend")) return; - event.deferReply().queue(); + event.deferReply().queue(); - final OptionMapping artistInput = event.getOption("artist"); - final OptionMapping genreInput = event.getOption("genre"); + final OptionMapping artistInput = event.getOption("artist"); + final OptionMapping genreInput = event.getOption("genre"); - final Optional maybeArtistId = findArtistId(artistInput); - final Optional maybeGenre = findGenre(genreInput); + final Optional maybeArtistId = findArtistId(artistInput); + final Optional maybeGenre = findGenre(genreInput); - final SpotifyClient spotifyClient = new SpotifyClient(); + final SpotifyClient spotifyClient = new SpotifyClient(); - final String artistId = maybeArtistId.orElse(""); - final String genre = maybeGenre.orElse(""); - final List tracks = spotifyClient.findRecommendations(artistId, genre); + final String artistId = maybeArtistId.orElse(""); + final String genre = maybeGenre.orElse(""); + final List tracks = spotifyClient.findRecommendations(artistId, genre); - final EmbedBuilder eb = new EmbedBuilder(); - if (!tracks.isEmpty()) { + final EmbedBuilder eb = new EmbedBuilder(); + if (!tracks.isEmpty()) { - eb - .setTitle("Recommendations") - .setDescription("Here are a list of recommendations based on your input. " + - "It will help you find new music to listen to.") - .setFooter("To find a song, select a button below."); + eb + .setTitle("Recommendations") + .setDescription("Here are a list of recommendations based on your input. " + + "It will help you find new music to listen to.") + .setFooter("To find a song, select a button below."); - tracks.forEach(track -> { - List trackArtists = Arrays.stream(track.getArtists()) - .map(ArtistSimplified::getName) - .collect(Collectors.toList()); - String artists = String.join(", ", trackArtists); + tracks.forEach(track -> { + List trackArtists = Arrays.stream(track.getArtists()) + .map(ArtistSimplified::getName) + .collect(Collectors.toList()); + String artists = String.join(", ", trackArtists); - eb.addField(track.getName(), artists, false); - }); + eb.addField(track.getName(), artists, false); + }); - final MessageEmbed embed = eb.build(); + final MessageEmbed embed = eb.build(); - final List