How can I configure my Discord bot to stream YouTube audio?

Hey everyone! I’m working on a Discord bot and I want it to play audio from YouTube links. Right now, I’ve got a command set up, but I’m not sure how to make it take the YouTube URL as an argument. Here’s what I’ve got so far:

@client.command()
async def play_yt(ctx):
    video_url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'

    user = ctx.author
    voice_channel = user.voice.channel
    voice_client = await voice_channel.connect()

    audio_player = await voice_client.create_ytdl_player(video_url)
    audio_player.start()

What I want is for users to be able to do something like !play_yt [YouTube link] and have the bot play that specific video. How can I modify my code to make this work? Any help would be awesome!

I’ve actually implemented something similar in my Discord bot project. Here’s what worked for me:

You’ll want to modify your command to accept an argument for the YouTube URL. You can do this by adding a parameter to your function:

@client.command()
async def play_yt(ctx, url: str):
# Your existing code here, but use ‘url’ instead of ‘video_url’

This allows users to input the URL as an argument. Also, I’d recommend using discord.py’s FFmpegPCMAudio and YoutubeDL for better audio streaming:

import discord
from youtube_dl import YoutubeDL

YDL_OPTIONS = {‘format’: ‘bestaudio’, ‘noplaylist’: ‘True’}
FFMPEG_OPTIONS = {‘before_options’: ‘-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5’, ‘options’: ‘-vn’}

with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info[‘formats’][0][‘url’]

voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))

This approach has been more reliable in my experience. Hope this helps!

I’ve implemented a similar feature in my Discord bot. Here’s a streamlined approach that might work for you:

Modify your command to accept a URL parameter:

@client.command()
async def play_yt(ctx, url: str):
voice_channel = ctx.author.voice.channel
voice_client = await voice_channel.connect()

ydl_opts = {'format': 'bestaudio/best'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info(url, download=False)
    url2 = info['formats'][0]['url']

voice_client.play(discord.FFmpegPCMAudio(url2))

This allows users to input any YouTube URL. The bot will extract the audio and play it in the voice channel. Remember to install the necessary libraries (youtube_dl and FFmpeg) for this to work properly. Let me know if you need any clarification!

hey there! i’ve done this before. try using discord.py’s wavelink library. it’s easier:

@bot.command()
async def play(ctx, *, query):
    player = bot.wavelink.get_player(ctx.guild.id)
    if not player.is_connected:
        await ctx.author.voice.channel.connect(cls=wavelink.Player)
    tracks = await wavelink.YouTubeTrack.search(query)
    await player.play(tracks[0])

this should work for both urls and search queries. good luck!