devoxin / Lavalink.py

A wrapper for Lavalink in Python, which aims to be powerful and intuitive.
https://lavalink.readthedocs.io/
MIT License
225 stars 96 forks source link

[HIKARI] get_tracks Return empty on command autocompletion but return results in the command itself #150

Closed Tech-User42 closed 2 months ago

Tech-User42 commented 2 months ago

Summary

Hi, i've tried to add in my atuocomplete option for my play command a search results from lavalink, so when you type in discord to search you see all the results from your query without sending the actual play command

Lavalink & System Version

Debian 12 Python 3.11.2 Lavalink.py 5.7.1 Lavalink 4.0.7

Reproduction

@plugin.command()
@lightbulb.add_checks(lightbulb.guild_only)
# @lightbulb.add_checks(CheckUserInSameChannelAsBot)
@lightbulb.option('recherche', 'URL ou môts clés', required=True, autocomplete=True)
@lightbulb.option("maintenant","Si vous voulez que la musique soit jouée maintenant",choices=["Oui","Non"],default="Non") # Option definition 1) --> the name of the option 2) --> The description of the option
@lightbulb.command('play', 'Recherche une vidéos sur YouTube ou ajoute un lien à la liste de lecture', auto_defer = True)
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def play_command(ctx: lightbulb.Context) -> None:

    """Searches the query on youtube, or adds the URL to the queue."""
    player = plugin.bot.d.lavalink.player_manager.get(ctx.guild_id)
    Settings = SettingsHandler(ctx.guild_id)
    # Remove leading and trailing <>. <> may be used to suppress embedding links in Discord.
    query = ctx.options.recherche.strip('<>')
    print(query)
    msg = await ctx.respond(embed=make_embed("M.A.R.I.O.N",IM_PROCESSING)) # On crée un message pour afficher les informations de la musique.
    if not player or not player.is_connected:
        channel_id = await _join(ctx)
        player = plugin.bot.d.lavalink.player_manager.get(ctx.guild_id)
        if not channel_id:
            await msg.edit(embed=make_embed("M.A.R.I.O.N",'Connect to a voice channel first!'))
            return 

    ###### URL HANDLING ######

    # Check if the user input might be a URL. If it isn't, we can Lavalink do a YouTube search for it instead.
    url_rx = re.compile(r'https?://(?:www\.)?.+')
    if not url_rx.match(query):
        query = f'ytsearch:{query}'

     ###### FETCHING RESULTS ######

    # Get the results for the query from Lavalink.
    results = await player.node.get_tracks(query)
    print(results)

    # Results could be None if Lavalink returns an invalid response (non-JSON/non-200 (OK)).
    # Alternatively, results.tracks could be an empty array if the query yielded no tracks.
    if not results or not results.tracks:
        return await msg.edit(embed=make_embed("M.A.R.I.O.N",f"Aucun résultat pour {ctx.options.recherche}"))

    ###### PLAYLIST HANDLING ######

    if results.load_type == 'PLAYLIST_LOADED':
        tracks = results.tracks
        for track in tracks: # Add all of the tracks from the playlist to the queue.
            player.add(requester=ctx.author.id, track=track)
        await msg.edit(embed=make_embed("M.A.R.I.O.N",f"J'ai ajouté la playlist comportant {len(tracks)} vidéos."))

    ###### SINGLE TRACK HANDLING ######

    else:
        track = results.tracks[0]
        ###### RADIO HANDLING ######
        player.add(requester=ctx.author.id, track=track)
        if track.stream : # Si le résultat est une musique en flux. result[0].stream
            for stream in Settings.Load()["radios"]: # 
                if stream["url"] == track.uri: # Si le résultat est une musique en flux de la liste de radios.
                    await msg.edit(embed=make_embed(f"M.A.R.I.O.N",f"{stream['msg']}")) # On affiche le message de la radio.
                    break
        else:
            if(player.current):
                await msg.edit(embed=make_embed("M.A.R.I.O.N",f"J'ajoute {to_bold(to_hyperlink(results.tracks[0].title,results.tracks[0].uri))} à la liste d'attente.",thumbnail=results.tracks[0].artwork_url))       
            else:
                await msg.edit(embed=make_embed("M.A.R.I.O.N",f"Je lis maintenant : {to_bold(to_hyperlink(results.tracks[0].title,results.tracks[0].uri))}",thumbnail=results.tracks[0].artwork_url))       

    if not player.is_playing: # Skip if already playing so add if
        await player.play()
    await MusicDashboardHandler.UpdateMusicDashboard(ctx.guild_id,player)

@play_command.autocomplete("recherche")
async def autocomplete_select_music(opt: hikari.AutocompleteInteractionOption, inter: hikari.AutocompleteInteraction) -> list:
    try:
        last_played = SettingsHandler(inter.guild_id).Load()["LastPlayed"]
        last_played = sorted(last_played, key=lambda x: x.get("count", 0), reverse=True)[:25]
    except KeyError:
        last_played = [{"title": "Rick Astley - Never Gonna Give You Up (Official Music Video)"}]

    query = opt.value
    if(len(query)) < 4:
        return [query]
    print(f"Autocomplete received value: {query}")

    if query and not query.isspace():
        if not query.startswith("http"):
            to_return = [title["title"] for title in last_played if query in title["title"].lower()]
            print(query)
            results = await plugin.bot.d.lavalink.get_tracks(query=str(query))
            print(f"Results: {results}")

            if results and results.tracks:
                to_return.extend(track['title'] for track in results.tracks)
            return to_return
        else:
            return [query]
    else:
        return [title["title"] for title in last_played]

Expected Results

Results: <LoadResult load_type=LoadType.SEARCH playlist_info= tracks=[19 item(s)]> I get this correct results in the play command so when i press enter the query is searched and played normally

Actual Results

Results: <LoadResult load_type=LoadType.EMPTY playlist_info= tracks=[0 item(s)]> I get this wrong result in the recherche autocomplete option

The query is the same for both command and option autocomplete i tried even with player.node.get_tracks same problem, idk what im doing wrong here, if someone could light my lantern that could be great 😃

Checklist

devoxin commented 2 months ago

You have to prefix the query with a search identifier.