Skip to content
Advertisement

How do I make my discord bot play music by using youtubedl’s search function instead of url? (Python)

I want it to search for the video and play it, how can i change the following code to achieve that? Every time I use the ytsearch function in ytdl, I notice that it only searches for the first word of the title and download it, however, it causes error later on and do nothing.

@commands.command()
    async def play(self, ctx, url):
        if ctx.author.voice is None:
            await ctx.send("You are not in a voice channel!")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio", 'default_search':"ytsearch"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            if 'entries' in info:
              url2 = info["entries"][0]["formats"][0]
            elif 'formats' in info:
              url2 = info["formats"][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)

And this is the error message:

Ignoring exception in command play:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/HandmadeLivelyLines/music.py", line 44, in play
    source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 387, in from_probe
    return cls(source, bitrate=bitrate, codec=codec, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 324, in __init__
    super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 138, in __init__
    self._process = self._spawn_process(args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 144, in _spawn_process
    process = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, **subprocess_kwargs)
  File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1639, in _execute_child
    self.pid = _posixsubprocess.fork_exec(
TypeError: expected str, bytes or os.PathLike object, not dict

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not dict

Thanks.

Advertisement

Answer

To resolve the issue of the URL:

url2 = info["entries"][0]["formats"][0]['url']

And the issue of only one word being taken into the search query:

async def play(self, ctx, *, url):
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement