Search code examples
pythondiscord.pyyoutube-dl

As im trying to use my discord music bot. It gives me an error


So basicly i have been making a music bot and it worked fine with !play {url link}, but when i wanted to change it from link to search i have been getting many errors and now i dont know what to do. Here is the code:

voice_clients = {}

yt_dl_opts = {'format': 'bestaudio/best', 'default_search': 'auto'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)

ffmpeg_options = {'options': "-vn"}
        
#play
    @bot.command()
    async def play(msg, *, url):
      try:
        voice_client = await msg.author.voice.channel.connect()
        voice_clients[voice_client.guild.id] = voice_client
      except:
        print("Already in vc!")
    
  loop = asyncio.get_event_loop()
  data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

  song = data[url]
  player = nextcord.FFmpegPCMAudio(song, **ffmpeg_options)

  voice_clients[msg.guild.id].play(player)
  await msg.send(f"Now playing {url}")

and here is the error im getting after trying to play a song:

    [download] Downloading playlist: macarena
[youtube:search] query "macarena": Downloading page 1
[youtube:search] playlist macarena: Downloading 1 videos
[download] Downloading video 1 of 1
[youtube] zWaymcVmJ-A: Downloading webpage
[download] Finished downloading playlist: macarena
Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\user\Desktop\Python Koneita\Discord botit\Legoshi\bot.py", line 43, in play
    song = data[url]
KeyError: 'macarena'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'macarena'

It seems that the problem is whit song = data[url] but i dont know how to fix it and i have been researching too. This is the last place im looking for help. Thank you!


Solution

  • It looks like you're getting a KeyError when trying to find 'macarena' in data. data must not have any key named 'macarena' in it.

    Whatever your await is returning as a dictionary doesn't have a key named 'macarena' in it, try printing data right after you define it so you can see what data looks like.