示例#1
0
async def edit_message(m: Message):
    """
    edit any type of pyrogram message using the messages dict.
    :param m: pyrogram.Message to edit.
    """
    if m.text:
        messages[m.date] = await messages[m.date].edit(m.text)
    elif m.caption and m.caption != messages[m.date].caption:
        messages[m.date] = await messages[m.date].edit_caption(m.caption)
    elif m.media:
        caption = {'caption': m.caption + '\n'} if m.caption else {}
        if m.photo and m.photo != messages[m.date].photo:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaPhoto(m.photo.file_id, m.photo.file_unique_id,
                                **caption))
        elif m.video and m.video != messages[m.date].video:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaVideo(m.video.file_id, m.video.file_unique_id,
                                **caption))
        elif m.document and m.document != messages[m.date].document:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaDocument(m.document.file_id,
                                   m.document.file_unique_id, **caption))
        elif m.animation and m.animation != messages[m.date].animation:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaAnimation(m.animation.file_id,
                                    m.animation.file_unique_id, **caption))
        elif m.audio and m.audio != messages[m.date].audio:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaAudio(m.audio.file_id, m.audio.file_unique_id,
                                **caption))
示例#2
0
async def upload_image_grp(results, message: Message, doc: bool = False):
    key_ = list(results[0])[0]
    medias_ = results[0][key_]
    if message.process_is_canceled:
        await message.client.stop_transmission()
    if len(medias_) == 0:
        await message.err(f"No result Found `'{key_}'`", del_in=7)
    if len(medias_) == 1:
        path_ = Path(medias_[0])
        if doc:
            await doc_upload(message=message, path=path_, del_path=True)
        else:
            await photo_upload(message=message, path=path_, del_path=True)
    else:
        mgroups = sublists(
            [(InputMediaDocument(media=x) if doc else InputMediaPhoto(media=x))
             for x in medias_
             if x.endswith((".jpg", ".jpeg", ".png", ".bmp"))],
            width=10,
        )
        for num, m_ in enumerate(mgroups, start=1):
            try:
                await message.edit(
                    f"Uploading **{round(num / len(mgroups) * 100)} %** ...")
                await message.client.send_media_group(message.chat.id,
                                                      media=m_)
                await asyncio.sleep(len(m_))
            except FloodWait as f:
                await asyncio.sleep(f.x + 5)
示例#3
0
def create_media_group(book: Book) -> List[InputMediaDocument]:

    group = []

    caption = f"**{book.type}**: {book.title}"

    for document in book.documents:
        group.append(InputMediaDocument(document.file_id, caption=caption))

    return group
示例#4
0
async def wall_(msg: Message):

    if os.path.exists("wallpapers/"):
        shutil.rmtree("wallpapers/", ignore_errors=True)

    limit = min(int(msg.flags.get('-l', 8)), 10)

    if msg.filtered_input_str:
        qu = msg.filtered_input_str
        await msg.edit(f"`Seraching Wallpapers for {qu}`")
        results = requests.get(
            "https://api.unsplash.com/search/"
            f"photos?client_id=HWlOs9dNZIbYEkjp87fiEzC9rmE6rKM64tBqXBOLzu8&query={qu}"
        )

        if results.status_code != 200:
            return await msg.edit('**Result Not Found**')
        _json = results.json()['results']
        if len(_json) < limit:
            limit = len(_json)

        ss = []
        os.mkdir("wallpapers")

        for i in range(limit):
            img = f"wallpapers/wall_{i+1}.png"

            if '-doc' in msg.flags:
                await pool.run_in_thread(wget.download
                                         )(_json[i]['urls']['raw'], img)
                ss.append(InputMediaDocument(str(img)))
                continue

            await pool.run_in_thread(wget.download)(_json[i]['urls']['thumb'],
                                                    img)
            image = Image.open(img)
            if not (image.height <= 1280 and image.width <= 1280):
                image.thumbnail((1280, 1280), Image.ANTIALIAS)
                a_dex = image.mode.find("A")
                if a_dex != -1:
                    new_im = Image.new('RGB', image.size, (255, 255, 255))
                    new_im.paste(image, mask=image.split()[a_dex])
                    new_im.save(img, 'JPEG', optimize=True)
            ss.append(InputMediaPhoto(str(img)))

        await msg.reply_chat_action("upload_photo" if '-doc' not in
                                    msg.flags else "upload_document")
        await msg.reply_media_group(ss, True)
        shutil.rmtree("wallpapers/", ignore_errors=True)
        await msg.delete()
    else:
        await msg.edit('**Give me Something to search.**')
        await msg.reply_sticker('CAADAQADmQADTusQR6fPCVZ3EhDoFgQ')
示例#5
0
 def generate_doc(self, attachment):
     try:
         attachment["doc"]["title"] = sub(r"[/\\:*?\"><|]", "",
                                          attachment["doc"]["title"])
         if attachment["doc"]["title"].endswith(attachment["doc"]["ext"]):
             doc = download(attachment["doc"]["url"],
                            out="{title}".format(**attachment["doc"]))
         else:
             doc = download(attachment["doc"]["url"],
                            out="{title}.{ext}".format(**attachment["doc"]))
         self.docs.append(InputMediaDocument(doc))
     except urllib.error.URLError as error:
         log.exception("[AP] Невозможно скачать вложенный файл: {0}.",
                       error)
         self.text += '\n📃 <a href="{url}">{title}</a>'.format(
             **attachment["doc"])
示例#6
0
def send_font(app, msg):

	media_group = []
	for i in ('Regular', 'Bold', 'Italic', 'Bold_Italic'):
		media_group.append(InputMediaDocument(f'{os.getcwd()}/fonts/Ебать/{i}.ttf'))
	
	media_group[3].caption = '''Установите эти шрифты в свою систему для правильного отображения.
	
**Для Windows:**
 - Скчайте файлы шрифтов.
 - Нажмите правой кнопкой мыши на файл шрифта.
 - Нажмите "Установить шрифт".

**Для Linux:**
 - Скчайте файлы шрифтов.
 - Создайте папку ".fonts" в домашней папке "~/".
 - Скопируйте туда шрифты.'''
	msg.reply_media_group(media_group)
示例#7
0
async def _callback(client, CallbackQuery):
    query = CallbackQuery.data.split()
    try:
        if query[0] == "anime":
            text, mal_url, trailer = data_from_id(query[0], query[-1])
            if trailer:
                buttons = [[
                    InlineKeyboardButton("More Info!", url=mal_url),
                    InlineKeyboardButton("Watch Trailer!", url=trailer)
                ]]
            else:
                buttons = [[InlineKeyboardButton("More Info!", url=mal_url)]]
            await CallbackQuery.edit_message_text(
                text=text, reply_markup=InlineKeyboardMarkup(buttons))
        elif query[0] == "manga" or query[0] == "char":
            text, mal_url = data_from_id(query[0], query[-1])
            buttons = [[InlineKeyboardButton("More Info!", url=mal_url)]]
            await CallbackQuery.edit_message_text(
                text=text, reply_markup=InlineKeyboardMarkup(buttons))

        elif query[0] == "download":
            title, num_pages, artist, lang, tags, page_links = await nhentai_data(
                query[-1])
            cwd = os.getcwd()
            new_dir = query[-1]
            dl_path = os.path.join(cwd, new_dir)
            os.mkdir(dl_path)
            outfile_path = os.path.join(dl_path, f"{new_dir}.pdf")
            await _download(query[-1], dl_path, outfile_path)
            print()
            text = f"**{title}**\n\n**Language:** {', '.join(lang)}\n**Artist:** {', '.join(artist)}\n**Pages:** {num_pages}\n\n**Tags:** {', '.join(tags)}"
            await CallbackQuery.edit_message_media(
                InputMediaDocument(outfile_path, caption=text))
            shutil.rmtree(dl_path)
    except Exception as e:
        await CallbackQuery.edit_message_text(text=f"**Error:**\n{e}")
示例#8
0
async def note_send(client: Client, message: Message):
    await message.edit("<code>Loading...</code>")
    if len(message.text.split()) >= 2:
        find_note = await db.find_one(
            {"NAME": f"{message.text.split(' ', maxsplit=1)[1]}"})
        if find_note:
            if "MEDIA_GROUP_ID" in find_note:
                messages_grouped = await client.get_media_group(
                    int(find_note["CHAT_ID"]), int(find_note["MESSAGE_ID"]))
                media_grouped_list = []
                for _ in messages_grouped:
                    if _.photo:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaPhoto(_.photo.file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaPhoto(_.photo.file_id))
                    elif _.video:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaVideo(_.video.file_id,
                                                _.video.thumbs[0].file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaVideo(_.video.file_id,
                                                _.video.thumbs[0].file_id))
                    elif _.audio:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaAudio(_.audio.file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaAudio(_.audio.file_id))
                    elif _.document:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaDocument(
                                    _.document.file_id,
                                    _.document.thumbs[0].file_id,
                                    _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaDocument(
                                    _.document.file_id,
                                    _.document.thumbs[0].file_id))
                if message.reply_to_message:
                    await client.send_media_group(
                        message.chat.id,
                        media_grouped_list,
                        reply_to_message_id=message.reply_to_message.message_id
                    )
                else:
                    await client.send_media_group(message.chat.id,
                                                  media_grouped_list)
                await message.delete()
            else:
                if message.reply_to_message:
                    await client.copy_message(
                        message.chat.id,
                        int(find_note["CHAT_ID"]),
                        int(find_note["MESSAGE_ID"]),
                        reply_to_message_id=message.reply_to_message.message_id
                    )
                else:
                    await client.copy_message(message.chat.id,
                                              int(find_note["CHAT_ID"]),
                                              int(find_note["MESSAGE_ID"]))
                await message.delete()
        else:
            await message.edit("There is no such note")
    else:
        await message.edit("Example: <code>.note name note</code>")
示例#9
0
async def upload_single_file(
    message, local_file_name, caption_str, from_user, client, edit_media, yt_thumb
):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    local_file_name = str(Path(local_file_name).resolve())
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(
        DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg"
    )
    # LOGGER.info(thumbnail_location)
    if UPLOAD_AS_DOC.upper() == "TRUE":  # todo: this code will be removed in future
        thumb = None
        thumb_image_path = None
        if os.path.exists(thumbnail_location):
            thumb_image_path = await copy_file(
                thumbnail_location, os.path.dirname(
                    os.path.abspath(local_file_name))
            )
            thumb = thumb_image_path
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name))
            )
        prog = Progress(from_user, client, message_for_progress_display)
        sent_message = await message.reply_document(
            document=local_file_name,
            thumb=thumb,
            caption=caption_str,
            parse_mode="html",
            disable_notification=True,
            progress=prog.progress_for_pyrogram,
            progress_args=(
                f"{os.path.basename(local_file_name)}",
                start_time,
            ),
        )
        if edit_media:
            await message_for_progress_display.delete()
        if message.message_id != message_for_progress_display.message_id:
            try:
                await message_for_progress_display.delete()
            except FloodWait as gf:
                time.sleep(gf.x)
            except Exception as rr:
                LOGGER.warning(str(rr))
        os.remove(local_file_name)
        if thumb is not None:
            os.remove(thumb)
    else:
        try:
            message_for_progress_display = message
            if not edit_media:
                message_for_progress_display = await message.reply_text(
                    "starting upload of {}".format(
                        os.path.basename(local_file_name))
                )
                prog = Progress(from_user, client,
                                message_for_progress_display)
            if local_file_name.upper().endswith(("MKV", "MP4", "WEBM", "M4V", "3GP")):
                duration = 0
                try:
                    metadata = extractMetadata(createParser(local_file_name))
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                except Exception as g_e:
                    LOGGER.info(g_e)
                width = 0
                height = 0
                thumb_image_path = None
                if os.path.exists(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                else:
                    if not yt_thumb:
                        thumb_image_path = await take_screen_shot(
                            local_file_name,
                            os.path.dirname(os.path.abspath(local_file_name)),
                            (duration / 2),
                        )
                    else:
                        req = requests.get(yt_thumb)
                        thumb_image_path = os.path.join(
                            os.path.dirname(os.path.abspath(local_file_name)),
                            str(time.time()) + ".jpg",
                        )
                        with open(thumb_image_path, "wb") as thum:
                            thum.write(req.content)
                        img = Image.open(thumb_image_path).convert("RGB")
                        img.save(thumb_image_path, format="jpeg")
                    # get the correct width, height, and duration for videos greater than 10MB
                    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")
                        # ref: https://t.me/PyrogramChat/44663
                        # https://stackoverflow.com/a/21669827/4723940
                        Image.open(thumb_image_path).convert("RGB").save(
                            thumb_image_path
                        )
                        img = Image.open(thumb_image_path)
                        # https://stackoverflow.com/a/37631799/4723940
                        img.resize((320, height))
                        img.save(thumb_image_path, "JPEG")
                        # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
                #
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                # send video
                if edit_media and message.photo:
                    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                    sent_message = await message.edit_media(
                        media=InputMediaVideo(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                            width=width,
                            height=height,
                            duration=duration,
                            supports_streaming=True,
                        )
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_video(
                        video=local_file_name,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        width=width,
                        height=height,
                        thumb=thumb,
                        supports_streaming=True,
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)
            elif local_file_name.upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")):
                metadata = extractMetadata(createParser(local_file_name))
                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")
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                # send audio
                if edit_media and message.photo:
                    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                    sent_message = await message.edit_media(
                        media=InputMediaAudio(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                            duration=duration,
                            performer=artist,
                            title=title,
                        )
                    )
                else:
                    sent_message = await message.reply_audio(
                        audio=local_file_name,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        thumb=thumb,
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)
            else:
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                # if a file, don't upload "thumb"
                # this "diff" is a major derp -_- 😔😭😭
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                #
                # send document
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaDocument(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                        )
                    )
                else:
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)

        except MessageNotModified as oY:
            LOGGER.info(oY)
        except FloodWait as g:
            LOGGER.info(g)
            time.sleep(g.x)
        except Exception as e:
            LOGGER.info(e)
            await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
        else:
            if message.message_id != message_for_progress_display.message_id:
                try:
                    if sent_message is not None:
                        await message_for_progress_display.delete()
                except FloodWait as gf:
                    time.sleep(gf.x)
                except Exception as rr:
                    LOGGER.warning(str(rr))
                    await asyncio.sleep(5)
        os.remove(local_file_name)
    return sent_message
示例#10
0
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None):
    if database is not None:
        if database.get_cancel_status(message.chat_id,message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
    
    force_docs = get_val("FORCE_DOCUMENTS")
    if user_msg is not None:
        force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id)

    thonmsg = message
    message = await message.client.pyro.get_messages(message.chat_id, message.id)
    tout = get_val("EDIT_SLEEP_SECS")
    sent_message = None
    start_time = time.time()
    #
    if user_msg is not None:
        dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id)
        if dis_thumb is False or dis_thumb is None:
            thumb_image_path = user_db.get_thumbnail(user_msg.sender_id)
            if not thumb_image_path:
                thumb_image_path = None
    #
    try:
        message_for_progress_display = message
        if not force_edit:
            data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id)
            markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]])
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(os.path.basename(path)),
                reply_markup=markup
            )
        if str(path).upper().endswith(("MKV", "MP4", "WEBM")) and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            if thumb_image_path is None:
                thumb_image_path = await thumb_manage.get_thumbnail(path)
                # get the correct width, height, and duration for videos greater than 10MB

            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            
            # send video
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        width=width,
                        height=height,
                        duration=duration,
                        supports_streaming=True
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        elif str(path).upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")) and not force_docs:
            metadata = extractMetadata(createParser(path))
            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")
            
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        else:
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(
                        media=path,
                        thumb=thumb,
                        parse_mode="html"
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=path,
                    # quote=True,
                    thumb=thumb,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("cancled an upload lol")
            await message_for_progress_display.delete()
        else:
            torlog.info(traceback.format_exc())
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    #os.remove(path)
    if sent_message is None:
        return None
    sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id)
    return sent_message
示例#11
0
async def catch_youtube_dldata(bot, update):
    thumb_image_path = os.getcwd() + "/" + "thumbnails" + "/" + str(
        update.from_user.id) + ".jpg"
    yt_thumb_image_path = os.getcwd() + "/" + "YouTubeThumb" + "/" + str(
        update.from_user.id) + ".jpg"
    if os.path.exists(thumb_image_path):
        thumb_image = thumb_image_path
    else:
        thumb_image = yt_thumb_image_path
    file_name = str(Config.PRE_FILE_TXT)
    cb_data = update.data
    # Callback Data Check (for Youtube formats)
    if cb_data.startswith(("video", "audio", "docaudio", "docvideo")):
        yturl = cb_data.split("||")[-1]
        format_id = cb_data.split("||")[-2]
        if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")):
            print("no data found")
            raise ContinuePropagation

        new_filext = "%(title)s.%(ext)s"
        filext = file_name + new_filext
        saved_file_path = os.getcwd() + "/" + "downloads" + "/" + str(
            update.from_user.id) + "/"
        if not os.path.isdir(saved_file_path):
            os.makedirs(saved_file_path)
        dl_folder = [f for f in os.listdir(saved_file_path)]
        for f in dl_folder:
            try:
                os.remove(os.path.join(saved_file_path, f))
            except IndexError:
                pass
        await update.edit_message_text(text=Translation.DOWNLOAD_START)
        filepath = os.path.join(saved_file_path, filext)

        audio_command = [
            "youtube-dl",
            "-c",
            "--prefer-ffmpeg",
            "--extract-audio",
            "--audio-format",
            "mp3",
            "--audio-quality",
            format_id,
            "-o",
            filepath,
            yturl,
        ]

        video_command = [
            "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio",
            "-o", filepath, "--hls-prefer-ffmpeg", yturl
        ]

        loop = asyncio.get_event_loop()
        med = None
        if cb_data.startswith("audio"):
            filename = await downloadaudiocli(audio_command)
            med = InputMediaAudio(media=filename,
                                  caption=os.path.basename(filename),
                                  title=os.path.basename(filename),
                                  thumb=thumb_image)

        if cb_data.startswith("video"):
            description = Translation.CUSTOM_CAPTION_VIDEO
            filename = await downloadvideocli(video_command)
            dur = round(duration(filename))
            med = InputMediaVideo(media=filename,
                                  duration=dur,
                                  caption=description,
                                  thumb=thumb_image,
                                  supports_streaming=True)

        if cb_data.startswith("docaudio"):
            filename = await downloadaudiocli(audio_command)
            med = InputMediaDocument(media=filename,
                                     caption=os.path.basename(filename),
                                     thumb=thumb_image)

        if cb_data.startswith("docvideo"):
            description = Translation.CUSTOM_CAPTION_DOC
            filename = await downloadvideocli(video_command)
            dur = round(duration(filename))
            med = InputMediaDocument(media=filename,
                                     caption=description,
                                     thumb=thumb_image)

        if med:
            loop.create_task(send_file(bot, update, med))

        else:
            print("med not found")

######################################### CB Data query for Bot Settings ###############################################
    else:
        # Callback Data Check (for bot settings)
        if cb_data.startswith(
            ("close", "view_thumb", "del_thumb", "conf_thumb", "start_help",
             "settings", "rename_doc", "convert_video", "d_copy", "v_copy",
             "clear_med")):
            if "close" in cb_data:
                await close_button(bot, update)
            elif "view_thumb" in cb_data:
                await view_thumbnail(bot, update)
            elif "del_thumb" in cb_data:
                await delete_thumbnail(bot, update)
            elif "conf_thumb" in cb_data:
                await del_thumb_confirm(bot, update)
            elif "start_help" in cb_data:
                await start_bot(bot, update)
            elif "settings" in cb_data:
                await bot_settings(bot, update)
            elif "rename_doc" in cb_data:
                await rename_file(bot, update)
            elif "convert_video" in cb_data:
                await convert_to_video(bot, update)
            elif "d_copy" in cb_data:
                await convert_to_doc_copy(bot, update)
            elif "v_copy" in cb_data:
                await convert_to_video_copy(bot, update)
            elif "clear_med" in cb_data:
                await clear_media(bot, update)
示例#12
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                      str(from_user) + ".jpg")
    LOGGER.info(thumbnail_location)
    #
    try:
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name)))
        if local_file_name.upper().endswith(
            ("WEBM", "MP4")) and not local_file_name.upper().startswith(
                ("KDG")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            thumb_image_path = None
            if os.path.exists(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            else:
                thumb_image_path = None
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send video
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        elif local_file_name.upper().endswith(
            ("MP3", "M4A", "M4B", "FLAC", "WAV")):
            metadata = extractMetadata(createParser(local_file_name))
            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")
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          duration=duration,
                                          performer=artist,
                                          title=title)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        else:
            base_file_name = os.path.basename(local_file_name)
            base_new_name = os.path.splitext(base_file_name)[0]
            extension_new_name = os.path.splitext(base_file_name)[1]
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(media=local_file_name,
                                             thumb=thumb,
                                             caption=caption_str,
                                             parse_mode="html")
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=local_file_name,
                    # quote=True,
                    thumb=thumb,
                    caption=caption_str,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))

            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    os.remove(local_file_name)
    return sent_message
async def youtube_dl_call_back(bot, update, cb_data):
    LOGGER.info(update)
    # youtube_dl extractors
    tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|")
    #
    current_user_id = update.message.reply_to_message.from_user.id
    current_touched_user_id = update.from_user.id
    if current_user_id != current_touched_user_id:
        return False, None
    user_working_dir = os.path.join(TMP_DOWNLOAD_DIRECTORY,
                                    str(current_user_id))
    # create download directory, if not exist
    if not os.path.isdir(user_working_dir):
        await bot.delete_messages(
            chat_id=update.message.chat.id,
            message_ids=[
                update.message.message_id,
                update.message.reply_to_message.message_id,
            ],
            revoke=True)
        return
    save_ytdl_json_path = user_working_dir + \
        "/" + str("ytdleech") + ".json"
    try:
        with open(save_ytdl_json_path, "r", encoding="utf8") as f_d:
            response_json = json.load(f_d)
        os.remove(save_ytdl_json_path)
    except FileNotFoundError:
        await bot.delete_messages(
            chat_id=update.message.chat.id,
            message_ids=[
                update.message.message_id,
                update.message.reply_to_message.message_id,
            ],
            revoke=True)
        return False
    #
    response_json = response_json[0]
    # TODO: temporary limitations
    LOGGER.info(response_json)
    #
    youtube_dl_url = response_json.get("webpage_url")
    LOGGER.info(youtube_dl_url)
    #
    custom_file_name = "%(title)s.%(ext)s"
    # https://superuser.com/a/994060
    LOGGER.info(custom_file_name)
    #
    await update.message.edit_caption(caption="trying to download")
    description = "@PyroGramBot"
    if "fulltitle" in response_json:
        description = response_json["fulltitle"][0:1021]
        # escape Markdown and special characters
    #
    tmp_directory_for_each_user = os.path.join(TMP_DOWNLOAD_DIRECTORY,
                                               str(update.from_user.id))
    if not os.path.isdir(tmp_directory_for_each_user):
        os.makedirs(tmp_directory_for_each_user)
    download_directory = tmp_directory_for_each_user
    download_directory = os.path.join(tmp_directory_for_each_user,
                                      custom_file_name)
    command_to_exec = []
    if tg_send_type == "audio":
        command_to_exec = [
            "youtube-dl",
            "-c",
            "--prefer-ffmpeg",
            "--extract-audio",
            "--add-metadata",
            "--embed-thumbnail",
            "--audio-format",
            youtube_dl_ext,
            "--audio-quality",
            youtube_dl_format,
            youtube_dl_url,
            "-o",
            download_directory,
            # "--external-downloader", "aria2c"
        ]
    else:
        # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory]
        minus_f_format = youtube_dl_format
        if "youtu" in youtube_dl_url:
            for for_mat in response_json["formats"]:
                format_id = for_mat.get("format_id")
                if format_id == youtube_dl_format:
                    acodec = for_mat.get("acodec")
                    vcodec = for_mat.get("vcodec")
                    if acodec == "none" or vcodec == "none":
                        minus_f_format = youtube_dl_format + "+bestaudio"
                    break
        command_to_exec = [
            "youtube-dl",
            "-c",
            # "--embed-subs",
            "-f",
            minus_f_format,
            "--hls-prefer-ffmpeg",
            youtube_dl_url,
            "-o",
            download_directory,
            # "--external-downloader", "aria2c"
        ]
    #
    command_to_exec.append("--no-warnings")
    # command_to_exec.append("--quiet")
    command_to_exec.append("--restrict-filenames")
    #
    if "hotstar" in youtube_dl_url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    LOGGER.info(command_to_exec)
    start = datetime.now()
    t_response, e_response = await run_command(command_to_exec)
    # LOGGER.info(e_response)
    # LOGGER.info(t_response)
    ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output."
    if e_response and ad_string_to_replace in e_response:
        error_message = e_response.replace(ad_string_to_replace, "")
        await update.message.edit_caption(caption=error_message)
        return False, None
    if t_response:
        # LOGGER.info(t_response)
        # os.remove(save_ytdl_json_path)
        end_one = datetime.now()
        time_taken_for_download = (end_one - start).seconds
        dir_contents = os.listdir(tmp_directory_for_each_user)
        # dir_contents.sort()
        await update.message.edit_caption(
            f"found {len(dir_contents)} files"
            f"\n Download took {time_taken_for_download} seconds"
            "\n Trying to Upload, now ...")
        LOGGER.info(dir_contents)
        #
        for single_file in dir_contents:
            local_file_name = os.path.join(tmp_directory_for_each_user,
                                           single_file)
            thumb = await is_thumb_image_exists(local_file_name)
            # caption_str = os.path.basename(local_file_name)
            metadata = extractMetadata(createParser(local_file_name))
            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")
            width, height = 0, 0
            if thumb is not None:
                metadata = extractMetadata(createParser(thumb))
                if metadata.has("height"):
                    height = metadata.get("height")
                if metadata.has("width"):
                    height = metadata.get("width")
            if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")):
                await update.message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=description,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True))
            elif local_file_name.upper().endswith(
                ("MP3", "M4A", "M4B", "FLAC", "WAV")):
                await update.message.edit_media(media=InputMediaAudio(
                    media=local_file_name,
                    thumb=thumb,
                    caption=description,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title)
                                                # quote=True,
                                                )
            else:
                await update.message.edit_media(media=InputMediaDocument(
                    media=local_file_name,
                    thumb=thumb,
                    caption=description,
                    parse_mode="html")
                                                # quote=True,
                                                )
        #
        try:
            shutil.rmtree(tmp_directory_for_each_user)
        except:
            pass
async def catch_youtube_dldata(c, q):
    cb_data = q.data
    # caption = q.message.caption
    user_id = q.from_user.id
    # Callback Data Assigning
    media_type, send_as, format_id, av_codec, video_id = cb_data.split("|")
    LOGGER.info(cb_data)

    filext = "%(title)s.%(ext)s"
    userdir = os.path.join(os.getcwd(), Config.DOWNLOAD_DIR, str(user_id),
                           video_id)

    if not os.path.isdir(userdir):
        os.makedirs(userdir)
    await q.edit_message_reply_markup(
        InlineKeyboardMarkup(
            [[InlineKeyboardButton("Downloading...", callback_data="down")]]))
    filepath = os.path.join(userdir, filext)
    # await q.edit_message_reply_markup([[InlineKeyboardButton("Processing..")]])

    fetch_media, caption = await yt_download(video_id, media_type, av_codec,
                                             format_id, filepath)
    if not fetch_media:
        await q.message.reply_text(caption)
        shutil.rmtree(userdir, ignore_errors=True)
        await q.message.delete()
        return
    else:
        LOGGER.info(os.listdir(userdir))
        for content in os.listdir(userdir):
            if ".jpg" not in content:
                file_name = os.path.join(userdir, content)

    thumb = os.path.join(userdir, video_id + ".jpg")
    width = height = 0
    if os.path.isfile(thumb):
        width, height = width_and_height(thumb)
    else:
        thumb = None

    duration = media_duration(file_name)
    if send_as == "Audio":
        med = InputMediaAudio(
            media=file_name,
            thumb=thumb,
            duration=duration,
            caption=caption,
            title=caption,
        )

    elif send_as == "Video":
        med = InputMediaVideo(
            media=file_name,
            thumb=thumb,
            width=width,
            height=height,
            duration=duration,
            caption=caption,
            supports_streaming=True,
        )

    else:
        med = InputMediaDocument(
            media=file_name,
            thumb=thumb,
            caption=caption,
        )

    if med:
        loop = asyncio.get_event_loop()
        loop.create_task(send_file(c, q, med, video_id, userdir))
    else:
        LOGGER.info("Media not found")
示例#15
0
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None):
    if database is not None:
        if database.get_cancel_status(message.chat_id,message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
    
    file_name = os.path.basename(path)
    caption_str = ""
    caption_str += "<code>"
    caption_str += file_name
    caption_str += "</code>"

    if user_msg is None:
        user_msg = await message.get_reply_message()

    force_docs = get_val("FORCE_DOCUMENTS")
    if user_msg is not None:
        force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id)
    
    # Avoid Flood in Express
    await asyncio.sleep(int(get_val("EDIT_SLEEP_SECS"))+5)

    metadata = extractMetadata(createParser(path))
    
    if metadata is not None:
        # handle none for unknown
        metadata = metadata.exportDictionary()
        try:
            mime = metadata.get("Common").get("MIME type")
        except:
            mime = metadata.get("Metadata").get("MIME type")

        ftype = mime.split("/")[0]
        ftype = ftype.lower().strip()
    else:
        ftype = "unknown"

    thonmsg = message
    message = await message.client.pyro.get_messages(message.chat_id, message.id)
    tout = get_val("EDIT_SLEEP_SECS")
    sent_message = None
    start_time = time.time()
    #
    if user_msg is not None:
        dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id)
        if dis_thumb is False or dis_thumb is None:
            thumb_image_path = user_db.get_thumbnail(user_msg.sender_id)
            if not thumb_image_path:
                thumb_image_path = None
    #
    try:
        message_for_progress_display = message
        if not force_edit:
            data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id)
            markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]])
            message_for_progress_display = await message.reply_text(
                "📤 **Starting upload of** `{}`".format(os.path.basename(path)),
                reply_markup=markup
            )
        
        if ftype == "video" and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            if thumb_image_path is None:
                thumb_image_path = await thumb_manage.get_thumbnail(path)
                # get the correct width, height, and duration for videos greater than 10MB

            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            
            # send video
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        width=width,
                        height=height,
                        duration=duration,
                        supports_streaming=True,
                        caption=caption_str
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    caption=caption_str,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        elif ftype == "audio" and not force_docs:
            metadata = extractMetadata(createParser(path))
            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")
            
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        caption=caption_str
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    caption=caption_str,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        else:
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(
                        media=path,
                        caption=caption_str,
                        thumb=thumb,
                        parse_mode="html"
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=path,
                    # quote=True,
                    thumb=thumb,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    caption=caption_str,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("Canceled an upload lol")
            try:
                await message_for_progress_display.edit(f"Failed to upload {e}")
            except:pass
        else:
            try:
                await message_for_progress_display.edit(f"Failed to upload {e}")
            except:pass
            torlog.exception("IN Pyro upload")
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    #os.remove(path)
    if sent_message is None:
        return None
    sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id)
    return sent_message
示例#16
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                      str(from_user) + ".jpg")
    LOGGER.info(thumbnail_location)
    #
    try:
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name)))
        if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            thumb_image_path = None
            if os.path.exists(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            else:
                thumb_image_path = await take_screen_shot(
                    local_file_name,
                    os.path.dirname(os.path.abspath(local_file_name)),
                    (duration / 2))
                # get the correct width, height, and duration for videos greater than 10MB
                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")
                    # resize image
                    # ref: https://t.me/PyrogramChat/44663
                    # https://stackoverflow.com/a/21669827/4723940
                    Image.open(thumb_image_path).convert("RGB").save(
                        thumb_image_path)
                    img = Image.open(thumb_image_path)
                    # https://stackoverflow.com/a/37631799/4723940
                    img.resize((320, height))
                    img.save(thumb_image_path, "JPEG")
                    # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
            #
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send video
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        elif local_file_name.upper().endswith(
            ("MP3", "M4A", "M4B", "FLAC", "WAV")):
            metadata = extractMetadata(createParser(local_file_name))
            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")
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          duration=duration,
                                          performer=artist,
                                          title=title)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        else:
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(media=local_file_name,
                                             thumb=thumb,
                                             caption=caption_str,
                                             parse_mode="html")
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=local_file_name,
                    # quote=True,
                    thumb=thumb,
                    caption=caption_str,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    # os.remove(local_file_name)
    return sent_message
示例#17
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):

    base_file_name = os.path.basename(local_file_name)
    if len(base_file_name) > 64 and base_file_name.lower().startswith(
        ("@dramaost", "[d&o]")):
        status_message = await message.reply_text("Renaming start")
        h = base_file_name
        c_h = local_file_name
        out_dir = os.path.dirname(os.path.abspath(local_file_name))
        g = f"opus opus2.0 aac aac2.0 ddp5.1 ddp2.0 ddp2 h264 h.264 x264 10bit 2017 2018 2019 2020 2021 nf webdl web-dl webrip webhd web-hd web-rip".split(
            " ")
        c = 0
        f = h.lower()
        f = re.sub("_", '.', f)
        f = re.sub("web.dl", 'webdl', f)
        if f[:3] == "d&o":
            f = re.sub("d&o", '[d&o]', f)
        for i in g:
            if len(f) <= 64:
                break
            if re.search(i, f):
                f = re.sub("." + i, '', f)
        if len(f) > 64:
            f = re.sub("@dramaost.", '', f)
        p = f.split('.')
        s = '.'.join(i.capitalize() for i in p)
        s = re.sub("Nf", 'NF', s)
        s = re.sub("Web-dl", 'WEB-DL', s)
        s = re.sub("Webdl", 'WEB-DL', s)
        s = re.sub("Webrip", 'WEBRip', s)
        s = re.sub("Sh3lby", 'SH3LBY', s)
        s = re.sub("sh3lby", 'SH3LBY', s)
        s = re.sub("ost", 'OST', s)
        s = re.sub("Mkv", 'mkv', s)
        s = re.sub("d&o", 'D&O', s)
        s = re.sub("D&o", 'D&O', s)
        s = re.sub("S01e", 'S01E', s)
        s = re.sub("S02e", 'S02E', s)
        s = re.sub("S03e", 'S03E', s)
        s = re.sub("S04e", 'S04E', s)
        s = re.sub("X265", 'x265', s)
        s = re.sub("X264", 'x264', s)
        out_file_name = os.path.join(out_dir, s)
        os.rename(local_file_name, out_file_name)
        local_file_name = out_file_name
        await status_message.edit(
            f"Old Name - <code>{c_h}</code>\n\nNew Name - <code>{local_file_name}</code>"
        )
    elif not base_file_name.lower().startswith(
        ("kdg")) and re.search('_', base_file_name.lower()):
        await message.reply_text(
            f"<code>{local_file_name}</code>\n\nfile name contain underscore please rename it"
        )
    else:
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        sent_message = None
        start_time = time.time()
        #
        thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                          str(from_user) + ".jpg")
        LOGGER.info(thumbnail_location)
        #
        try:
            message_for_progress_display = message
            if not edit_media:
                message_for_progress_display = await message.reply_text(
                    "starting upload of {}".format(
                        os.path.basename(local_file_name)))
            if local_file_name.upper().endswith(
                ("WEBM", "MP4")) and not local_file_name.upper().startswith(
                    ("KDG")):
                metadata = extractMetadata(createParser(local_file_name))
                duration = 0
                if metadata.has("duration"):
                    duration = metadata.get('duration').seconds
                #
                width = 0
                height = 0
                thumb_image_path = None
                if os.path.exists(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                else:
                    thumb_image_path = await take_screen_shot(
                        local_file_name,
                        os.path.dirname(os.path.abspath(local_file_name)),
                        (duration / 2))
                    # get the correct width, height, and duration for videos greater than 10MB
                    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")
                        # resize image
                        # ref: https://t.me/PyrogramChat/44663
                        # https://stackoverflow.com/a/21669827/4723940
                        Image.open(thumb_image_path).convert("RGB").save(
                            thumb_image_path)
                        img = Image.open(thumb_image_path)
                        # https://stackoverflow.com/a/37631799/4723940
                        img.resize((320, height))
                        img.save(thumb_image_path, "JPEG")
                        # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
                #
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                # send video
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaVideo(media=local_file_name,
                                              thumb=thumb,
                                              caption=caption_str,
                                              parse_mode="html",
                                              width=width,
                                              height=height,
                                              duration=duration,
                                              supports_streaming=True)
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_video(
                        video=local_file_name,
                        # quote=True,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        width=width,
                        height=height,
                        thumb=thumb,
                        supports_streaming=True,
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))
                if thumb is not None:
                    os.remove(thumb)
            elif local_file_name.upper().endswith(
                ("MP3", "M4A", "M4B", "FLAC", "WAV")):
                metadata = extractMetadata(createParser(local_file_name))
                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")
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                # send audio
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaAudio(media=local_file_name,
                                              thumb=thumb,
                                              caption=caption_str,
                                              parse_mode="html",
                                              duration=duration,
                                              performer=artist,
                                              title=title)
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_audio(
                        audio=local_file_name,
                        # quote=True,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        thumb=thumb,
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))
                if thumb is not None:
                    os.remove(thumb)
            else:
                base_file_name = os.path.basename(local_file_name)
                base_new_name = os.path.splitext(base_file_name)[0]
                extension_new_name = os.path.splitext(base_file_name)[1]
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                # if a file, don't upload "thumb"
                # this "diff" is a major derp -_- 😔😭😭
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                #
                # send document
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaDocument(media=local_file_name,
                                                 thumb=thumb,
                                                 caption=caption_str,
                                                 parse_mode="html")
                        # quote=True,
                    )
                elif base_file_name.lower().startswith(("@dramaost", "[d&o]")):
                    for l, s in zip(name_ids, chan_ids):
                        h = l.lower()
                        b = base_file_name.lower()
                        if re.search(h, b):
                            m4 = f"<b>Join: {s}</b>"
                            caption_str = re.sub(".mkv",
                                                 f".mkv</code>\n\n{m4}",
                                                 caption_str)
                            break
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        # quote=True,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))

                else:
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        # quote=True,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))

                if thumb is not None:
                    os.remove(thumb)
        except Exception as e:
            await message_for_progress_display.edit_text("**FAILED**\n" +
                                                         str(e))
        else:
            if message.message_id != message_for_progress_display.message_id:
                await message_for_progress_display.delete()
        os.remove(local_file_name)
        return sent_message