Cheesebellies
Cheesebellies

Reputation: 52

How to use youtube_dl and FFMpegPCM audio to play live streams from youtube? Discord.py rewrite

I have been working on a simple music bot for discord, and my friends requested a feature where you can stream audio from a youtube live stream. This has had me puzzled, and I can't find any good sources to solve this. Here is the important code:

from discord.ext import commands
from discord.ext import tasks
import discord
from itertools import cycle
import os
from dotenv import load_dotenv
import asyncio
from ytsearch import searchr
from discord.utils import get
from discord import FFmpegPCMAudio
from youtube_dl import YoutubeDL

list_to_play = []
paused = False

load_dotenv()
TOKEN = os.getenv("TOKEN")

bot = commands.Bot(command_prefix='-')
@bot.event
async def on_ready():
  for guild in bot.guilds:
    print(
    f'{bot.user} is connected to the following guild(s):\n'
    f'{guild.name}(id: {guild.id})'
    )
  change_status.start()
  play_the_list.start()
  
status = cycle(['Music is here!','More features soon!'])

@tasks.loop(seconds=10)
async def change_status():
  await bot.change_presence(activity=discord.Game(next(status)))

async def playa(ctx,url):
    YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':   'True'}
    FFMPEG_OPTIONS = {
          'before_options': '-reconnect 1   -reconnect_streamed 1 -reconnect_delay_max 5',  'options': '-vn'}

    voice = get(bot.voice_clients, guild=ctx.guild)
    with YoutubeDL(YDL_OPTIONS) as ydl:
          info = ydl.extract_info(url, download=False)
          URL = info['url']
          voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
          voice.is_playing()


@tasks.loop(seconds=3)
async def play_the_list():
  global list_to_play
  
  if paused == False:
    
      if len(list_to_play) != 0:
        ctx = list_to_play[0][1]

        voice = get(bot.voice_clients, guild=ctx.guild)
        if voice.is_playing() == False:

          if len(list_to_play) != 0:
            await playa(list_to_play[0][1],list_to_play[0][0])
            del list_to_play[0]




bot.run(TOKEN) 

I'm looking for something like playa() (or ways to edit playa() so it plays live videos)

Upvotes: 0

Views: 1732

Answers (1)

nsde
nsde

Reputation: 92

I would recommend checking out the official example for such a player:

These snippets might help :)

For the FFmpeg Class:

data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

and

filename = data['url'] if stream else ytdl.prepare_filename(data)

Command:

@commands.command()
async def stream(self, ctx, *, url):
    """Streams from a url (same as yt, but doesn't predownload)"""
    async with ctx.typing():
    player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
    ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

        await ctx.send(f'Now playing: {player.title}')

Upvotes: 2

Related Questions