Пример #1
0
async def leech2tg(event):
    if event.fwd_from:
        return
    var = event.pattern_match.group(1)
    if not var:
        rep = event.get_reply_message()
        var = rep.text
    # print(var)
    uris = [var]
    # Add URL Into Queue
    try:
        download = aria2.add_uris(uris, options=None, position=None)
    except Exception as e:
        await log(str(e))
        return await event.delete()

    gid = download.gid
    complete = None
    await progress_status(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
    while complete != True:
        file = aria2.get_download(gid)
        complete = file.is_complete
        try:
            msg = "**Leeching:** "+req_file + "\n**Speed:** " + str(file.download_speed_string())+"\n**Progress:** "+str(
                file.progress_string())+"\n**Total Size:** "+str(file.total_length_string())+"\n**ETA:**  "+str(file.eta_string())+"\n\n"
            await event.edit(msg)
            await asyncio.sleep(10)
        except Exception as e:
            await log(str(e))
            pass
        # TG UPLOAD
        to_upload = f"./{req_file}"
    if os.path.isdir(to_upload):
        input_str = to_upload
        if os.path.exists(input_str):
            start = datetime.now()
            # await event.edit("Processing...")
            lst_of_files = sorted(get_lst_of_files(input_str, []))
            logger.info(lst_of_files)
            u = 0
            await event.edit(
                "Found {} files. ".format(len(lst_of_files)) +
                "Uploading will start soon. " +
                "Please wait!"
            )
            thumb = None
            if os.path.exists(thumb_image_path):
                thumb = thumb_image_path
            for single_file in lst_of_files:
                if os.path.exists(single_file):
                    # https://stackoverflow.com/a/678242/4723940
                    caption_rts = os.path.basename(single_file)
                    force_document = True
                    supports_streaming = False
                    document_attributes = []
                    width = 0
                    height = 0
                    if os.path.exists(thumb_image_path):
                        metadata = extractMetadata(
                            createParser(thumb_image_path))
                        if metadata.has("width"):
                            width = metadata.get("width")
                        if metadata.has("height"):
                            height = metadata.get("height")
                    if single_file.endswith((".mkv", ".mp4", ".webm")):
                        metadata = extractMetadata(createParser(single_file))
                        duration = 0
                        if metadata.has("duration"):
                            duration = metadata.get('duration').seconds
                        document_attributes = [
                            DocumentAttributeVideo(
                                duration=duration,
                                w=width,
                                h=height,
                                round_message=False,
                                supports_streaming=True
                            )
                        ]
                        supports_streaming = True
                        force_document = False
                    if single_file.endswith((".mp3", ".flac", ".wav")):
                        metadata = extractMetadata(createParser(single_file))
                        duration = 0
                        title = ""
                        artist = ""
                        if metadata.has("duration"):
                            duration = metadata.get('duration').seconds
                        if metadata.has("title"):
                            title = metadata.get("title")
                        if metadata.has("artist"):
                            artist = metadata.get("artist")
                        document_attributes = [
                            DocumentAttributeAudio(
                                duration=duration,
                                voice=False,
                                title=title,
                                performer=artist,
                                waveform=None
                            )
                        ]
                        supports_streaming = True
                        force_document = False
                    try:
                        await bot.send_file(
                            event.chat_id,
                            single_file,
                            caption=caption_rts,
                            force_document=force_document,
                            supports_streaming=supports_streaming,
                            allow_cache=False,
                            reply_to=event.message.id,
                            thumb=thumb,
                            attributes=document_attributes,
                            # progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                            #     progress(d, t, event, c_time, "trying to upload")
                            # )
                        )
                    except Exception as e:
                        await bot.send_message(
                            event.chat_id,
                            "{} caused `{}`".format(caption_rts, str(e)),
                            reply_to=event.message.id
                        )
                        # some media were having some issues
                        continue
                    os.remove(single_file)
                    u = u + 1
                    # await event.edit("Uploaded {} / {} files.".format(u, len(lst_of_files)))
                    # @ControllerBot was having issues,
                    # if both edited_updates and update events come simultaneously.
                    await asyncio.sleep(5)
            end = datetime.now()
            ms = (end - start).seconds
            await event.edit("Uploaded {} files in {} seconds.".format(u, ms))
        else:
            await event.edit("Oh snap! Something went wrong!")
    elif os.path.isfile(to_upload):
        mone = await event.edit("Uploading required file..")
        input_str = to_upload
        thumb = None
        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        if os.path.exists(input_str):
            start = datetime.now()
            c_time = time.time()
            await bot.send_file(
                event.chat_id,
                input_str,
                force_document=True,
                supports_streaming=False,
                allow_cache=False,
                reply_to=event.message.id,
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "")
                )
            )
            end = datetime.now()
            # os.remove(input_str)
            ms = (end - start).seconds
            await mone.edit(f"Uploaded {input_str} in {ms} seconds.")
        else:
            await mone.edit("Oh snap! Something went wrong!")
    else:
        await ("Oh snap! Something went wrong!")
Пример #2
0
async def download_video(v_url):
    """ .rip komutu ile YouTube ve birkaç farklı siteden medya çekebilirsin. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`İndirmeye hazırlanıyor...`")

    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

    elif 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 v_url.edit("`Veri çekiliyor, lütfen bekleyin...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`İndirilecek içerik fazla kısa.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Maalesef coğrafi kısıtlamalar sebebiyle bu videoyla işlem yapamazsın.`")
        return
    except MaxDownloadsReached:
        await v_url.edit("`Maksimum indirme limitini aştın.`")
        return
    except PostProcessingError:
        await v_url.edit("`İstek işlenirken bir hata oluştu.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Medya belirtilen dosya formatında mevcut değil.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`Bilgi çıkarılırken bir hata gerçekleşti.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await v_url.edit(f"`Şarkı yüklenmeye hazırlanıyor:`\
        \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, "Karşıya yükleniyor...",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(f"`Şarkı yüklenmeye hazırlanıyor:`\
        \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=rip_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Karşıya yükleniyor...",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
Пример #3
0
async def download_video(v_url):
    """ For .rip command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.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

    elif 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 v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`Video is not available from your geographic location "
            "due to geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await v_url.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await v_url.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`Media is not available in the requested format.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if song:
        await v_url.edit(
            f"`Preparing to upload song:`\n**{rip_data['title']}**")
        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")
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Preparing to upload video:`\n**{rip_data['title']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
            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 v_url.delete()
Пример #4
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 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...`")
    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 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"`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")
        await v_url.delete()
    elif video:
        await rkp.edit(f"`Preparing to upload video 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=rip_data['title'],
            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()
Пример #5
0
async def download_video(v_url):
    """ For .ytdl command, download media from YouTube and many other sites. """
    reply = await v_url.get_reply_message()
    if v_url.pattern_match.group(2) != "":
        url = v_url.pattern_match.group(2)
    elif reply is not None:
        url = reply.message
        url = re.findall(r'\bhttps?://.*\.\S+', reply.message)[0]
    else:
        return
    type = v_url.pattern_match.group(1).lower() if v_url.pattern_match.group(1) is not None else "a"

    await v_url.edit("`Preparing to download...`")

    if type == "a":
        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':out_folder+'%(id)s.mp3',
            'quiet':True,
            'logtostderr':False
        }
        video = False
        song = True

    elif type == "v":
        opts = {
            'format':'best',
            'addmetadata':True,
            'key':'FFmpegMetadata',
            'prefer_ffmpeg':True,
            'getthumbnail':True,
            'embedthumbnail': True,
            'writethumbnail': True,
            'geo_bypass':True,
            'nocheckcertificate':True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':out_folder+'%(id)s.mp4',
            'logtostderr':False,
            'quiet':True
        }
        song = False
        video = True

    try:
        await v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
        filename = sorted(get_lst_of_files(out_folder, []))
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await v_url.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        # raster_size = os.path.getsize(f"{out_folder + ytdl_data['id']}.mp3")
        # song_size = size(raster_size)
        file_path = f"{out_folder + ytdl_data['id']}.mp3"
        song_size = file_size(file_path)
        await v_url.edit(f"`Preparing to upload song:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{out_folder + ytdl_data['id']}.mp3",
            caption=ytdl_data['title'] + "\n\n" + f"`{song_size}`",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(ytdl_data['duration']),
                                       title=str(ytdl_data['title']),
                                       performer=str(ytdl_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"💩 {ytdl_data['title']}.mp3")))
        os.remove(f"{out_folder + ytdl_data['id']}.mp3")
        await asyncio.sleep(DELETE_TIMEOUT)
        await v_url.delete()
    elif video:
        for single_file in filename:
            # image_link = ytdl_data['thumbnail']
            # downloaded_image = wget.download(image_link,out_folder)
            # thumb = downloaded_image
            # raster_size = os.path.getsize(f"{out_folder + ytdl_data['id']}.mp4")
            file_path = f"{out_folder + ytdl_data['id']}.mp4"
            video_size = file_size(file_path)
            image = f"{ytdl_data['id']}.jpg"
            thumb = f"{out_folder + ytdl_data['id']}.jpg"
            await v_url.edit(f"`Preparing to upload video:`\
            \n**{ytdl_data['title']}**\
            \nby *{ytdl_data['uploader']}*")
            await v_url.client.send_file(
                v_url.chat_id,
                f"{out_folder + ytdl_data['id']}.mp4",
                supports_streaming=True,
                caption=ytdl_data['title'] + "\n\n" + f"`{video_size}`",
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, v_url, c_time, "Uploading..",
                            f"💥 {ytdl_data['title']}.mp4")))
            os.remove(f"{out_folder + ytdl_data['id']}.mp4")
            await v_url.delete()
            os.remove(single_file)
        os.removedirs(out_folder)
Пример #6
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 lazy.reply("`memproses...`")
    else:
    	rkp = await lazy.edit("`memproses...`")   
    url = v_url.pattern_match.group(1)
    if not url:
         return await rkp.edit("`Error \n Ketik /lagu <judul laguny bro>`")
    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("`gagal mencari`")
    type = "audio"
    await rkp.edit("`Mencoba untuk mendownload..`")
    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': '128',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True    
    try:
        await rkp.edit("`Lagi ngambil data, tunggu bentar..`")
        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("`Error! Konten downloadnya kependekan.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Videonya ga tersedia dinegara kita bro.`"
        )
        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"`Mencoba mengupload lagu:`\
        \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, "Lagi diupload..",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
    elif video:
        await rkp.edit(f"`Mencoba mengupload lagu:`\
        \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, "Lagi diupload..",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
Пример #7
0
async def download_video(v_url):
    """ For .ytdl command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`📶Preparando al download...`")

    if type == "a":
        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

    elif type == "v":
        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 v_url.edit("`🔁Prendendo i dati, aspetta..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`Il contenuto è poco grande per il download.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Questo contenuto non è disponibile in Italia a causa delle restrizioni del Sito.`"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("`Limite massimo di download raggiunto.`")
        return
    except PostProcessingError:
        await v_url.edit("`C'è stato un errore durante il processo.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Contenuto non disponibile in questo formato.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit(
            "`C'è stato un errore durante l'estrazione delle informazioni.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await v_url.edit(f"`🎶Preparando la canzone:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(ytdl_data['duration']),
                                       title=str(ytdl_data['title']),
                                       performer=str(ytdl_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp3")))
        os.remove(f"{ytdl_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(f"`🎥Preparando il video:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp4",
            supports_streaming=True,
            caption=ytdl_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp4")))
        os.remove(f"{ytdl_data['id']}.mp4")
        await v_url.delete()
Пример #8
0
async def upload(event):
    if event.fwd_from:
        return
    await event.edit("`Processing...`")
    input_str = event.pattern_match.group(1)
    if os.path.exists(input_str):
        if os.path.isfile(input_str):
            c_time = time.time()
            start_time = datetime.now()
            file_name = os.path.basename(input_str)
            thumb = None
            attributes = []
            with open(input_str, "rb") as f:
                result = await upload_file(
                    client=event.client,
                    file=f,
                    name=file_name,
                    progress_callback=lambda d, t: asyncio.get_event_loop().
                    create_task(
                        progress(d, t, event, c_time, "[FILE - UPLOAD]",
                                 input_str)),
                )
            up_time = (datetime.now() - start_time).seconds
            if input_str.lower().endswith(("mp4", "mkv", "webm")):
                thumb = await get_video_thumb(input_str, "thumb_image.jpg")
                metadata = extractMetadata(createParser(input_str))
                duration = 0
                width = 0
                height = 0
                if metadata.has("duration"):
                    duration = metadata.get("duration").seconds
                if metadata.has("width"):
                    width = metadata.get("width")
                if metadata.has("height"):
                    height = metadata.get("height")
                attributes = [
                    DocumentAttributeVideo(
                        duration=duration,
                        w=width,
                        h=height,
                        round_message=False,
                        supports_streaming=True,
                    )
                ]
            elif input_str.lower().endswith(("mp3", "flac", "wav")):
                metadata = extractMetadata(createParser(input_str))
                duration = 0
                artist = ""
                title = ""
                if metadata.has("duration"):
                    duration = metadata.get("duration").seconds
                if metadata.has("title"):
                    title = metadata.get("title")
                if metadata.has("artist"):
                    artist = metadata.get("artist")
                attributes = [
                    DocumentAttributeAudio(
                        duration=duration,
                        title=title,
                        performer=artist,
                    )
                ]
            await event.client.send_file(
                event.chat_id,
                result,
                thumb=thumb,
                caption=file_name,
                force_document=False,
                allow_cache=False,
                reply_to=event.message.id,
                attributes=attributes,
            )
            if thumb is not None:
                os.remove(thumb)
            await event.edit(f"Uploaded successfully in `{up_time}` seconds.")
        elif os.path.isdir(input_str):
            start_time = datetime.now()
            lst_files = []
            for root, dirs, files in os.walk(input_str):
                for file in files:
                    lst_files.append(os.path.join(root, file))
            if len(lst_files) == 0:
                return await event.edit(f"`{input_str}` is empty.")
            await event.edit(
                f"Found `{len(lst_files)}` files. Now uploading...")
            for files in sorted(lst_files):
                file_name = os.path.basename(files)
                thumb = None
                attributes = []
                msg = await event.reply(f"Uploading `{files}`")
                with open(files, "rb") as f:
                    result = await upload_file(
                        client=event.client,
                        file=f,
                        name=file_name,
                    )
                if file_name.lower().endswith(("mp4", "mkv", "webm")):
                    thumb = await get_video_thumb(files, "thumb_image.jpg")
                    metadata = extractMetadata(createParser(files))
                    duration = 0
                    width = 0
                    height = 0
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                    attributes = [
                        DocumentAttributeVideo(
                            duration=duration,
                            w=width,
                            h=height,
                            round_message=False,
                            supports_streaming=True,
                        )
                    ]
                elif file_name.lower().endswith(("mp3", "flac", "wav")):
                    metadata = extractMetadata(createParser(files))
                    duration = 0
                    title = ""
                    artist = ""
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                    if metadata.has("title"):
                        title = metadata.get("title")
                    if metadata.has("artist"):
                        artist = metadata.get("artist")
                    attributes = [
                        DocumentAttributeAudio(
                            duration=duration,
                            title=title,
                            performer=artist,
                        )
                    ]
                await event.client.send_file(
                    event.chat_id,
                    result,
                    thumb=thumb,
                    caption=file_name,
                    force_document=False,
                    allow_cache=False,
                    attributes=attributes,
                )
                await msg.delete()
                if thumb is not None:
                    os.remove(thumb)

            await event.delete()
            up_time = (datetime.now() - start_time).seconds
            await event.respond(
                f"Uploaded `{len(lst_files)}` files in `{input_str}` folder "
                f"in `{up_time}` seconds.")
    else:
        await event.edit("`404: File/Folder Not Found`")
Пример #9
0
async def download_video(v_url):
    """ For .rip command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`Bersiap untuk mengunduh...`")

    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

    elif 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 v_url.edit("`Mengambil data, harap tunggu..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`Konten unduhan terlalu pendek.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`Video tidak tersedia dari lokasi geografis Anda "
            "karena batasan geografis yang diberlakukan oleh situs web.`")
    except MaxDownloadsReached:
        return await v_url.edit("`Batas unduhan maksimal telah tercapai.`")
    except PostProcessingError:
        return await v_url.edit("`Ada kesalahan selama pemrosesan posting.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`Media tidak tersedia dalam format yang diminta.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit("`Terjadi kesalahan selama mengekstraks info.`"
                                )
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if song:
        await v_url.edit(f"`Bersiap mengunggah lagu:`\n**{rip_data['title']}**"
                         "\noleh *{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, "Mengunggah...",
                         f"{rip_data['title']}.mp3")),
        )
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Bersiap mengunggah video:`\n**{rip_data['title']}**"
            "\noleh *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Mengunggah...",
                         f"{rip_data['title']}.mp4")),
        )
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
Пример #10
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")
Пример #11
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")
Пример #12
0
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
Пример #13
0
async def text_to_speech(e):
    """ For .tts command, a wrapper for Google Text-to-Speech. """
    textx = await e.get_reply_message()
    message = e.pattern_match.group(1)
    if message:
        pass
    elif textx:
        message = textx.text
    else:
        await e.edit("`Give a text or reply to a "
                     "message for Text-to-Speech!`")
        return

    opts, message = parse_arguments(message,
                                    ['slow', 'fast', 'lang', 'gender', 'file'])

    lang = opts.get('lang', DEFAULT_LANG)
    voice = opts.get('voice', DEFAULT_VOICE)
    gender = GENDERS.get(opts.get('gender', "neutral"),
                         SsmlVoiceGender.NEUTRAL)

    if opts.get('slow'):
        speed = 0.5
    elif opts.get('fast'):
        speed = 2.0
    else:
        speed = 1.0

    synthesis_input = tts.types.SynthesisInput(text=message)

    voice = tts.types.VoiceSelectionParams(name=voice,
                                           language_code=lang,
                                           ssml_gender=gender)

    audio_config = tts.types.AudioConfig(
        audio_encoding=tts.enums.AudioEncoding.MP3, speaking_rate=speed)

    try:
        response = TTSClient.synthesize_speech(synthesis_input, voice,
                                               audio_config)
    except AssertionError:
        await e.edit('The text is empty.\n'
                     'Nothing left to speak after pre-precessing, '
                     'tokenizing and cleaning.')
        return
    except ValueError as err:
        await e.edit('Language is not supported.')
        return
    except RuntimeError:
        await e.edit('Error loading the languages dictionary.')
        return

    await e.delete()

    with open("k.mp3", "wb") as file:
        file.write(response.audio_content)
        audio = MP3("k.mp3")
        await e.client.send_file(
            e.chat_id,
            "k.mp3",
            reply_to=textx,
            attributes=[
                DocumentAttributeAudio(voice=True,
                                       waveform=bytes(response.audio_content),
                                       duration=int(audio.info.length))
            ])

    if BOTLOG:
        await e.client.send_message(
            BOTLOG_CHATID, "tts of `" + message + "` executed successfully!")
Пример #14
0
def upload_file(chat_id: int,
                user_id: int,
                file_path: str,
                uid,
                title=None,
                performer=None,
                duration=None,
                t_thumb=0,
                is_gif=False):
    try:
        job = get_current_job()
        job.meta['handled_by'] = socket.gethostname()
        job.save_meta()
        mimetypes.add_type('audio/aac', '.aac')
        mimetypes.add_type('audio/ogg', '.ogg')
        filename = str(os.path.basename(file_path))
        print(filename)
        client.start()
        entity = client.get_entity(int(chat_id))
        if filename.endswith('.mp4'):
            clip = VideoFileClip(str(file_path))
            thumbnail_path = str(file_path)[:-4] + '.jpg'
            frame_path = str(file_path)[:-4] + 'f.jpg'
            if (not os.path.exists(thumbnail_path)) or (t_thumb != 0):
                t_thumb = float(t_thumb)
                t_thumb = t_thumb if clip.duration > t_thumb else clip.duration
                clip.save_frame(frame_path, t=t_thumb)
            else:
                os.rename(thumbnail_path, frame_path)
            im = Image.open(frame_path)
            thumb_w = clip.w
            thumb_h = clip.h
            if thumb_w >= thumb_h:
                thumb_w = 180
                thumb_h = int(thumb_h * thumb_w / clip.w)
            else:
                thumb_w = 102
                thumb_h = int(thumb_h * thumb_w / clip.w)
            im = im.resize((thumb_w, thumb_h))
            im.save(thumbnail_path, "JPEG")
            if t_thumb == 1.0:
                thumbnail_path = 'thumb_one.jpg'
            if is_gif:
                if int(clip.duration) > 120:
                    raise Exception
                gif_filename = str(file_path)[:-4] + 'gif.mp4'
                file_path = gif_filename
                clip.write_videofile(str(file_path), audio=False)
            document_attribute = [
                DocumentAttributeVideo(duration=int(clip.duration),
                                       w=clip.w,
                                       h=clip.h,
                                       supports_streaming=True),
                DocumentAttributeFilename(filename)
            ]

            client.send_file(entity,
                             str(file_path),
                             caption=str(
                                 str(user_id) + ':' + str(uid) + ':' +
                                 str(int(clip.duration)) + ':v'),
                             file_name=str(filename),
                             allow_cache=False,
                             part_size_kb=512,
                             thumb=str(thumbnail_path),
                             attributes=document_attribute,
                             progress_callback=on_upload_progress)
            return 'SUCCESS'
        else:
            print(duration)
            if title is None:
                title = str(filename[:-4])
            if performer is None:
                performer = ''
            document_attribute = [
                DocumentAttributeAudio(int(duration),
                                       voice=False,
                                       title=str(title),
                                       performer=performer)
            ]
            print(file_path, user_id, uid, duration)
            client.send_file(entity,
                             str(file_path),
                             caption=str(
                                 str(user_id) + ':' + str(uid) + ':' +
                                 str(duration)),
                             file_name=str(filename),
                             allow_cache=False,
                             part_size_kb=512,
                             attributes=document_attribute,
                             progress_callback=on_upload_progress)

            return 'SUCCESS'
    except Exception as e:
        print(e)
        if os.path.exists(os.path.dirname(file_path)):
            shutil.rmtree(os.path.dirname(file_path))
        raise Exception
    finally:
        client.disconnect()
        if os.path.exists(os.path.dirname(file_path)):
            shutil.rmtree(os.path.dirname(file_path))
Пример #15
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 edit_or_reply(lazy, "Processing video song request....")
    else:
        rkp = await edit_or_reply(lazy, "Processing video song request....")
    url = v_url.pattern_match.group(1)
    if not url:
        return await rkp.edit("**Error** \n__Usage:__ `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:
        return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("Video Song Request Processed. **Downloading Now!!**")
    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 rkp.edit("Fetching Video Song")
        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 video 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=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")
        await v_url.delete()
    elif video:
        await rkp.edit(f"🎶 Preparing to upload video 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=rip_data["title"],
            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()
Пример #16
0
async def download_video(v_url):
    """ For .ytdl command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()
    lmao = await v_url.reply("`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': '256',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True
    elif 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 lmao.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except DownloadError as DE:
        await lmao.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await lmao.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await lmao.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await lmao.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await lmao.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await lmao.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await lmao.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await lmao.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await lmao.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await lmao.edit(f"`Preparing to upload song:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(ytdl_data['duration']),
                                       title=str(ytdl_data['title']),
                                       performer=str(ytdl_data['uploader']))
            ])
        os.remove(f"{ytdl_data['id']}.mp3")
    elif video:
        await lmao.edit(f"`Preparing to upload video:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(v_url.chat_id,
                                     f"{ytdl_data['id']}.mp4",
                                     supports_streaming=True,
                                     caption=ytdl_data['title'])
        os.remove(f"{ytdl_data['id']}.mp4")
Пример #17
0
async def download_video(v_url):
    """ For .rip command, download media from YouTube and many other sites. """
    dl_type = v_url.pattern_match.group(1).lower()
    reso = v_url.pattern_match.group(2)
    reso = reso.strip() if reso else None
    url = v_url.pattern_match.group(3)

    await v_url.edit("`Preparing to download...`")
    s_time = time.time()
    video = False
    audio = False

    if "audio" in dl_type:
        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.%(ext)s",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        audio = True

    elif "video" in dl_type:
        quality = (f"bestvideo[height<={reso}]+bestaudio/best[height<={reso}]"
                   if reso else "bestvideo+bestaudio/best")
        opts = {
            "format":
            quality,
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "outtmpl":
            os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                         "%(title)s.%(ext)s"),
            "logtostderr":
            False,
            "quiet":
            True,
        }
        video = True

    try:
        await v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`Video is not available from your geographic location "
            "due to geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await v_url.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await v_url.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`Media is not available in the requested format.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if audio:
        await v_url.edit(
            f"`Preparing to upload song:`\n**{rip_data.get('title')}**"
            f"\nby **{rip_data.get('uploader')}**")
        f_name = rip_data.get("id") + ".mp3"
        with open(f_name, "rb") as f:
            result = await upload_file(
                client=v_url.client,
                file=f,
                name=f_name,
                progress_callback=lambda d, t: get_event_loop().create_task(
                    progress(d, t, v_url, c_time, "Uploading..",
                             f"{rip_data['title']}.mp3")),
            )
        img_extensions = ["jpg", "jpeg", "webp"]
        img_filenames = [
            fn_img for fn_img in os.listdir() if any(
                fn_img.endswith(ext_img) for ext_img in img_extensions)
        ]
        thumb_image = img_filenames[0]
        metadata = extractMetadata(createParser(f_name))
        duration = 0
        if metadata.has("duration"):
            duration = metadata.get("duration").seconds
        await v_url.client.send_file(
            v_url.chat_id,
            result,
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=duration,
                    title=rip_data.get("title"),
                    performer=rip_data.get("uploader"),
                )
            ],
            thumb=thumb_image,
        )
        os.remove(thumb_image)
        os.remove(f_name)
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Preparing to upload video:`\n**{rip_data.get('title')}**"
            f"\nby **{rip_data.get('uploader')}**")
        f_path = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                                   "*"))[0]
        # Noob way to convert from .mkv to .mp4
        if f_path.endswith(".mkv"):
            base = os.path.splitext(f_path)[0]
            os.rename(f_path, base + ".mp4")
            f_path = glob(
                os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))[0]
        f_name = os.path.basename(f_path)
        with open(f_path, "rb") as f:
            result = await upload_file(
                client=v_url.client,
                file=f,
                name=f_name,
                progress_callback=lambda d, t: get_event_loop().create_task(
                    progress(d, t, v_url, c_time, "Uploading..", f_name)),
            )
        thumb_image = await get_video_thumb(f_path, "thumb.png")
        metadata = extractMetadata(createParser(f_path))
        duration = 0
        width = 0
        height = 0
        if metadata.has("duration"):
            duration = metadata.get("duration").seconds
        if metadata.has("width"):
            width = metadata.get("width")
        if metadata.has("height"):
            height = metadata.get("height")
        await v_url.client.send_file(
            v_url.chat_id,
            result,
            thumb=thumb_image,
            attributes=[
                DocumentAttributeVideo(
                    duration=duration,
                    w=width,
                    h=height,
                    supports_streaming=True,
                )
            ],
            caption=f"[{rip_data.get('title')}]({url})",
        )
        shutil.rmtree(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time)))
        os.remove(thumb_image)
        await v_url.delete()
Пример #18
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")
Пример #19
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    if os.path.exists(input_str):
        start = datetime.now()
        # await event.edit("Processing ...")
        lst_of_files = sorted(get_lst_of_files(input_str, []))
        logger.info(lst_of_files)
        u = 0
        await event.edit(
            "Found {} files. ".format(len(lst_of_files)) + \
            "Uploading will start soon. " + \
            "Please wait!"
        )
        thumb = None
        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        for single_file in lst_of_files:
            if os.path.exists(single_file):
                # https://stackoverflow.com/a/678242/4723940
                caption_rts = os.path.basename(single_file)
                force_document = True
                supports_streaming = False
                document_attributes = []
                width = 0
                height = 0
                if os.path.exists(thumb_image_path):
                    metadata = extractMetadata(createParser(thumb_image_path))
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                if single_file.endswith((".mp4", ".webm")):
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    if metadata.has("duration"):
                        duration = metadata.get('duration').seconds
                    document_attributes = [
                        DocumentAttributeVideo(duration=duration,
                                               w=width,
                                               h=height,
                                               round_message=False,
                                               supports_streaming=True)
                    ]
                    supports_streaming = True
                    force_document = False
                if single_file.endswith((".mp3", ".flac", ".wav")):
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    title = ""
                    artist = ""
                    if metadata.has("duration"):
                        duration = metadata.get('duration').seconds
                    if metadata.has("title"):
                        title = metadata.get("title")
                    if metadata.has("artist"):
                        artist = metadata.get("artist")
                    document_attributes = [
                        DocumentAttributeAudio(duration=duration,
                                               voice=False,
                                               title=title,
                                               performer=artist,
                                               waveform=None)
                    ]
                    supports_streaming = True
                    force_document = False
                try:
                    await borg.send_file(
                        event.chat_id,
                        single_file,
                        caption=caption_rts,
                        force_document=force_document,
                        supports_streaming=supports_streaming,
                        allow_cache=False,
                        reply_to=event.message.id,
                        thumb=thumb,
                        attributes=document_attributes,
                        # progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                        #     progress(d, t, event, c_time, "trying to upload")
                        # )
                    )
                except Exception as e:
                    await borg.send_message(event.chat_id,
                                            "{} caused `{}`".format(
                                                caption_rts, str(e)),
                                            reply_to=event.message.id)
                    # some media were having some issues
                    continue
                os.remove(single_file)
                u = u + 1
                # await event.edit("Uploaded {} / {} files.".format(u, len(lst_of_files)))
                # @ControllerBot was having issues,
                # if both edited_updates and update events come simultaneously.
                await asyncio.sleep(5)
        end = datetime.now()
        ms = (end - start).seconds
        await event.edit("Uploaded {} files in {} seconds.".format(u, ms))
    else:
        await event.edit("404: Directory Not Found")
Пример #20
0
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
Пример #21
0
async def download_video(v_url):
    sender = await v_url.get_sender()
    me = await v_url.client.get_me()
    if not sender.id == me.id:
        rkp = await v_url.reply("`processing...`")
    else:
        rkp = await v_url.edit("`processing...`")
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()
    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

    elif 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:
        return await rkp.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await rkp.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await rkp.edit(
            "`Video is not available from your geographic location "
            "due to geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await rkp.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await rkp.edit("`There was an error during post processing....`"
                              )
    except UnavailableVideoError:
        return await rkp.edit(
            "`Media is not available in the requested format.`")
    except XAttrMetadataError as XAME:
        return await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await rkp.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await rkp.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if song:
        await rkp.edit(f"`Preparing to upload audio:`\n**{rip_data['title']}**"
                       )
        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")
        await v_url.delete()
    elif video:
        await rkp.edit(f"`Preparing to upload video:`\n**{rip_data['title']}**"
                       )
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data['title'],
            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 v_url.delete()
Пример #22
0
async def download_video(v_url):
    """ For .ytdl command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()
    out_folder = Config.TMP_DOWNLOAD_DIRECTORY + "youtubedl/"

    if not os.path.isdir(out_folder):
        os.makedirs(out_folder)

    await v_url.edit("`Preparing to download...`")

    if type == "a":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'embedthumbnail':
            True,
            'audioquality':
            0,
            'audioformat':
            'mp3',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            out_folder + '%(title)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True

    elif type == "v":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'write_all_thumbnails':
            True,
            'embedthumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'hls_prefer_native':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            out_folder + '%(title)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True

    try:
        await v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
        filename = sorted(get_lst_of_files(out_folder, []))
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await v_url.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()

    # cover_url = f"https://img.youtube.com/vi/{ytdl_data['id']}/0.jpg"
    # thumb_path = wget.download(cover_url, out_folder + "cover.jpg")

    # relevant_path = "./DOWNLOADS/youtubedl"
    # included_extensions = ["mp4","mp3"]
    # file_names = [fn for fn in os.listdir(relevant_path)
    #             if any(fn.endswith(ext) for ext in included_extensions)]

    if song:
        relevant_path = "./DOWNLOADS/youtubedl"
        included_extensions = ["mp3"]
        file_names = [
            fn for fn in os.listdir(relevant_path) if any(
                fn.endswith(ext) for ext in included_extensions)
        ]
        img_extensions = ["webp", "jpg", "jpeg"]
        img_filenames = [
            fn_img for fn_img in os.listdir(relevant_path) if any(
                fn_img.endswith(ext_img) for ext_img in img_extensions)
        ]
        thumb_image = out_folder + img_filenames[0]

        # thumb = out_folder + "cover.jpg"
        file_path = out_folder + file_names[0]
        song_size = file_size(file_path)
        j = await v_url.edit(f"`Preparing to upload song:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            file_path,
            caption=ytdl_data['title'] + "\n" + f"`{song_size}`",
            supports_streaming=True,
            thumb=thumb_image,
            attributes=[
                DocumentAttributeAudio(duration=int(ytdl_data['duration']),
                                       title=str(ytdl_data['title']),
                                       performer=str(ytdl_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp3")))
        # os.remove(file_path)
        await asyncio.sleep(DELETE_TIMEOUT)
        os.remove(thumb_image)
        await j.delete()

    elif video:
        relevant_path = "./DOWNLOADS/youtubedl/"
        included_extensions = ["mp4"]
        file_names = [
            fn for fn in os.listdir(relevant_path) if any(
                fn.endswith(ext) for ext in included_extensions)
        ]
        img_extensions = ["webp", "jpg", "jpeg"]
        img_filenames = [
            fn_img for fn_img in os.listdir(relevant_path) if any(
                fn_img.endswith(ext_img) for ext_img in img_extensions)
        ]
        thumb_image = out_folder + img_filenames[0]

        file_path = out_folder + file_names[0]
        video_size = file_size(file_path)
        # thumb = out_folder + "cover.jpg"

        j = await v_url.edit(f"`Preparing to upload video:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            file_path,
            supports_streaming=True,
            caption=ytdl_data['title'] + "\n" + f"`{video_size}`",
            thumb=thumb_image,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp4")))
        os.remove(file_path)
        await asyncio.sleep(DELETE_TIMEOUT)
        os.remove(thumb_image)
        await v_url.delete()
        await j.delete()
    shutil.rmtree(out_folder)
Пример #23
0
async def download_video(v_url):
    """ .rip komutu ile YouTube ve birkaç farklı siteden medya çekebilirsin. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`Yuklenme hazirlanir...`")

    if type == "a":
        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

    elif type == "v":
        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 v_url.edit("`Lazımlı məlumatlar çəkilir...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`Yüklənəcək içərik çox qısadır`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Maalesef coğrafi kısıtlamalar sebebiyle bu videoyla işlem yapamazsın.`")
        return
    except MaxDownloadsReached:
        await v_url.edit("`Maksimum yüklənmə limiti aşıldı.`")
        return
    except PostProcessingError:
        await v_url.edit("`İstək sırasında bir xəta baş verdi.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Error UnavialableVideoError |//\\| Bu mesajı görürsənsə böyük ehtimal userbotunda _youtube_ modulu xəta verdi bu mesajı @SpaceAid grupuna gonder`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`Melumatlar alinanda xeta bas verdi.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await v_url.edit(f"`Mahnı yüklənməyə hazırlanır:`\
        \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, "Qarşıya yüklenir...",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(f"`Mahnı yüklənməyə hazırlanır:`\
        \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=rip_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Qarşıya yüklenir...",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
Пример #24
0
async def download(event):
    if event.text[1:].startswith("ultroid"):
        return
    xx = await eor(event, get_string("com_1"))
    hmm = event.pattern_match.group(1)
    try:
        kk = hmm.split(" | stream")[0]
    except BaseException:
        pass
    try:
        title = kk.split("/")[-1]
    except BaseException:
        title = hmm
    s = dt.now()
    tt = time.time()
    if not kk:
        return await eor(xx, get_string("udl_3"), time=5)
    if os.path.isdir(kk):
        if not os.listdir(kk):
            return await eor(xx, "`This Directory is Empty.`", time=5)
        ok = glob.glob(f"{kk}/*")
        kk = [*sorted(ok)]
        for kk in kk:
            tt = time.time()
            try:
                try:
                    res = await uploader(kk, kk, tt, xx, f"Uploading {kk}...")
                except MessageNotModifiedError as err:
                    return await xx.edit(str(err))
                title = kk.split("/")[-1]
                if (title.endswith((".mp3", ".m4a", ".opus", ".ogg", ".flac"))
                        and " | stream" in hmm):
                    metadata = extractMetadata(createParser(res.name))
                    wi = 512
                    hi = 512
                    duration = 0
                    artist = ""
                    try:
                        if metadata.has("width"):
                            wi = metadata.get("width")
                        if metadata.has("height"):
                            hi = metadata.get("height")
                        if metadata.has("duration"):
                            duration = metadata.get("duration").seconds
                        if metadata.has("artist"):
                            artist = metadata.get("artist")
                        else:
                            artist = udB.get(
                                "artist") or ultroid_bot.first_name
                    except AttributeError:
                        return await event.client.send_file(
                            event.chat_id,
                            res,
                            caption=f"`{kk}/{title}`",
                            supports_streaming=True,
                        )
                    if res.name.endswith((".mkv", ".mp4", ".avi", "webm")):
                        attributes = [
                            DocumentAttributeVideo(w=wi,
                                                   h=hi,
                                                   duration=duration,
                                                   supports_streaming=True)
                        ]
                    elif res.name.endswith(
                        (".mp3", ".m4a", ".opus", ".ogg", ".flac")):
                        attributes = [
                            DocumentAttributeAudio(
                                duration=duration,
                                title=title.split(".")[0],
                                performer=artist,
                            )
                        ]
                    else:
                        attributes = None
                    try:
                        await event.client.send_file(
                            event.chat_id,
                            res,
                            caption=f"`{kk}`",
                            attributes=attributes,
                            supports_streaming=True,
                            thumb="resources/extras/ultroid.jpg",
                        )
                    except BaseException:
                        await event.client.send_file(
                            event.chat_id,
                            res,
                            caption=f"`{kk}`",
                            thumb="resources/extras/ultroid.jpg",
                        )
                else:
                    await event.client.send_file(
                        event.chat_id,
                        res,
                        caption=f"`{kk}`",
                        force_document=True,
                        thumb="resources/extras/ultroid.jpg",
                    )
            except Exception as ve:
                return await eor(xx, str(ve))
    else:
        try:
            try:
                res = await uploader(kk, kk, tt, xx, f"Uploading {kk}...")
            except MessageNotModifiedError as err:
                return await xx.edit(str(err))
            if title.endswith((".mp3", ".m4a", ".opus", ".ogg", ".flac")):
                hmm = " | stream"
            if " | stream" in hmm:
                metadata = extractMetadata(createParser(res.name))
                wi = 512
                hi = 512
                duration = 0
                artist = ""
                try:
                    if metadata.has("width"):
                        wi = metadata.get("width")
                    if metadata.has("height"):
                        hi = metadata.get("height")
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                    if metadata.has("artist"):
                        artist = metadata.get("artist")
                    else:
                        artist = udB.get("artist") or ultroid_bot.first_name
                except AttributeError:
                    await event.client.send_file(
                        event.chat_id,
                        res,
                        caption=f"`{title}`",
                        supports_streaming=True,
                    )
                if res.name.endswith((".mkv", ".mp4", ".avi", "webm")):
                    attributes = [
                        DocumentAttributeVideo(w=wi,
                                               h=hi,
                                               duration=duration,
                                               supports_streaming=True)
                    ]
                elif res.name.endswith(
                    (".mp3", ".m4a", ".opus", ".ogg", ".flac")):
                    attributes = [
                        DocumentAttributeAudio(
                            duration=duration,
                            title=title.split(".")[0],
                            performer=artist,
                        )
                    ]
                else:
                    attributes = None
                try:
                    await event.client.send_file(
                        event.chat_id,
                        res,
                        caption=f"`{title}`",
                        attributes=attributes,
                        supports_streaming=True,
                        thumb="resources/extras/ultroid.jpg",
                    )
                except BaseException:
                    await event.client.send_file(
                        event.chat_id,
                        res,
                        caption=f"`{title}`",
                        force_document=True,
                        thumb="resources/extras/ultroid.jpg",
                    )
            else:
                await event.client.send_file(
                    event.chat_id,
                    res,
                    caption=f"`{title}`",
                    force_document=True,
                    thumb="resources/extras/ultroid.jpg",
                )
        except Exception as ve:
            return await eor(xx, str(ve))
    e = dt.now()
    t = time_formatter(((e - s).seconds) * 1000)
    if t == "":
        await eor(xx, f"Uploaded `{kk}` in `0 second(s)`")

    elif os.path.isdir(kk):
        size = 0
        for path, dirs, files in os.walk(kk):
            for f in files:
                fp = os.path.join(path, f)
                size += os.path.getsize(fp)
        c = len(os.listdir(kk))
        await xx.delete()
        await event.client.send_message(
            event.chat_id,
            f"Uploaded Total - `{c}` files of `{humanbytes(size)}` in `{t}`",
        )
    else:
        await eor(xx, f"Uploaded `{kk}` in `{t}`")
Пример #25
0
async def nem(context):
    proxies = {}
    proxynum = 0
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063',
               "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,"
                         "application/signed-exchange;v=b3;q=0.9", "X-Real-IP": "223.252.199.66"}
    proxy = [{'http': 'http://music.lolico.me:39000', 'https': 'http://music.lolico.me:39000'},
             {'http': 'http://netease.unlock.feiwuis.me:6958', 'https': 'https://netease.unlock.feiwuis.me:6958'}]
    helptext = "**使用方法:** `-nem` `<指令>` `<关键词>`\n\n指令s为搜索,p为点歌,id为歌曲ID点歌,r为随机热歌(无关键词)\n搜索在s后添加数字如`-nem` `s8` " \
               "`<关键词>`调整结果数量\n搜索灰色歌曲请尽量**指定歌手**\n可回复搜索结果消息`-nem` `p` `<歌曲数字序号>`点歌 "
    apifailtext = "出错了呜呜呜 ~ 试了好多好多次都无法访问到 API 服务器 。"

    if len(context.parameter) < 2:
        if len(context.parameter) == 0:
            await context.edit(helptext)
            return
        elif context.parameter[0] == "r":  # 随机热歌
            await context.edit("随机中 . . .")
            for _ in range(20):  # 最多重试20次
                apinum = random.randint(0, 1)
                apitype = random.randint(0, 1)
                if apitype == 0:
                    apitype = "飙升榜"
                else:
                    apitype = "热歌榜"
                if apinum == 0:
                    url = "https://api.vvhan.com/api/rand.music?type=json&sort=" + apitype
                else:
                    url = "https://api.uomg.com/api/rand.music?sort=" + apitype + "&format=json"
                status = False
                try:
                    randsong = requests.get(url, headers=headers)
                    if randsong.status_code == 200:
                        randsong = json.loads(randsong.content)
                        if apinum == 0 and randsong['success'] is True:
                            context.parameter[0] = "id"
                            context.parameter.append(
                                str(randsong['info']['id']))
                            status = True
                            break
                        elif apinum == 1 and randsong['code'] == 1:
                            context.parameter[0] = "id"
                            context.parameter.append(
                                str(randsong['data']['url'][45:]))
                            status = True
                            break
                except:
                    continue
            if status is False:
                await context.edit(apifailtext)
                sleep(3)
                await context.delete()
                return
        else:  # 错误输入
            await context.edit(helptext)
            return
    # 整理关键词
    keyword = ''
    for i in range(1, len(context.parameter)):
        keyword += context.parameter[i] + " "
    keyword = keyword[:-1]
    idplay = False
    if context.parameter[0] == "id":  # ID点歌功能
        if len(context.parameter) > 2:
            await context.edit(helptext)
            return
        idplay = keyword
        context.parameter[0] = "p"
    if context.parameter[0][0] == "s":  # 搜索功能
        await context.edit(f"【{keyword}】搜索中 . . .")
        if len(context.parameter[0]) > 1:
            limit = str(context.parameter[0][1:])
        else:
            limit = "5"
        url = "http://music.163.com/api/search/pc?&s=" + \
            keyword + "&offset=0&limit=" + limit + "&type=1"
        for _ in range(20):  # 最多尝试20次
            status = False
            req = requests.request("GET", url, headers=headers)
            if req.status_code == 200:
                req = json.loads(req.content)
                if req['code'] == 200:
                    result = req['result']
                    if req['result']['songCount'] == 0:
                        result = False
                else:
                    result = False
                if result:
                    info = defaultdict()
                    for i in range(len(req['result']['songs'])):
                        info[i] = {'id': '', 'title': '', 'alias': '',
                                   'album': '', 'albumpic': '', 'artist': ''}
                        info[i]['id'] = req['result']['songs'][i]['id']
                        info[i]['title'] = req['result']['songs'][i]['name']
                        info[i]['alias'] = req['result']['songs'][i]['alias']
                        info[i]['album'] = req['result']['songs'][i]['album']['name']
                        info[i]['albumpic'] = req['result']['songs'][i]['album']['picUrl']
                        for j in range(len(req['result']['songs'][i]['artists'])):
                            info[i]['artist'] += req['result']['songs'][i]['artists'][j]['name'] + " "
                    text = f"<strong>关于【{keyword}】的结果如下</strong> \n"
                    for i in range(len(info)):
                        text += f"#{i+1}: \n<strong>歌名</strong>: {info[i]['title']}\n"
                        if info[i]['alias']:
                            text += f"<strong>别名</strong>: <i>{info[i]['alias'][0]}</i>\n"
                        if info[i]['album']:
                            res = '<a href="' + \
                                info[i]['albumpic'] + '">' + \
                                info[i]['album'] + '</a>'
                            text += f"<strong>专辑</strong>: {res} \n"
                        text += f"<strong>作者</strong>: {info[i]['artist']}\n<strong>歌曲ID</strong>: <code>{info[i]['id']}</code>\n————————\n"
                    text += "\n<strong>回复此消息</strong><code>-nem p <歌曲序号></code><strong>即可点歌</strong>"
                    await context.edit(text, parse_mode='html', link_preview=True)
                    status = True
                    break
                else:
                    await context.edit("**未搜索到结果**")
                    sleep(3)
                    await context.delete()
                    status = True
                    break
            else:
                continue
        if status is False:
            await context.edit(apifailtext)
            sleep(3)
            await context.delete()
        return
    elif context.parameter[0] == "p":  # 点歌功能
        try:
            reply = await context.get_reply_message()
        except ValueError:
            await context.edit("出错了呜呜呜 ~ 无效的参数。")
            return
        search = ""
        title = ""
        if reply:
            msg = reply.message
            search = re.findall(".*【(.*)】.*", msg)
            if search:
                try:
                    start = "#" + context.parameter[1] + ":"
                    search = ".*" + start + "(.*?)" + '————————' + ".*"
                    msg = re.findall(search, msg, re.S)[0]
                    search = ".*歌曲ID: (.*)\n.*"
                    title = ".*歌名: (.*?)\n.*"
                    title = "【"+re.findall(title, msg, re.S)[0]+"】"
                    idplay = re.findall(search, msg, re.S)[0]
                    if reply.sender.is_self:
                        await reply.edit(f"{title}点歌完成")
                except:
                    await context.edit("出错了呜呜呜 ~ 无效的歌曲序号。")
                    return
            else:
                await context.edit("出错了呜呜呜 ~ 无效的参数。")
                return

        await context.edit("获取中 . . .")
        try:
            import eyed3
            imported = True
        except ImportError:
            imported = False
            await bot.send_message(context.chat_id, '(`eyeD3`支持库未安装,歌曲文件信息将无法导入\n请使用 `-sh` `pip3` `install` `eyed3` '
                                                    '安装,或自行ssh安装)')
        url = "http://music.163.com/api/search/pc?&s=" + \
            keyword + "&offset=0&limit=1&type=1"
        for _ in range(20):  # 最多尝试20次
            status = False
            if proxynum > (len(proxy) - 1):  # 代理自动切换至下一个
                proxynum = 0
            proxies = proxy[proxynum]
            proxynum += 1
            if idplay:  # 指定ID播放
                url = "http://music.163.com/api/song/detail?id=" + \
                    idplay + "&ids=[" + idplay + "]"
            # 搜索后播放
            req = requests.request("GET", url, headers=headers)
            if req.status_code == 200:
                req = json.loads(req.content)
                if req['code'] == 200:
                    if idplay:
                        req['result'] = req
                    result = req['result']
                    if not idplay:
                        if req['result']['songCount'] == 0:
                            result = False
                else:
                    result = False
                if result:
                    info = {'id': req['result']['songs'][0]['id'], 'title': req['result']['songs'][0]['name'],
                            'alias': req['result']['songs'][0]['alias'],
                            'album': req['result']['songs'][0]['album']['name'],
                            'albumpic': req['result']['songs'][0]['album']['picUrl'], 'artist': '', 'br': ''}
                    if req['result']['songs'][0]['hMusic']:
                        info['br'] = req['result']['songs'][0]['hMusic']['bitrate']
                    elif req['result']['songs'][0]['mMusic']:
                        info['br'] = req['result']['songs'][0]['mMusic']['bitrate']
                    elif req['result']['songs'][0]['lMusic']:
                        info['br'] = req['result']['songs'][0]['lMusic']['bitrate']
                    for j in range(len(req['result']['songs'][0]['artists'])):
                        info['artist'] += req['result']['songs'][0]['artists'][j]['name'] + "; "
                    info['artist'] = info['artist'][:-2]
                    if title:
                        title = ""
                    else:
                        title = f"【{info['title']}】"
                    await context.edit(f"{title}下载中 . . .")
                    try:
                        from Crypto.Cipher import AES
                        AES.new("0CoJUm6Qyw8W8jud".encode('utf-8'),
                                AES.MODE_CBC, "0102030405060708".encode('utf-8'))
                        ccimported = True
                    except ImportError:
                        ccimported = False
                        await bot.send_message(context.chat_id, '(`PyCryptodome`支持库未安装,音乐曲库/音质受限\n请使用 `-sh` `pip3` '
                                                                '`install` `pycryptodome` 安装,或自行ssh安装)')
                    name = info['title'].replace('/', " ") + ".mp3"
                    name = name.encode('utf-8').decode('utf-8')
                    if ccimported:  # 尝试使用高清音质下载
                        songid = str(info['id'])

                        class WangyiyunDownload(object):
                            def __init__(self):
                                self.key = '0CoJUm6Qyw8W8jud'
                                self.public_key = "010001"
                                self.modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b72515' \
                                               '2b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92' \
                                               '557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d' \
                                               '3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7 '
                                # 偏移量
                                self.iv = "0102030405060708"
                                # 请求头
                                self.headers = {
                                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ('
                                                  'KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
                                    # 传入登录cookie,
                                    'Cookie': 'MUSIC_U=f52f220df171da480dbf33ce899479615'
                                              '85a7fdf08c89a2a4bdd6efebd86544233a649814e309366;',
                                    "X-Real-IP": "223.252.199.66",
                                }
                                # 请求url
                                self.url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token='

                            # 生成16位随机数字符串
                            def set_random_num(self):
                                random_num = ''
                                # 随机取16个字符
                                string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
                                for ___ in range(16):
                                    n = math.floor(
                                        random.uniform(0, 1) * len(string))
                                    random_num += string[n]
                                # 返回16位随机数字符串
                                return random_num

                            # 生成encSecKey
                            # 通过public_key和modulus对random_num进行RSA加密
                            def RSA_encrypt(self, random_num):
                                # 将16位随机数字符串倒序并以utf-8编码
                                random_num = random_num[::-1].encode('utf-8')
                                # 将其以hex(16进制)编码
                                random_num = codecs.encode(
                                    random_num, 'hex_codec')
                                # 加密(三者均要从16进制转换为10进制)
                                # int(n, 16) --> 将16进制字符串n转换为10进制
                                encryption = int(
                                    random_num, 16) ** int(self.public_key, 16) % int(self.modulus, 16)
                                # 将加密后的数据转换为16进制字符串
                                encryption = format(encryption, 'x')
                                # 返回加密后的字符串
                                return encryption

                            # 生成params
                            # 根据key和iv对msg进行AES加密,需调用两次
                            # key:
                            #   第一次: key
                            #   第二次: random_num
                            # iv: 偏移量iv
                            def AES_encrypt(self, msg, key, iv):
                                # 先将msg按需补全至16的倍数
                                # 需补全的位数
                                pad = (16 - len(msg) % 16)
                                # 补全
                                msg = msg + pad * chr(pad)
                                # 将key,iv和msg均以utf-8编码
                                key = key.encode('utf-8')
                                iv = iv.encode('utf-8')
                                msg = msg.encode('utf-8')
                                # 根据key和iv生成密钥,模式为CBC模式
                                encryptor = AES.new(key, AES.MODE_CBC, iv)
                                # 加密
                                encrypt_aes = encryptor.encrypt(msg)
                                # 先将加密后的值进行base64编码
                                encrypt_text = base64.encodebytes(encrypt_aes)
                                # 将其转换为utf-8字符串
                                encrypt_text = str(encrypt_text, 'utf-8')
                                # 返回加密后的字符串
                                return encrypt_text

                            # 根据歌曲song_id,生成需要传输的data
                            # 其中包括params和encSecKey
                            def construct_data(self, song_id):
                                # 生成16位随机数字符串
                                random_num = self.set_random_num()
                                # 生成encSecKey
                                encSecKey = self.RSA_encrypt(
                                    random_num=random_num)
                                # 调用两次AES加密生成params
                                # 初始化歌曲song_info
                                song_info = '{"ids":"[%s]","level":"exhigh","encodeType":"mp3",' \
                                            '"csrf_token":"477c1bd99fddedb3adc074f47fee2d35"}' % song_id
                                # 第一次加密,传入encText, key和iv
                                first_encryption = self.AES_encrypt(
                                    msg=song_info, key=self.key, iv=self.iv)
                                # 第二次加密, 传入first_encryption, random_num和iv
                                encText = self.AES_encrypt(
                                    msg=first_encryption, key=random_num, iv=self.iv)
                                # 生成data
                                data = {
                                    'params': encText,
                                    'encSecKey': encSecKey
                                }
                                # 返回data
                                return data

                            # 发送请求,获取下载链接
                            def get_real_url(self):
                                # 输入歌曲song_id
                                self.song_id = songid
                                # 获取data
                                data = self.construct_data(
                                    song_id=self.song_id)
                                # 发送请求
                                request = requests.post(
                                    url=self.url, headers=self.headers, data=data, proxies=proxies, verify=False)
                                # 初始化real_url
                                real_url = ''
                                # 处理返回信息
                                try:
                                    js_text = json.loads(request.text)
                                    data = js_text['data']
                                    if len(data) != 0:
                                        code = data[0]['code']
                                        # 获取成功
                                        if code == 200:
                                            # 歌曲真实地址
                                            real_url = data[0]['url']
                                        else:
                                            raise RetryError
                                except:
                                    print('生成的params和encSecKey有误!重试中!')
                                    raise RetryError
                                # 返回real_url
                                return real_url

                            def download(self):
                                # 获取下载链接
                                real_url = self.get_real_url()
                                if real_url == '':
                                    print('链接获取失败!')
                                    raise RetryError
                                else:
                                    file = name
                                    # 开始下载
                                    try:
                                        content = requests.get(
                                            url=real_url, headers=self.headers).content
                                        with open(file, 'wb') as fp:
                                            fp.write(content)
                                    except:
                                        print('服务器连接出错')
                                        raise RetryError
                        for __ in range(6):  # 最多尝试6次
                            if proxynum > (len(proxy) - 1):  # 代理自动切换至下一个
                                proxynum = 0
                            proxies = proxy[proxynum]
                            proxynum += 1
                            try:
                                WangyiyunDownload().download()
                                ccimported = True
                                break
                            except:
                                ccimported = False
                        if not exists(name):
                            ccimported = False
                    if ccimported is False:  # 下载(普通音质)
                        music = requests.request(
                            "GET", "http://music.163.com/api/song/enhance/download/url?&br=" + str(info['br']) + "&id=" + str(info['id']), headers=headers, proxies=proxies, verify=False)
                        if music.status_code == 200:
                            music = json.loads(music.content)
                            if not music['data']['url']:
                                music = requests.request(
                                    "GET", "https://music.163.com/song/media/outer/url?id=" + str(info['id']) + ".mp3", headers=headers, verify=False)
                                if music.status_code != 200:
                                    continue
                            else:
                                music = requests.request(
                                    "GET", music['data']['url'], headers=headers)
                        else:
                            continue
                    performers = info['artist'].replace(';', ',')
                    cap = performers + " - " + "**" + info['title'] + "**"

                    if ccimported is False:
                        with open(name, 'wb') as f:
                            f.write(music.content)
                    if (path.getsize(name) / 1024) < 100:
                        remove(name)
                        try:
                            if reply.sender.is_self:
                                await reply.delete()
                        except:
                            pass
                        await context.delete()
                        res = '或者你可以点击<a href="https://music.163.com/#/song?id=' + \
                            str(info['id']) + '">' + \
                            ' <strong>这里</strong> ' + '</a>' + '前往网页版收听'
                        await bot.send_message(context.chat_id, f"<strong>【{info['title']}】</strong>\n" +
                                               "歌曲获取失败,资源获取可能受限,你可以再次尝试。\n" + res, parse_mode='html', link_preview=True)
                        return
                    duration = 0
                    imagedata = requests.get(
                        info['albumpic'], headers=headers).content
                    if imported is True:
                        await context.edit(f"{title}信息导入中 . . .")
                        tag = eyed3.load(name)
                        duration = int(tag.info.time_secs)
                        tag.initTag()
                        tag = tag.tag
                        tag.artist = info['artist']
                        tag.title = info['title']
                        tag.album = info['album']
                        tag.images.remove('')
                        tag.images.set(6, imagedata, "image/jpeg", u"Media")
                        tag.save(version=eyed3.id3.ID3_DEFAULT_VERSION,
                                 encoding='utf-8')
                    br = ""
                    if imported is True:
                        br = "#" + \
                            str(eyed3.mp3.Mp3AudioFile(
                                name).info.bit_rate[1]) + "kbps "
                    alias = ""
                    if info['alias']:
                        alias = "\n\n__" + info['alias'][0] + "__"
                    cap += "\n#NeteaseMusic " + br + alias
                    await context.edit(f"{title}上传中 . . .")
                    if not exists("plugins/NeteaseMusicExtra/FastTelethon.py"):
                        if not exists("plugins/NeteaseMusicExtra"):
                            mkdir("plugins/NeteaseMusicExtra")
                        for ____ in range(6):  # 最多尝试6次
                            faster = requests.request(
                                "GET", "https://gist.githubusercontent.com/TNTcraftHIM"
                                       "/ca2e6066ed5892f67947eb2289dd6439/raw"
                                       "/86244b02c7824a3ca32ce01b2649f5d9badd2e49/FastTelethon.py")
                            if faster.status_code == 200:
                                with open("plugins/NeteaseMusicExtra/FastTelethon.py", "wb") as f:
                                    f.write(faster.content)
                                break
                            else:
                                if exists("plugins/NeteaseMusicExtra/NoFastTelethon.txt"):
                                    break
                    try:
                        from NeteaseMusicExtra.FastTelethon import upload_file
                        file = await upload_file(context.client, open(name, 'rb'), name)
                    except:
                        file = name
                        if not exists("plugins/NeteaseMusicExtra/NoFastTelethon.txt"):
                            with open("plugins/NeteaseMusicExtra/NoFastTelethon.txt", "w") as f:
                                f.write("此文件出现表示FastTelethon支持文件在首次运行NeteaseMusic插件时导入失败\n这可能是因为Github"
                                        "服务器暂时性的访问出错导致的\nFastTelethon可以提升低网络性能机型在上传文件时的效率,但是正常情况提升并不明显\n"
                                        "如想要手动导入,可以手动下载:\nhttps://gist.githubusercontent.com/TNTcraftHIM"
                                        "/ca2e6066ed5892f67947eb2289dd6439/raw"
                                        "/86244b02c7824a3ca32ce01b2649f5d9badd2e49/FastTelethon.py\n并放入当前文件夹")
                            await bot.send_message(context.chat_id, '`FastTelethon`支持文件导入失败,上传速度可能受到影响\n'
                                                                    '此提示仅出现**一次**,手动导入可参考:\n`' + getcwd() +
                                                   '/plugins/NeteaseMusicExtra/NoFastTelethon.txt`')

                    await context.client.send_file(
                        context.chat_id,
                        file,
                        caption=cap,
                        link_preview=False,
                        force_document=False,
                        thumb=imagedata,
                        attributes=(DocumentAttributeAudio(
                            duration, False, info['title'], performers),)
                    )
                    try:
                        if reply.sender.is_self:
                            await reply.delete()
                    except:
                        pass
                    try:
                        remove(name)
                    except:
                        pass
                    await context.delete()
                    status = True
                    break
                else:
                    await context.edit("**未搜索到结果**")
                    sleep(3)
                    await context.delete()
                    status = True
                    break
            else:
                continue

        if status is False:
            await context.edit(apifailtext)
            sleep(3)
            await context.delete()
    else:  # 错误输入
        await context.edit(helptext)
        return
Пример #26
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)
Пример #27
0
async def handler(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    if os.path.exists(input_str):
        start = datetime.now()
        lst_of_files = sorted(get_lst_of_files(input_str, []))
        logger.info(lst_of_files)
        u = 0
        await event.edit("Found {} files. ".format(len(lst_of_files)) +
                         "Uploading will start soon. " + "Please wait!")
        thumb = None
        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        for single_file in lst_of_files:
            if os.path.exists(single_file):
                caption_rts = os.path.basename(single_file)
                force_document = True
                supports_streaming = False
                document_attributes = []
                width = 0
                height = 0
                if os.path.exists(thumb_image_path):
                    metadata = extractMetadata(createParser(thumb_image_path))
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                if single_file.endswith((".mkv", ".mp4", ".webm")):
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    if metadata.has("duration"):
                        duration = metadata.get('duration').seconds
                    document_attributes = [
                        DocumentAttributeVideo(duration=duration,
                                               w=width,
                                               h=height,
                                               round_message=False,
                                               supports_streaming=True)
                    ]
                    supports_streaming = True
                    force_document = False
                if single_file.endswith((".mp3", ".flac", ".wav")):
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    title = ""
                    artist = ""
                    if metadata.has("duration"):
                        duration = metadata.get('duration').seconds
                    if metadata.has("title"):
                        title = metadata.get("title")
                    if metadata.has("artist"):
                        artist = metadata.get("artist")
                    document_attributes = [
                        DocumentAttributeAudio(duration=duration,
                                               voice=False,
                                               title=title,
                                               performer=artist,
                                               waveform=None)
                    ]
                    supports_streaming = True
                    force_document = False
                try:
                    await client.send_file(
                        event.chat_id,
                        single_file,
                        caption=caption_rts,
                        force_document=force_document,
                        supports_streaming=supports_streaming,
                        allow_cache=False,
                        reply_to=event.message.id,
                        thumb=thumb,
                        attributes=document_attributes,
                    )
                except Exception as e:
                    await client.send_message(event.chat_id,
                                              "{} caused `{}`".format(
                                                  caption_rts, str(e)),
                                              reply_to=event.message.id)
                    continue
                os.remove(single_file)
                u = u + 1
                await asyncio.sleep(5)
        end = datetime.now()
        ms = (end - start).seconds
        await event.edit("Uploaded {} files in {} seconds.".format(u, ms))
    else:
        await event.edit("404: Directory not found.")
Пример #28
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()
Пример #29
0
async def _(event):
    url = event.pattern_match.group(1).decode("UTF-8")
    lets_split = url.split("_", maxsplit=1)
    vid_id = lets_split[1].split(":")[0]
    link = _yt_base_url + vid_id
    format = url.split(":")[1]
    if lets_split[0] == "audio":
        opts = {
            "format": str(format),
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "outtmpl": "%(id)s.mp3",
            "quiet": True,
            "logtostderr": False,
        }
        ytdl_data = await dler(event, link, opts, True)
        title = ytdl_data["title"]
        if ytdl_data.get("artist"):
            artist = ytdl_data["artist"]
        elif ytdl_data.get("creator"):
            artist = ytdl_data["creator"]
        elif ytdl_data.get("channel"):
            artist = ytdl_data["channel"]
        views = numerize.numerize(ytdl_data["view_count"])
        await download_file(f"https://i.ytimg.com/vi/{vid_id}/hqdefault.jpg",
                            f"{title}.jpg")
        thumb = f"{title}.jpg"
        duration = ytdl_data["duration"]
        os.rename(f"{ytdl_data['id']}.mp3", f"{title}.mp3")
        c_time = time.time()
        file = await uploader(f"{title}.mp3", f"{title}.mp3", c_time, event,
                              "Uploading " + title + "...")
        attributes = [
            DocumentAttributeAudio(
                duration=int(duration),
                title=title,
                performer=artist,
            ),
        ]
    elif lets_split[0] == "video":
        opts = {
            "format": str(format),
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "outtmpl": "%(id)s.mp4",
            "logtostderr": False,
            "quiet": True,
        }
        ytdl_data = await dler(event, link, opts, True)
        title = ytdl_data["title"]
        if ytdl_data.get("artist"):
            artist = ytdl_data["artist"]
        elif ytdl_data.get("creator"):
            artist = ytdl_data["creator"]
        elif ytdl_data.get("channel"):
            artist = ytdl_data["channel"]
        views = numerize.numerize(ytdl_data["view_count"])
        thumb = await fast_download(
            f"https://i.ytimg.com/vi/{vid_id}/hqdefault.jpg",
            filename=f"{title}.jpg")
        hi, wi = ytdl_data["height"], ytdl_data["width"]
        duration = ytdl_data["duration"]
        try:
            os.rename(f"{ytdl_data['id']}.mp4", f"{title}.mp4")
        except FileNotFoundError:
            try:
                os.rename(f"{ytdl_data['id']}.mkv", f"{title}.mp4")
            except FileNotFoundError:
                os.rename(f"{ytdl_data['id']}.mp4.webm", f"{title}.mp4")
        except Exception as ex:
            return await event.edit(str(ex))
        c_time = time.time()
        file = await uploader(f"{title}.mp4", f"{title}.mp4", c_time, event,
                              "Uploading " + title + "...")
        attributes = [
            DocumentAttributeVideo(
                duration=int(duration),
                w=wi,
                h=hi,
                supports_streaming=True,
            ),
        ]
    text = f"**Title:** `{title}`\n"
    text += f"**Duration:** `{time_formatter(int(duration)*1000)}`\n"
    text += f"**Views:** `{views}`\n"
    text += f"**Artist:** `{artist}`\n\n"
    await event.edit(
        text,
        file=file,
        buttons=Button.switch_inline("Search More",
                                     query="yt ",
                                     same_peer=True),
        attributes=attributes,
        thumb=thumb,
    )
    await bash(f'rm "{title}"*')
Пример #30
0
async def download_video(v_url):
    """For .ytdl command, download media from YouTube and many other sites."""
    url = v_url.pattern_match.group(2)
    if not url:
        rmsg = await v_url.get_reply_message()
        myString = rmsg.text
        url = re.search("(?P<url>https?://[^\s]+)", myString).group("url")
    if not url:
        await edit_or_reply(v_url, "What I am Supposed to find? Give link")
        return
    ytype = v_url.pattern_match.group(1).lower()
    v_url = await edit_or_reply(v_url, "`Preparing to download...`")
    reply_to_id = await reply_id(v_url)
    if ytype == "a":
        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
    elif ytype == "v":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "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 v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await v_url.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    catthumb = Path(f"{ytdl_data['id']}.jpg")
    if not os.path.exists(catthumb):
        catthumb = Path(f"{ytdl_data['id']}.webp")
    if not os.path.exists(catthumb):
        catthumb = None
    if song:
        await v_url.edit(f"`Preparing to upload song:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp3",
            supports_streaming=True,
            thumb=catthumb,
            reply_to=reply_to_id,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(ytdl_data["duration"]),
                    title=str(ytdl_data["title"]),
                    performer=str(ytdl_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp3")),
        )
        os.remove(f"{ytdl_data['id']}.mp3")
    elif video:
        await v_url.edit(f"`Preparing to upload video:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp4",
            reply_to=reply_to_id,
            supports_streaming=True,
            caption=ytdl_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp4")),
        )
        os.remove(f"{ytdl_data['id']}.mp4")
    if catthumb:
        os.remove(catthumb)
    await v_url.delete()