I am using the following code to play a video. This works great, but I needed to implement the ability to play the video from the moment specified in the link. With re
I get the time reference into the start_position
variable and then pass it as a parameter to FFMPEG
.
This works great with short videos and 2-3 minute timecodes. But if you try to play 10-hour video with timecode, for example, at 3 hour, the bot will simply remain silent. And the further the timecode is from the start, the longer the bot is silent.
How can this problem be solved and what causes it?
import discord
import asyncio
import re
from yt_dlp import YoutubeDL
YDL_OPTIONS = {
'format': 'bestaudio/best',
}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn -ss {start_position}'
}
bot = discord.Bot(intents=discord.Intents.all())
async def get_source_url(url: str) -> str:
with YoutubeDL(YDL_OPTIONS) as ydl:
return ydl.extract_info(url, download=False).get('url')
@bot.slash_command()
async def test(ctx: discord.ApplicationContext, url: str) -> None:
await ctx.defer()
start_position = 0
if len(timecode := re.findall('[?|&]t=\d{1,}', url)):
start_position = int(re.findall('\d{1,}', timecode[0])[0])
await ctx.respond(f'<{url}>, {start_position}')
source = await get_source_url(url)
vc = await ctx.author.voice.channel.connect()
vc.play(discord.FFmpegPCMAudio(
source=source,
before_options=FFMPEG_OPTIONS['before_options'],
options=FFMPEG_OPTIONS['options'].format(start_position=start_position)
))
while vc.is_playing() or vc.is_paused():
await asyncio.sleep(1)
await vc.disconnect()
bot.run('TOKEN')