Youtube Search Command for JDA Discord Music Bot

1.9k Views Asked by At

I've been working on a Discord bot for a few days now.

Initially only with simpler commands etc. But slowly I also devoted myself to the topic of music bot.

I also use the YouTube Data API for this and everything works so far. However, I would now like to incorporate a Youtube Search Command or build it into another (Play Command). I already have half a search command.

So far you can do $play (song title)

and the first track found will be selected.

However, I want to be able to see the first 10 search results and then choose between them.

I have already figured out how to display the search results, but now I need a little help with how to enter a command, after you have already entered another.

So you enter: $play Faded

Then a normal EmbedBuilder comes up and shows you the search results, and then you can select the desired track by entering 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10.

This is the code:

public class PlayCommand implements ServerCommand {
    private final YouTube youTube;

    public PlayCommand() {
        YouTube temp = null;

        try {
            temp = new YouTube.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(),
                    JacksonFactory.getDefaultInstance(),
                    null
            )
                    .setApplicationName("JDA Discord Bot")
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        youTube = temp;
    }

    @Override
    public void performCommand(List<String> args, Member m, TextChannel channel, Message message) throws RiotApiException {
        String input = String.join(" ", args.subList(1, args.size() - 1));

        if (!isUrl(input)) {
            String ytSearched = searchYoutube(channel, input);

            if (ytSearched == null) {
                channel.sendMessage("Keine Ergebnisse!").queue();

                return;
            }


            input = ytSearched;
        }

        PlayerManager manager = PlayerManager.getInstance();

        manager.loadAndPlay(channel, input);
        manager.getGuildMusicManager(channel.getGuild()).player.setVolume(100);
    }

    private boolean isUrl(String input) {
        try {
            new URL(input);

            return true;
        } catch (MalformedURLException ignored) {
            return false;
        }
    }

    @Nullable
    private String searchYoutube(TextChannel channel, String input) {
        String youtubeKey = "AIzaSyDoQ4OInMTYth7hdlWwQSIaHuxpxxv7eJs";

        try {
            List<SearchResult> results = youTube.search()
                    .list("id,snippet")
                    .setQ(input)
                    .setMaxResults(10L)
                    .setType("video")
                    .setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)")
                    .setKey(youtubeKey)
                    .execute()
                    .getItems();

            if (!results.isEmpty()) {
                String videoId = results.get(0).getId().getVideoId();


                /*EmbedBuilder builder = new EmbedBuilder();
                builder.setTitle("Suchergebnisse");
                builder.setColor(Color.RED);
                builder.setDescription( "1. " + results.get(0).getSnippet().getTitle() + "\n" +
                                        "2. " + results.get(1).getSnippet().getTitle() + "\n" +
                                        "3. " + results.get(2).getSnippet().getTitle() + "\n" +
                                        "4. " + results.get(3).getSnippet().getTitle() + "\n" +
                                        "5. " + results.get(4).getSnippet().getTitle() + "\n" +
                                        "6. " + results.get(5).getSnippet().getTitle() + "\n" +
                                        "7. " + results.get(6).getSnippet().getTitle() + "\n" +
                                        "8. " + results.get(7).getSnippet().getTitle() + "\n" +
                                        "9. " + results.get(8).getSnippet().getTitle() + "\n" +
                                        "10. " + results.get(9).getSnippet().getTitle());

                channel.sendMessage(builder.build()).queue();
                */


                return "https://www.youtube.com/watch?v=" + videoId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
1

There are 1 best solutions below

2
On

I think you are looking for an EventWaiter. With JDA-Utilities you can achieve what you want.

You just basically wait for an event, check if it's suitable for the use case of yours (eg: is a specific event, or contains a specific text) Check out this stackoverflow answer about EventWaiter and adding it as an EventListener.

You would want to check if the received text for example is part of the youtube search result. Also don't forget about having a time limit for accepting answers.