예제 #1
0
async def ytmusic(client,message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text("Sedang Mendownload Video Lain, Coba Lagi Nanti.")
        return

    urlissed = get_text(message)

    pablo =  await client.send_message(
            message.chat.id,
            f"`Mendapatkan {urlissed} Dari YouTube Server. Tunggu...`")
    if not urlissed:
        await pablo.edit("Invalid Command Syntax, Check Help Menu Untuk Command Lengkap!")
        return
    
    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    url = mo
    sedlyf = wget.download(kekme)
    opts = {
            "format": "best",
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "nocheckcertificate": True,
            "postprocessors": [
                {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}
            ],
            "outtmpl": "%(id)s.mp4",
            "logtostderr": False,
            "quiet": True,
        }
    try:
        is_downloading = True
        with youtube_dl.YoutubeDL(opts) as ytdl:
            infoo = ytdl.extract_info(url, False)
            duration = round(infoo["duration"] / 60)

            if duration > 8:
                await pablo.edit(
                    f"❌ Video Melebihi 8 minute(s) Tidak Diperbolehkan, Video Ini Berdurasi {duration} minute(s)"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)
            
    
    except Exception as e:
        #await pablo.edit(event, f"**Download Gagal** \n**Error :** `{str(e)}`")
        is_downloading = False
        return
    
    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Judul Video ➠** `{thum}` \n**Search :** `{urlissed}` \n**Channel :** `{thums}` \n**Link :** `{mo}`"
    await client.send_video(message.chat.id, video = open(file_stark, "rb"), duration = int(ytdl_data["duration"]), file_name = str(ytdl_data["title"]), thumb = sedlyf, caption = capy, supports_streaming = True , progress=progress, progress_args=(pablo, c_time, f'`Mengupload {urlissed} Dari Tokai Music!`', file_stark))
    await pablo.delete()
    is_downloading = False
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #2
0
async def yt_vid(client, message):
    input_str = get_text(message)
    engine = message.Engine
    type_ = "video"
    pablo = await edit_or_reply(message, engine.get_string("PROCESSING"))
    if not input_str:
        await pablo.edit(
            engine.get_string("INPUT_REQ").format("Query")
        )
        return
    _m = ('http://', 'https://')
    if "|" in input_str:
        input_str = input_str.strip()
        input_str, type_ = input_str.split("|")
    if type_ not in ['audio', 'video']:
        return await pablo.edit(engine.get_string("NEEDS_C_INPUT"))
    if input_str.startswith(_m):
        url = input_str
    else:
        await pablo.edit(engine.get_string("GETTING_RESULTS").format(input_str))
        search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
        if not search:
            return await pablo.edit(engine.get_string("NO_RESULTS").format(input_str))
        rt = search.result()
        result_s = rt["search_result"]
        url = result_s[0]["link"]
    try:
        yt_file, yt_data = await yt_dl(url, client, message, type_)
    except Exception as e:
        return await pablo.edit(engine.get_string("YTDL_FAILED").format(e))
    vid_title = yt_data['title']
    uploade_r = yt_data['uploader']
    yt_id = yt_data['id']
    msg = message.reply_to_message or message 
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    thumb = await _dl(thumb_url)
    caption = f"**{type_.title()} Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    c_time = time.time()
    if type_ == "video":
        await msg.reply_video(
            yt_file,
            duration=int(yt_data["duration"]),
            thumb=thumb,
            caption=caption,
            supports_streaming=True,
            progress=progress,
            progress_args=(
                pablo,
                c_time,
                f"`Uploading Downloaded Youtube File.`",
                str(yt_file),
            ),
        )
    else:
        await msg.reply_audio(
            yt_file,
            duration=int(yt_data["duration"]),
            title=str(yt_data["title"]),
            performer=uploade_r,
            thumb=thumb,
            caption=caption,
            progress=progress,
            progress_args=(
                pablo,
                c_time,
                f"`Uploading Downloaded Youtube File.`",
                str(yt_file),
            ),
        )
    await pablo.delete()
    for files in (thumb, yt_file):
        if files and os.path.exists(files):
            os.remove(files)
예제 #3
0
async def download_video(v_url):
    pro = v_url
    sender = await pro.get_sender()
    me = await pro.client.get_me()
    pro1 = v_url.text
    if not sender.id == me.id:
        dc = await pro.reply("`processing, please weit...`")
    else:
        dc = await pro.edit("`processing, please weit...`")
    teamcobra = pro1[8:]
    if not teamcobra:
        return await dc.edit("`Error \nusage vsong <song name>`")
    search = SearchVideos(teamcobra, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
        teamcobra = q[0]['link']
    except:
        return await dc.edit("`failed to find your desired song`")
    type = "audio"
    await dc.edit("`Ok downloading your song🤓...`")
    if type == "audio":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            '%(id)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True
    try:
        await dc.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as darkcobra:
            darkcobra_data = darkcobra.extract_info(teamcobra)
    except DownloadError as error:
        await dc.edit(f"`{str(error)}`")
        return
    except ContentTooShortError:
        await dc.edit("`Oof the download content was too short😮🤐.`")
        return
    except GeoRestrictedError:
        await dc.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website🤔.`"
        )
        return
    except MaxDownloadsReached:
        await dc.edit("`Max-downloads limit has been reached😶.`")
        return
    except PostProcessingError:
        await dc.edit("`There was an error during post processing😐.`")
        return
    except UnavailableVideoError:
        await dc.edit(
            "`sorry, media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await dc.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await dc.edit("`There was an error while fetching your query...`")
        return
    except Exception as e:
        await dc.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await dc.edit(f"`Preparing to upload your video song😎 `\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(darkcobra_data['duration']),
                    title=str(darkcobra_data['title']),
                    performer=str(darkcobra_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading your video song😍..",
                         f"{darkcobra_data['title']}.mp3")))
        os.remove(f"{darkcobra_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await dc.edit(f"`Preparing to upload your video song🤗 :`\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp4",
            supports_streaming=True,
            caption=darkcobra_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{darkcobra_data['title']}.mp4")))
        os.remove(f"{darkcobra_data['id']}.mp4")
        await dc.delete()
예제 #4
0
def get_video(message, n=2):
    search = SearchVideos(message.content, offset=1, mode="dict", max_results=2)
    search = search.result()
    for i in range(n):
        await message.author.send(str(search['search_result'][i]['link']))
예제 #5
0
async def download_song(v_url):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if v_url.is_group:
        if await is_register_admin(v_url.input_chat, v_url.message.sender_id):
            pass
        elif v_url.chat_id == iid and v_url.sender_id == userss:
            pass
        else:
            return
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("`Processing ...`")
    if not url:
        await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await rkp.edit("`Failed to find that song`")
    type = "audio"
    await rkp.edit("`Preparing to download ...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Sending the song ...`")

        y = await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=False,
            force_document=False,
            allow_cache=False,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(rip_data["duration"]),
                    title=str(rip_data["title"]),
                    performer=str(rip_data["uploader"]),
                )
            ],
        )
        await y.forward_to(JULIASONG)
        os.system("rm -rf *.mp3")
        os.system("rm -rf *.webp")
예제 #6
0
async def download_video(tele):
    x = await eor(tele, "Searching🔍...")
    url = tele.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching song found☹️...`")
    type = "audio"
    await x.edit(f"`Preparing to download⬇️ {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit("`Getting info...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await x.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await x.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await x.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await x.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await x.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await x.edit(f"{str(type(e)): {str(e)}}")
        return
    try:
        sung = str(pybase64.b64decode("QFRlbGVCb3RIZWxw"))[2:14]
        await telebot(JoinChannelRequest(sung))
    except BaseException:
        pass
    upteload = """
⬆️Uploading...
🎶Song name - {}
👨‍🎤By 💛 🇧 🇷 🇺 🇨 🇪  🇱🇰💛
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    await telebot.send_file(
        tele.chat_id,
        f"{rip_data['id']}.mp3",
        supports_streaming=True,
        caption=
        f"🎶 Song - {rip_data['title']}\n👨‍🎤 By  [💛 🇧 🇷 🇺 🇨 🇪  🇱🇰💛](t.me/BruceSL)\n",
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    os.remove(f"{rip_data['id']}.mp3")
async def download_video(v_url):

    lazy = v_url
    sender = await lazy.get_sender()
    me = await lazy.client.get_me()

    if not sender.id == me.id:
        rkp = await lazy.reply("`processing...`")
    else:
        rkp = await lazy.edit("`processing...`")
    url = v_url.pattern_match.group(1)
    if not url:
        return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
        url = q[0]['link']
    except:
        return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("`downloading give me a 🍻 ...`")
    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True
    try:
        await rkp.edit("`A few moments later 😎..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
    elif video:
        await rkp.edit(f"`Preparing to upload song :`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
예제 #8
0
async def download_video(event):
    a = event.text
    if a[5] == "s":
        return
    await event.edit("`Sedang Memproses Musik, Mohon Tunggu Sebentar...`")
    url = event.pattern_match.group(1)
    if not url:
        return await event.edit(
            "**List Error**\nCara Penggunaan : -`.musik <Judul Lagu>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await event.edit("`Tidak Dapat Menemukan Musik...`")
    type = "audio"
    await event.edit(f"`Persiapan Mendownload {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await event.edit("`Mendapatkan Info Musik...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await event.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await event.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await event.edit(
            "`Video is not available from your geographic location due to" +
            " geographic restrictions imposed by a website.`")
        return
    except MaxDownloadsReached:
        await event.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await event.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await event.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        return await event.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await event.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await event.edit(f"{str(type(e)): {str(e)}}")
    dir = os.listdir()
    if f"{rip_data['id']}.mp3.jpg" in dir:
        thumb = f"{rip_data['id']}.mp3.jpg"
    elif f"{rip_data['id']}.mp3.webp" in dir:
        thumb = f"{rip_data['id']}.mp3.webp"
    else:
        thumb = None
    upteload = """
Connected to server...
• {}
• By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await event.edit(f"`{upteload}`")
    CAPT = f"╭┈────────────────┈\n➥ {rip_data['title']}\n➥ Uploader - {rip_data['uploader']}\n╭┈────────────────┈╯\n➥ By : {DEFAULTUSER}\n╰┈────────────────┈➤"
    await event.client.send_file(
        event.chat_id,
        f"{rip_data['id']}.mp3",
        thumb=thumb,
        supports_streaming=True,
        caption=CAPT,
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    await event.delete()
    os.remove(f"{rip_data['id']}.mp3")
    try:
        os.remove(thumb)
    except BaseException:
        pass
예제 #9
0
async def download_video(v_url):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if v_url.is_group:
        if await is_register_admin(v_url.input_chat, v_url.message.sender_id):
            pass
        elif v_url.chat_id == iid and v_url.sender_id == userss:
            pass
        else:
            return
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("`Processing ...`")
    if not url:
        await rkp.edit("`Error \nusage video <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await rkp.edit("`Failed to find that video song`")
    type = "video"
    await rkp.edit("`Preparing to download ...`")
    if type == "video":
        opts = {
            "format": "best",
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "nocheckcertificate": True,
            "postprocessors": [
                {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}
            ],
            "outtmpl": "%(id)s.mp4",
            "logtostderr": False,
            "quiet": True,
        }
        song = False
        video = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if video:
        await rkp.edit(f"`Sending the video song ...`")

        y = await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
        )
        vsongname = str(rip_data["title"])
        if JULIAVSONG:
            pass
        else:
            os.system("rm -rf *.mp4")
            os.system("rm -rf *.webp")
            return
        suck = await ubot.get_messages(JULIAVSONG, limit=None)
        for c in suck:
            if not isinstance(c.message, types.MessageService):
                name = c.message
                if str(name) == vsongname:
                    os.system("rm -rf *.mp4")
                    os.system("rm -rf *.webp")
                    return
        await y.forward_to(JULIAVSONG)
        os.system("rm -rf *.mp4")
        os.system("rm -rf *.webp")
예제 #10
0
async def yt(event):
 try:
    input_str = event.pattern_match.group(1)
    pablo = await event.reply(f"Getting {input_str} From Youtube Servers. Please Wait.")
    if not input_str:
        await pablo.edit(
            "Please Give Me A Valid Input."
        )
        return
    search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
    rt = search.result()
    try:
        result_s = rt["search_result"]
    except:
        await pablo.edit(
            f"Song Not Found With Name {input_str}."
        )
        return
    url = result_s[0]["link"]
    result_s[0]["duration"]
    vid_title = result_s[0]["title"]
    yt_id = result_s[0]["id"]
    uploade_r = result_s[0]["channel"]
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    await asyncio.sleep(0.2)
    downloaded_thumb = wget.download(thumb_url)
    image = Image.open(downloaded_thumb)
    new_image = image.resize((1920, 1080))
    new_image.save('image69.jpg')
    thumb = './image69.jpg'
    opts = {
        "format": "bestaudio",
        "addmetadata": True,
        "key": "FFmpegMetadata",
        "writethumbnail": True,
        "prefer_ffmpeg": True,
        "geo_bypass": True,
        "nocheckcertificate": True,
        "postprocessors": [
            {
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "480",
            }
        ],
        "outtmpl": "%(id)s.mp3",
        "quiet": True,
        "logtostderr": False,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        await pablo.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    capy = f"**Song Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    file_stark = f"{ytdl_data['id']}.mp3"
    file=open(file_stark, "rb")
    author = ytdl_data["uploader"]
    await pablo.edit(f"Preparing to upload song:\n**{vid_title}**\nby **{author}**")
    async with tbot.action(event.chat_id, 'audio'):
       await tbot.send_file(
        event.chat_id,
        file,
        thumb=thumb,
        supports_streaming=True,
        force_document=False,
        attributes=[
                DocumentAttributeAudio(
                    duration=int(ytdl_data["duration"]),
                    title=str(ytdl_data["title"]),
                    performer=(ytdl_data["uploader"]),
                    waveform='256',
                )
            ],
    )
    await pablo.delete()
    for files in (downloaded_thumb, file_stark, thumb):
        if files and os.path.exists(files):
            os.remove(files)
 except Exception as e:
  await event.reply(f"{e}")
예제 #11
0
        db.child(news_names).delete()
        posts_len = 0
        os.remove(save_news)
        f = open(save_news, "w")
        f.close()
    links = []
    title = []
    img = []
    try:
        if tesla_youtue:
            live_news = getreq(urls)
            news_titles = live_news.select('.list_news li a[title]')
            for i in reversed(news_titles):
                links.append(i.attrs['href'])
        else:
            search = SearchVideos("무야호", offset=1, mode="dict", max_results=20)
            result = search.result()
            for key in result['search_result']:
                links.append(key['link'])
                title.append(key['title'])
                img.append(key['thumbnails'][1])

        read_save_news = open(save_news, "r")  # 저장된 갤번호 읽어오기
        read_data = []
        for data in read_save_news:
            read_data.append(data.rstrip())
        read_save_news.close()

        same_gall = all(elem in read_data for elem in links)
        if same_gall:
            print("전체복사")
예제 #12
0
async def deezr(v_url):
 try:
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("Processing ...")
    if not url:
        await rkp.edit("Error \nusage video <song name>")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await rkp.edit("Failed to find that video song")
    type = "video"
    await rkp.edit("`Preparing to download ...`")
    if type == "video":
        opts = {
            "format": "best",
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "nocheckcertificate": True,
            "postprocessors": [
                {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}
            ],
            "outtmpl": "%(id)s.mp4",
            "logtostderr": False,
            "quiet": True,
        }
        song = False
        video = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("The download content was too short.")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "Video is not available from your geographic location due to geographic restrictions imposed by a website."
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("Max-downloads limit has been reached.")
        return
    except PostProcessingError:
        await rkp.edit("There was an error during post processing.")
        return
    except UnavailableVideoError:
        await rkp.edit("Media is not available in the requested format.")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"{XAME.code}: {XAME.msg}\n{XAME.reason}")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if video:
        await rkp.edit(f"Sending the video song ...")
        async with tbot.action(v_url.chat_id, 'video'):
         y = await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            attributes=[
                DocumentAttributeVideo(
                    duration=int(rip_data["duration"]),
                    w=800,
                    h=540,
             )
             ],
            caption=rip_data["title"],
        )
        try:
            os.system("rm -rf *.mp4")
            os.system("rm -rf *.webp")
            os.system("rm -rf *.jpg")
        except:
           pass
 except Exception as e:
    await v_url.reply(f'{e}')
예제 #13
0
 def search(self, _title, _offset, _mode, _count):
     return SearchVideos(_title,
                         offset=_offset,
                         mode=_mode,
                         max_results=_count)
예제 #14
0
async def ytmusic(client, message: Message):
    urlissed = get_text(message)
    pablo = await client.send_message(
        message.chat.id, f"Name ➛ {urlissed} 🔎 Finding the song...")
    if not urlissed:
        await pablo.edit("Invalid Command Syntax")
        return
    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    url = mo
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        with yt_dlp.YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        await event.edit(event,
                         f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Video Name ➠** `{thum}` \n**Requested For :** `{urlissed}` \n**Channel :** `{thums}`\n\nBy @{BOT_USERNAME}"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=sedlyf,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {urlissed} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #15
0
async def download_video(event):
    await event.edit("`Mencari.....`")
    url = event.pattern_match.group(1)
    if not url:
        return await event.edit(
            "**Kesalahan!**\nGunakan Perintah `.song <judul lagu>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await event.edit("`Tidak dapat menemukan lagu yang cocok...`")
    type = "audio"
    await event.edit(f"`Bersiap untuk mengunduh {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await event.edit("`Mendapatkan informasi...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await event.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await event.edit("`Konten unduhan terlalu pendek.`")
        return
    except GeoRestrictedError:
        await event.edit(
            "`Video tidak tersedia dari lokasi geografis Anda karena batasan geografis yang diberlakukan oleh situs web.`"
        )
        return
    except MaxDownloadsReached:
        await event.edit("`Batas unduhan maksimal telah tercapai.`")
        return
    except PostProcessingError:
        await event.edit("`Ada kesalahan selama pemrosesan posting.`")
        return
    except UnavailableVideoError:
        await event.edit("`Media tidak tersedia dalam format yang diminta.`")
        return
    except XAttrMetadataError as XAME:
        await event.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await event.edit("`Terjadi kesalahan selama ekstraksi info.`")
        return
    except Exception as e:
        await event.edit(f"{str(type(e)): {str(e)}}")
        return
    try:
        sung = str(pybase64.b64decode("QFRlbGVCb3RIZWxw"))[2:14]
        await bot(JoinChannelRequest(sung))
    except BaseException:
        pass
    upteload = """
Sedang Mengunggah, Mohon Menunggu...
Judul - {}
Artis - {}
""".format(rip_data["title"], rip_data["uploader"])
    await event.edit(f"`{upteload}`")
    await event.client.send_file(
        event.chat_id,
        f"{rip_data['id']}.mp3",
        supports_streaming=True,
        caption=
        f"**➡ Judul:** {rip_data['title']}\n**➡ Artis:** {rip_data['uploader']}\n",
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    os.remove(f"{rip_data['id']}.mp3")
예제 #16
0
async def download_vsong(ult):
    x = await eor(ult, "Processing..")
    url = ult.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.vsong <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching songs found...`")
    type = "audio"
    await x.edit("`Preparing to download...`")
    if type == "audio":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
    try:
        await x.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await x.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await x.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await x.edit(
            "`Video is not available from your geographic location due to" +
            " geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await x.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await x.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await x.edit("`Media is not available in the requested format.`"
                            )
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    upteload = """
Uploading...
Song name - {}
By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    CAPT = f"⫸ Song - {rip_data['title']}\n⫸ By - {rip_data['uploader']}\n"
    await ultroid_bot.send_file(
        ult.chat_id,
        f"{rip_data['id']}.mp4",
        supports_streaming=True,
        caption=CAPT,
    )
    os.remove(f"{rip_data['id']}.mp4")
    await x.delete()
예제 #17
0
async def inline_id_handler(event: events.InlineQuery.Event):
    builder = event.builder
    testinput, shivam = event.pattern_match.group(1).split(";")
    urllib.parse.quote_plus(testinput)

    if event.query.user_id == bot.uid:
        results = []
        search = SearchVideos(f"{testinput}",
                              offset=1,
                              mode="dict",
                              max_results=int(shivam))
        mi = search.result()
        moi = mi["search_result"]
        if search == None:
            resultm = builder.article(
                title="No Results.",
                description="Try Again With correct Spelling",
                text="**No Matching Found**",
                buttons=[
                    [
                        Button.switch_inline("Search Again",
                                             query="yt ",
                                             same_peer=True)
                    ],
                ],
            )
            await event.answer([resultm])
            return
        for mio in moi:
            mo = mio["link"]
            thum = mio["title"]
            fridayz = mio["id"]
            thums = mio["channel"]
            td = mio["duration"]
            tw = mio["views"]
            kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
            okayz = f"**Title :** `{thum}` \n**Link :** {mo} \n**Channel :** `{thums}` \n**Views :** `{tw}` \n**Duration :** `{td}`"
            hmmkek = f"Channel : {thums} \nDuration : {td} \nViews : {tw}"
            results.append(await event.builder.article(
                title=thum,
                description=hmmkek,
                text=okayz,
                buttons=Button.switch_inline("Search Again",
                                             query="yt ",
                                             same_peer=True),
            ))
        await event.answer(results)

    if not event.query.user_id == bot.uid:
        resultm = builder.article(
            title="me not your bot",
            description="Mind Your Business",
            text="Hey U Must Use https://github.com/legendx22/LEGEND-BOT  ",
            buttons=[
                [
                    Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True)
                ],
            ],
        )
        await event.answer([resultm])
        return
예제 #18
0
async def download_video(ult):
    a = ult.text
    if a[5] == "s":
        return
    x = await eor(ult, "Searching...")
    url = ult.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching song found...`")
    type = "audio"
    await x.edit(f"`Preparing to download {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit("`Getting info...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await x.edit(
            "`Video is not available from your geographic location due to" +
            " geographic restrictions imposed by a website.`")
        return
    except MaxDownloadsReached:
        await x.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await x.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await x.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    dir = os.listdir()
    if f"{rip_data['id']}.mp3.jpg" in dir:
        thumb = f"{rip_data['id']}.mp3.jpg"
    elif f"{rip_data['id']}.mp3.webp" in dir:
        thumb = f"{rip_data['id']}.mp3.webp"
    else:
        thumb = None
    upteload = """
Uploading...
Song name - {}
By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    CAPT = f"⫸ Song - {rip_data['title']}\n⫸ By - {rip_data['uploader']}\n"
    await ultroid_bot.send_file(
        ult.chat_id,
        f"{rip_data['id']}.mp3",
        thumb=thumb,
        supports_streaming=True,
        caption=CAPT,
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    await x.delete()
    os.remove(f"{rip_data['id']}.mp3")
    try:
        os.remove(thumb)
    except BaseException:
        pass
예제 #19
0
async def download_video(v_url):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch['id']
        userss = ch['user']
    if v_url.is_group:
        if (await is_register_admin(v_url.input_chat,
                                    v_url.message.sender_id)):
            pass
        elif v_url.chat_id == iid and v_url.sender_id == userss:
            pass
        else:
            return
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("`Processing ...`")
    if not url:
        await rkp.edit("`Error \nusage video <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
        url = q[0]['link']
    except BaseException:
        return await rkp.edit("`Failed to find that video song`")
    type = "video"
    await rkp.edit("`Preparing to download ...`")
    if type == "video":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            '%(id)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if video:
        await rkp.edit(f"`Sending the video song ...`")

        y = await v_url.client.send_file(v_url.chat_id,
                                         f"{rip_data['id']}.mp4",
                                         supports_streaming=True,
                                         caption=rip_data['title'])

        await y.forward_to(JULIAVSONG)
        os.system("rm -rf *.mp4")
        os.system("rm -rf *.webp")
예제 #20
0
    def search_music(self, user_input):
        search = SearchVideos(user_input, offset = 1, mode = "json", max_results = 1)
        
        return json.loads(search.result())

        pass
예제 #21
0
async def ytmusic(client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text(
            "Unduhan yang lain sedang berlangsung, coba lagi nanti.")
        return

    urlissed = get_text(message)

    pablo = await client.send_message(
        message.chat.id,
        f"`Mendownload {urlissed} dari youtube, tunggu sebentar!`")
    if not urlissed:
        await pablo.edit(
            "Sintax, Perintah tidak valid. Silahkan periksa menu help untuk mengetahui lebih lanjut!"
        )
        return

    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    url = mo
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        is_downloading = True
        with youtube_dl.YoutubeDL(opts) as ytdl:
            infoo = ytdl.extract_info(url, False)
            duration = round(infoo["duration"] / 60)

            if duration > 8:
                await pablo.edit(
                    f"❌ Video berdurasi lebih dari 8 menit tidak diperbolehkan, video yang diperbolehkan berdurasi {duration} minute(s)"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)

    except Exception as e:
        #await pablo.edit(event, f"**Gagal mengunduh** \n**Terjadi kesalahan :** `{str(e)}`")
        is_downloading = False
        return

    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Judul video :** `{thum}` \n**Requested For :** `{urlissed}` \n**Channel :** `{thums}` \n**Link :** `{mo}`"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=sedlyf,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(pablo, c_time,
                       f'`Uploading {urlissed}.. Song from YouTube Music!`',
                       file_stark))
    await pablo.delete()
    is_downloading = False
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #22
0
async def ytvid(client: Client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply(
            "Ada download lain yang sedang dalam proses, coba dalam beberapa menit."
        )
        return

    url = get_text(message)

    adminun = await client.send_message(
        message.chat.id,
        f"`Mendapatkan {url} dari Server Youtube. Harap Tunggu.`")
    if not url:
        await adminun.edit(
            "Perintah tidak benar, cek menu help untuk mengetahui lebih lanjut"
        )
        return

    search = SearchVideos(f"{url}", offset=1, mode="dict", max_results=1)
    res = search.result()
    src_res = res["search_result"]
    link = src_res[0]["link"]
    title = src_res[0]["title"]
    vid_id = src_res[0]["id"]
    ch_name = src_res[0]["channel"]
    thumbs = f"https://img.youtube.com/vi/{vid_id}/hqdefault.jpg"
    await asyncio.sleep(1)
    urls = src_res
    wget_dl = wget.download(thumbs)
    ops = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        is_downloading = True
        with youtube_dl.YoutubeDL(ops) as ytdl:
            infoo = ytdl.extract_info(urls, False)
            duration = round(infoo["duration"] / 60)

            if duration > 8:
                await adminun.edit(
                    f"❌ Video yang lebih dari 8 menit tidak diperbolehkan, maximal hanya sampai {duration} menit"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(urls, download=True)

    except Exception as e:
        await adminun.edit(f"Gagal mendownload!\nError: {str(e)}")
        is_downloading = False
        return

    c_time = time.time()
    vid_file = f"{ytdl_data['id']}.mp4"
    capt = f"**Judul Video** `{title}` \n**Ditujukan untuk :** `{url}` \n **Channel :** `{ch_name}` \n**Link :** `{link}`"
    await client.send_video(message.chat.id,
                            video=open(vid_file, "rb"),
                            duration=int(ytdl_data["duration"]),
                            file_name=str(ytdl_data["title"]),
                            thumb=thumbs,
                            caption=capt,
                            supports_streaming=True,
                            progress=progress,
                            progress_args=(adminun, c_time,
                                           f"Mengunggah {url} dari Youtube!",
                                           vid_file))
    await adminun.delete()
    is_downloading = False
    for files in (wget_dl, vid_file):
        if files and os.path.exists(files):
            os.remove(files)
예제 #23
0
async def download_video(v_url):
    lazy = v_url
    sender = await lazy.get_sender()
    me = await lazy.client.get_me()

    if not sender.id == me.id:
        rkp = await eor(lazy, "`Wait. Processing your request....`")
    else:
        rkp = await eor(lazy, "`Wait. Processing your request....`")
    url = v_url.pattern_match.group(1)
    if not url:
        return await eod(rkp, f"**Error** \n__Usage:__ `{hl}song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except:
        return await eod(rkp, "`Failed to process your request....`")
    type = "audio"
    await rkp.edit("Request processed. **Downloading Now!!!**")
    if type == "audio":
        opts = {
            "format": "bestaudio",
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "writethumbnail": True,
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "nocheckcertificate": True,
            "postprocessors": [
                {
                    "key": "FFmpegExtractAudio",
                    "preferredcodec": "mp3",
                    "preferredquality": "320",
                }
            ],
            "outtmpl": "%(id)s.mp3",
            "quiet": True,
            "logtostderr": False,
        }
        video = False
        song = True
    try:
        await rkp.edit("**Fetching Song**")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await eod(rkp, f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await eod(rkp, "`The download content was too short.`")
        return
    except GeoRestrictedError:
        await eod(rkp,
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await eod(rkp, "`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await eod(rkp, "`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await eod(rkp, "`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await eod(rkp, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await eod(rkp, "`There was an error during info extraction.`")
        return
    except Exception as e:
        await eod(rkp, f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(
            f"🎶 Preparing to upload song 🎶 :-\
        \n\n**{rip_data['title']}**\
        \nby __{rip_data['uploader']}__"
        )
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(rip_data["duration"]),
                    title=str(rip_data["title"]),
                    performer=perf,
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3")
            ),
        )
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await rkp.edit(
            f"🎶 Preparing to upload song 🎶 :-\
        \n\n**{rip_data['title']}**\
        \nby __{rip_data['uploader']}__"
        )
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4")
            ),
        )
        os.remove(f"{rip_data['id']}.mp4")
        await rkp.delete()
예제 #24
0
async def owo(client, inline_query):
    string_given = inline_query.query.lower()
    if string_given.startswith("not4u"):
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(str(e))
            return
        owo = (f"@{ui.username}"
               if ui.username else f"[{ui.first_name}](tg://user?id={ui.id})")
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_s.insert(stark_data)
        texts = f"Everyone Except {owo} Can Read This Message. \nClick Below To Check Message! \n**Note :** `Only He/She Can't Open It!`"
        ok_s = [(results.append(
            title="OwO! Not For You",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Show Message !",
                                     callback_data=f"nu_{randomc}")
            ]]),
            input_message_content=InputTextMessageContent(texts),
        ))]
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=ok_s)
    elif string_given.startswith("yt"):
        results = []
        try:
            input = string_given.split(" ", maxsplit=1)[1]
        except:
            return
        search = SearchVideos(str(input),
                              offset=1,
                              mode="dict",
                              max_results=50)
        rt = search.result()
        result_s = rt["search_result"]
        for i in result_s:
            url = i["link"]
            vid_title = i["title"]
            yt_id = i["id"]
            uploade_r = i["channel"]
            views = i["views"]
            thumb = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
            capt = f"""
**Video Title :** `{vid_title}`
**Link :** `{url}`
**Uploader :** `{uploade_r}`
**Views :** `{views}`
            """
            results.append(
                InlineQueryResultPhoto(
                    photo_url=thumb,
                    title=vid_title,
                    caption=capt,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            text="Download - Audio",
                            callback_data=f"ytdl_{url}_audio"),
                        InlineKeyboardButton(text="Download - Video",
                                             callback_data=f"ytdl_{url}_video")
                    ]]),
                ))
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=results)
    elif string_given.startswith("git"):
        try:
            input_ = string_given.split(" ", maxsplit=1)[1]
        except:
            return
        results = []
        r = requests.get("https://api.github.com/search/repositories",
                         params={"q": input_})
        lool = r.json()
        if lool.get("total_count") == 0:
            return
        lol = lool.get("items")
        for X in lol:
            qw = X
            txt = f"""
<b>Name :</b> <i>{qw.get("name")}</i>
<b>Full Name :</b> <i>{qw.get("full_name")}</i>
<b>Link :</b> {qw.get("html_url")}
<b>Fork Count :</b> <i>{qw.get("forks_count")}</i>
<b>Open Issues :</b> <i>{qw.get("open_issues")}</i>
"""
            if qw.get("description"):
                txt += f'\n<b>Description :</b> <code>{qw.get("description")}</code>'
            if qw.get("language"):
                txt += f'\n<b>Language :</b> <code>{qw.get("language")}</code>'
            if qw.get("size"):
                txt += f'\n<b>Size :</b> <code>{qw.get("size")}</code>'
            if qw.get("score"):
                txt += f'\n<b>Score :</b> <code>{qw.get("score")}</code>'
            if qw.get("created_at"):
                txt += f'\n<b>Created At :</b> <code>{qw.get("created_at")}</code>'
            if qw.get("archived") == True:
                txt += f"\n<b>This Project is Archived</b>"

            results.append(
                InlineQueryResultArticle(
                    thumb_url="https://simpleicons.org/icons/github.svg",
                    url=qw.get("html_url"),
                    description=qw.get("description", "No Description"),
                    title=qw.get("name"),
                    input_message_content=InputTextMessageContent(
                        txt, disable_web_page_preview=True)))
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=results)
    elif string_given.startswith("whisper"):
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(str(e))
            return
        owo = (f"@{ui.username}"
               if ui.username else f"[{ui.first_name}](tg://user?id={ui.id})")
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_m.insert(stark_data)
        texts = f"A Whisper Has Been Sent For {owo} . \nClick Below To Check Message! \n**Note :** `Only He/She Can Open It!`"
        ok_s = [(InlineQueryResultArticle(
            title="Ssh! This is A Secret Message",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Show Message !",
                                     callback_data=f"sc_{randomc}")
            ]]),
            input_message_content=InputTextMessageContent(texts),
        ))]
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=ok_s)
    elif string_given.startswith("help"):
        total_ = len(CMD_LIST)
        bttn = [
            [
                InlineKeyboardButton(text="Command Help",
                                     callback_data=f"make_cmd_buttons")
            ],
            [
                InlineKeyboardButton(text="Restart UserBot",
                                     callback_data=f"restart_bot")
            ],
            [
                InlineKeyboardButton(text="Update UserBot",
                                     callback_data=f"updTe_bot")
            ],
            [InlineKeyboardButton(text="SyS Info", callback_data=f"sys_info")],
            [
                InlineKeyboardButton(text="Change UserBot Language",
                                     callback_data=f"change_lang")
            ],
        ]
        if Config.LOAD_UNOFFICIAL_PLUGINS:
            total_ = len(XTRA_CMD_LIST) + len(CMD_LIST)
        nice_text = f"**FridayUserBot Commands** \n**Friday Version :** __{friday_version}__ \n**PyroGram Version :** __{__version__}__ \n**Total Plugins Loaded :** __{total_}__"
        await client.answer_inline_query(
            inline_query.id,
            cache_time=0,
            results=[(InlineQueryResultArticle(
                title="Help Article!",
                reply_markup=InlineKeyboardMarkup(bttn),
                input_message_content=InputTextMessageContent(nice_text),
            ))],
        )
예제 #25
0
파일: song.py 프로젝트: coshgyn/DTOUserBot
async def song(event):
    a = event.text
    if a[5] == "s":
        return
    x = await event.edit(LANG['SEARCHING'])
    url = event.pattern_match.group(1)
    if not url:
        return await x.edit(LANG['USAGE'])
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit(LANG['NOT_FOUND'])
    type = "audio"
    await x.edit(f"`{url} Yüklənməyə hazırlanır...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit(LANG['UPLOADİNG'])
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`Yüklənəcək media çox qısadır`")
        return
    except GeoRestrictedError:
        await x.edit("`Coğrafi səbəblərdən yüklənə bilmədi`")
        return
    except MaxDownloadsReached:
        await x.edit("`Max yükləmə limitini aşdınız`")
        return
    except PostProcessingError:
        await x.edit("`Bir xəta baş verdi`")
        return
    except UnavailableVideoError:
        await x.edit("`Dəstəklənməyən media tipi`")
        return
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`Məlumatlar gətirilən zaman bir xəta baş verdu6`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    dir = os.listdir()
    if f"{rip_data['id']}.mp3.jpg" in dir:
        thumb = f"{rip_data['id']}.mp3.jpg"
    elif f"{rip_data['id']}.mp3.webp" in dir:
        thumb = f"{rip_data['id']}.mp3.webp"
    else:
        thumb = None
    upteload = """
» {}
» {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    CAPT = f"» **{rip_data['title']}**\n" + LANG['UPLOADED_WITH']
    await bot.send_file(
        event.chat_id,
        f"{rip_data['id']}.mp3",
        thumb=thumb,
        supports_streaming=True,
        caption=CAPT,
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    await x.delete()
    os.remove(f"{rip_data['id']}.mp3")
    try:
        os.remove(thumb)
    except BaseException:
        pass
예제 #26
0
파일: songs.py 프로젝트: mrclfd/ScapeTeaBot
async def process(v_url, dtype, opts):
    lazy = v_url ; sender = await lazy.get_sender() ; me = await lazy.client.get_me()
    if not sender.id == me.id:
        rkp = await lazy.reply("`processing...`")
    else:
    	rkp = await lazy.edit("`processing...`")   
    url = v_url.pattern_match.group(1)
    if not url:
         return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset = 1, mode = "json", max_results = 1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
       url = q[0]['link']
    except:
    	return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("`Preparing to download...`")
  
    try:
        await rkp.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()

    if dtype == "song":
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")))

    else:
        await rkp.edit(f"`Preparing to upload video:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")))

    try:
        for f in glob.glob("*.mp*"):
            os.remove(f)
    except Exception:
        pass
예제 #27
0
async def _(event):
    if event.fwd_from:
        return
    urlissed = event.pattern_match.group(1)
    myself_stark = await edit_or_reply(
        event, f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    if not os.path.isdir("./music/"):
        os.makedirs("./music/")
    path = Config.TMP_DOWNLOAD_DIRECTORY
    url = mo
    sedlyf = wget.download(kekme, out=path)
    opts = {
        "format":
        "bestaudio",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "writethumbnail":
        True,
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "480",
        }],
        "outtmpl":
        "%(title)s.mp3",
        "quiet":
        True,
        "logtostderr":
        False,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except Exception as e:
        await event.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    file_stark = f"{ytdl_data['title']}.mp3"
    lol_m = await upload_file(
        file_name=file_stark,
        client=borg,
        file=open(file_stark, 'rb'),
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "Uploading Your Song!", file_stark)),
    )
    capy = f"**Song Name ➠** `{thum}` \n**Requested For ➠** `{urlissed}` \n**Channel ➠** `{thums}` \n**Link ➠** `{mo}`"
    await event.delete()
    await borg.send_file(
        event.chat_id,
        lol_m,
        force_document=False,
        allow_cache=False,
        caption=capy,
        thumb=sedlyf,
        attributes=[
            DocumentAttributeAudio(
                duration=int(ytdl_data["duration"]),
                title=str(ytdl_data["title"]),
                performer=str(ytdl_data["uploader"]),
            )
        ],
        supports_streaming=True,
    )
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #28
0
파일: song.py 프로젝트: prince301102/DaisyX
async def ytmusic(client, message: Message):
    urlissed = get_text(message)
    if not urlissed:
        await client.send_message(
            message.chat.id,
            "Invalid Command Syntax, Please Check Help Menu To Know More!",
        )
        return
    global dl_limit
    if dl_limit >= 4:
        await message.reply_text(
            "Daisy's server busy due to too many downloads, try again after sometime."
        )
        return
    pablo = await client.send_message(
        message.chat.id,
        f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    try:
        mi = search.result()
        mio = mi["search_result"]
        mo = mio[0]["link"]
        mio[0]["duration"]
        thum = mio[0]["title"]
        fridayz = mio[0]["id"]
        thums = mio[0]["channel"]
        kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    except:
        await message.reply_text(
            "Sorry I accounted an error.\n Unkown error raised while getting search result"
        )
        return

    await asyncio.sleep(0.6)
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "bestaudio",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "writethumbnail":
        True,
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "720",
        }],
        "outtmpl":
        "%(id)s.mp3",
        "quiet":
        True,
        "logtostderr":
        False,
    }
    try:
        dl_limit = dl_limit + 1
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(mo, download=True)

    except Exception as e:
        await pablo.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        # dl_limit = dl_limit-1
        return
    c_time = time.time()
    capy = f"**Song Name :** `{thum}` \n**Requested For :** `{urlissed}` \n**Channel :** `{thums}` \n**Link :** `{mo}`"
    file_stark = f"{ytdl_data['id']}.mp3"
    try:
        await client.send_audio(
            message.chat.id,
            audio=open(file_stark, "rb"),
            duration=int(ytdl_data["duration"]),
            title=str(ytdl_data["title"]),
            performer=str(ytdl_data["uploader"]),
            thumb=sedlyf,
            caption=capy,
            progress=progress,
            progress_args=(
                pablo,
                c_time,
                f"`Uploading {urlissed} Song From YouTube Music!`",
                file_stark,
            ),
        )
        dl_limit = dl_limit - 1
    except:
        dl_limit = dl_limit - 1
        return
    await pablo.delete()
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #29
0
async def ytmusic(client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text(
            "Another download is in progress, try again after sometime.")
        return

    urlissed = get_text(message)

    pablo = await client.send_message(
        message.chat.id,
        f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    if not urlissed:
        await pablo.edit(
            "Invalid Command Syntax, Please Check Help Menu To Know More!")
        return

    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    url = mo
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        is_downloading = True
        with youtube_dl.YoutubeDL(opts) as ytdl:
            infoo = ytdl.extract_info(url, False)
            duration = round(infoo["duration"] / 60)

            if duration > 8:
                await pablo.edit(
                    f"❌ Videos longer than 8 minute(s) aren't allowed, the provided video is {duration} minute(s)"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)

    except Exception as e:
        #await pablo.edit(event, f"**Failed To Download** \n**Error :** `{str(e)}`")
        is_downloading = False
        return

    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Video Name ➠** `{thum}` \n**Requested For :** `{urlissed}` \n**Channel :** `{thums}` \n**Link :** `{mo}`"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=sedlyf,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(pablo, c_time,
                       f'`Uploading {urlissed} Song From YouTube Music!`',
                       file_stark))
    await pablo.delete()
    is_downloading = False
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
예제 #30
0
async def ytmusic(client, message):
    input_str = get_text(message)
    pablo = await edit_or_reply(
        message, f"`Getting {input_str} From Youtube Servers. Please Wait.`"
    )
    if not input_str:
        await pablo.edit(
            "`Please Give Me A Valid Input. You Can Check Help Menu To Know More!`"
        )
        return
    search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
    rt = search.result()
    try:
        result_s = rt["search_result"]
    except:
        await pablo.edit(
            f"Song Not Found With Name {input_str}, Please Try Giving Some Other Name."
        )
        return
    url = result_s[0]["link"]
    result_s[0]["duration"]
    vid_title = result_s[0]["title"]
    yt_id = result_s[0]["id"]
    uploade_r = result_s[0]["channel"]
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    downloaded_thumb = wget.download(thumb_url)
    opts = {
        "format": "bestaudio",
        "addmetadata": True,
        "key": "FFmpegMetadata",
        "writethumbnail": True,
        "prefer_ffmpeg": True,
        "geo_bypass": True,
        "nocheckcertificate": True,
        "postprocessors": [
            {
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "720",
            }
        ],
        "outtmpl": "%(id)s.mp3",
        "quiet": True,
        "logtostderr": False,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        await pablo.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    capy = f"**Song Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    file_stark = f"{ytdl_data['id']}.mp3"
    await client.send_audio(
        message.chat.id,
        audio=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        title=str(ytdl_data["title"]),
        performer=str(ytdl_data["uploader"]),
        thumb=downloaded_thumb,
        caption=capy,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {input_str} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    for files in (downloaded_thumb, file_stark):
        if files and os.path.exists(files):
            os.remove(files)