YT Search on Discord Bot

2019-09-20 17:48发布

问题:

i would like to know how to make my bot play music based on YouTube search rather than having to copy in a URL.

Here's my code for playing music right now,

  @client.command(pass_context=True)
     async def play(ctx, url):
    server = ctx.message.server
    await client.say ('Music now playing...')
    voice_client = client.voice_client_in(server)
    player = await voice_client.create_ytdl_player(url, after=lambda: 
    check_queue(server.id))
    players[server.id] = player
    player.start()

What is it that I need to add to make it play search results instead of URL's.

Thanks!

回答1:

You can do this by setting default_search to auto in the options. This means that it still functions as expected when a URL is specified, but if it's not a URL then a search will be done instead. Documentation here:https://github.com/rg3/youtube-dl/blob/master/README.md#options

In your code, you can modify it as such.

@client.command(pass_context=True)
    async def play(ctx, url):
    server = ctx.message.server
    await client.say ('Music now playing...')
    voice_client = client.voice_client_in(server)
    player = await voice_client.create_ytdl_player(url, ytdl_options={'default_search': 'auto'} after=lambda: check_queue(server.id))
    players[server.id] = player
    player.start()