Exemple #1
0
async def fix_attributes(path,
                         info_dict: dict,
                         supports_streaming: bool = False,
                         round_message: bool = False) -> list:
    """Evite múltiples instancias de un atributo."""
    new_attributes = []
    video = False
    audio = False

    uploader = info_dict.get("uploader", "Unknown artist")
    duration = int(info_dict.get("duration", 0))
    suffix = path.suffix[1:]
    if supports_streaming and suffix != "mp4":
        supports_streaming = True

    attributes, mime_type = get_attributes(path)
    if suffix == "mp3":
        title = str(
            info_dict.get("title", info_dict.get("id", "Unknown title")))
        audio = types.DocumentAttributeAudio(duration=duration,
                                             voice=None,
                                             title=title,
                                             performer=uploader)
    elif suffix == "mp4":
        width = int(info_dict.get("width", 0))
        height = int(info_dict.get("height", 0))
        for attr in attributes:
            if isinstance(attr, types.DocumentAttributeVideo):
                duration = duration or attr.duration
                width = width or attr.w
                height = height or attr.h
                break
        video = types.DocumentAttributeVideo(
            duration=duration,
            w=width,
            h=height,
            round_message=round_message,
            supports_streaming=supports_streaming,
        )

    if audio and isinstance(audio, types.DocumentAttributeAudio):
        new_attributes.append(audio)
    if video and isinstance(video, types.DocumentAttributeVideo):
        new_attributes.append(video)

    for attr in attributes:
        if (isinstance(attr, types.DocumentAttributeAudio) and not audio
                or not isinstance(attr, types.DocumentAttributeAudio)
                and not video
                or not isinstance(attr, types.DocumentAttributeAudio)
                and not isinstance(attr, types.DocumentAttributeVideo)):
            new_attributes.append(attr)
    return new_attributes, mime_type
Exemple #2
0
async def fix_attributes(path,
                         info_dict: dict,
                         round_message: bool = False,
                         supports_streaming: bool = False) -> list:
    """Avoid multiple instances of an attribute."""
    new_attributes = []
    video = False
    audio = False

    title = str(info_dict.get('title', info_dict.get('id', 'Unknown title')))
    uploader = info_dict.get('uploader', 'Unknown artist')
    duration = int(info_dict.get('duration', 0))
    suffix = path.suffix[1:]
    if supports_streaming and suffix != 'mp4':
        supports_streaming = False

    attributes, mime_type = get_attributes(path)
    if suffix in audioFormats:
        audio = types.DocumentAttributeAudio(duration, None, title, uploader)
    elif suffix in videoFormats:
        width = int(info_dict.get('width', 0))
        height = int(info_dict.get('height', 0))
        for attr in attributes:
            if isinstance(attr, types.DocumentAttributeVideo):
                duration = duration or attr.duration
                width = width or attr.w
                height = height or attr.h
                break
        video = types.DocumentAttributeVideo(duration, width, height,
                                             round_message, supports_streaming)

    if audio and isinstance(audio, types.DocumentAttributeAudio):
        new_attributes.append(audio)
    if video and isinstance(video, types.DocumentAttributeVideo):
        new_attributes.append(video)

    for attr in attributes:
        if isinstance(attr, types.DocumentAttributeAudio):
            if not audio:
                new_attributes.append(attr)
        elif isinstance(attr, types.DocumentAttributeVideo):
            if not video:
                new_attributes.append(attr)
        else:
            new_attributes.append(attr)

    return new_attributes, mime_type
Exemple #3
0
    def __init__(
            self,
            user_id: int,
            plain_text: Optional[str] = None,
            format_entities: Optional[list[types.TypeMessageEntity]] = None,
            media: Optional[Union[Sequence[TypeMessageMedia],
                                  TypeMessageMedia]] = None,
            media_type: Optional[TypeMessage] = None,
            link_preview: bool = False,
            silent: bool = False):
        self.user_id = user_id
        self.plain_text = plain_text
        self.format_entities = format_entities
        self.media = media
        self.media_type = media_type
        self.link_preview = link_preview
        self.silent = silent
        self.retries = 0

        self.attributes = ((types.DocumentAttributeVideo(0, 0, 0), )
                           if media_type == VIDEO else
                           ((types.DocumentAttributeAnimated(), )
                            if media_type == ANIMATION else None))
Exemple #4
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()