async def incoming_compress_message_f(bot, update):
    """/compress command"""

    if update.from_user.id not in AUTH_USERS:
        try:
            await update.message.delete()
        except:
            pass
        return
    if update.reply_to_message is None:
        try:
            await bot.send_message(chat_id=update.chat.id,
                                   text="ЁЯдм Reply to telegram media ЁЯдм",
                                   reply_to_message_id=update.message_id)
        except:
            pass
        return
    target_percentage = 50
    isAuto = False
    if len(update.command) > 1:
        try:
            if int(update.command[1]) <= 90 and int(update.command[1]) >= 10:
                target_percentage = int(update.command[1])
            else:
                try:
                    await bot.send_message(
                        chat_id=update.chat.id,
                        text="ЁЯдм Value should be 10 - 90",
                        reply_to_message_id=update.message_id)
                    return
                except:
                    pass
        except:
            pass
    else:
        isAuto = True
    user_file = str(update.from_user.id) + ".FFMpegRoBot.mkv"
    saved_file_path = DOWNLOAD_LOCATION + "/" + user_file
    LOGGER.info(saved_file_path)
    d_start = time.time()
    c_start = time.time()
    u_start = time.time()
    status = DOWNLOAD_LOCATION + "/status.json"
    if not os.path.exists(status):
        sent_message = await bot.send_message(
            chat_id=update.chat.id,
            text=Localisation.DOWNLOAD_START,
            reply_to_message_id=update.message_id)
        try:
            d_start = time.time()
            status = DOWNLOAD_LOCATION + "/status.json"
            with open(status, 'w') as f:
                statusMsg = {
                    'running': True,
                    'message': sent_message.message_id
                }

                json.dump(statusMsg, f, indent=2)
            video = await bot.download_media(
                message=update.reply_to_message,
                file_name=saved_file_path,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.DOWNLOAD_START, sent_message,
                               d_start))
            LOGGER.info(video)
            if (video is None):
                try:
                    await sent_message.edit_text(text="Download stopped")
                except:
                    pass
                delete_downloads()
                LOGGER.info("Download stopped")
                return
        except (ValueError) as e:
            try:
                await sent_message.edit_text(text=str(e))
            except:
                pass
            delete_downloads()
        try:
            await sent_message.edit_text(text=Localisation.SAVED_RECVD_DOC_FILE
                                         )
        except:
            pass
    else:
        try:
            await bot.send_message(
                chat_id=update.chat.id,
                text=Localisation.FF_MPEG_RO_BOT_STOR_AGE_ALREADY_EXISTS,
                reply_to_message_id=update.message_id)
        except:
            pass
        return

    if os.path.exists(saved_file_path):
        downloaded_time = TimeFormatter((time.time() - d_start) * 1000)
        duration, bitrate = await media_info(saved_file_path)
        if duration is None or bitrate is None:
            try:
                await sent_message.edit_text(
                    text="тЪая╕П Getting video meta data failed тЪая╕П")
            except:
                pass
            delete_downloads()
            return
        thumb_image_path = await take_screen_shot(
            saved_file_path, os.path.dirname(os.path.abspath(saved_file_path)),
            (duration / 2))
        await sent_message.edit_text(text=Localisation.COMPRESS_START)
        c_start = time.time()
        o = await convert_video(saved_file_path, DOWNLOAD_LOCATION, duration,
                                bot, sent_message, target_percentage, isAuto)
        compressed_time = TimeFormatter((time.time() - c_start) * 1000)
        LOGGER.info(o)
        if o == 'stopped':
            return
        if o is not None:
            await sent_message.edit_text(text=Localisation.UPLOAD_START, )
            u_start = time.time()
            caption = Localisation.COMPRESS_SUCCESS.replace(
                '{}', downloaded_time, 1).replace('{}', compressed_time, 1)
            upload = await bot.send_video(
                chat_id=update.chat.id,
                video=o,
                caption=caption,
                supports_streaming=True,
                duration=duration,
                thumb=thumb_image_path,
                reply_to_message_id=update.message_id,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.UPLOAD_START, sent_message,
                               u_start))
            if (upload is None):
                try:
                    await sent_message.edit_text(text="Upload stopped")
                except:
                    pass
                delete_downloads()
                return
            uploaded_time = TimeFormatter((time.time() - u_start) * 1000)
            await sent_message.delete()
            delete_downloads()
            LOGGER.info(upload.caption)
            try:
                await upload.edit_caption(
                    caption=upload.caption.replace('{}', uploaded_time))
            except:
                pass
        else:
            delete_downloads()
            try:
                await sent_message.edit_text(
                    text="тЪая╕П Compression failed тЪая╕П")
            except:
                pass

    else:
        delete_downloads()
        try:
            await sent_message.edit_text(
                text="тЪая╕П Failed Downloaded path not exist тЪая╕П")
        except:
            pass
예제 #2
0
async def convert_video(video_file, output_directory, total_time, bot, message, target_percentage, isAuto):
    # https://stackoverflow.com/a/13891070/4723940
    out_put_file_name = output_directory + \
        "/" + str(round(time.time())) + ".mp4"
    progress = output_directory + "/" + "progress.txt"
    with open(progress, 'w') as f:
      pass
    
    file_genertor_command = [
      "ffmpeg",
      "-hide_banner",
      "-loglevel",
      "quiet",
      "-progress",
      progress,
      "-i",
      video_file,
      "-c:v", 
      "h264",
      "-preset", 
      "ultrafast",
      "-tune",
      "film",
      "-c:a",
      "copy",
      out_put_file_name
    ]
    if not isAuto:
      filesize = os.stat(video_file).st_size
      calculated_percentage = 100 - target_percentage
      target_size = ( calculated_percentage / 100 ) * filesize
      target_bitrate = int(math.floor( target_size * 8 / total_time ))
      if target_bitrate // 1000000 >= 1:
        bitrate = str(target_bitrate//1000000) + "M"
      elif target_bitrate // 1000 > 1:
        bitrate = str(target_bitrate//1000) + "k"
      else:
        return None
      extra = [ "-b:v", 
                bitrate,
                "-bufsize",
                bitrate
              ]
      for elem in reversed(extra) :
        file_genertor_command.insert(10, elem)
    else:
       target_percentage = 'auto'
    COMPRESSION_START_TIME = time.time()
    process = await asyncio.create_subprocess_exec(
        *file_genertor_command,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    LOGGER.info("ffmpeg_process: "+str(process.pid))
    status = output_directory + "/status.json"
    with open(status, 'r+') as f:
      statusMsg = json.load(f)
      statusMsg['pid'] = process.pid
      statusMsg['message'] = message.message_id
      f.seek(0)
      json.dump(statusMsg,f,indent=2)
    # os.kill(process.pid, 9)
    isDone = False
    while process.returncode != 0:
      await asyncio.sleep(3)
      with open("/app/DOWNLOADS/progress.txt",'r+') as file:
        text = file.read()
        frame = re.findall("frame=(\d+)", text)
        time_in_us=re.findall("out_time_ms=(\d+)", text)
        progress=re.findall("progress=(\w+)", text)
        speed=re.findall("speed=(\d+\.?\d*)", text)
        if len(frame):
          frame = int(frame[-1])
        else:
          frame = 1;
        if len(speed):
          speed = speed[-1]
        else:
          speed = 1;
        if len(time_in_us):
          time_in_us = time_in_us[-1]
        else:
          time_in_us = 1;
        if len(progress):
          if progress[-1] == "end":
            LOGGER.info(progress[-1])
            isDone = True
            break
        execution_time = TimeFormatter((time.time() - COMPRESSION_START_TIME)*1000)
        elapsed_time = int(time_in_us)/1000000
        difference = math.floor( (total_time - elapsed_time) / float(speed) )
        ETA = "-"
        if difference > 0:
          ETA = TimeFormatter(difference*1000)
        percentage = math.floor(elapsed_time * 100 / total_time)
        progress_str = "⭕<b>Progress:</b> {0}%\n[{1}{2}]".format(
            round(percentage, 2),
            ''.join(["□" for i in range(math.floor(percentage / 5))]),
            ''.join(["■" for i in range(20 - math.floor(percentage / 5))])
            )
        stats = f'⭕<b>Compressing</b> {target_percentage}%\n\n' \
                f'⭕<b>ETA:</b> {ETA}\n\n' \
                f'{progress_str}\n'
        try:
          await message.edit_text(
            text=stats
          )
        except:
            pass
        
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    #if( not isDone):
      #return None
    e_response = stderr.decode().strip()
    t_response = stdout.decode().strip()
    LOGGER.info(e_response)
    LOGGER.info(t_response)
    if os.path.lexists(out_put_file_name):
        return out_put_file_name
    else:
        return None
예제 #3
0
async def convert_video(video_file, output_directory, total_time, bot, message,
                        chan_msg):
    # https://stackoverflow.com/a/13891070/4723940
    out_put_file_name = output_directory + \
        "/" + str(round(time.time())) + ".mp4"
    progress = output_directory + "/" + "progress.txt"
    with open(progress, 'w') as f:
        pass

    file_genertor_command = [
        "ffmpeg", "-hide_banner", "-loglevel", "quiet", "-progress", progress,
        "-i", video_file, "-c:v", "libx265", "-vtag", "hvc1", "-preset",
        "ultrafast", "-c:a", "copy", out_put_file_name
    ]
    #Done !!
    COMPRESSION_START_TIME = time.time()
    process = await asyncio.create_subprocess_exec(
        *file_genertor_command,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    LOGGER.info("ffmpeg_process: " + str(process.pid))
    status = output_directory + "/status.json"
    with open(status, 'r+') as f:
        statusMsg = json.load(f)
        statusMsg['pid'] = process.pid
        statusMsg['message'] = message.message_id
        f.seek(0)
        json.dump(statusMsg, f, indent=2)
    # os.kill(process.pid, 9)
    isDone = False
    while process.returncode != 0:
        await asyncio.sleep(3)
        with open("/app/downloads/progress.txt", 'r+') as file:
            text = file.read()
            frame = re.findall("frame=(\d+)", text)
            time_in_us = re.findall("out_time_ms=(\d+)", text)
            progress = re.findall("progress=(\w+)", text)
            speed = re.findall("speed=(\d+\.?\d*)", text)
            if len(frame):
                frame = int(frame[-1])
            else:
                frame = 1
            if len(speed):
                speed = speed[-1]
            else:
                speed = 1
            if len(time_in_us):
                time_in_us = time_in_us[-1]
            else:
                time_in_us = 1
            if len(progress):
                if progress[-1] == "end":
                    LOGGER.info(progress[-1])
                    isDone = True
                    break
            execution_time = TimeFormatter(
                (time.time() - COMPRESSION_START_TIME) * 1000)
            elapsed_time = int(time_in_us) / 1000000
            difference = math.floor((total_time - elapsed_time) / float(speed))
            ETA = "-"
            if difference > 0:
                ETA = TimeFormatter(difference * 1000)
            percentage = math.floor(elapsed_time * 100 / total_time)
            progress_str = "📊 <b>Progress:</b> {0}%\n[{1}{2}] \n\n© @TheAzimOff | @Discovery_Updates".format(
                round(percentage, 2), ''.join([
                    FINISHED_PROGRESS_STR
                    for i in range(math.floor(percentage / 10))
                ]), ''.join([
                    UN_FINISHED_PROGRESS_STR
                    for i in range(10 - math.floor(percentage / 10))
                ]))
            stats = f'📦️ <b>Converting To H256 </b>\n\n' \
                    f'⏰️ <b>TimeLeft:</b> {ETA}\n\n' \
                    f'{progress_str}\n'
            try:
                await message.edit_text(text=stats)
            except:
                pass

            try:
                await chan_msg.edit_text(text=stats)
            except:
                pass

    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    #if( not isDone):
    #return None
    e_response = stderr.decode().strip()
    t_response = stdout.decode().strip()
    LOGGER.info(e_response)
    LOGGER.info(t_response)
    if os.path.lexists(out_put_file_name):
        return out_put_file_name
    else:
        return None
예제 #4
0
async def incoming_compress_message_f(bot, update):
    """/compress command"""
    update_channel = UPDATES_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
                await bot.send_message(
                    chat_id=update.chat.id,
                    text=
                    "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/UniversalBotsSupport).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            await bot.send_message(
                chat_id=update.chat.id,
                text="**Please Join My Updates Channel to use this Bot!**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton("Join Updates Channel",
                                         url=f"https://t.me/{update_channel}")
                ]]),
                parse_mode="markdown")
            return
        except Exception:
            await bot.send_message(
                chat_id=update.chat.id,
                text=
                f"Add me into your [Updates Channel](https://t.me/{update_channel}), for more help Contact my [Support Group](https://t.me/UniversalBotsSupport).",
                parse_mode="markdown",
                disable_web_page_preview=True)
            return
    if update.reply_to_message is None:
        try:
            await bot.send_message(chat_id=update.chat.id,
                                   text="ЁЯдм Reply to telegram media ЁЯдм",
                                   reply_to_message_id=update.message_id)
        except:
            pass
        return
    target_percentage = 50
    isAuto = False
    if len(update.command) > 1:
        try:
            if int(update.command[1]) <= 90 and int(update.command[1]) >= 10:
                target_percentage = int(update.command[1])
            else:
                try:
                    await bot.send_message(
                        chat_id=update.chat.id,
                        text="ЁЯдм Value should be 10 to 90",
                        reply_to_message_id=update.message_id)
                    return
                except:
                    pass
        except:
            pass
    else:
        isAuto = True
    user_file = str(update.from_user.id) + ".FFMpegRoBot.mkv"
    saved_file_path = DOWNLOAD_LOCATION + "/" + user_file
    LOGGER.info(saved_file_path)
    d_start = time.time()
    c_start = time.time()
    u_start = time.time()
    status = DOWNLOAD_LOCATION + "/status.json"
    if not os.path.exists(status):
        sent_message = await bot.send_message(
            chat_id=update.chat.id,
            text=Localisation.DOWNLOAD_START,
            reply_to_message_id=update.message_id)
        chat_id = LOG_CHANNEL
        utc_now = datetime.datetime.utcnow()
        ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
        ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
        bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
        bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
        now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
        download_start = await bot.send_message(
            chat_id,
            f"**Bot Become Busy Now !!** \n\nDownload Started at `{now}`",
            parse_mode="markdown")
        try:
            d_start = time.time()
            status = DOWNLOAD_LOCATION + "/status.json"
            with open(status, 'w') as f:
                statusMsg = {
                    'running': True,
                    'message': sent_message.message_id
                }

                json.dump(statusMsg, f, indent=2)
            video = await bot.download_media(
                message=update.reply_to_message,
                file_name=saved_file_path,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.DOWNLOAD_START, sent_message,
                               d_start))
            LOGGER.info(video)
            if (video is None):
                try:
                    await sent_message.edit_text(text="Download stopped")
                    chat_id = LOG_CHANNEL
                    utc_now = datetime.datetime.utcnow()
                    ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                    ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                    bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                    bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                    now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                    await bot.send_message(
                        chat_id,
                        f"**Download Stopped, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                        parse_mode="markdown")
                    await download_start.delete()
                except:
                    pass
                delete_downloads()
                LOGGER.info("Download stopped")
                return
        except (ValueError) as e:
            try:
                await sent_message.edit_text(text=str(e))
            except:
                pass
            delete_downloads()
        try:
            await sent_message.edit_text(text=Localisation.SAVED_RECVD_DOC_FILE
                                         )
        except:
            pass
    else:
        try:
            await bot.send_message(
                chat_id=update.chat.id,
                text=Localisation.FF_MPEG_RO_BOT_STOR_AGE_ALREADY_EXISTS,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton('Show Bot Status',
                                         url=f'https://t.me/{LOG_CHANNEL}'
                                         )  # That's Username na ...
                ]]),
                reply_to_message_id=update.message_id)
        except:
            pass
        return

    if os.path.exists(saved_file_path):
        downloaded_time = TimeFormatter((time.time() - d_start) * 1000)
        duration, bitrate = await media_info(saved_file_path)
        if duration is None or bitrate is None:
            try:
                await sent_message.edit_text(
                    text="тЪая╕П Getting video meta data failed тЪая╕П")
                chat_id = LOG_CHANNEL
                utc_now = datetime.datetime.utcnow()
                ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                await bot.send_message(
                    chat_id,
                    f"**Download Failed, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                    parse_mode="markdown")
                await download_start.delete()
            except:
                pass
            delete_downloads()
            return
        thumb_image_path = await take_screen_shot(
            saved_file_path, os.path.dirname(os.path.abspath(saved_file_path)),
            (duration / 2))
        chat_id = LOG_CHANNEL
        utc_now = datetime.datetime.utcnow()
        ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
        ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
        bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
        bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
        now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
        await download_start.delete()
        compress_start = await bot.send_message(
            chat_id,
            f"**Compressing Video ...** \n\nProcess Started at `{now}`",
            parse_mode="markdown")
        await sent_message.edit_text(text=Localisation.COMPRESS_START)
        c_start = time.time()
        o = await convert_video(saved_file_path, DOWNLOAD_LOCATION, duration,
                                bot, sent_message, target_percentage, isAuto)
        compressed_time = TimeFormatter((time.time() - c_start) * 1000)
        LOGGER.info(o)
        if o == 'stopped':
            return
        if o is not None:
            chat_id = LOG_CHANNEL
            utc_now = datetime.datetime.utcnow()
            ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
            ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
            bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
            bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
            now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
            await compress_start.delete()
            upload_start = await bot.send_message(
                chat_id,
                f"**Uploading Video ...** \n\nProcess Started at `{now}`",
                parse_mode="markdown")
            await sent_message.edit_text(text=Localisation.UPLOAD_START, )
            u_start = time.time()
            caption = Localisation.COMPRESS_SUCCESS.replace(
                '{}', downloaded_time, 1).replace('{}', compressed_time, 1)
            upload = await bot.send_video(
                chat_id=update.chat.id,
                video=o,
                caption=caption,
                supports_streaming=True,
                duration=duration,
                thumb=thumb_image_path,
                reply_to_message_id=update.message_id,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.UPLOAD_START, sent_message,
                               u_start))
            if (upload is None):
                try:
                    await sent_message.edit_text(text="Upload stopped")
                    chat_id = LOG_CHANNEL
                    utc_now = datetime.datetime.utcnow()
                    ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                    ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                    bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                    bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                    now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                    await bot.send_message(
                        chat_id,
                        f"**Upload Stopped, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                        parse_mode="markdown")
                    await upload_start.delete()
                except:
                    pass
                delete_downloads()
                return
            uploaded_time = TimeFormatter((time.time() - u_start) * 1000)
            await sent_message.delete()
            delete_downloads()
            chat_id = LOG_CHANNEL
            utc_now = datetime.datetime.utcnow()
            ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
            ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
            bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
            bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
            now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
            await upload_start.delete()
            await bot.send_message(
                chat_id,
                f"**Upload Done, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                parse_mode="markdown")
            LOGGER.info(upload.caption)
            try:
                await upload.edit_caption(
                    caption=upload.caption.replace('{}', uploaded_time))
            except:
                pass
        else:
            delete_downloads()
            try:
                await sent_message.edit_text(
                    text="тЪая╕П Compression failed тЪая╕П")
                chat_id = LOG_CHANNEL
                now = datetime.datetime.now()
                await bot.send_message(
                    chat_id,
                    f"**Compression Failed, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                    parse_mode="markdown")
                await download_start.delete()
            except:
                pass

    else:
        delete_downloads()
        try:
            await sent_message.edit_text(
                text="тЪая╕П Failed Downloaded path not exist тЪая╕П")
            chat_id = LOG_CHANNEL
            utc_now = datetime.datetime.utcnow()
            ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
            ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
            bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
            bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
            now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
            await bot.send_message(
                chat_id,
                f"**Download Error, Bot is Free Now !!** \n\nProcess Done at `{now}`",
                parse_mode="markdown")
            await download_start.delete()
        except:
            pass
예제 #5
0
async def incoming_compress_message_f(bot, update):
    """/compress command"""
    update_channel = UPDATES_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
                await bot.send_message(
                    chat_id=update.chat.id,
                    text=
                    "**Sorry Sir, You Are Banned From Using Me. Contact My** [Support Bot](https://t.me/FlixHelpBot).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            await bot.send_message(
                chat_id=update.chat.id,
                text=
                "**Please Join My Updates Channel Below To Use This Bot!**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton("Join Our Updates Channel 📢",
                                         url=f"https://t.me/{update_channel}")
                ]]),
                parse_mode="markdown")
            return
        except Exception:
            await bot.send_message(
                chat_id=update.chat.id,
                text=
                "**Something Went Wrong. Contact My [Support Bot](https://t.me/FlixHelpBot).",
                parse_mode="markdown",
                disable_web_page_preview=True)
            return
    if update.reply_to_message is None:
        try:
            await bot.send_message(chat_id=update.chat.id,
                                   text="🤬 Reply to telegram media 🤬",
                                   reply_to_message_id=update.message_id)
        except:
            pass
        return
    target_percentage = 50
    isAuto = False
    if len(update.command) > 1:
        try:
            if int(update.command[1]) <= 90 and int(update.command[1]) >= 10:
                target_percentage = int(update.command[1])
            else:
                try:
                    await bot.send_message(
                        chat_id=update.chat.id,
                        text="🤬 Value should be 10 to 90",
                        reply_to_message_id=update.message_id)
                    return
                except:
                    pass
        except:
            pass
    else:
        isAuto = True
    user_file = str(update.from_user.id) + ".FFMpegRoBot.mkv"
    saved_file_path = DOWNLOAD_LOCATION + "/" + user_file
    LOGGER.info(saved_file_path)
    d_start = time.time()
    c_start = time.time()
    u_start = time.time()
    status = DOWNLOAD_LOCATION + "/status.json"
    if not os.path.exists(status):
        sent_message = await bot.send_message(
            chat_id=update.chat.id,
            text=Localisation.DOWNLOAD_START,
            reply_to_message_id=update.message_id)
        chat_id = LOG_CHANNEL
        utc_now = datetime.datetime.utcnow()
        ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
        ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
        bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
        bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
        now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
        await bot.send_message(
            chat_id,
            f"**Video Compressing Started\n\nBot Status : Busy Now  🔴**\n\n➤ @CompressFlixBot\n\n**A Process Started At** `{now}`",
            parse_mode="markdown")
        try:
            d_start = time.time()
            status = DOWNLOAD_LOCATION + "/status.json"
            with open(status, 'w') as f:
                statusMsg = {
                    'running': True,
                    'message': sent_message.message_id
                }

                json.dump(statusMsg, f, indent=2)
            video = await bot.download_media(
                message=update.reply_to_message,
                file_name=saved_file_path,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.DOWNLOAD_START, sent_message,
                               d_start))
            LOGGER.info(video)
            if (video is None):
                try:
                    await sent_message.edit_text(text="Download stopped")
                    chat_id = LOG_CHANNEL
                    utc_now = datetime.datetime.utcnow()
                    ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                    ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                    bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                    bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                    now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                    await bot.send_message(
                        chat_id,
                        f"**Download Stopped ❌\n\nBot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Stopped At** `{now}`",
                        parse_mode="markdown")
                except:
                    pass
                delete_downloads()
                LOGGER.info("Download stopped")
                return
        except (ValueError) as e:
            try:
                await sent_message.edit_text(text=str(e))
            except:
                pass
            delete_downloads()
        try:
            await sent_message.edit_text(text=Localisation.SAVED_RECVD_DOC_FILE
                                         )
        except:
            pass
    else:
        try:
            await bot.send_message(
                chat_id=update.chat.id,
                text=Localisation.FF_MPEG_RO_BOT_STOR_AGE_ALREADY_EXISTS,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton('🥳 Bot Status 🥳',
                                         url='https://t.me/CompressFlixLogs'
                                         )  # Replace With Your's
                ]]),
                reply_to_message_id=update.message_id)
        except:
            pass
        return

    if os.path.exists(saved_file_path):
        downloaded_time = TimeFormatter((time.time() - d_start) * 1000)
        duration, bitrate = await media_info(saved_file_path)
        if duration is None or bitrate is None:
            try:
                await sent_message.edit_text(
                    text="⚠️ Getting video meta data failed ⚠️")
                chat_id = LOG_CHANNEL
                utc_now = datetime.datetime.utcnow()
                ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                await bot.send_message(
                    chat_id,
                    f"**Download Failed ❌**\n\n**Bot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Stopped At** `{now}`",
                    parse_mode="markdown")
            except:
                pass
            delete_downloads()
            return
        thumb_image_path = await take_screen_shot(
            saved_file_path, os.path.dirname(os.path.abspath(saved_file_path)),
            (duration / 2))
        await sent_message.edit_text(text=Localisation.COMPRESS_START)
        c_start = time.time()
        o = await convert_video(saved_file_path, DOWNLOAD_LOCATION, duration,
                                bot, sent_message, target_percentage, isAuto)
        compressed_time = TimeFormatter((time.time() - c_start) * 1000)
        LOGGER.info(o)
        if o == 'stopped':
            return
        if o is not None:
            await sent_message.edit_text(text=Localisation.UPLOAD_START, )
            u_start = time.time()
            caption = Localisation.COMPRESS_SUCCESS.replace(
                '{}', downloaded_time, 1).replace('{}', compressed_time, 1)
            upload = await bot.send_video(
                chat_id=update.chat.id,
                video=o,
                caption=caption,
                supports_streaming=True,
                duration=duration,
                thumb=thumb_image_path,
                reply_to_message_id=update.message_id,
                progress=progress_for_pyrogram,
                progress_args=(bot, Localisation.UPLOAD_START, sent_message,
                               u_start))
            if (upload is None):
                try:
                    await sent_message.edit_text(text="Upload stopped")
                    chat_id = LOG_CHANNEL
                    utc_now = datetime.datetime.utcnow()
                    ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                    ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                    bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                    bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                    now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                    await bot.send_message(
                        chat_id,
                        f"**Upload Stopped ❌**\n\n**Bot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Stopped At** `{now}`",
                        parse_mode="markdown")
                except:
                    pass
                delete_downloads()
                return
            uploaded_time = TimeFormatter((time.time() - u_start) * 1000)
            await sent_message.delete()
            delete_downloads()
            chat_id = LOG_CHANNEL
            utc_now = datetime.datetime.utcnow()
            ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
            ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
            bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
            bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
            now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
            await bot.send_message(
                chat_id,
                f"**Uploaded Successfully 🎦**\n\n**Bot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Done At** `{now}`",
                parse_mode="markdown")
            LOGGER.info(upload.caption)
            try:
                await upload.edit_caption(
                    caption=upload.caption.replace('{}', uploaded_time))
            except:
                pass
        else:
            delete_downloads()
            try:
                await sent_message.edit_text(text="⚠️ Compression failed ⚠️")
                chat_id = LOG_CHANNEL
                utc_now = datetime.datetime.utcnow()
                ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
                ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
                bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
                bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
                now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
                await bot.send_message(
                    chat_id,
                    f"**Compression Failed 📀**\n\n**Bot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Stopped At** `{now}`",
                    parse_mode="markdown")
            except:
                pass

    else:
        delete_downloads()
        try:
            await sent_message.edit_text(
                text="⚠️ Failed To Download, Path  Does Not Exist ⚠️")
            chat_id = LOG_CHANNEL
            utc_now = datetime.datetime.utcnow()
            ist_now = utc_now + datetime.timedelta(minutes=30, hours=5)
            ist = ist_now.strftime("%d/%m/%Y, %H:%M:%S")
            bst_now = utc_now + datetime.timedelta(minutes=00, hours=6)
            bst = bst_now.strftime("%d/%m/%Y, %H:%M:%S")
            now = f"\n{ist} (GMT+05:30)`\n`{bst} (GMT+06:00)"
            await bot.send_message(
                chat_id,
                f"**Download Error ‼️**\n\n**Bot Status : Free  🟢**\n\n➤ @CompressFlixBot\n\n**Process Stopped At** `{now}`",
                parse_mode="markdown")
        except:
            pass