Ejemplo n.º 1
0
async def upload(event: NewMessage.Event) -> None:
    """
    Upload media to Telegram.


    **{prefix}upload (path)** or **{prefix}ul (path)**
    """
    match = event.matches[0].group(3)
    target_files = []
    if not match:
        await event.answer("`Uploaded the void.`")
        return

    match = match.strip().replace("\\", "/") if match else ""
    fmatch = pathlib.Path(match)
    dmatch = pathlib.Path(downloads / match)

    if "*" not in match:
        if fmatch.exists():
            target_files.append(fmatch)
        elif dmatch.exists():
            target_files.append(dmatch)
    if not target_files:
        for f in downloads.glob("*.*"):
            if f.match(match) and f.is_file():
                target_files.append(f)
    # Un-comment this for recursive file fetching from the bot's root dir
    """for f in pathlib.Path('.').glob('**/*.*'):
        if f in target_files:
            continue
        if not f.match('*/__pycache__/*') and f.match(match) and f.is_file():
            target_files.append(f)"""

    if not target_files:
        await event.answer("`Couldn't find what you were looking for.`")
        return

    files = "\n".join([f"`{await _get_file_name(f)}`" for f in target_files])
    if len(target_files) > 1:
        await event.answer(f"**Found multiple files for {match}:**\n{files}")
        return

    for f in target_files:
        f = f.absolute()
        prog = ProgressCallback(event, filen=await _get_file_name(f, False))
        attributes, mime_type = get_attributes(str(f))
        ul = io.open(f, "rb")
        uploaded = await client.fast_upload_file(
            file=ul, progress_callback=prog.up_progress)
        ul.close()
        media = types.InputMediaUploadedDocument(file=uploaded,
                                                 mime_type=mime_type,
                                                 attributes=attributes,
                                                 thumb=None)
        await client.send_file(event.chat_id,
                               file=media,
                               force_document=True,
                               reply_to=event)

    await event.answer(f"`Successfully uploaded {files}.`")
Ejemplo n.º 2
0
async def download(event: NewMessage.Event) -> None:
    """
    Download documents from Telegram.


    `{prefix}download` or `{prefix}dl` or **{prefix}download (path)**
    """
    name = NAME
    path = None
    match = event.matches[0].group(3)
    if match:
        path = pathlib.Path(match.strip())

    if not event.reply_to_msg_id:
        await event.answer("`Downloaded the void.`")
        return

    reply = await event.get_reply_message()
    if not (reply.document or reply.media):
        await event.answer("`There is no document/media in here to download!`")
        return

    for attr in getattr(reply.document, "attributes", []):
        if isinstance(attr, types.DocumentAttributeFilename):
            name = attr.file_name
    ext = get_extension(reply.document)
    if path and not path.suffix and ext:
        path = path.with_suffix(ext)
    if name == NAME:
        name += "_" + str(getattr(reply.document, "id", reply.id)) + ext

    if path and path.exists():
        if path.is_file():
            newname = str(path.stem) + "_OLD"
            path.rename(path.with_name(newname).with_suffix(path.suffix))
            file_name = path
        else:
            file_name = path / name
    elif path and not path.suffix and ext:
        file_name = downloads / path.with_suffix(ext)
    elif path:
        file_name = path
    else:
        file_name = downloads / name
    file_name.parent.mkdir(parents=True, exist_ok=True)

    prog = ProgressCallback(event,
                            filen=await _get_file_name(file_name, False))
    if reply.document:
        dl = io.FileIO(file_name.absolute(), "a")
        await client.fast_download_file(location=reply.document,
                                        out=dl,
                                        progress_callback=prog.dl_progress)
        dl.close()
    else:
        await reply.download_media(file=file_name.absolute(),
                                   progress_callback=prog.dl_progress)

    await event.answer(f"__Downloaded successfully!__\n"
                       f"**Path:** `{await _get_file_name(file_name)}`")
Ejemplo n.º 3
0
async def upload(event: NewMessage.Event) -> None:
    """Upload media to Telegram."""
    match = event.matches[0].group(3)
    target_files = []
    if not match:
        await event.answer("__Uploaded the void?__")
        return

    match = match.strip().replace('\\', '/') if match else ''
    fmatch = pathlib.Path(match)

    if '*' in match and '/' not in match:
        for f in downloads.glob('*.*'):
            if f.match(match):
                target_files.append(f)
    elif '*' not in match and '/' in match:
        if fmatch.exists():
            target_files.append(fmatch)
        elif (downloads / match).exists():
            target_files.append(downloads / match)
    for f in pathlib.Path('.').glob('**/*.*'):
        if f in target_files:
            continue
        if not f.match('*/__pycache__/*') and f.match(match):
            target_files.append(f)

    if not target_files:
        await event.answer("__Couldn't find what you were looking for.__")
        return

    files = ', '.join([f.stem for f in target_files])
    for f in target_files:
        f = f.resolve()
        prog = ProgressCallback(event, filen=f.stem)
        attributes, mime_type = get_attributes(str(f))
        ul = io.open(f, 'rb')
        uploaded = await client.fast_upload_file(
            file=ul, progress_callback=prog.up_progress)
        ul.close()
        media = types.InputMediaUploadedDocument(file=uploaded,
                                                 mime_type=mime_type,
                                                 attributes=attributes,
                                                 thumb=None)
        await client.send_file(event.chat_id,
                               file=media,
                               caption=str(f.parent / f.name),
                               force_document=True,
                               reply_to=event)

    await event.answer(f"__Successfully uploaded {files}.__")
Ejemplo n.º 4
0
async def download(event: NewMessage.Event) -> None:
    """Download documents from Telegram."""
    name = NAME
    path = downloads
    match = event.matches[0].group(3)
    if match:
        path = pathlib.Path(match.strip())

    if not event.reply_to_msg_id:
        await event.answer("__Downloaded the void?__")
        return

    reply = await event.get_reply_message()
    if not (reply.document or reply.media):
        await event.answer("__There is no document to download.__")
        return

    for attr in getattr(reply.document, 'attributes', []):
        if isinstance(attr, types.DocumentAttributeFilename):
            name = attr.file_name
    ext = get_extension(reply.document)
    if name == NAME:
        name += ('_' + str(getattr(reply.document, 'id', reply.id)) + ext)

    if path.exists():
        if path.is_file():
            newname = str(path.stem) + '_OLD'
            path.rename(path.with_name(newname).with_suffix(path.suffix))
            file_name = path
        else:
            file_name = path / name
    elif not path.suffix and ext:
        file_name = downloads / path.with_suffix(ext)
    else:
        downloads.mkdir(parents=True, exist_ok=True)
        file_name = downloads / name

    prog = ProgressCallback(event, filen=file_name.stem)
    if reply.document:
        dl = io.FileIO(file_name.resolve(), 'a')
        await client.fast_download_file(location=reply.document,
                                        out=dl,
                                        progress_callback=prog.dl_progress)
        dl.close()
    else:
        await reply.download_media(file=file_name.resolve(),
                                   progress_callback=prog.dl_progress)

    await event.answer(f"__Successfully downloaded {file_name.stem}.__")
Ejemplo n.º 5
0
async def yt_dl(event):
    """
    Download videos from YouTube with their url in multiple formats.


    **{prefix}ytdl link1 link2 link3 [kwargs]**
        Stream and progress are set to True, while update is at 10% by default.
        **Arguments:**
            `format` (The format to convert/download the video in),
            `delete` (Whether to delete the local files or not),
            `upload` (Whether to upload the downloaded files or not),
            `update` (The percentage to update the progress at),
            `stream` (Whether to upload the files as streamable or not),
            `progress` (Whether to update the progress by edits or not)
    """
    match = event.matches[0].group(1)
    force_document = True
    if not match:
        await event.answer(
            "`.ytdl <url>` or `.ytdl <url1> .. <urln> format=<fmt>`")
        return

    args, kwargs = await client.parse_arguments(match)
    fmt = kwargs.get('format', kwargs.get('fmt', False))
    auto_delete = kwargs.get('delete', False)
    upload = kwargs.get('upload', True)
    round_message = kwargs.get('round_message', kwargs.get('round', False))
    update = kwargs.get('update', 10)
    supports_streaming = kwargs.get('supports_streaming',
                                    kwargs.get('stream', True))
    progress = kwargs.get('progress', True)
    if not upload and auto_delete:
        await event.answer(
            "`The void doesn't make sense! Either don't upload or delete.`")
        return
    ffmpeg = await is_ffmpeg_there()
    params = copy.deepcopy(ydl_opts)
    warnings = []

    if fmt:
        fmt = fmt.strip().lower()
        if fmt == 'listformats':
            fmts = []
            for url in args:
                info = await extract_info(
                    client.loop, concurrent.futures.ThreadPoolExecutor(),
                    params, url)
                if isinstance(info, dict):
                    fmts.append(await list_formats(info))
                elif isinstance(info, str):
                    warnings.append(info)
                else:
                    warnings.append(
                        f'```{await client.get_traceback(info)}```')
            if fmts:
                text = "**Formats:**\n"
                text += "\n\n".join(fmts)
                await event.answer(text)
            if warnings:
                text = "**Warnings:**\n"
                text += "\n\n".join(f"```{w}```" for w in warnings)
                reply = True if fmts else False
                await event.answer(text, reply=reply)
            return
        elif fmt in audioFormats and ffmpeg:
            params.update(format='bestaudio')
            params['postprocessors'].append({
                'key': 'FFmpegExtractAudio',
                'preferredcodec': fmt,
                'preferredquality': '320',
            })
        elif fmt in videoFormats and ffmpeg:
            params['postprocessors'].append({
                'key': 'FFmpegVideoConvertor',
                'preferedformat': fmt
            })
        else:
            params.update(format=fmt)
            if ffmpeg:
                params.update(key='FFmpegMetadata')
                if fmt in ['mp3', 'mp4', 'm4a']:
                    params.update(writethumbnail=True)
                    params['postprocessors'].append({'key': 'EmbedThumbnail'})

    if progress:
        event.media = None
        progress = ProgressHook(event, update)
        params['progress_hooks'].append(progress.hook)
        progress_cb = ProgressCallback(event, update=update)

    for url in args:
        await event.answer(f"`Processing {url}...`")
        output = await extract_info(
            loop=client.loop,
            ydl_opts=params,
            url=url,
            download=True,
            executor=concurrent.futures.ThreadPoolExecutor())
        if isinstance(output, str):
            result = warning + output if not ffmpeg else output
            warnings.append(result)
        elif isinstance(output, BaseException):
            warnings.append(f'```{await client.get_traceback(output)}```')
        elif output is None:
            await event.answer('`Oh oh, sum ting went wong`')
            return
        else:
            if upload:
                path, thumb, info = output
                title = info.get('title', info.get('id', 'Unknown title'))
                url = info.get('webpage_url', None)
                href = f"[{title}]({url})"
                text = success.format(href)
                result = warning + text if not ffmpeg else text

                dl = io.open(path, 'rb')
                if progress:
                    progress_cb.filen = title
                uploaded = await client.fast_upload_file(
                    dl, progress_cb.up_progress if progress else None)
                dl.close()

                attributes, mime_type = await fix_attributes(
                    path, info, round_message, supports_streaming)
                media = types.InputMediaUploadedDocument(
                    file=uploaded,
                    mime_type=mime_type,
                    attributes=attributes,
                    thumb=await client.upload_file(thumb) if thumb else None)

                if supports_streaming and path.suffix == '.mp4':
                    force_document = False
                if round_message:
                    force_document = False
                await client.send_file(event.chat_id,
                                       media,
                                       caption=href,
                                       force_document=force_document)
                if thumb:
                    os.remove(thumb)
                if auto_delete:
                    os.remove(path)
            else:
                if thumb:
                    os.remove(thumb)
    if warnings:
        text = "**Warnings:**\n"
        text += ",\n\n".join(warnings)
        await event.answer(text)
    else:
        await event.delete()
Ejemplo n.º 6
0
async def yt_dl(event):
    """
    Download videos from YouTube with their url in multiple formats.


    **{prefix}ytdl link1 link2 link3 [kwargs]**
        Stream and progress are set to True, while update is at 10% by default.
        **Arguments:**
            `format` (The format to convert/download the video in),
            `delete` (Whether to delete the local files or not),
            `upload` (Whether to upload the downloaded files or not),
            `update` (The percentage to update the progress at),
            `stream` (Whether to upload the files as streamable or not),
            `progress` (Whether to update the progress by edits or not)
    """
    match = event.matches[0].group(1)
    force_document = True
    if not match:
        await event.answer(
            "`.ytdl <url>` or `.ytdl <url1> .. <urln> format=<fmt>`")
        return

    args, kwargs = await client.parse_arguments(match)
    fmt = kwargs.get("format", kwargs.get("fmt", False))
    auto_delete = kwargs.get("delete", False)
    upload = kwargs.get("upload", True)
    progress = kwargs.get("progress", True)
    round_message = kwargs.get("round_message", kwargs.get("round", False))
    update = kwargs.get("update", 10)
    supports_streaming = kwargs.get("supports_streaming",
                                    kwargs.get("stream", True))
    if not upload and auto_delete:
        await event.answer("`The void doesn't make sense!\
            \nEither don't upload or delete.`")
        return
    ffmpeg = await is_ffmpeg_there()
    params = copy.deepcopy(ydl_opts)
    params["postprocessor_args"] = (
        ["-preset", "ultrafast", "-tune", "fastdecode"] if ffmpeg else [])
    warnings = []

    if fmt:
        fmt = fmt.strip().lower()
        if fmt in audioFormats and ffmpeg:
            params.update(format="bestaudio")
            params["postprocessors"].append({
                "key": "FFmpegExtractAudio",
                "preferredcodec": fmt,
                "preferredquality": "320",
            })
            if fmt in ["mp3", "m4a"]:
                params["postprocessors"].append({"key": "EmbedThumbnail"})
                if fmt in ["mp3"]:
                    params["postprocessor_args"] += [
                        "-write_id3v1",
                        "1",
                        "-id3v2_version",
                        "3",
                    ]
        elif fmt in videoFormats and ffmpeg:
            params["postprocessors"].append({
                "key": "FFmpegVideoConvertor",
                "preferedformat": fmt
            })
            if fmt in ["mp4"]:
                params["postprocessors"].append({"key": "EmbedThumbnail"})
        else:
            params.update(format=fmt)
            if ffmpeg:
                params.update(key="FFmpegMetadata")
    else:
        fmts = []
        for url in args:
            info = await extract_info(client.loop,
                                      concurrent.futures.ThreadPoolExecutor(),
                                      params, url)
            if isinstance(info, dict):
                fmts.append(await list_formats(info))
            elif isinstance(info, str):
                warnings.append(info)
            else:
                warnings.append(f"```{await client.get_traceback(info)}```")
        if fmts:
            text = "**Formats:**\n"
            text += ",\n\n".join(f"```{f}```" for f in fmts)
            await event.answer(text)
        if warnings:
            text = "**Warnings:**\n"
            text += ",\n\n".join(f"```{w}```" for w in warnings)
            reply = bool(fmts)
            await event.answer(text, reply=reply)
        return

    if progress:
        event.media = None
        progress = ProgressHook(event, update)
        params["progress_hooks"].append(progress.hook)
        progress_cb = ProgressCallback(event, update=update)

    for url in args:
        await event.answer(f"`Processing {url}...`")
        output = await extract_info(
            loop=client.loop,
            ydl_opts=params,
            url=url,
            download=True,
            executor=concurrent.futures.ThreadPoolExecutor(),
        )
        if isinstance(output, str):
            result = warning + output if not ffmpeg else output
            warnings.append(result)
        elif isinstance(output, BaseException):
            warnings.append(f"```{await client.get_traceback(output)}```")
        elif output is None:
            await event.answer("`Oh oh, some thing went wrong!`")
            return
        else:
            path, thumb, info = output
            if upload:
                title = info.get("title", info.get("id", "Unknown title"))
                url = info.get("webpage_url", None)
                href = f"[{title}]({url})"
                text = success.format(href)
                result = warning + text if not ffmpeg else text

                dl = io.open(path, "rb")
                if progress:
                    progress_cb.filen = title
                uploaded = await client.fast_upload_file(
                    dl, progress_cb.up_progress if progress else None)
                dl.close()

                attributes, mime_type = await fix_attributes(
                    path, info, round_message, supports_streaming)
                media = types.InputMediaUploadedDocument(
                    file=uploaded,
                    mime_type=mime_type,
                    attributes=attributes,
                    thumb=await client.upload_file(thumb) if thumb else None,
                )

                if supports_streaming and path.suffix == ".mp4":
                    force_document = False
                if round_message:
                    force_document = False
                await client.send_file(
                    event.chat_id,
                    media,
                    caption=href,
                    reply_to=event.reply_to_msg_id,
                    force_document=force_document,
                )
                if thumb:
                    os.remove(thumb)
                if auto_delete:
                    os.remove(path)
            else:
                if thumb:
                    os.remove(thumb)
    if warnings:
        text = "**Warnings:**\n"
        text += ",\n\n".join(warnings)
        await event.answer(text)
    else:
        await event.delete()
Ejemplo n.º 7
0
async def yt_dl(event):
    """Download videos from YouTube with their url in multiple formats."""
    url = event.matches[0].group(1)
    fmt = event.matches[0].group(2)
    if not url:
        await event.answer("`.ytdl <url>` or `.ytdl <url> <format>`")
        return

    ffmpeg = await is_ffmpeg_there()
    params = copy.deepcopy(ydl_opts)

    if fmt:
        fmt = fmt.strip()
        if fmt == 'listformats':
            info = await extract_info(
                client.loop, concurrent.futures.ThreadPoolExecutor(),
                params, url
            )
            if isinstance(info, dict):
                fmts = await list_formats(info)
                await event.answer(fmts)
            else:
                await event.answer(info)
            return
        elif fmt in audioFormats and ffmpeg:
            params.update(format='bestaudio')
            params['postprocessors'].append(
                {
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': fmt,
                    'preferredquality': '320',
                }
            )
        elif fmt in videoFormats and ffmpeg:
            params.update(format='bestvideo')
            params['postprocessors'].append(
                {
                    'key': 'FFmpegVideoConvertor',
                    'preferedformat': fmt
                }
            )
        else:
            params.update(format=fmt)
            if ffmpeg:
                params.update(key='FFmpegMetadata')
                if fmt in ['mp3', 'mp4', 'm4a']:
                    params.update(writethumbnail=True)
                    params['postprocessors'].append({'key': 'EmbedThumbnail'})

    progress = ProgressHook(event)
    await event.answer("`Processing...`")
    params['progress_hooks'].append(progress.hook)
    output = await extract_info(
        loop=client.loop, executor=concurrent.futures.ThreadPoolExecutor(),
        ydl_opts=params, url=url, download=True
    )
    warning = (
        f"`WARNING: FFMPEG is not installed!` [FFMPEG install guide]({ffurl})"
        " `If you requested multiple formats, they won't be merged.`\n\n"
    )
    if isinstance(output, str):
        result = warning + output if not ffmpeg else output
        await event.answer(result, link_preview=False)
    else:
        path, thumb, info = output
        title = info.get('title', info.get('id', 'Unknown title'))
        uploader = info.get('uploader', None)
        duration = int(info.get('duration', 0))
        width = info.get('width', None)
        height = info.get('height', None)
        url = info.get('webpage_url', None)
        href = f"[{title}]({url})"
        text = success.format(href)
        result = warning + text if not ffmpeg else text

        progress_cb = ProgressCallback(event, filen=title)
        dl = io.open(path, 'rb')
        uploaded = await client.fast_upload_file(dl, progress_cb.up_progress)
        dl.close()

        attributes, mime_type = get_attributes(path)
        if path.suffix[1:] in audioFormats:
            attributes.append(
                types.DocumentAttributeAudio(duration, None, title, uploader)
            )
        elif path.suffix[1:] in videoFormats:
            attributes.append(
                types.DocumentAttributeVideo(duration, width, height)
            )
        media = types.InputMediaUploadedDocument(
            file=uploaded,
            mime_type=mime_type,
            attributes=attributes,
            thumb=await client.upload_file(thumb) if thumb else None
        )

        await client.send_file(
            event.chat_id, media, caption=href, force_document=True
        )
        if thumb:
            os.remove(thumb)
        await event.delete()