Hey everyone! I’m working on a Discord bot for my school project. I want it to play YouTube audio but I’m stuck. I’ve looked at some guides online but they don’t seem to work for me. Does anyone know how to do this with Discord.py Rewrite?
I found some code that plays MP3 files, but I’m not sure how to make it work with YouTube links. Here’s what I have so far:
@bot.command()
async def play_song(ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
voice = await channel.connect()
voice.play(discord.FFmpegPCMAudio('music.mp3'))
while voice.is_playing():
await asyncio.sleep(1)
await voice.disconnect()
else:
await ctx.send('You need to be in a voice channel to use this command!')
Can someone help me figure out how to stream YouTube audio instead? Thanks!
I’ve actually implemented a similar feature in one of my Discord bots. The key is to use the youtube_dl library along with FFmpeg. Here’s a simplified version of how I got it working:
First, install youtube_dl and FFmpeg. Then, modify your code to fetch the YouTube audio stream:
import youtube_dl
@bot.command()
async def play(ctx, url):
if ctx.author.voice:
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_channel = ctx.author.voice.channel
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio(url2))
else:
await ctx.send('Join a voice channel first!')
This code fetches the audio stream URL from YouTube and plays it directly. Remember to handle errors and disconnections properly in a real-world scenario. Hope this helps!
As someone who’s worked extensively with Discord bots, I can offer some insights. While the youtube_dl approach mentioned is viable, it’s worth noting that YouTube’s terms of service can be a bit tricky when it comes to bots. A more robust solution might be to use a library like youtube-dl-python or yt-dlp, which are actively maintained forks of youtube-dl.
Here’s a crucial tip: make sure to implement a queue system. This allows users to add multiple songs and prevents conflicts when multiple people try to play music simultaneously. Also, don’t forget to handle potential errors, like invalid URLs or connection issues.
Lastly, consider adding basic controls like pause, resume, and skip. These features greatly enhance the user experience and are relatively straightforward to implement once you have the base functionality working.