示例#1
0
async def upload_to_gdrive(file_upload, message):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    await message.edit_text("🔊 Now Uploading to ☁️ cloud...")
    subprocess.Popen(('touch', 'rclone.conf'), stdout=subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n") as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        tmp = subprocess.Popen([
            'rclone', 'copy', '--config=rclone.conf', f'{file_upload}',
            'DRIVE:'
            f'{destination}', '-v'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        gk_file = re.escape(file_upload)
        print(gk_file)
        with open('filter.txt', 'w+') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
        process1 = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        #os.remove("filter.txt")
        popi, popp = process1.communicate()
        print(popi)
        p = popi.decode("utf-8")
        print(p)
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{p}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        print(gau_link)
        indexurl = f"{INDEX_LINK}/{file_upload}"
        tam_link = requests.utils.requote_uri(indexurl)
        #s_tr = '-'*40
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ FileCloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        button.append([
            pyrogram.InlineKeyboardButton(text="ℹ️ FileIndexUrl ℹ️",
                                          url=f"{tam_link}")
        ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await message.edit_text(
            f"🤖: {file_upload} has been Uploaded successfully to your cloud 🤒",
            reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
    else:
        tt = os.path.join(destination, file_upload)
        print(tt)
        tmp = subprocess.Popen([
            'rclone', 'copy', '--config=rclone.conf', f'{file_upload}',
            'DRIVE:'
            f'{tt}', '-v'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        print(pro)
        g_file = re.escape(file_upload)
        print(g_file)
        with open('filter1.txt', 'w+') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
        process12 = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
        #os.remove("filter1.txt")
        popie, popp = process12.communicate()
        print(popie)
        p = popie.decode("utf-8")
        print(p)
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={p}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        print(gau_link)
        indexurl = f"{INDEX_LINK}/{file_upload}/"
        tam_link = requests.utils.requote_uri(indexurl)
        print(tam_link)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ FolderCloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        button.append([
            pyrogram.InlineKeyboardButton(text="ℹ️ FolderIndexUrl ℹ️",
                                          url=f"{tam_link}")
        ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await message.edit_text(
            f"🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒",
            reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await message.edit_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
async def gdrive_upload(bot, update):
    dl_url, custom_file_name, _, _ = await extract_link(update.reply_to_message, "GLEECH")
    txt = update.text
    logger.info("command is : "+txt)
    if txt.find("rename") > -1 and len(txt[txt.find("rename") + 7:]) > 0:
        custom_file_name = txt[txt.find("rename") + 7:]
        custom_file_name = await sanitize_file_name(custom_file_name)
        custom_file_name = await sanitize_text(custom_file_name)
    logger.info(dl_url)
    logger.info(custom_file_name)
    reply_message = await bot.send_message(
        text=Translation.DOWNLOAD_START,
        chat_id=update.chat.id,
        reply_to_message_id=update.message_id
    )
    tmp_directory_for_each_user = f"{Config.DOWNLOAD_LOCATION}{update.message_id}"
    if not os.path.isdir(tmp_directory_for_each_user):
        os.makedirs(tmp_directory_for_each_user)
    if custom_file_name is None:
        if dl_url.find('workers.dev') > -1 or dl_url.find('uploadbot') > -1:
            custom_file_name = dl_url[dl_url.rindex("/")+1:]
        elif dl_url.find('seedr') > -1:
            custom_file_name = dl_url[int(dl_url.rindex("/")) + 1:int(dl_url.rindex("?"))]
        else:
            if dl_url.rindex("/") > -1 and dl_url.rindex("?") > -1:
                custom_file_name = dl_url[int(dl_url.rindex("/")) + 1:int(dl_url.rindex("?"))]
            else:
                custom_file_name = dl_url[dl_url.rindex("/") + 1:]
        custom_file_name = urllib.parse.unquote(custom_file_name)
    download_directory = tmp_directory_for_each_user + "/" + custom_file_name
    async with aiohttp.ClientSession() as session:
        c_time = time.time()
        try:
            await download_coroutine(
                bot,
                session,
                dl_url,
                download_directory,
                reply_message.chat.id,
                reply_message.message_id,
                c_time
            )
        except :
            await bot.edit_message_text(
                text=Translation.SLOW_URL_DECED,
                chat_id=reply_message.chat.id,
                message_id=reply_message.message_id
            )
            return False
    if os.path.exists(download_directory):
        end_one = datetime.now()
        up_name = pathlib.PurePath(download_directory).name
        size= get_readable_file_size(get_path_size(download_directory))
        try:
            await bot.edit_message_text(
                text="<b>Download Completed😍😂😁!!!</b> \n<code>Now Started Uploading In Progress...</code>",
                chat_id=reply_message.chat.id,
                message_id=reply_message.message_id
            )
        except Exception as e:
            logger.info(str(e))
            pass
        logger.info(f"Upload Name : {up_name}")
        drive = gdriveTools.GoogleDriveHelper(up_name)
        gd_url,index_url=drive.upload(download_directory)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="⚡ CloudUrl ⚡", url=f"{gd_url}")])
        if Config.INDEX_URL:
            logger.info(index_url)
            button.append([pyrogram.InlineKeyboardButton(text="🔥 IndexUrl 🔥", url=f"{index_url}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await bot.send_message(
            text=f"🤖: <code>{up_name}</code> has been Uploaded successfully to your Cloud🤒 \n📀 Size: {size}",
            chat_id=update.chat.id,
            reply_to_message_id=update.message_id,
            reply_markup=button_markup)
        if Config.INDEX_URL:
            await generate_short_link(reply_message, index_url, custom_file_name)
        await reply_message.delete()
示例#3
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("<b>🔊 Now Uploading to ☁️ Cloud!!!</b>")
    subprocess.Popen(('touch', 'rclone.conf'), stdout=subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n") as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        tmp = subprocess.Popen([
            'rclone', 'copy', '--config=rclone.conf', f'/app/{file_upload}',
            'DRIVE:'
            f'{destination}', '-v'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        gk_file = re.escape(file_upload)
        print(gk_file)
        with open('filter.txt', 'w+') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
        process1 = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        #os.remove("filter.txt")
        popi, popp = process1.communicate()
        print(popi)
        p = popi.decode("utf-8")
        print(p)
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{p}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        print(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="👉 GOOGLE DRIVE URL😎",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            print(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="👉INDEX URL😉",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: {file_upload} <b>has been Uploaded successfully to your Cloud</b> <a href='tg://user?id={g_id}'>😌</a>\n\n<i><b>🛑YOU MUST BE JOIN TEAM DRIVE FOR ACCESS LINK😂 👉 <a href=\"https://groups.google.com/forum/m/#!forum/maxxleech_uplpad\">JOIN_TEAM_DRIVE</a>",
            reply_markup=button_markup,
            disable_web_page_preview=True)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt = os.path.join(destination, file_upload)
        print(tt)
        tmp = subprocess.Popen([
            'rclone', 'copy', '--config=rclone.conf', f'/app/{file_upload}',
            'DRIVE:'
            f'{tt}', '-v'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        print(pro)
        g_file = re.escape(file_upload)
        print(g_file)
        with open('filter1.txt', 'w+') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
        process12 = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
        #os.remove("filter1.txt")
        popie, popp = process12.communicate()
        print(popie)
        p = popie.decode("utf-8")
        print(p)
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={p}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        print(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ FolderCloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            print(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ FolderIndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Folder has been Uploaded successfully to {tt} in your Cloud <a href='tg://user?id={g_id}'>🤒</a>",
            reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#4
0
async def echo(bot, update):
    if update.from_user.id in Config.BANNED_USERS:
        await bot.delete_messages(chat_id=update.chat.id,
                                  message_ids=update.message_id,
                                  revoke=True)
        return
    TRChatBase(update.from_user.id, update.text, "/echo")
    logger.info(update.from_user)
    url = update.text
    youtube_dl_username = None
    youtube_dl_password = None
    file_name = None
    if "|" in url:
        url_parts = url.split("|")
        if len(url_parts) == 2:
            url = url_parts[0]
            file_name = url_parts[1]
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if url is not None:
            url = url.strip()
        if file_name is not None:
            file_name = file_name.strip()
    else:
        for entity in update.entities:
            if entity.type == "text_link":
                url = entity.url
            elif entity.type == "url":
                o = entity.offset
                l = entity.length
                url = url[o:o + l]
    command_to_exec = [
        "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j",
        url
    ]
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    logger.info(e_response)
    t_response = stdout.decode().strip()
    logger.info(t_response)
    if e_response and "nonnumeric port" not in e_response:
        error_message = e_response.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 "This video is only available for registered users." in error_message:
            error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.NO_VOID_FORMAT_FOUND.format(
                                   str(error_message)),
                               reply_to_message_id=update.message_id,
                               parse_mode="html",
                               disable_web_page_preview=True)
        return False
    if t_response:
        x_reponse = t_response
        if "\n" in x_reponse:
            x_reponse, _ = x_reponse.split("\n")
        response_json = json.loads(x_reponse)
        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        format_id = response_json["format_id"]
        format_ext = response_json["ext"]
        inline_keyboard = []
        cb_string_file = "{}={}={}".format("file", format_id, format_ext)
        inline_keyboard.append([
            pyrogram.InlineKeyboardButton(
                "File", callback_data=(cb_string_file).encode("UTF-8"))
        ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.FORMAT_SELECTION,
                               reply_markup=reply_markup,
                               parse_mode="html",
                               reply_to_message_id=update.message_id)
    else:
        inline_keyboard = []
        cb_string_file = "{}={}={}".format("file", "LFO", "NONE")
        inline_keyboard.append([
            pyrogram.InlineKeyboardButton(
                "DFile", callback_data=(cb_string_file).encode("UTF-8"))
        ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.FORMAT_SELECTION,
                               reply_markup=reply_markup,
                               parse_mode="html",
                               reply_to_message_id=update.message_id)
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text(f"<a href='tg://user?id={g_id}'>🔊</a> Now Uploading to ☁️ Cloud!!!")
    #subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding = 'utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = ['rclone', 'copy', '--config=./rclone.conf', f'./{file_upload}', 'DRIVE:'f'{destination}', '-v']
        tmp = await asyncio.create_subprocess_exec(*g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding = 'utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
            
        t_a_m = ['rclone', 'lsf', '--config=./rclone.conf', '-F', 'i', "--filter-from=./filter.txt", "--files-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: Uploaded successfully `{file_upload}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}", reply_markup=button_markup)
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt= os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = ['rclone', 'copy', '--config=./rclone.conf', f'./{file_upload}', 'DRIVE:'f'{tt}', '-v']
        tmp = await asyncio.create_subprocess_exec(*t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding = 'utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
            
        g_a_u = ['rclone', 'lsf', '--config=./rclone.conf', '-F', 'i', "--filter-from=./filter1.txt", "--dirs-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: Uploaded successfully `{file_upload}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}", reply_markup=button_markup)
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#6
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    tam_link = None
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("🔊 Now Uploading to ☁️ Cloud!!!")
    # subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding='utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = [
            'rclone', 'copy', '--config=/app/rclone.conf',
            f'/app/app/main/skabajileech-master/tobrot/DOWNLOADS/{file_upload}',
            'DRIVE:'
            f'{destination}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *g_au,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding='utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)

        t_a_m = [
            'rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i',
            "--filter-from=/app/filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *t_a_m,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        # os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        # indexurl = f"{INDEX_LINK}/{file_upload}"
        # tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            tam_link = tam_link.replace('+', '%2B')
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: {file_upload} has been Uploaded successfully to your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        # await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        if not messa_ge.command[0] in ["rename", "gtleech"]:
            LOGGER.info(
                'deleting the downloaded file after uploading to Gdrive beacuse it is not rename command'
            )
            os.remove(file_upload)
        else:
            LOGGER.info(
                'Not deleting the downloaded file Even after uploading to Gdrive beacuse it is rename command'
            )
        await del_it.delete()
    else:
        tt = os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = [
            'rclone', 'copy', '--config=/app/rclone.conf',
            f'/app/{file_upload}', 'DRIVE:'
            f'{tt}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *t_am,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding='utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)

        g_a_u = [
            'rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i',
            "--filter-from=/app/filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *g_a_u,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        # os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        # indexurl = f"{INDEX_LINK}/{file_upload}/"
        # tam_link = requests.utils.requote_uri(indexurl)
        # print(tam_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            tam_link = tam_link.replace('+', '%2B')
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Folder has been Uploaded successfully to {tt} in your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        # await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        # await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        if not messa_ge.command[0] == "rename":
            LOGGER.info(
                'Not deleting the downloaded file Even after uploading to Gdrive beacuse it is rename command'
            )
            shutil.rmtree(file_upload)
        await del_it.delete()
        # os.remove('rclone.conf')
    if GP_LINKS_API_KEY is not None and tam_link is not None:
        await gplink_generator.generate_gp_link(messa_ge, tam_link,
                                                file_upload)
示例#7
0
def echo(bot, update):
    # logger.info(update)
    TRChatBase(update.from_user.id, update.text, "/echo")
    bot.send_chat_action(chat_id=update.from_user.id, action="typing")
    text = update.text
    if (text.startswith("http")):
        url = text
        if "|" in url:
            if str(update.from_user.id) not in Config.SUPER_DLBOT_USERS:
                bot.send_message(chat_id=update.from_user.id,
                                 text=Translation.NOT_AUTH_USER_TEXT,
                                 reply_to_message_id=update.message_id)
                return
            thumb_image_path = Config.DOWNLOAD_LOCATION + \
                "/" + str(update.from_user.id) + ".jpg"
            if not os.path.exists(thumb_image_path):
                thumb_image_path = None
            else:
                # 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
                new_img = img.resize((90, 90))
                new_img.save(thumb_image_path, "JPEG", optimize=True)
            url, file_name = url.split("|")
            url = url.strip()
            # https://stackoverflow.com/a/761825/4723940
            file_name = file_name.strip()
            logger.info(url)
            logger.info(file_name)
            a = bot.send_message(chat_id=update.from_user.id,
                                 text=Translation.DOWNLOAD_START,
                                 reply_to_message_id=update.message_id)
            after_download_path = DownLoadFile(
                url, Config.DOWNLOAD_LOCATION + "/" + file_name)
            description = Translation.CUSTOM_CAPTION_UL_FILE
            bot.edit_message_text(text=Translation.SAVED_RECVD_DOC_FILE,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id)
            bot.edit_message_text(text=Translation.UPLOAD_START,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id)
            file_size = os.stat(after_download_path).st_size
            if file_size > Config.TG_MAX_FILE_SIZE:
                bot.edit_message_text(text=Translation.RCHD_TG_API_LIMIT,
                                      chat_id=update.from_user.id,
                                      message_id=a.message_id)
            else:
                # try to upload file
                bot.send_document(
                    chat_id=update.from_user.id,
                    document=after_download_path,
                    caption=description,
                    # reply_markup=reply_markup,
                    thumb=thumb_image_path,
                    reply_to_message_id=update.message_id)
                bot.edit_message_text(
                    text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG,
                    chat_id=update.from_user.id,
                    message_id=a.message_id,
                    disable_web_page_preview=True)
            try:
                os.remove(after_download_path)
                os.remove(thumb_image_path)
            except:
                pass
        else:
            try:
                if "hotstar.com" in url:
                    command_to_exec = [
                        "youtube-dl", "--no-warnings", "-j", url, "--proxy",
                        Config.HTTP_PROXY
                    ]
                else:
                    command_to_exec = [
                        "youtube-dl", "--no-warnings", "-j", url
                    ]
                logger.info(command_to_exec)
                t_response = subprocess.check_output(command_to_exec,
                                                     stderr=subprocess.STDOUT)
                # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
            except subprocess.CalledProcessError as exc:
                # print("Status : FAIL", exc.returncode, exc.output)
                bot.send_message(chat_id=update.from_user.id,
                                 text=exc.output.decode("UTF-8"),
                                 reply_to_message_id=update.message_id)
            else:
                # logger.info(t_response)
                x_reponse = t_response.decode("UTF-8")
                response_json = json.loads(x_reponse)
                # logger.info(response_json)
                inline_keyboard = []
                if "formats" in response_json:
                    for formats in response_json["formats"]:
                        format_id = formats["format_id"]
                        format_string = formats["format"]
                        format_ext = formats["ext"]
                        approx_file_size = ""
                        if "filesize" in formats:
                            approx_file_size = humanbytes(formats["filesize"])
                        cb_string = "{}|{}|{}".format("video", format_id,
                                                      format_ext)
                        if not "audio only" in format_string:
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    "[" + format_string + "] (" + format_ext +
                                    " - " + approx_file_size + ")",
                                    callback_data=(cb_string).encode("UTF-8"))
                            ]
                            inline_keyboard.append(ikeyboard)
                    cb_string = "{}|{}|{}".format("audio", "5", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "medium" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
                    cb_string = "{}|{}|{}".format("audio", "0", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "best" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
                else:
                    format_id = response_json["format_id"]
                    format_ext = response_json["ext"]
                    cb_string = "{}|{}|{}".format("file", format_id,
                                                  format_ext)
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "unknown video format",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
                reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
                logger.info(reply_markup)
                thumbnail = Config.DEF_THUMB_NAIL_VID_S
                thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
                if "thumbnail" in response_json:
                    thumbnail = response_json["thumbnail"]
                    thumbnail_image = response_json["thumbnail"]
                thumb_image_path = DownLoadFile(
                    thumbnail_image, Config.DOWNLOAD_LOCATION + "/" +
                    str(update.from_user.id) + ".jpg")
                bot.send_message(
                    chat_id=update.from_user.id,
                    text=Translation.FORMAT_SELECTION.format(thumbnail),
                    reply_markup=reply_markup,
                    parse_mode=pyrogram.ParseMode.HTML,
                    reply_to_message_id=update.message_id)
    elif "===" in text:
        logger.info("cult_small_video")
        if str(update.from_user.id) not in Config.SUPER7X_DLBOT_USERS:
            bot.send_message(chat_id=update.from_user.id,
                             text=Translation.NOT_AUTH_USER_TEXT,
                             reply_to_message_id=update.message_id)
            return
        if update.reply_to_message is not None:
            a = bot.send_message(chat_id=update.from_user.id,
                                 text=Translation.DOWNLOAD_START,
                                 reply_to_message_id=update.message_id)
            url = update.reply_to_message.text
            for entity in update.reply_to_message.entities:
                if entity.type == "text_link":
                    url = entity.url
            start_time, end_time = text.split("===")
            mp4_file = cult_small_video(url, Config.DOWNLOAD_LOCATION,
                                        start_time, end_time)
            bot.edit_message_text(text=Translation.SAVED_RECVD_DOC_FILE,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id)
            thumb_image_path = Config.DOWNLOAD_LOCATION + \
                "/" + str(update.from_user.id) + ".jpg"
            # get the correct width, height, and duration for videos greater than 10MB
            # ref: message from @BotSupport
            width = 0
            height = 0
            duration = 0
            metadata = extractMetadata(createParser(mp4_file))
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            # 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
                new_img = img.resize((90, 90))
                new_img.save(thumb_image_path, "JPEG", optimize=True)
            else:
                thumb_image_path = None
            # try to upload file
            bot.edit_message_text(text=Translation.UPLOAD_START,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id)
            bot.send_video(
                chat_id=update.from_user.id,
                video=mp4_file,
                # caption=description,
                duration=duration,
                width=width,
                height=height,
                supports_streaming=True,
                # reply_markup=reply_markup,
                thumb=thumb_image_path,
                reply_to_message_id=update.reply_to_message.message_id)
            os.remove(mp4_file)
            bot.edit_message_text(text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id,
                                  disable_web_page_preview=True)
        else:
            bot.send_message(chat_id=update.from_user.id,
                             text=Translation.START_TEXT,
                             reply_to_message_id=update.message_id)
    elif ":" in text:
        logger.info("take_screen_shot")
        if str(update.from_user.id) not in Config.SUPER7X_DLBOT_USERS:
            bot.send_message(chat_id=update.from_user.id,
                             text=Translation.FF_MPEG_RO_BOT_RE_SURRECT_ED,
                             reply_to_message_id=update.message_id)
            return
        if update.reply_to_message is not None:
            a = bot.send_message(chat_id=update.from_user.id,
                                 text=Translation.DOWNLOAD_START,
                                 reply_to_message_id=update.message_id)
            url = update.reply_to_message.text
            for entity in update.reply_to_message.entities:
                if entity.type == "text_link":
                    url = entity.url
            img_file = take_screen_shot(url, Config.DOWNLOAD_LOCATION, text)
            # try to upload file
            bot.edit_message_text(text=Translation.UPLOAD_START,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id)
            bot.send_document(
                chat_id=update.from_user.id,
                document=img_file,
                # caption=description,
                # reply_markup=reply_markup,
                # thumb=thumb_image_path,
                reply_to_message_id=update.message_id)
            bot.send_photo(
                chat_id=update.from_user.id,
                photo=img_file,
                # caption=description,
                # reply_markup=reply_markup,
                # thumb=thumb_image_path,
                reply_to_message_id=update.message_id)
            os.remove(img_file)
            bot.edit_message_text(text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG,
                                  chat_id=update.from_user.id,
                                  message_id=a.message_id,
                                  disable_web_page_preview=True)
        else:
            bot.send_message(chat_id=update.from_user.id,
                             text=Translation.FF_MPEG_RO_BOT_RE_SURRECT_ED,
                             reply_to_message_id=update.message_id)
示例#8
0
def echo(bot, update):
    # logger.info(update)
    TRChatBase(update.from_user.id, update.text, "/echo")
    # bot.send_chat_action(
    #     chat_id=update.chat.id,
    #     action="typing"
    # )
    logger.info(update.from_user)
    if str(update.from_user.id) in Config.BANNED_USERS:
        bot.send_message(chat_id=update.chat.id,
                         text=Translation.ABUSIVE_USERS,
                         reply_to_message_id=update.message_id,
                         disable_web_page_preview=True,
                         parse_mode=pyrogram.ParseMode.HTML)
        return
    url = update.text
    if "http" in url:
        if "|" in url:
            url, file_name = url.split("|")
            url = url.strip()
            # https://stackoverflow.com/a/761825/4723940
            file_name = file_name.strip()
            logger.info(url)
            logger.info(file_name)
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        try:
            if ("hotstar" in url) and (Config.HTTP_PROXY != ""):
                command_to_exec = [
                    "youtube-dl", "--no-warnings",
                    "--youtube-skip-dash-manifest", "-j", url, "--proxy",
                    Config.HTTP_PROXY
                ]
            else:
                command_to_exec = [
                    "youtube-dl", "--no-warnings",
                    "--youtube-skip-dash-manifest", "-j", url
                ]
            logger.info(command_to_exec)
            t_response = subprocess.check_output(command_to_exec,
                                                 stderr=subprocess.STDOUT)
            # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
        except subprocess.CalledProcessError as exc:
            # print("Status : FAIL", exc.returncode, exc.output)
            bot.send_message(chat_id=update.chat.id,
                             text=exc.output.decode("UTF-8"),
                             reply_to_message_id=update.message_id)
        else:
            # logger.info(t_response)
            x_reponse = t_response.decode("UTF-8")
            response_json = json.loads(x_reponse)
            save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
                "/" + str(update.from_user.id) + ".json"
            with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
                json.dump(response_json, outfile, ensure_ascii=False)
            # logger.info(response_json)
            inline_keyboard = []
            duration = None
            if "duration" in response_json:
                duration = response_json["duration"]
            if "formats" in response_json:
                for formats in response_json["formats"]:
                    format_id = formats.get("format_id")
                    format_string = formats.get("format_note")
                    if format_string is None:
                        format_string = formats.get("format")
                    format_ext = formats.get("ext")
                    approx_file_size = ""
                    if "filesize" in formats:
                        approx_file_size = humanbytes(formats["filesize"])
                    cb_string_video = "{}|{}|{}".format(
                        "video", format_id, format_ext)
                    cb_string_file = "{}|{}|{}".format("file", format_id,
                                                       format_ext)
                    if format_string is not None and not "audio only" in format_string:
                        ikeyboard = [
                            pyrogram.InlineKeyboardButton(
                                "S" + format_ext + "Video [" + format_string +
                                "] ( " + approx_file_size + " )",
                                callback_data=(
                                    cb_string_video).encode("UTF-8")),
                            pyrogram.InlineKeyboardButton(
                                "D" + format_ext + "File [" + format_string +
                                "] ( " + approx_file_size + " )",
                                callback_data=(cb_string_file).encode("UTF-8"))
                        ]
                        if duration is not None and duration <= 30:
                            cb_string_video_message = "{}|{}|{}".format(
                                "vm", format_id, format_ext)
                            ikeyboard.append(
                                pyrogram.InlineKeyboardButton(
                                    "VMessage [" + format_string + "] ( " +
                                    approx_file_size + " )",
                                    callback_data=(cb_string_video_message
                                                   ).encode("UTF-8")))
                    else:
                        # special weird case :\
                        ikeyboard = [
                            pyrogram.InlineKeyboardButton(
                                "SVideo [" + "] ( " + approx_file_size + " )",
                                callback_data=(
                                    cb_string_video).encode("UTF-8")),
                            pyrogram.InlineKeyboardButton(
                                "DFile [" + "] ( " + approx_file_size + " )",
                                callback_data=(cb_string_file).encode("UTF-8"))
                        ]
                    inline_keyboard.append(ikeyboard)
                if duration is not None:
                    cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                    cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                    cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "64 kbps" + ")",
                            callback_data=cb_string_64.encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "128 kbps" + ")",
                            callback_data=cb_string_128.encode("UTF-8"))
                    ])
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "320 kbps" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
            else:
                format_id = response_json["format_id"]
                format_ext = response_json["ext"]
                tg_send_type = "file"
                if duration is not None:
                    tg_send_type = "video"
                cb_string = "{}|{}|{}".format(tg_send_type, format_id,
                                              format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "Download", callback_data=cb_string.encode("UTF-8"))
                ])
            reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
            # logger.info(reply_markup)
            thumbnail = Config.DEF_THUMB_NAIL_VID_S
            thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
            if "thumbnail" in response_json:
                if response_json["thumbnail"] is not None:
                    thumbnail = response_json["thumbnail"]
                    thumbnail_image = response_json["thumbnail"]
            thumb_image_path = DownLoadFile(
                thumbnail_image,
                Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) +
                ".jpg",
                Config.CHUNK_SIZE,
                None,  # bot,
                Translation.DOWNLOAD_START,
                update.message_id,
                update.chat.id)
            bot.send_message(
                chat_id=update.chat.id,
                text=Translation.FORMAT_SELECTION.format(thumbnail),
                reply_markup=reply_markup,
                parse_mode=pyrogram.ParseMode.HTML,
                reply_to_message_id=update.message_id)
    else:
        bot.send_message(chat_id=update.chat.id,
                         text=Translation.INVALID_UPLOAD_BOT_URL_FORMAT,
                         reply_to_message_id=update.message_id)
示例#9
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("🔊 Now Uploading to ☁️ Cloud!!!")
    #subprocess.Popen(('touch', 'memek.conf'), stdout = subprocess.PIPE)
    with open('memek.conf', 'a', newline="\n", encoding = 'utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{UPLOADER_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = ['memek', 'copy', '--config=/opt/memek.conf', f'/opt/{file_upload}', 'DRIVE:'f'{destination}', '-v']
        tmp = await asyncio.create_subprocess_exec(*g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        gk_file = re.escape(file_upload)
        with open('filter.txt', 'w+', encoding = 'utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
            
        t_a_m = ['memek', 'lsf', '--config=/opt/memek.conf', '-F', 'i', "--filter-from=/opt/filter.txt", "--files-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        gautam = gau.decode("utf-8")
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="☁️ CLOUD LINK ☁️", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            button.append([pyrogram.InlineKeyboardButton(text="⚡ INDEX URL LINK ⚡", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: {file_upload} has been Uploaded successfully to your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}", disable_web_page_preview=True, reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt= os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = ['memek', 'copy', '--config=/opt/memek.conf', f'/opt/{file_upload}', 'DRIVE:'f'{tt}', '-v']
        tmp = await asyncio.create_subprocess_exec(*t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        g_file = re.escape(file_upload)
        with open('filter1.txt', 'w+', encoding = 'utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
            
        g_a_u = ['memek', 'lsf', '--config=/opt/memek.conf', '-F', 'i', "--filter-from=/opt/filter1.txt", "--dirs-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        gautam = gau.decode("utf-8")
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        gjay = size(getFolderSize(file_upload))
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="☁️ CLOUD URL ☁️", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            button.append([pyrogram.InlineKeyboardButton(text="⚡ INDEX URL LINK ⚡", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: Folder has been Uploaded successfully to {tt} in your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}", disable_web_page_preview=True, reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#10
0
async def rclone_command_fd(client, message):

    """/rclone command"""

    LOGGER.info(

        f"rclone command from chatid:{message.chat.id}, userid:{message.from_user.id}"

    )

    if message.from_user.id == OWNER_ID and message.chat.type == "private":

        config.read("rclone_bak.conf")

        sections = list(config.sections())

        inline_keyboard = []

        for section in sections:

            ikeyboard = [

                pyrogram.InlineKeyboardButton(

                    section, callback_data=(f"rclone_{section}").encode("UTF-8")

                )

            ]

            inline_keyboard.append(ikeyboard)

        config.read("rclone.conf")

        section = config.sections()[0]

        msg_text = f"""Default section of rclone config is: **{section}**\n\n

There are {len(sections)} sections in your rclone.conf file, 

please choose which section you want to use:"""

        ikeyboard = [

            pyrogram.InlineKeyboardButton(

                "‼️ Cancel ‼️", callback_data=(f"rcloneCancel").encode("UTF-8")

            )

        ]

        inline_keyboard.append(ikeyboard)

        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)

        await message.reply_text(text=msg_text, reply_markup=reply_markup)

    else:

        await message.reply_text("You have no permission!")

        LOGGER.warning(

            f"uid={message.from_user.id} have no permission to edit rclone config!"

        )
示例#11
0
async def extract_youtube_dl_formats(url, user_working_dir):
    command_to_exec = [
        "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j",
        url
    ]
    if "hotstar" in url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    LOGGER.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    LOGGER.info(e_response)
    t_response = stdout.decode().strip()
    LOGGER.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.replace(
            "Tolong laporkan masalah ini di https://yt-dl.org/bug. Pastikan Anda menggunakan versi terbaru; lihat https://yt-dl.org/update tentang cara memperbarui. Pastikan untuk memanggil youtube-dl dengan flag --verbose dan sertakan output lengkapnya."
        )
        return error_message, None
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        response_json = []
        if "\n" in x_reponse:
            for yu_r in x_reponse.split("\n"):
                response_json.append(json.loads(yu_r))
        else:
            response_json.append(json.loads(x_reponse))
        # response_json = json.loads(x_reponse)
        save_ytdl_json_path = user_working_dir + \
            "/" + str("ytdleech") + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        for current_r_json in response_json:
            duration = None
            if "duration" in current_r_json:
                duration = current_r_json["duration"]
            if "formats" in current_r_json:
                for formats in current_r_json["formats"]:
                    format_id = formats.get("format_id")
                    format_string = formats.get("format_note")
                    if format_string is None:
                        format_string = formats.get("format")
                    format_ext = formats.get("ext")
                    approx_file_size = ""
                    if "filesize" in formats:
                        approx_file_size = humanbytes(formats["filesize"])
                    dipslay_str_uon = " " + format_string + " (" + format_ext.upper(
                    ) + ") " + approx_file_size + " "
                    cb_string_video = "{}|{}|{}".format(
                        "video", format_id, format_ext)
                    ikeyboard = []
                    if "drive.google.com" in url:
                        if format_id == "source":
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    else:
                        if format_string is not None and not "audio saja" in format_string:
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                        else:
                            # special weird case :\
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    "SVideo [" + "] ( " + approx_file_size +
                                    " )",
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    inline_keyboard.append(ikeyboard)
                if duration is not None:
                    cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                    cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                    cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "64 kbps" + ")",
                            callback_data=cb_string_64.encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "128 kbps" + ")",
                            callback_data=cb_string_128.encode("UTF-8"))
                    ])
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "320 kbps" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
            else:
                format_id = current_r_json["format_id"]
                format_ext = current_r_json["ext"]
                cb_string_video = "{}|{}|{}".format("video", format_id,
                                                    format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "SVideo",
                        callback_data=(cb_string_video).encode("UTF-8"))
                ])
            break
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        # LOGGER.info(reply_markup)
        succss_mesg = """Pilih format yang diinginkan: 👇
<u>mention</u> <i>perkiraan ukuran file</i>"""
        return succss_mesg, reply_markup
示例#12
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("🔊 Now Uploading to Gdrive!!!")
    #subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding = 'utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = ['rclone', 'copy', '--config=/app/rclone.conf', f'/app/{file_upload}', 'DRIVE:'f'{destination}', '-vvv']
        tmp = await asyncio.create_subprocess_exec(*g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding = 'utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
            
        t_a_m = ['rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i', "--filter-from=/app/filter.txt", "--files-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="Join Team Drive🏃‍♂", url="https://telegra.ph/How-To-Join-In-HB4All-Team-Drive-05-19")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="Index Link", url="https://happyboy.hb4all.workers.dev")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: Uploaded..🤯\n\n📎File Name: {file_upload}\n\n📀 Size: {gjay}\n\n GDrive Link🔗:{gau_link}\n\n Shareable Link🔗:{tam_link}\n\nStream Link🖥:{tam_link}?a=view\n\n #HB4All More @HB4All_Bot", reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt= os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = ['rclone', 'copy', '--config=/app/rclone.conf', f'/app/{file_upload}', 'DRIVE:'f'{tt}', '-vvv']
        tmp = await asyncio.create_subprocess_exec(*t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding = 'utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
            
        g_a_u = ['rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i', "--filter-from=/app/filter1.txt", "--dirs-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="Join Team Drive🏃‍♂", url="https://telegra.ph/How-To-Join-In-HB4All-Team-Drive-05-19")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="Index Link", url="https://happyboy.hb4all.workers.dev")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: Uploaded..🤯\n\n📎File Name: {file_upload}\n\n📀 Size: {gjay}\n\n GDrive Link🔗:{gau_link} \n\n Shareable Link🔗:{tam_link}\n\nStream Link🖥:{tam_link}?a=view\n\n #HB4All More @HB4All_Bot", reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#13
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("🔊 Now Uploading to ☁️ Cloud!!!")
    subprocess.Popen(('touch', 'rclone.conf'), stdout=subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n") as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        tmp = subprocess.Popen([
            'rclone', 'copy', '--drive-chunk-size=512M', '--transfers=10',
            '--local-no-check-updated', '--config=rclone.conf',
            f'/app/{file_upload}', 'DRIVE:'
            f'{destination}', '-vvv'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        gk_file = re.escape(file_upload)
        print(gk_file)
        with open('filter.txt', 'w+') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
        gau_tam = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = gau_tam.communicate()
        print(gau)
        gautam = gau.decode("utf-8")
        print(gautam)
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        print(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        print(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            print(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: {file_upload} has been Uploaded successfully to your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt = os.path.join(destination, file_upload)
        print(tt)
        tmp = subprocess.Popen([
            'rclone', 'copy', '--drive-chunk-size=512M', '--transfers=10',
            '--local-no-check-updated', '--config=rclone.conf',
            f'/app/{file_upload}', 'DRIVE:'
            f'{tt}', '-vvv'
        ],
                               stdout=subprocess.PIPE)
        pro, cess = tmp.communicate()
        print(pro)
        g_file = re.escape(file_upload)
        print(g_file)
        with open('filter1.txt', 'w+') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
        gau_tam = subprocess.Popen([
            'rclone', 'lsf', '--config=rclone.conf', '-F', 'i',
            "--filter-from=filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = gau_tam.communicate()
        print(gau)
        gautam = gau.decode("utf-8")
        print(gautam)
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        print(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        gjay = size(getFolderSize(file_upload))
        print(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            print(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Folder has been Uploaded successfully to {tt} in your Cloud <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#14
0
async def extract_youtube_dl_formats(url, yt_dl_user_name, yt_dl_pass_word,
                                     user_working_dir):
    command_to_exec = [
        "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j",
        url
    ]
    if "hotstar" in url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    #
    if yt_dl_user_name is not None:
        command_to_exec.append("--username")
        command_to_exec.append(yt_dl_user_name)
    if yt_dl_pass_word is not None:
        command_to_exec.append("--password")
        command_to_exec.append(yt_dl_pass_word)

    LOGGER.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    LOGGER.info(e_response)
    t_response = stdout.decode().strip()
    LOGGER.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.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.",
            "")
        return None, error_message, None
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        response_json = []
        if "\n" in x_reponse:
            for yu_r in x_reponse.split("\n"):
                response_json.append(json.loads(yu_r))
        else:
            response_json.append(json.loads(x_reponse))
        # response_json = json.loads(x_reponse)
        save_ytdl_json_path = user_working_dir + \
            "/" + str("ytdleech") + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        #
        thumb_image = DEF_THUMB_NAIL_VID_S
        #
        for current_r_json in response_json:
            #
            thumb_image = current_r_json.get("thumbnail", thumb_image)
            #
            duration = None
            if "duration" in current_r_json:
                duration = current_r_json["duration"]
            if "formats" in current_r_json:
                for formats in current_r_json["formats"]:
                    format_id = formats.get("format_id")
                    format_string = formats.get("format_note")
                    if format_string is None:
                        format_string = formats.get("format")
                    format_ext = formats.get("ext")
                    approx_file_size = ""
                    if "filesize" in formats:
                        approx_file_size = humanbytes(formats["filesize"])
                    dipslay_str_uon = " " + format_string + " (" + format_ext.upper(
                    ) + ") " + approx_file_size + " "
                    cb_string_video = "{}|{}|{}".format(
                        "video", format_id, format_ext)
                    ikeyboard = []
                    if "drive.google.com" in url:
                        if format_id == "source":
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    else:
                        if format_string is not None and not "audio only" in format_string:
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                        else:
                            # special weird case :\
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    "SVideo [" + "] ( " + approx_file_size +
                                    " )",
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    inline_keyboard.append(ikeyboard)
                if duration is not None:
                    cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                    cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                    cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "64 kbps" + ")",
                            callback_data=cb_string_64.encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "128 kbps" + ")",
                            callback_data=cb_string_128.encode("UTF-8"))
                    ])
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "320 kbps" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
            else:
                format_id = current_r_json["format_id"]
                format_ext = current_r_json["ext"]
                cb_string_video = "{}|{}|{}".format("video", format_id,
                                                    format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "SVideo",
                        callback_data=(cb_string_video).encode("UTF-8"))
                ])
            break
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        # LOGGER.info(reply_markup)
        succss_mesg = """Select the desired format : ⚙⚙⚙
<u>mentioned</u> <i>file size might be approximate</i>"""
        return thumb_image, succss_mesg, reply_markup
async def tg_to_gdrive_upload(bot, update):
    download_location = Config.DOWNLOAD_LOCATION + "/"
    reply_message = await bot.send_message(
        chat_id=update.chat.id,
        text=Translation.DOWNLOAD_START,
        reply_to_message_id=update.message_id)
    c_time = time.time()
    the_real_download_location = await bot.download_media(
        message=update.reply_to_message,
        file_name=download_location,
        progress=progress_for_pyrogram,
        progress_args=(Translation.DOWNLOAD_START, reply_message, c_time))
    if the_real_download_location is not None:
        try:
            await bot.edit_message_text(text=Translation.SAVED_RECVD_DOC_FILE,
                                        chat_id=update.chat.id,
                                        message_id=reply_message.message_id)
        except:
            pass
    txt = update.text
    if txt.find("rename") > -1 and len(txt[txt.find("rename") + 7:]) > 0:
        custom_file_name = txt[txt.find("rename") + 7:]
        custom_file_name = await sanitize_file_name(custom_file_name)
        custom_file_name = await sanitize_text(custom_file_name)
        new_file_name = download_location + custom_file_name
        os.rename(the_real_download_location, new_file_name)
        the_real_download_location = new_file_name
    download_directory = the_real_download_location
    if os.path.exists(download_directory):
        end_one = datetime.now()
        up_name = pathlib.PurePath(download_directory).name
        size = get_readable_file_size(get_path_size(download_directory))
        try:
            await bot.edit_message_text(
                text=
                "<b>Download Completed😍😂😁!!!</b> \n<code>Now Started Uploading In Progress...</code>",
                chat_id=reply_message.chat.id,
                message_id=reply_message.message_id)
        except Exception as e:
            logger.info(str(e))
            pass
        logger.info(f"Upload Name : {up_name}")
        drive = gdriveTools.GoogleDriveHelper(up_name)
        gd_url, index_url = drive.upload(download_directory)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="⚡ CloudUrl ⚡", url=f"{gd_url}")
        ])
        if Config.INDEX_URL:
            logger.info(index_url)
            button.append([
                pyrogram.InlineKeyboardButton(text="🔥 IndexUrl 🔥",
                                              url=f"{index_url}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await bot.send_message(
            text=
            f"🤖: <code>{up_name}</code> has been Uploaded successfully to your Cloud🤒 \n📀 Size: {size}",
            chat_id=update.chat.id,
            reply_to_message_id=update.message_id,
            reply_markup=button_markup)
        if Config.INDEX_URL:
            await generate_short_link(reply_message, index_url, up_name)
        await reply_message.delete()
示例#16
0
async def unzip(bot, update):
    if update.from_user.id not in Config.AUTH_USERS:
        await bot.delete_messages(chat_id=update.chat.id,
                                  message_ids=update.message_id,
                                  revoke=True)
        return
    TRChatBase(update.from_user.id, update.text, "unzip")
    saved_file_path = Config.DOWNLOAD_LOCATION + \
        "/" + str(update.from_user.id) + ".unzip.zip"
    if not os.path.isdir(saved_file_path):
        os.makedirs(saved_file_path)

    reply_message = update.reply_to_message
    if ((reply_message is not None) and (reply_message.document is not None)
            and (reply_message.document.file_name.endswith(
                Translation.UNZIP_SUPPORTED_EXTENSIONS))):
        a = await bot.send_message(chat_id=update.chat.id,
                                   text=Translation.DOWNLOAD_START,
                                   reply_to_message_id=update.message_id)
        c_time = time.time()
        try:
            await bot.download_media(message=reply_message,
                                     file_name=saved_file_path,
                                     progress=progress_for_pyrogram,
                                     progress_args=(Translation.DOWNLOAD_START,
                                                    a, c_time))
        except (ValueError) as e:
            await bot.edit_message_text(chat_id=update.chat.id,
                                        text=str(e),
                                        message_id=a.message_id)
        else:
            await bot.edit_message_text(chat_id=update.chat.id,
                                        text=Translation.SAVED_RECVD_DOC_FILE,
                                        message_id=a.message_id)
            extract_dir_path = extracted
            if not os.path.isdir(extract_dir_path):
                os.makedirs(extract_dir_path)
            await bot.edit_message_text(
                chat_id=update.chat.id,
                text=Translation.EXTRACT_ZIP_INTRO_THREE,
                message_id=a.message_id)
            try:
                command_to_exec = [
                    "7z", "e", "-o" + extract_dir_path, saved_file_path
                ]
                # https://stackoverflow.com/a/39629367/4723940
                logger.info(command_to_exec)
                t_response = subprocess.check_output(command_to_exec,
                                                     stderr=subprocess.STDOUT)
                # https://stackoverflow.com/a/26178369/4723940
            except:
                try:
                    os.remove(saved_file_path)
                    shutil.rmtree(extract_dir_path)
                except:
                    pass
                await bot.edit_message_text(
                    chat_id=update.chat.id,
                    text=Translation.EXTRACT_ZIP_ERRS_OCCURED,
                    disable_web_page_preview=True,
                    parse_mode="html",
                    message_id=a.message_id)
            else:
                os.remove(saved_file_path)
                inline_keyboard = []
                zip_file_contents = os.listdir(extract_dir_path)
                i = 0
                for current_file in zip_file_contents:
                    cb_string = "ZIP:{}:ZIP".format(str(i))
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            current_file,
                            callback_data=cb_string.encode("UTF-8"))
                    ])
                    i = i + 1
                cb_string = "ZIP:{}:ZIP".format("ALL")
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "Upload All Files",
                        callback_data=cb_string.encode("UTF-8"))
                ])
                cb_string = "ZIP:{}:ZIP".format("NONE")
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "Cancel", callback_data=cb_string.encode("UTF-8"))
                ])
                reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
                await bot.edit_message_text(
                    chat_id=update.chat.id,
                    text=Translation.EXTRACT_ZIP_STEP_TWO,
                    message_id=a.message_id,
                    reply_markup=reply_markup,
                )
    else:
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.EXTRACT_ZIP_INTRO_ONE,
                               reply_to_message_id=update.message_id)
示例#17
0
async def echo(bot, update):
    if update.from_user.id in Config.BANNED_USERS:
        await update.reply_text("You are B A N N E D 🤣🤣🤣🤣")
        return
    TRChatBase(update.from_user.id, update.text, "/echo")
    update_channel = Config.UPDATE_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
               await update.reply_text("🤭 Sorry Dude, You are **B A N N E D 🤣🤣🤣**")
               return
        except UserNotParticipant:
            #await update.reply_text(f"Join @{update_channel} To Use Me")
            await update.reply_text(
                text="**Join My Updates Channel to use ME 😎 🤭**",
                reply_markup=InlineKeyboardMarkup([
                    [ InlineKeyboardButton(text="Join My Updates Channel", url=f"https://t.me/{update_channel}")]
              ])
            )
            return
        except Exception:
            await update.reply_text("Something Wrong. Contact my Support Group")
            return
    logger.info(update.from_user)
    linkup =update.text.split('/')[-1]
    w =linkup

   # markup = client.build_reply_markup(Button.url("https://www.zee5.com/tvshows/details/sembaruthi/0-6-675/sembaruthi-november-18-2020/0-1-manual_7adlhget67b0"+link))

   # req1 = requests.get(urls.token_url1, headers=headers).json()

    #req2 = requests.get(urls.platform_token).json()["token"]

    #headers["X-Access-Token"] = req2

   # req3 = requests.get(urls.token_url2, headers=headers).json()

           

    #r1 = requests.get(urls.search_api_endpoint + w,headers=headers, params={"translation":"en", "country":"IN"}).json()

    #g1 = (r1["hls"][0].replace("drm", "hls") + req1["video_token"])
    #trtr = .
   # print(trtr)
  #  linksd = message.matches[0].group(0)
    zxc = update.text.split('/')[-1]
    wida = 'https://zee5-player.vercel.app/player?id='+zxc
    print (zxc)
    #outF = open("./DOWNLOADS/gh.txt", "w")
 #   outF.write(zxc)
   # outF.close()
    url = update.text
    #await bot.delete_messages(chat_id=update.chat.id,message_ids=update.message_id)

            

   #         ,

            

       # )
  #  outF.close()
    print (url)
    youtube_dl_username = None
    youtube_dl_password = None
    file_name = None
    if "|" in url:
        url_parts = url.split("|")
        if len(url_parts) == 2:
            url = url_parts[0]
            file_name = url_parts[1]
        elif len(url_parts) == 4:
            url = url_parts[0]
            file_name = url_parts[1]
            youtube_dl_username = url_parts[2]
            youtube_dl_password = url_parts[3]
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if url is not None:
            url = url.strip()
        if file_name is not None:
            file_name = file_name.strip()
        # https://stackoverflow.com/a/761825/4723940
        if youtube_dl_username is not None:
            youtube_dl_username = youtube_dl_username.strip()
        if youtube_dl_password is not None:
            youtube_dl_password = youtube_dl_password.strip()
        logger.info(url)
        logger.info(file_name)
    else:
        for entity in update.entities:
            if entity.type == "text_link":
                url = entity.url
            elif entity.type == "url":
                o = entity.offset
                l = entity.length
                url = url[o:o + l]
    if Config.HTTP_PROXY != "":
        command_to_exec = [
            "youtube-dl",
            "--no-warnings",
            "--youtube-skip-dash-manifest",
            "-j",
            url,
            "--proxy", Config.HTTP_PROXY
        ]
    else:
        command_to_exec = [
            "youtube-dl",
            "--no-warnings",
            "--youtube-skip-dash-manifest",
            "-j",
            url
        ]
    if "hotstar" in url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    if youtube_dl_username is not None:
        command_to_exec.append("--username")
        command_to_exec.append(youtube_dl_username)
    if youtube_dl_password is not None:
        command_to_exec.append("--password")
        command_to_exec.append(youtube_dl_password)
    # logger.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    # logger.info(e_response)
    t_response = stdout.decode().strip()
    # logger.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response and "nonnumeric port" not in e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.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 "This video is only available for registered users." in error_message:
            error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.NO_VOID_FORMAT_FOUND.format(str(error_message)),
            reply_to_message_id=update.message_id,
            parse_mode="html",
            disable_web_page_preview=True
        )
        return False
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        if "\n" in x_reponse:
            x_reponse, _ = x_reponse.split("\n")
        response_json = json.loads(x_reponse)
        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        duration = None
        if "duration" in response_json:
            duration = response_json["duration"]
        if "formats" in response_json:
            for formats in response_json["formats"]:
                format_id = formats.get("format_id")
                format_string = formats.get("format_note")
                if format_string is None:
                    format_string = formats.get("format")
                format_ext = formats.get("ext")
                approx_file_size = ""
                if "filesize" in formats:
                    approx_file_size = humanbytes(formats["filesize"])
                cb_string_video = "{}|{}|{}".format(
                    "video", format_id, format_ext)
                cb_string_file = "{}|{}|{}".format(
                    "file", format_id, format_ext)
                if format_string is not None and not "audio only" in format_string:
                    ikeyboard = [
                        pyrogram.InlineKeyboardButton(
                            "S " + format_string + " video " + approx_file_size + " ",
                            callback_data=(cb_string_video).encode("UTF-8")
                        ),
                        pyrogram.InlineKeyboardButton(
                            "D " + format_ext + " " + approx_file_size + " ",
                            callback_data=(cb_string_file).encode("UTF-8")
                        )
                    ]
                    """if duration is not None:
                        cb_string_video_message = "{}|{}|{}".format(
                            "vm", format_id, format_ext)
                        ikeyboard.append(
                            pyrogram.InlineKeyboardButton(
                                "VM",
                                callback_data=(
                                    cb_string_video_message).encode("UTF-8")
                            )
                        )"""
                else:
                    # special weird case :\
                    ikeyboard = [
                        pyrogram.InlineKeyboardButton(
                            "SVideo [" +
                            "] ( " +
                            approx_file_size + " )",
                            callback_data=(cb_string_video).encode("UTF-8")
                        ),
                        pyrogram.InlineKeyboardButton(
                            "DFile [" +
                            "] ( " +
                            approx_file_size + " )",
                            callback_data=(cb_string_file).encode("UTF-8")
                        )
                    ]
                inline_keyboard.append(ikeyboard)
            if duration is not None:
                cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8")),
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8"))
                ])
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8"))
                ])
        else:
            format_id = response_json["format_id"]
            format_ext = response_json["ext"]
            cb_string_file = "{}|{}|{}".format(
                "file", format_id, format_ext)
            cb_string_video = "{}|{}|{}".format(
                "video", format_id, format_ext)
            inline_keyboard.append([
                pyrogram.InlineKeyboardButton(
                    "SVideo",
                    callback_data=(cb_string_video).encode("UTF-8")
                ),
                pyrogram.InlineKeyboardButton(
                    "DFile",
                    callback_data=(cb_string_file).encode("UTF-8")
                )
            ])
            cb_string_file = "{}={}={}".format(
                "file", format_id, format_ext)
            cb_string_video = "{}={}={}".format(
                "video", format_id, format_ext)
            inline_keyboard.append([
                pyrogram.InlineKeyboardButton(
                    "video",
                    callback_data=(cb_string_video).encode("UTF-8")
                ),
                pyrogram.InlineKeyboardButton(
                    "file",
                    callback_data=(cb_string_file).encode("UTF-8")
                )
            ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        # logger.info(reply_markup)
        thumbnail = Config.DEF_THUMB_NAIL_VID_S
        thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
        if "thumbnail" in response_json:
            if response_json["thumbnail"] is not None:
                thumbnail = response_json["thumbnail"]
                thumbnail_image = response_json["thumbnail"]
                logger.info(f"Thumbnail :{thumbnail_image}")
        thumb_image_path = DownLoadFile(
            thumbnail_image,
            Config.DOWNLOAD_LOCATION + "/" +
            str(update.from_user.id) + ".webp",
            Config.CHUNK_SIZE,
            None,  # bot,
            Translation.DOWNLOAD_START,
            update.message_id,
            update.chat.id
        )
        logger.info(f"Thumbnail22:{thumb_image_path}")
        if os.path.exists(thumb_image_path):
            im = Image.open(thumb_image_path).convert("RGB")
            im.save(thumb_image_path.replace(".webp", ".jpg"), "jpeg")
            logger.info(f"Thumbnail New JPG:{thumb_image_path}")
        else:
            thumb_image_path = None
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" + Translation.SET_CUSTOM_USERNAME_PASSWORD,
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id
        )
    else:
        # fallback for nonnumeric port a.k.a seedbox.io
        inline_keyboard = []
        cb_string_file = "{}={}={}".format(
            "file", "LFO", "NONE")
        cb_string_video = "{}={}={}".format(
            "video", "OFL", "ENON")
        inline_keyboard.append([
            pyrogram.InlineKeyboardButton(
                "SVideo",
                callback_data=(cb_string_video).encode("UTF-8")
            ),
            pyrogram.InlineKeyboardButton(
                "DFile",
                callback_data=(cb_string_file).encode("UTF-8")
            )
        ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(""),
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id
        )
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("🔊 𝐍𝐨𝐰 𝐔𝐩𝐥𝐨𝐚𝐝𝐢𝐧𝐠 𝐭𝐨 ☁️ 𝐂𝐥𝐨𝐮𝐝!!!")
    #subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding='utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = [
            'rclone', 'copy', '--config=/app/rclone.conf',
            f'/app/{file_upload}', 'DRIVE:'
            f'{destination}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *g_au,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding='utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)

        t_a_m = [
            'rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i',
            "--filter-from=/app/filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *t_a_m,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ 𝗖𝗹𝗼𝘂𝗱𝗨𝗿𝗹 ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ 𝗜𝗻𝗱𝗲𝘅𝗨𝗿𝗹 ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: {file_upload} 𝗵𝗮𝘀 𝗯𝗲𝗲𝗻 𝗨𝗽𝗹𝗼𝗮𝗱𝗲𝗱 𝘀𝘂𝗰𝗰𝗲𝘀𝘀𝗳𝘂𝗹𝗹𝘆 𝘁𝗼 𝘆𝗼𝘂𝗿 𝗖𝗹𝗼𝘂𝗱 <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt = os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = [
            'rclone', 'copy', '--config=/app/rclone.conf',
            f'/app/{file_upload}', 'DRIVE:'
            f'{tt}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *t_am,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding='utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)

        g_a_u = [
            'rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i',
            "--filter-from=/app/filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *g_a_u,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ 𝗖𝗹𝗼𝘂𝗱𝗨𝗿𝗹 ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ 𝗜𝗻𝗱𝗲𝘅𝗨𝗿𝗹 ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: 𝗙𝗼𝗹𝗱𝗲𝗿 𝗵𝗮𝘀 𝗯𝗲𝗲𝗻 𝗨𝗽𝗹𝗼𝗮𝗱𝗲𝗱 𝘀𝘂𝗰𝗰𝗲𝘀𝘀𝗳𝘂𝗹𝗹𝘆 𝘁𝗼 {tt} 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗖𝗹𝗼𝘂𝗱 <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: 𝗙𝗼𝗹𝗱𝗲𝗿 𝗵𝗮𝘀 𝗯𝗲𝗲𝗻 𝗨𝗽𝗹𝗼𝗮𝗱𝗲𝗱 𝘀𝘂𝗰𝗰𝗲𝘀𝘀𝗳𝘂𝗹𝗹𝘆 𝘁𝗼 {tt} 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗖𝗹𝗼𝘂𝗱 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
示例#19
0
async def rename_message_f(client, message):
    inline_keyboard = []
    inline_keyboard.append([pyrogram.InlineKeyboardButton(text="", url="")])
    reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
    await message.reply_text("", quote=True, reply_markup=reply_markup)
示例#20
0
async def echo(bot, update):
    if update.from_user.id in Config.BANNED_USERS:
        await bot.delete_messages(chat_id=update.chat.id,
                                  message_ids=update.message_id,
                                  revoke=True)
        return
    # logger.info(update)
    TRChatBase(update.from_user.id, update.text, "/echo")
    # await bot.send_chat_action(
    #     chat_id=update.chat.id,
    #     action="typing"
    # )
    logger.info(update.from_user)
    url = update.text
    youtube_dl_username = None
    youtube_dl_password = None
    file_name = None
    if "|" in url:
        url_parts = url.split("|")
        if len(url_parts) == 2:
            url = url_parts[0]
            file_name = url_parts[1]
        elif len(url_parts) == 4:
            url = url_parts[0]
            file_name = url_parts[1]
            youtube_dl_username = url_parts[2]
            youtube_dl_password = url_parts[3]
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if url is not None:
            url = url.strip()
        if file_name is not None:
            file_name = file_name.strip()
        # https://stackoverflow.com/a/761825/4723940
        if youtube_dl_username is not None:
            youtube_dl_username = youtube_dl_username.strip()
        if youtube_dl_password is not None:
            youtube_dl_password = youtube_dl_password.strip()
        logger.info(url)
        logger.info(file_name)
    else:
        for entity in update.entities:
            if entity.type == "text_link":
                url = entity.url
            elif entity.type == "url":
                o = entity.offset
                l = entity.length
                url = url[o:o + l]
    if Config.HTTP_PROXY != "":
        command_to_exec = [
            "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
            "-j", url, "--proxy", Config.HTTP_PROXY
        ]
    else:
        command_to_exec = [
            "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
            "-j", url
        ]
    if youtube_dl_username is not None:
        command_to_exec.append("--username")
        command_to_exec.append(youtube_dl_username)
    if youtube_dl_password is not None:
        command_to_exec.append("--password")
        command_to_exec.append(youtube_dl_password)
    # logger.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    # logger.info(e_response)
    t_response = stdout.decode().strip()
    # logger.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response and "nonnumeric port" not in e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.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 "This video is only available for registered users." in error_message:
            error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.NO_VOID_FORMAT_FOUND.format(
                                   str(error_message)),
                               reply_to_message_id=update.message_id,
                               parse_mode="html",
                               disable_web_page_preview=True)
        return False
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        if "\n" in x_reponse:
            x_reponse, _ = x_reponse.split("\n")
        response_json = json.loads(x_reponse)
        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        duration = None
        if "duration" in response_json:
            duration = response_json["duration"]
        if "formats" in response_json:
            for formats in response_json["formats"]:
                format_id = formats.get("format_id")
                format_string = formats.get("format_note")
                if format_string is None:
                    format_string = formats.get("format")
                format_ext = formats.get("ext")
                approx_file_size = ""
                if "filesize" in formats:
                    approx_file_size = humanbytes(formats["filesize"])
                cb_string_video = "{}|{}|{}".format("video", format_id,
                                                    format_ext)
                cb_string_file = "{}|{}|{}".format("file", format_id,
                                                   format_ext)
                if format_string is not None and not "audio only" in format_string:
                    ikeyboard = [
                        pyrogram.InlineKeyboardButton(
                            "S " + format_string + " video " +
                            approx_file_size + " ",
                            callback_data=(cb_string_video).encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "D " + format_ext + " " + approx_file_size + " ",
                            callback_data=(cb_string_file).encode("UTF-8"))
                    ]
                    """if duration is not None:
                        cb_string_video_message = "{}|{}|{}".format(
                            "vm", format_id, format_ext)
                        ikeyboard.append(
                            pyrogram.InlineKeyboardButton(
                                "VM",
                                callback_data=(
                                    cb_string_video_message).encode("UTF-8")
                            )
                        )"""
                else:
                    # special weird case :\
                    ikeyboard = [
                        pyrogram.InlineKeyboardButton(
                            "SVideo [" + "] ( " + approx_file_size + " )",
                            callback_data=(cb_string_video).encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "DFile [" + "] ( " + approx_file_size + " )",
                            callback_data=(cb_string_file).encode("UTF-8"))
                    ]
                inline_keyboard.append(ikeyboard)
            if duration is not None:
                cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "64 kbps" + ")",
                        callback_data=cb_string_64.encode("UTF-8")),
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "128 kbps" + ")",
                        callback_data=cb_string_128.encode("UTF-8"))
                ])
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "MP3 " + "(" + "320 kbps" + ")",
                        callback_data=cb_string.encode("UTF-8"))
                ])
        else:
            format_id = response_json["format_id"]
            format_ext = response_json["ext"]
            cb_string_file = "{}|{}|{}".format("file", format_id, format_ext)
            cb_string_video = "{}|{}|{}".format("video", format_id, format_ext)
            inline_keyboard.append([
                pyrogram.InlineKeyboardButton(
                    "SVideo", callback_data=(cb_string_video).encode("UTF-8")),
                pyrogram.InlineKeyboardButton(
                    "DFile", callback_data=(cb_string_file).encode("UTF-8"))
            ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        # logger.info(reply_markup)
        thumbnail = Config.DEF_THUMB_NAIL_VID_S
        thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
        if "thumbnail" in response_json:
            if response_json["thumbnail"] is not None:
                thumbnail = response_json["thumbnail"]
                thumbnail_image = response_json["thumbnail"]
        thumb_image_path = DownLoadFile(
            thumbnail_image,
            Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) + ".jpg",
            Config.CHUNK_SIZE,
            None,  # bot,
            Translation.DOWNLOAD_START,
            update.message_id,
            update.chat.id)
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" +
            Translation.SET_CUSTOM_USERNAME_PASSWORD,
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id)
    else:
        # fallback for nonnumeric port a.k.a seedbox.io
        inline_keyboard = []
        cb_string_file = "{}={}={}".format("file", "LFO", "NONE")
        cb_string_video = "{}={}={}".format("video", "OFL", "ENON")
        inline_keyboard.append([
            pyrogram.InlineKeyboardButton(
                "SVideo", callback_data=(cb_string_video).encode("UTF-8")),
            pyrogram.InlineKeyboardButton(
                "DFile", callback_data=(cb_string_file).encode("UTF-8"))
        ])
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.FORMAT_SELECTION.format(""),
                               reply_markup=reply_markup,
                               parse_mode="html",
                               reply_to_message_id=update.message_id)
示例#21
0
async def echo(bot, update):
    if update.from_user.id not in Config.AUTH_USERS:
        await bot.delete_messages(chat_id=update.chat.id,
                                  message_ids=update.message_id,
                                  revoke=True)
        return
    # logger.info(update)
    TRChatBase(update.from_user.id, update.text, "/echo")
    # await bot.send_chat_action(
    #     chat_id=update.chat.id,
    #     action="typing"
    # )
    logger.info(update.from_user)
    url = update.text
    if url.count("|") == 2:
        shomar = random.randint(1, 10000)
        # youtube_dl extractors
        youtube_dl_url, custom_file_name, youtube_dl_format = url.split("|")
        if ") FullHD" in custom_file_name:
            await bot.send_message(
                text=Translation.DOWNLOAD_START,
                chat_id=update.chat.id,
                reply_to_message_id=update.message_id,
            )
            description = "@BachehayeManoto FullHD"
            custom_file_name = custom_file_name + ".mp4"
            tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + str(
                shomar)
            if not os.path.isdir(tmp_directory_for_each_user):
                os.makedirs(tmp_directory_for_each_user)
            download_directory = tmp_directory_for_each_user + "/" + custom_file_name
            command_to_exec = []
            # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory]
            command_to_exec = [
                "youtube-dl", "-c", "--max-filesize",
                str(Config.TG_MAX_FILE_SIZE), "--embed-subs", "-f",
                youtube_dl_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o",
                download_directory
            ]
            command_to_exec.append("--no-warnings")
            # command_to_exec.append("--quiet")
            logger.info(command_to_exec)
            start = datetime.now()
            process = await asyncio.create_subprocess_exec(
                *command_to_exec,
                # stdout must a pipe to be accessible as process.stdout
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            # Wait for the subprocess to finish
            stdout, stderr = await process.communicate()
            e_response = stderr.decode().strip()
            t_response = stdout.decode().strip()
            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 bot.edit_message_text(chat_id=update.chat.id,
                                            message_id=update.message_id + 1,
                                            text=error_message)
                return False
            if t_response:
                # logger.info(t_response)
                end_one = datetime.now()
                time_taken_for_download = (end_one - start).seconds
                file_size = Config.TG_MAX_FILE_SIZE + 1
                try:
                    file_size = os.stat(download_directory).st_size
                except FileNotFoundError as exc:
                    download_directory = os.path.splitext(
                        download_directory)[0] + "." + "mkv"
                    # https://stackoverflow.com/a/678242/4723940
                    file_size = os.stat(download_directory).st_size
                if file_size > Config.TG_MAX_FILE_SIZE:
                    await bot.edit_message_text(
                        chat_id=update.chat.id,
                        text=Translation.RCHD_TG_API_LIMIT.format(
                            time_taken_for_download, humanbytes(file_size)),
                        message_id=update.message_id + 1)
                else:
                    is_w_f = False
                    images = await generate_screen_shots(
                        download_directory, tmp_directory_for_each_user,
                        is_w_f, Config.DEF_WATER_MARK_FILE, 300, 9)
                    logger.info(images)
                    await bot.edit_message_text(text=Translation.UPLOAD_START,
                                                chat_id=update.chat.id,
                                                message_id=update.message_id +
                                                1)
                    # get the correct width, height, and duration for videos greater than 10MB
                    width = 0
                    height = 0
                    duration = 0
                    start_time = time.time()
                    # try to upload file
                    await bot.send_document(
                        chat_id=update.chat.id,
                        document=download_directory,
                        # thumb=thumb_image_path,
                        caption=description,
                        parse_mode="HTML",
                        # reply_markup=reply_markup,
                        reply_to_message_id=update.message_id + 1,
                        progress=progress_for_pyrogram,
                        progress_args=(Translation.UPLOAD_START, update,
                                       start_time))
                    end_two = datetime.now()
                    time_taken_for_upload = (end_two - end_one).seconds
                    #
                    media_album_p = []
                    if images is not None:
                        i = 0
                        # caption = "© @AnyDLBot"
                        if is_w_f:
                            caption = "/upgrade to Plan D to remove the watermark\n© @AnyDLBot"
                        for image in images:
                            if os.path.exists(image):
                                if i == 0:
                                    media_album_p.append(
                                        pyrogram.InputMediaPhoto(
                                            media=image,
                                            # caption=caption,
                                            parse_mode="html"))
                                else:
                                    media_album_p.append(
                                        pyrogram.InputMediaPhoto(media=image))
                                i = i + 1
                    await bot.send_media_group(
                        chat_id=update.chat.id,
                        disable_notification=True,
                        reply_to_message_id=update.message_id + 1,
                        media=media_album_p)
                    #
                    try:
                        shutil.rmtree(tmp_directory_for_each_user)
                    except:
                        pass
                    await bot.edit_message_text(
                        text=
                        "Downloaded in {} seconds. \nUploaded in {} seconds.".
                        format(time_taken_for_download, time_taken_for_upload),
                        chat_id=update.chat.id,
                        message_id=update.message_id + 1,
                        disable_web_page_preview=True)
        if ") HD" in custom_file_name:
            await bot.send_message(
                text=Translation.DOWNLOAD_START,
                chat_id=update.chat.id,
                reply_to_message_id=update.message_id,
            )
            description = "@BachehayeManoto HD"
            custom_file_name = custom_file_name + ".mp4"
            tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + str(
                shomar)
            if not os.path.isdir(tmp_directory_for_each_user):
                os.makedirs(tmp_directory_for_each_user)
            download_directory = tmp_directory_for_each_user + "/" + custom_file_name
            command_to_exec = []
            # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory]
            command_to_exec = [
                "youtube-dl", "-c", "--max-filesize",
                str(Config.TG_MAX_FILE_SIZE), "--embed-subs", "-f",
                youtube_dl_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o",
                download_directory
            ]
            command_to_exec.append("--no-warnings")
            # command_to_exec.append("--quiet")
            logger.info(command_to_exec)
            start = datetime.now()
            process = await asyncio.create_subprocess_exec(
                *command_to_exec,
                # stdout must a pipe to be accessible as process.stdout
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            # Wait for the subprocess to finish
            stdout, stderr = await process.communicate()
            e_response = stderr.decode().strip()
            t_response = stdout.decode().strip()
            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 bot.edit_message_text(chat_id=update.chat.id,
                                            message_id=update.message_id + 1,
                                            text=error_message)
                return False
            if t_response:
                # logger.info(t_response)
                end_one = datetime.now()
                time_taken_for_download = (end_one - start).seconds
                file_size = Config.TG_MAX_FILE_SIZE + 1
                try:
                    file_size = os.stat(download_directory).st_size
                except FileNotFoundError as exc:
                    download_directory = os.path.splitext(
                        download_directory)[0] + "." + "mkv"
                    # https://stackoverflow.com/a/678242/4723940
                    file_size = os.stat(download_directory).st_size
                if file_size > Config.TG_MAX_FILE_SIZE:
                    await bot.edit_message_text(
                        chat_id=update.chat.id,
                        text=Translation.RCHD_TG_API_LIMIT.format(
                            time_taken_for_download, humanbytes(file_size)),
                        message_id=update.message_id + 1)
                else:
                    is_w_f = False
                    images = await generate_screen_shots(
                        download_directory, tmp_directory_for_each_user,
                        is_w_f, Config.DEF_WATER_MARK_FILE, 300, 9)
                    logger.info(images)
                    await bot.edit_message_text(text=Translation.UPLOAD_START,
                                                chat_id=update.chat.id,
                                                message_id=update.message_id +
                                                1)
                    # get the correct width, height, and duration for videos greater than 10MB
                    width = 0
                    height = 0
                    duration = 0
                    start_time = time.time()
                    # try to upload file
                    await bot.send_document(
                        chat_id=update.chat.id,
                        document=download_directory,
                        # thumb=thumb_image_path,
                        caption=description,
                        parse_mode="HTML",
                        # reply_markup=reply_markup,
                        reply_to_message_id=update.message_id + 1,
                        progress=progress_for_pyrogram,
                        progress_args=(Translation.UPLOAD_START, update,
                                       start_time))
                    end_two = datetime.now()
                    time_taken_for_upload = (end_two - end_one).seconds
                    #
                    media_album_p = []
                    if images is not None:
                        i = 0
                        # caption = "© @AnyDLBot"
                        if is_w_f:
                            caption = "/upgrade to Plan D to remove the watermark\n© @AnyDLBot"
                        for image in images:
                            if os.path.exists(image):
                                if i == 0:
                                    media_album_p.append(
                                        pyrogram.InputMediaPhoto(
                                            media=image,
                                            # caption=caption,
                                            parse_mode="html"))
                                else:
                                    media_album_p.append(
                                        pyrogram.InputMediaPhoto(media=image))
                                i = i + 1
                    await bot.send_media_group(
                        chat_id=update.chat.id,
                        disable_notification=True,
                        reply_to_message_id=update.message_id + 1,
                        media=media_album_p)
                    #
                    try:
                        shutil.rmtree(tmp_directory_for_each_user)
                    except:
                        pass
                    await bot.edit_message_text(
                        text=
                        "Downloaded in {} seconds. \nUploaded in {} seconds.".
                        format(time_taken_for_download, time_taken_for_upload),
                        chat_id=update.chat.id,
                        message_id=update.message_id + 1,
                        disable_web_page_preview=True)
    else:
        youtube_dl_username = None
        youtube_dl_password = None
        file_name = None
        if "|" in url:
            url_parts = url.split("|")
            if len(url_parts) == 2:
                url = url_parts[0]
                file_name = url_parts[1]
            elif len(url_parts) == 4:
                url = url_parts[0]
                file_name = url_parts[1]
                youtube_dl_username = url_parts[2]
                youtube_dl_password = url_parts[3]
            else:
                for entity in update.entities:
                    if entity.type == "text_link":
                        url = entity.url
                    elif entity.type == "url":
                        o = entity.offset
                        l = entity.length
                        url = url[o:o + l]
            if url is not None:
                url = url.strip()
            if file_name is not None:
                file_name = file_name.strip()
            # https://stackoverflow.com/a/761825/4723940
            if youtube_dl_username is not None:
                youtube_dl_username = youtube_dl_username.strip()
            if youtube_dl_password is not None:
                youtube_dl_password = youtube_dl_password.strip()
            logger.info(url)
            logger.info(file_name)
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if Config.HTTP_PROXY != "":
            command_to_exec = [
                "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
                "-j", url, "--proxy", Config.HTTP_PROXY
            ]
        else:
            command_to_exec = [
                "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
                "-j", url
            ]
        if youtube_dl_username is not None:
            command_to_exec.append("--username")
            command_to_exec.append(youtube_dl_username)
        if youtube_dl_password is not None:
            command_to_exec.append("--password")
            command_to_exec.append(youtube_dl_password)
        # logger.info(command_to_exec)
        process = await asyncio.create_subprocess_exec(
            *command_to_exec,
            # stdout must a pipe to be accessible as process.stdout
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        # Wait for the subprocess to finish
        stdout, stderr = await process.communicate()
        e_response = stderr.decode().strip()
        # logger.info(e_response)
        t_response = stdout.decode().strip()
        # logger.info(t_response)
        # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
        if e_response and "nonnumeric port" not in e_response:
            # logger.warn("Status : FAIL", exc.returncode, exc.output)
            error_message = e_response.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 "This video is only available for registered users." in error_message:
                error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
            await bot.send_message(
                chat_id=update.chat.id,
                text=Translation.NO_VOID_FORMAT_FOUND.format(
                    str(error_message)),
                reply_to_message_id=update.message_id,
                parse_mode="html",
                disable_web_page_preview=True)
            return False
        if t_response:
            # logger.info(t_response)
            x_reponse = t_response
            if "\n" in x_reponse:
                x_reponse, _ = x_reponse.split("\n")
            response_json = json.loads(x_reponse)
            save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
                "/" + str(update.from_user.id) + ".json"
            with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
                json.dump(response_json, outfile, ensure_ascii=False)
            # logger.info(response_json)
            inline_keyboard = []
            duration = None
            if "duration" in response_json:
                duration = response_json["duration"]
            if "formats" in response_json:
                for formats in response_json["formats"]:
                    format_id = formats.get("format_id")
                    format_string = formats.get("format_note")
                    if format_string is None:
                        format_string = formats.get("format")
                    format_ext = formats.get("ext")
                    approx_file_size = ""
                    if "filesize" in formats:
                        approx_file_size = humanbytes(formats["filesize"])
                    cb_string_video = "{}-{}-{}".format(
                        "video", format_id, format_ext)
                    cb_string_file = "{}-{}-{}".format("file", format_id,
                                                       format_ext)
                    if format_string is not None and not "audio only" in format_string:
                        ikeyboard = [
                            pyrogram.InlineKeyboardButton(
                                "S " + format_string + " video " +
                                approx_file_size + " ",
                                callback_data=(
                                    cb_string_video).encode("UTF-8")),
                            pyrogram.InlineKeyboardButton(
                                "D " + format_ext + " " + approx_file_size +
                                " ",
                                callback_data=(cb_string_file).encode("UTF-8"))
                        ]
                        """if duration is not None:
                            cb_string_video_message = "{}-{}-{}".format(
                                "vm", format_id, format_ext)
                            ikeyboard.append(
                                pyrogram.InlineKeyboardButton(
                                    "VM",
                                    callback_data=(
                                        cb_string_video_message).encode("UTF-8")
                                )
                            )"""
                    else:
                        # special weird case :\
                        ikeyboard = [
                            pyrogram.InlineKeyboardButton(
                                "SVideo [" + "] ( " + approx_file_size + " )",
                                callback_data=(
                                    cb_string_video).encode("UTF-8")),
                            pyrogram.InlineKeyboardButton(
                                "DFile [" + "] ( " + approx_file_size + " )",
                                callback_data=(cb_string_file).encode("UTF-8"))
                        ]
                    inline_keyboard.append(ikeyboard)
                if duration is not None:
                    cb_string_64 = "{}-{}-{}".format("audio", "64k", "mp3")
                    cb_string_128 = "{}-{}-{}".format("audio", "128k", "mp3")
                    cb_string = "{}-{}-{}".format("audio", "320k", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "64 kbps" + ")",
                            callback_data=cb_string_64.encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "128 kbps" + ")",
                            callback_data=cb_string_128.encode("UTF-8"))
                    ])
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "320 kbps" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
            else:
                format_id = response_json["format_id"]
                format_ext = response_json["ext"]
                cb_string_file = "{}-{}-{}".format("file", format_id,
                                                   format_ext)
                cb_string_video = "{}-{}-{}".format("video", format_id,
                                                    format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "SVideo",
                        callback_data=(cb_string_video).encode("UTF-8")),
                    pyrogram.InlineKeyboardButton(
                        "DFile",
                        callback_data=(cb_string_file).encode("UTF-8"))
                ])
                cb_string_file = "{}+{}+{}".format("file", format_id,
                                                   format_ext)
                cb_string_video = "{}+{}+{}".format("video", format_id,
                                                    format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "video",
                        callback_data=(cb_string_video).encode("UTF-8")),
                    pyrogram.InlineKeyboardButton(
                        "file", callback_data=(cb_string_file).encode("UTF-8"))
                ])
            reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
            # logger.info(reply_markup)
            thumbnail = Config.DEF_THUMB_NAIL_VID_S
            thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
            if "thumbnail" in response_json:
                if response_json["thumbnail"] is not None:
                    thumbnail = response_json["thumbnail"]
                    thumbnail_image = response_json["thumbnail"]
            thumb_image_path = DownLoadFile(
                thumbnail_image,
                Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) +
                ".jpg",
                Config.CHUNK_SIZE,
                None,  # bot,
                Translation.DOWNLOAD_START,
                update.message_id,
                update.chat.id)
            await bot.send_message(
                chat_id=update.chat.id,
                text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" +
                Translation.SET_CUSTOM_USERNAME_PASSWORD,
                reply_markup=reply_markup,
                parse_mode="html",
                reply_to_message_id=update.message_id)
        else:
            # fallback for nonnumeric port a.k.a seedbox.io
            inline_keyboard = []
            cb_string_file = "{}+{}+{}".format("file", "LFO", "NONE")
            cb_string_video = "{}+{}+{}".format("video", "OFL", "ENON")
            inline_keyboard.append([
                pyrogram.InlineKeyboardButton(
                    "SVideo", callback_data=(cb_string_video).encode("UTF-8")),
                pyrogram.InlineKeyboardButton(
                    "DFile", callback_data=(cb_string_file).encode("UTF-8"))
            ])
            reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
            await bot.send_message(
                chat_id=update.chat.id,
                text=Translation.FORMAT_SELECTION.format(""),
                reply_markup=reply_markup,
                parse_mode="html",
                reply_to_message_id=update.message_id)