Skip to content

Commit

Permalink
support for both player and scheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
subinps committed Oct 12, 2021
1 parent 6763ab5 commit eed5aaa
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 83 deletions.
59 changes: 37 additions & 22 deletions plugins/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
start_stream,
stream_from_link,
chat_filter,
c_play
c_play,
is_ytdl_supported
)
from pyrogram.types import (
InlineKeyboardMarkup,
Expand Down Expand Up @@ -76,6 +77,7 @@ async def add_to_playlist(_, message: Message):
type=""
yturl=""
ysearch=""
url=""
if message.command[0] == "fplay":
if not (message.from_user is None and message.sender_chat or message.from_user.id in admins):
k=await message.reply("This command is only for admins.")
Expand Down Expand Up @@ -119,20 +121,25 @@ async def add_to_playlist(_, message: Message):
except:
has_audio_ = False
LOGGER.error("Unable to get Audio properties within time.")
if not has_audio_:
await msg.edit("This is an invalid link, provide me a direct link or a youtube link.")
await delete_messages([message, msg])
return
try:
dur=await get_duration(query)
except:
dur=0
if dur == 0:
await msg.edit("This is a live stream, Use /stream command.")
await delete_messages([message, msg])
return
type="direct"
url=query
if has_audio_:
try:
dur=await get_duration(query)
except:
dur=0
if dur == 0:
await msg.edit("This is a live stream, Use /stream command.")
await delete_messages([message, msg])
return
type="direct"
url=query
else:
if is_ytdl_supported(query):
type="ytdl_s"
url=query
else:
await msg.edit("This is an invalid link, provide me a direct link or a youtube link.")
await delete_messages([message, msg])
return
else:
type="query"
ysearch=query
Expand Down Expand Up @@ -165,7 +172,7 @@ async def add_to_playlist(_, message: Message):
Config.playlist.append(data)
await add_to_db_playlist(data)
await msg.edit("Media added to playlist")
elif type=="youtube" or type=="query":
elif type in ["youtube", "query", "ytdl_s"]:
if type=="youtube":
await msg.edit("⚡️ **Fetching Video From YouTube...**")
url=yturl
Expand All @@ -183,6 +190,8 @@ async def add_to_playlist(_, message: Message):
LOGGER.error(str(e), exc_info=True)
await delete_messages([message, msg])
return
elif type == "ytdl_s":
url=url
else:
return
ydl_opts = {
Expand All @@ -201,11 +210,18 @@ async def add_to_playlist(_, message: Message):
LOGGER.error(str(e))
await delete_messages([message, msg])
return
title = info["title"]
if info['duration'] is None:
await msg.edit("This is a live stream, Use /stream command.")
await delete_messages([message, msg])
return
if type == "ytdl_s":
title = "Music"
try:
title = info['title']
except:
pass
else:
title = info["title"]
if info['duration'] is None:
await msg.edit("This is a live stream, Use /stream command.")
await delete_messages([message, msg])
return
data={1:title, 2:url, 3:"youtube", 4:user, 5:f"{nyav}_{user_id}"}
if message.command[0] == "fplay":
pla = [data] + Config.playlist
Expand Down Expand Up @@ -359,7 +375,6 @@ async def channel_play_list(client, m: Message):




@Client.on_message(filters.command(["yplay", f"yplay@{Config.BOT_USERNAME}"]) & admin_filter & chat_filter)
async def yt_play_list(client, m: Message):
with suppress(MessageIdInvalid, MessageNotModified):
Expand Down
42 changes: 20 additions & 22 deletions plugins/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
sync_to_db,
is_audio,
chat_filter,
scheduler
scheduler,
is_ytdl_supported
)

from pyrogram.types import (
Expand Down Expand Up @@ -95,27 +96,15 @@ async def schedule_vc(bot, message):
type="youtube"
yturl=query
elif query.startswith("http"):
"""if Config.IS_VIDEO:
try:
width, height = get_height_and_width(query)
except:
width, height = None, None
LOGGER.error("Unable to get video properties within time.")
if not width or \
not height:
has_audio_ = await is_audio(query)
if not has_audio_:
if is_ytdl_supported(query):
type="ytdl_s"
url=query
else:
await msg.edit("This is an invalid link, provide me a direct link or a youtube link.")
await delete_messages([message, msg])
return """
#else:
try:
has_audio_ = await is_audio(query)
except:
has_audio_ = False
LOGGER.error("Unable to get Audio properties within time.")
if not has_audio_:
await msg.edit("This is an invalid link, provide me a direct link or a youtube link.")
await delete_messages([message, msg])
return
return
type="direct"
url=query
else:
Expand Down Expand Up @@ -145,7 +134,7 @@ async def schedule_vc(bot, message):
sid=f"{message.chat.id}_{msg.message_id}"
Config.SCHEDULED_STREAM[sid] = data
await sync_to_db()
elif type=="youtube" or type=="query":
elif type in ["youtube", "query", "ytdl_s"]:
if type=="youtube":
await msg.edit("⚡️ **Fetching Video From YouTube...**")
url=yturl
Expand All @@ -163,6 +152,8 @@ async def schedule_vc(bot, message):
LOGGER.error(str(e), exc_info=True)
await delete_messages([message, msg])
return
elif type == "ytdl_s":
url=url
else:
return
ydl_opts = {
Expand All @@ -181,7 +172,14 @@ async def schedule_vc(bot, message):
LOGGER.error(str(e))
await delete_messages([message, msg])
return
title = info["title"]
if type == "ytdl_s":
title = "Music"
try:
title=info['title']
except:
pass
else:
title = info["title"]
data={'1':title, '2':url, '3':"youtube", '4':user, '5':f"{nyav}_{user_id}"}
sid=f"{message.chat.id}_{msg.message_id}"
Config.SCHEDULED_STREAM[sid] = data
Expand Down
66 changes: 27 additions & 39 deletions utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from apscheduler.jobstores.base import ConflictingIdError
from pyrogram.raw.functions.channels import GetFullChannel
from pytgcalls import StreamType
from yt_dlp import YoutubeDL
import yt_dlp
from pyrogram import filters
from pymongo import MongoClient
from datetime import datetime
Expand All @@ -36,7 +36,6 @@
import asyncio
import json
import random
import re
import time
import sys
import os
Expand Down Expand Up @@ -109,6 +108,7 @@ async def play():
if not file:
file = await dl.pyro_dl(song[2])
Config.GET_FILE[song[5]] = file
await sleep(3)
while not os.path.exists(file):
file=Config.GET_FILE.get(song[5])
await sleep(1)
Expand Down Expand Up @@ -705,7 +705,7 @@ async def restart_playout():


def is_ytdl_supported(input_url: str) -> bool:
shei = YoutubeDL.extractor.gen_extractors()
shei = yt_dlp.extractor.gen_extractors()
return any(int_extraactor.suitable(input_url) and int_extraactor.IE_NAME != "generic" for int_extraactor in shei)


Expand Down Expand Up @@ -777,44 +777,32 @@ async def stream_from_link(link):
return True, None



async def get_link(file):
def_ydl_opts = {'quiet': True, 'prefer_insecure': False, "geo-bypass": True}
with YoutubeDL(def_ydl_opts) as ydl:
try:
ydl_info = ydl.extract_info(file, download=False)
except Exception as e:
LOGGER.error(f"Errors occured while getting link from youtube video {e}", exc_info=True)
if Config.playlist or Config.STREAM_LINK:
return await skip()
else:
LOGGER.error("This stream is not supported , leaving VC.")
return False
url=None
for each in ydl_info['formats']:
if each['width'] == 640 \
and each['acodec'] != 'none' \
and each['vcodec'] != 'none':
url=each['url']
break #prefer 640x360
elif each['width'] \
and each['width'] <= 1280 \
and each['acodec'] != 'none' \
and each['vcodec'] != 'none':
url=each['url']
continue # any other format less than 1280
else:
continue
if url:
return url
ytdl_cmd = [ "yt-dlp", "--geo-bypass", "-g", "-f", "best[height<=?720][width<=?1280]/best", file]
process = await asyncio.create_subprocess_exec(
*ytdl_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
output, err = await process.communicate()
if not output:
LOGGER.error(str(err.decode()))
if Config.playlist or Config.STREAM_LINK:
return await skip()
else:
LOGGER.error(f"Errors occured while getting link from youtube video - No Video Formats Found")
if Config.playlist or Config.STREAM_LINK:
return await skip()
else:
LOGGER.error("This stream is not supported , leaving VC.")
return False

LOGGER.error("This stream is not supported , leaving VC.")
await leave_call()
return False
stream = output.decode().strip()
link = (stream.split("\n"))[-1]
if link:
return link
else:
LOGGER.error("Unable to get sufficient info from link")
if Config.playlist or Config.STREAM_LINK:
return await skip()
else:
LOGGER.error("This stream is not supported , leaving VC.")
await leave_call()
return False


async def download(song, msg=None):
Expand Down

0 comments on commit eed5aaa

Please sign in to comment.