Пример #1
0
async def download_coroutine(session, url, file_name, event, start):
    display_message = ""
    async with session.get(url) as response:
        total_length = int(response.headers["Content-Length"])
        content_type = response.headers["Content-Type"]
        if "text" in content_type and total_length < 500:
            return await response.release()
        await event.edit("""Initiating Download
URL: {}
File Name: {}
File Size: {}""".format(url, file_name, humanbytes(total_length)))
        with open(file_name, "wb") as f_handle:
            CHUNK_SIZE = 2341
            downloaded = 0
            while True:
                chunk = await response.content.read(CHUNK_SIZE)
                if not chunk:
                    break
                f_handle.write(chunk)
                downloaded += CHUNK_SIZE
                now = time.time()
                diff = now - start
                if round(diff % 5.00) == 0 or downloaded == total_length:
                    percentage = downloaded * 100 / total_length
                    speed = downloaded / diff
                    elapsed_time = round(diff) * 1000
                    time_to_completion = round(
                        (total_length - downloaded) / speed) * 1000
                    estimated_total_time = elapsed_time + time_to_completion
                    try:
                        current_message = """**Download Status**
URL: {}
File Name: {}
File Size: {}
Downloaded: {}
ETA: {}""".format(url, file_name, humanbytes(total_length),
                        humanbytes(downloaded), time_formatter(estimated_total_time))
                        if current_message != display_message:
                            await event.edit(current_message)
                            display_message = current_message
                    except Exception as e:
                        logger.info(str(e))
        return await response.release()
Пример #2
0
async def drivesch(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1).strip()
    drive = GDriveHelper()
    await drive.authorize(event)
    files = await drive.getFilesByParentId(Config.GDRIVE_FOLDER_ID, input_str, 20)
    msg = f"**G-Drive Search Query**\n`{input_str}`\n**Results**\n"
    for file in files:
        if file.get("mimeType") == drive.G_DRIVE_DIR_MIME_TYPE:
            msg += "⁍ [{}]({}) (folder)".format(file.get('name'),
                                                drive.formatLink(file.get('id')))+"\n"
        else:
            msg += "⁍ [{}]({}) ({})".format(file.get('name'), drive.formatLink(
                file.get('id'), folder=False), humanbytes(int(file.get('size'))))+"\n"
    await event.edit(msg)
Пример #3
0
async def _(event):
    if event.fwd_from:
        return
    entity = event.chat_id
    input_str = event.pattern_match.group(1)
    if input_str:
        entity = input_str
    status_message = await event.reply("... this might take some time "
                                       "depending on the number of messages "
                                       "in the chat ...")
    mus = 0
    hmm = {}
    async for message in event.client.iter_messages(entity=entity, limit=None):
        if message and message.file:
            if message.file.mime_type not in hmm:
                hmm[message.file.mime_type] = 0
            hmm[message.file.mime_type] += message.file.size
    hnm = {key: humanbytes(hmm[key]) for key in hmm}
    await status_message.edit(yaml_format(hnm), parse_mode=parse_pre)
Пример #4
0
async def inline_handler(event):
    me = await bot.get_me()
    builder = event.builder
    result = None
    query = event.text
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if query.startswith("ytdl"):
        # input format should be ytdl URL
        p = re.compile("ytdl (.*)")
        r = p.search(query)
        ytdl_url = r.group(1).strip()
        if ytdl_url.startswith("http"):
            command_to_exec = [
                "youtube-dl",
                "--no-warnings",
                "--youtube-skip-dash-manifest",
                "-j",
                ytdl_url
            ]
            logging.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()
            logging.info(command_to_exec)
            if 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.", "")
                # throw error
                result = builder.article(
                    "YTDL Errors © @UserBot",
                    text=f"{error_message} Powered by @UserBot",
                    link_preview=False
                )
            elif 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.TMP_DOWNLOAD_DIRECTORY + \
                    "/" + "YouTubeDL" + ".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 = "ytdl|{}|{}|{}".format(
                            "video", format_id, format_ext)
                        if format_string is not None:
                            ikeyboard = [
                                custom.Button.inline(
                                    " " + format_ext + " video [" + format_string +
                                    "] ( " +
                                    approx_file_size + " )",
                                    data=(cb_string_video)
                                )
                            ]
                        else:
                            # special weird case :\
                            ikeyboard = [
                                custom.Button.inline(
                                    " " + approx_file_size + " ",
                                    data=cb_string_video
                                )
                            ]
                        inline_keyboard.append(ikeyboard)
                    if duration is not None:
                        cb_string_64 = "ytdl|{}|{}|{}".format(
                            "audio", "64k", "mp3")
                        cb_string_128 = "ytdl|{}|{}|{}".format(
                            "audio", "128k", "mp3")
                        cb_string = "ytdl|{}|{}|{}".format(
                            "audio", "320k", "mp3")
                        inline_keyboard.append([
                            custom.Button.inline(
                                "MP3 " + "(" + "64 kbps" + ")", data=cb_string_64
                            ),
                            custom.Button.inline(
                                "MP3 " + "(" + "128 kbps" + ")", data=cb_string_128
                            )
                        ])
                        inline_keyboard.append([
                            custom.Button.inline(
                                "MP3 " + "(" + "320 kbps" + ")", data=cb_string
                            )
                        ])
                else:
                    format_id = response_json["format_id"]
                    format_ext = response_json["ext"]
                    cb_string_video = "ytdl|{}|{}|{}".format(
                        "video", format_id, format_ext)
                    inline_keyboard.append([
                        custom.Button.inline(
                            "video",
                            data=cb_string_video
                        )
                    ])
                result = builder.article(
                    "YouTube © UserBOT",
                    text=f"{ytdl_url} powered by UserBOT",
                    buttons=inline_keyboard,
                    link_preview=True
                )
    else:
        result = builder.article(
            "© UserBOT",
            text=(
                "Try UserBOT\n"
                "You can log-in as Bot or User and do many cool things with your Telegram account.\n\n"
                "All instaructions to run UserBOT in your PC has been explained in https://github.com/muhammedfurkan/TelethonUserBot"
            ),
            buttons=[
                [custom.Button.url("Join the Channel", "https://telegram.dog/telethon"), custom.Button.url(
                    "Join the Group", "tg://some_unsupported_feature")],
                [custom.Button.url(
                    "Source Code", "tg://some_unsupported_feature")]
            ],
            link_preview=False
        )
    await event.answer([result] if result else None)