Browse Source

Reformat code

main
Stephanie Gredell 2 years ago
parent
commit
f9693cd772
  1. 92
      app/src/main/java/musicbot/Listeners.java
  2. 20
      app/src/main/java/musicbot/Main.java
  3. 140
      app/src/main/java/musicbot/SpotifyClient.java
  4. 134
      app/src/main/java/musicbot/YoutubeSearch.java
  5. 33
      app/src/main/java/musicbot/commands/Artist.java
  6. 26
      app/src/main/java/musicbot/commands/Genres.java
  7. 18
      app/src/main/java/musicbot/commands/MusicVideo.java
  8. 98
      app/src/main/java/musicbot/commands/Recommend.java

92
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; import org.jetbrains.annotations.NotNull;
public class Listeners extends ListenerAdapter { public class Listeners extends ListenerAdapter {
@Override @Override
public void onReady(@NotNull final ReadyEvent event) { public void onReady(@NotNull final ReadyEvent event) {
//final JDA jda = event.getJDA().getGuildById(1197770092243599431L).getJDA(); //final JDA jda = event.getJDA().getGuildById(1197770092243599431L).getJDA();
final JDA jda = event.getJDA(); final JDA jda = event.getJDA();
jda.upsertCommand("music", "find music to play").addOptions( jda.upsertCommand("music", "find music to play").addOptions(
new OptionData( new OptionData(
OptionType.STRING, OptionType.STRING,
"title", "title",
"The name of the song", "The name of the song",
true), true),
new OptionData( new OptionData(
OptionType.STRING, OptionType.STRING,
"artist", "artist",
"The artist of the song", "The artist of the song",
true) true)
).queue(); ).queue();
jda.upsertCommand("recommend", "find recommendations for music").addOptions( jda.upsertCommand("recommend", "find recommendations for music").addOptions(
new OptionData( new OptionData(
OptionType.STRING, OptionType.STRING,
"artist", "artist",
"Find other songs and artists based on an artist you like" "Find other songs and artists based on an artist you like"
), ),
new OptionData( new OptionData(
OptionType.STRING, OptionType.STRING,
"genre", "genre",
"Find other songs and artists based on a genre you like" "Find other songs and artists based on a genre you like"
) )
).queue(); ).queue();
jda.upsertCommand("artist", "find songs by artist").addOptions( jda.upsertCommand("artist", "find songs by artist").addOptions(
new OptionData( new OptionData(
OptionType.STRING, OptionType.STRING,
"name", "name",
"Find tracks by an artist.", "Find tracks by an artist.",
true true
) )
).queue(); ).queue();
jda.upsertCommand("genres", "find supported genres").queue(); jda.upsertCommand("genres", "find supported genres").queue();
} }
@Override @Override
public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { public void onButtonInteraction(@NotNull ButtonInteractionEvent event) {
final String artist = event.getComponent().getId(); final String artist = event.getComponent().getId();
final String title = event.getComponent().getLabel(); final String title = event.getComponent().getLabel();
final YoutubeSearch youtubeSearch = new YoutubeSearch(); final YoutubeSearch youtubeSearch = new YoutubeSearch();
final String result = youtubeSearch.searchForMusic(title, artist); final String result = youtubeSearch.searchForMusic(title, artist);
event.reply(result).queue(); event.reply(result).queue();
} }
} }

20
app/src/main/java/musicbot/Main.java

@ -8,14 +8,14 @@ import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
public class Main { public class Main {
public static void main(final String[] args) { public static void main(final String[] args) {
final JDA jda = JDABuilder final JDA jda = JDABuilder
.createDefault(Token.TOKEN) .createDefault(Token.TOKEN)
.build(); .build();
jda.addEventListener(new Listeners()); jda.addEventListener(new Listeners());
jda.addEventListener(new MusicVideo()); jda.addEventListener(new MusicVideo());
jda.addEventListener(new Recommend()); jda.addEventListener(new Recommend());
jda.addEventListener(new Genres()); jda.addEventListener(new Genres());
jda.addEventListener(new Artist()); jda.addEventListener(new Artist());
} }
} }

140
app/src/main/java/musicbot/SpotifyClient.java

@ -23,94 +23,94 @@ import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class SpotifyClient { public class SpotifyClient {
private static final SpotifyApi SPOTIFY_API = new SpotifyApi.Builder() private static final SpotifyApi SPOTIFY_API = new SpotifyApi.Builder()
.setClientId(Token.SPOTIFY_CLIENT_ID) .setClientId(Token.SPOTIFY_CLIENT_ID)
.setClientSecret(Token.SPOTIFY_CLIENT_SECRET) .setClientSecret(Token.SPOTIFY_CLIENT_SECRET)
.build(); .build();
private static final ClientCredentialsRequest CLIENT_CREDENTIALS_REQUEST = SPOTIFY_API private static final ClientCredentialsRequest CLIENT_CREDENTIALS_REQUEST = SPOTIFY_API
.clientCredentials() .clientCredentials()
.build(); .build();
public SpotifyClient() { public SpotifyClient() {
clientCredentialsSync(); clientCredentialsSync();
}
public Optional<Artist> findArtist(final String artist) {
try {
final SearchArtistsRequest searchArtistsRequest = SPOTIFY_API.searchArtists(artist)
.limit(1)
.build();
final Paging<Artist> artists = searchArtistsRequest.execute();
return Arrays.stream(artists.getItems()).findFirst();
} catch (SpotifyWebApiException | ParseException | IOException exception) {
return Optional.empty();
} }
}
public Optional<Artist> findArtist(final String artist) { public List<Track> findTracks(final String query) {
try { try {
final SearchArtistsRequest searchArtistsRequest = SPOTIFY_API.searchArtists(artist) final SearchTracksRequest searchTracksRequest = SPOTIFY_API.searchTracks(query).limit(10).build();
.limit(1)
.build();
final Paging<Artist> artists = searchArtistsRequest.execute(); final Paging<Track> tracks = searchTracksRequest.execute();
return Arrays.stream(artists.getItems()).findFirst(); return Arrays.stream(tracks.getItems()).collect(Collectors.toList());
} catch (SpotifyWebApiException | ParseException | IOException exception) { } catch (SpotifyWebApiException | ParseException | IOException exception) {
return Optional.empty(); return List.of();
}
} }
}
public List<Track> findTracks(final String query) { public List<Track> findRecommendations(final String artistId, final String genres) {
try { final GetRecommendationsRequest.Builder recommendationsRequestBuilder = SPOTIFY_API.getRecommendations()
final SearchTracksRequest searchTracksRequest = SPOTIFY_API.searchTracks(query).limit(10).build(); .limit(5);
final Paging<Track> tracks = searchTracksRequest.execute();
return Arrays.stream(tracks.getItems()).collect(Collectors.toList()); if (!artistId.isEmpty()) {
} catch (SpotifyWebApiException | ParseException | IOException exception) { recommendationsRequestBuilder
return List.of(); .seed_artists(artistId);
}
} }
public List<Track> findRecommendations(final String artistId, final String genres) { if (!genres.isEmpty()) {
final GetRecommendationsRequest.Builder recommendationsRequestBuilder = SPOTIFY_API.getRecommendations() recommendationsRequestBuilder
.limit(5); .seed_genres(genres);
}
if (!artistId.isEmpty()) {
recommendationsRequestBuilder
.seed_artists(artistId);
}
if (!genres.isEmpty()) {
recommendationsRequestBuilder
.seed_genres(genres);
}
final GetRecommendationsRequest recommendationsRequest = recommendationsRequestBuilder.build(); final GetRecommendationsRequest recommendationsRequest = recommendationsRequestBuilder.build();
try { try {
final Recommendations recommendations = recommendationsRequest.execute(); final Recommendations recommendations = recommendationsRequest.execute();
System.out.println("Length: " + recommendations.getTracks().length); System.out.println("Length: " + recommendations.getTracks().length);
return Arrays.stream(recommendations.getTracks()).collect(Collectors.toList()); return Arrays.stream(recommendations.getTracks()).collect(Collectors.toList());
} catch (IOException | SpotifyWebApiException | ParseException e) { } catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
return ImmutableList.of(); return ImmutableList.of();
}
} }
}
public List<String> findGenres() { public List<String> findGenres() {
final GetAvailableGenreSeedsRequest request = SPOTIFY_API.getAvailableGenreSeeds().build(); final GetAvailableGenreSeedsRequest request = SPOTIFY_API.getAvailableGenreSeeds().build();
try { try {
final String[] genres = request.execute(); final String[] genres = request.execute();
return Arrays.stream(genres).collect(Collectors.toList()); return Arrays.stream(genres).collect(Collectors.toList());
} catch (IOException | SpotifyWebApiException | ParseException e) { } catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
return ImmutableList.of(); return ImmutableList.of();
}
} }
}
private static void clientCredentialsSync() { private static void clientCredentialsSync() {
try { try {
final ClientCredentials clientCredentials = CLIENT_CREDENTIALS_REQUEST.execute(); final ClientCredentials clientCredentials = CLIENT_CREDENTIALS_REQUEST.execute();
// Set access token for further "spotifyApi" object usage // Set access token for further "spotifyApi" object usage
SPOTIFY_API.setAccessToken(clientCredentials.getAccessToken()); SPOTIFY_API.setAccessToken(clientCredentials.getAccessToken());
System.out.println("Expires in: " + clientCredentials.getExpiresIn()); System.out.println("Expires in: " + clientCredentials.getExpiresIn());
} catch (final IOException | SpotifyWebApiException | ParseException e) { } catch (final IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
}
} }
}
} }

134
app/src/main/java/musicbot/YoutubeSearch.java

@ -1,4 +1,5 @@
package musicbot; package musicbot;
import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequest;
@ -18,71 +19,72 @@ import java.util.Optional;
import java.util.Properties; import java.util.Properties;
public class YoutubeSearch { public class YoutubeSearch {
private static final String PROPERTIES_FILENAME = "youtube.properties"; private static final String PROPERTIES_FILENAME = "youtube.properties";
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final long NUMBER_VIDEOS_RETURNED = 1; private static final long NUMBER_VIDEOS_RETURNED = 1;
private static YouTube _youtube; private static YouTube _youtube;
public String searchForMusic(final String title, final String artist) { public String searchForMusic(final String title, final String artist) {
_youtube = get_youtube(); _youtube = get_youtube();
final List<SearchResult> searchResults = doSearch(title, artist); final List<SearchResult> searchResults = doSearch(title, artist);
final Optional<SearchResult> maybeResult = searchResults.stream().findFirst(); final Optional<SearchResult> maybeResult = searchResults.stream().findFirst();
searchResults.stream().forEach(result -> { searchResults.stream().forEach(result -> {
System.out.println("result ID = " + result.getId()); System.out.println("result ID = " + result.getId());
}); });
return maybeResult.map(result -> "http://www.youtube.com/watch?v=" + result.getId().getVideoId()) return maybeResult.map(result -> "http://www.youtube.com/watch?v=" + result.getId().getVideoId())
.orElse("No videos found."); .orElse("No videos found.");
} }
private YouTube get_youtube() { private YouTube get_youtube() {
return new YouTube.Builder( return new YouTube.Builder(
HTTP_TRANSPORT, HTTP_TRANSPORT,
JSON_FACTORY, JSON_FACTORY,
createRequestInitializer() createRequestInitializer()
).setApplicationName("discord-musicbot").build(); ).setApplicationName("discord-musicbot").build();
} }
private HttpRequestInitializer createRequestInitializer() { private HttpRequestInitializer createRequestInitializer() {
final HttpRequestInitializer initializer = new HttpRequestInitializer() { final HttpRequestInitializer initializer = new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {} public void initialize(HttpRequest request) throws IOException {
}; }
};
return initializer;
} return initializer;
}
private List<SearchResult> doSearch(final String title, final String artist) {
try { private List<SearchResult> doSearch(final String title, final String artist) {
final String apiKey = Token.YOUTUBE_API_KEY; try {
final String apiKey = Token.YOUTUBE_API_KEY;
final String query = title + " by " + artist;
final String query = title + " by " + artist;
final YouTube.Search.List search = _youtube.search().list("id,snippet")
.setKey(apiKey) final YouTube.Search.List search = _youtube.search().list("id,snippet")
.setType("video") .setKey(apiKey)
.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)") .setType("video")
.setMaxResults(NUMBER_VIDEOS_RETURNED) .setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)")
.setQ(query); .setMaxResults(NUMBER_VIDEOS_RETURNED)
.setQ(query);
final SearchListResponse response = search.execute();
return response.getItems(); final SearchListResponse response = search.execute();
} catch (GoogleJsonResponseException e) { return response.getItems();
System.err.println("There was a service error: " + e.getDetails().getCode() + " : " } catch (GoogleJsonResponseException e) {
+ e.getDetails().getMessage()); System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
return ImmutableList.of(); + e.getDetails().getMessage());
} catch (IOException e) { return ImmutableList.of();
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); } catch (IOException e) {
return ImmutableList.of(); System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) { return ImmutableList.of();
t.printStackTrace(); } catch (Throwable t) {
return ImmutableList.of(); t.printStackTrace();
} return ImmutableList.of();
} }
}
} }

33
app/src/main/java/musicbot/commands/Artist.java

@ -14,28 +14,27 @@ import java.util.List;
public class Artist extends ListenerAdapter { public class Artist extends ListenerAdapter {
@Override @Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
if (!event.getName().equals("artist")) return; if (!event.getName().equals("artist")) return;
event.deferReply().queue(); event.deferReply().queue();
final String artist = event.getOption("name").getAsString(); final String artist = event.getOption("name").getAsString();
System.out.print("hey!");
final SpotifyClient spotifyClient = new SpotifyClient(); final SpotifyClient spotifyClient = new SpotifyClient();
final List<Track> tracks = spotifyClient.findTracks("artist:"+artist); final List<Track> tracks = spotifyClient.findTracks("artist:" + artist);
final EmbedBuilder eb = new EmbedBuilder(); final EmbedBuilder eb = new EmbedBuilder();
eb eb
.setTitle("Some tracks by " + artist); .setTitle("Some tracks by " + artist);
tracks.forEach(track -> { tracks.forEach(track -> {
eb.addField(track.getName(), "", false); 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();
} }
} }

26
app/src/main/java/musicbot/commands/Genres.java

@ -12,21 +12,21 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class Genres extends ListenerAdapter { public class Genres extends ListenerAdapter {
@Override @Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
if (!event.getName().equals("genres")) return; if (!event.getName().equals("genres")) return;
final SpotifyClient spotifyClient = new SpotifyClient(); final SpotifyClient spotifyClient = new SpotifyClient();
final List<String> genres = spotifyClient.findGenres(); final List<String> genres = spotifyClient.findGenres();
final List<List<String>> batches = Lists.partition(genres, 20); final List<List<String>> batches = Lists.partition(genres, 20);
final List<MessageEmbed> embeds = batches.stream().map(genresList -> { final List<MessageEmbed> embeds = batches.stream().map(genresList -> {
final EmbedBuilder eb = new EmbedBuilder(); final EmbedBuilder eb = new EmbedBuilder();
genresList.forEach(genre -> eb.addField(genre, "", false)); genresList.forEach(genre -> eb.addField(genre, "", false));
return eb.build(); return eb.build();
}).collect(Collectors.toList()); }).collect(Collectors.toList());
event.getChannel().sendMessageEmbeds(embeds).queue(); event.getChannel().sendMessageEmbeds(embeds).queue();
} }
} }

18
app/src/main/java/musicbot/commands/MusicVideo.java

@ -8,16 +8,16 @@ import org.jetbrains.annotations.NotNull;
import java.util.Objects; import java.util.Objects;
public class MusicVideo extends ListenerAdapter { public class MusicVideo extends ListenerAdapter {
@Override @Override
public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) {
if (!event.getName().equals("music")) return; if (!event.getName().equals("music")) return;
final String title = Objects.requireNonNull(event.getOption("title")).getAsString(); final String title = Objects.requireNonNull(event.getOption("title")).getAsString();
final String artist = Objects.requireNonNull(event.getOption("artist")).getAsString(); final String artist = Objects.requireNonNull(event.getOption("artist")).getAsString();
final YoutubeSearch youtubeSearch = new YoutubeSearch(); final YoutubeSearch youtubeSearch = new YoutubeSearch();
final String result = youtubeSearch.searchForMusic(title, artist); final String result = youtubeSearch.searchForMusic(title, artist);
event.reply(result).queue(); event.reply(result).queue();
} }
} }

98
app/src/main/java/musicbot/commands/Recommend.java

@ -19,72 +19,72 @@ import java.util.stream.Collectors;
public class Recommend extends ListenerAdapter { public class Recommend extends ListenerAdapter {
@Override @Override
public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) {
if (!event.getName().equals("recommend")) return; if (!event.getName().equals("recommend")) return;
event.deferReply().queue(); event.deferReply().queue();
final OptionMapping artistInput = event.getOption("artist"); final OptionMapping artistInput = event.getOption("artist");
final OptionMapping genreInput = event.getOption("genre"); final OptionMapping genreInput = event.getOption("genre");
final Optional<String> maybeArtistId = findArtistId(artistInput); final Optional<String> maybeArtistId = findArtistId(artistInput);
final Optional<String> maybeGenre = findGenre(genreInput); final Optional<String> maybeGenre = findGenre(genreInput);
final SpotifyClient spotifyClient = new SpotifyClient(); final SpotifyClient spotifyClient = new SpotifyClient();
final String artistId = maybeArtistId.orElse(""); final String artistId = maybeArtistId.orElse("");
final String genre = maybeGenre.orElse(""); final String genre = maybeGenre.orElse("");
final List<Track> tracks = spotifyClient.findRecommendations(artistId, genre); final List<Track> tracks = spotifyClient.findRecommendations(artistId, genre);
final EmbedBuilder eb = new EmbedBuilder(); final EmbedBuilder eb = new EmbedBuilder();
if (!tracks.isEmpty()) { if (!tracks.isEmpty()) {
eb eb
.setTitle("Recommendations") .setTitle("Recommendations")
.setDescription("Here are a list of recommendations based on your input. " + .setDescription("Here are a list of recommendations based on your input. " +
"It will help you find new music to listen to.") "It will help you find new music to listen to.")
.setFooter("To find a song, select a button below."); .setFooter("To find a song, select a button below.");
tracks.forEach(track -> { tracks.forEach(track -> {
List<String> trackArtists = Arrays.stream(track.getArtists()) List<String> trackArtists = Arrays.stream(track.getArtists())
.map(ArtistSimplified::getName) .map(ArtistSimplified::getName)
.collect(Collectors.toList()); .collect(Collectors.toList());
String artists = String.join(", ", trackArtists); 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<Button> buttons = tracks.stream().map(track -> final List<Button> buttons = tracks.stream().map(track ->
Button.primary(track.getName(), track.getName())).toList(); Button.primary(track.getName(), track.getName())).toList();
event.getHook().sendMessageEmbeds(embed).addActionRow(buttons).queue(); event.getHook().sendMessageEmbeds(embed).addActionRow(buttons).queue();
} else { } else {
eb.setTitle("No recommendations found"); eb.setTitle("No recommendations found");
final MessageEmbed embed = eb.build(); final MessageEmbed embed = eb.build();
event.getHook().sendMessageEmbeds(embed).queue(); event.getHook().sendMessageEmbeds(embed).queue();
}
} }
}
private Optional<String> findArtistId(final OptionMapping artistInput) { private Optional<String> findArtistId(final OptionMapping artistInput) {
if (artistInput == null) { if (artistInput == null) {
return Optional.empty(); return Optional.empty();
}
final SpotifyClient spotifyClient = new SpotifyClient();
final Optional<Artist> maybeArtist = spotifyClient.findArtist(artistInput.getAsString());
return maybeArtist.map(Artist::getId);
} }
private Optional<String> findGenre(final OptionMapping genreInput) { final SpotifyClient spotifyClient = new SpotifyClient();
if (genreInput == null) { final Optional<Artist> maybeArtist = spotifyClient.findArtist(artistInput.getAsString());
return Optional.empty();
}
return Optional.of(genreInput.getAsString()); return maybeArtist.map(Artist::getId);
}
private Optional<String> findGenre(final OptionMapping genreInput) {
if (genreInput == null) {
return Optional.empty();
} }
return Optional.of(genreInput.getAsString());
}
} }

Loading…
Cancel
Save