async def get_document_from_file_id(file_id: str) -> raw.base.InputDocument: decoded = FileId.decode(file_id) return raw.types.InputDocument( id=decoded.media_id, access_hash=decoded.access_hash, file_reference=decoded.file_reference, )
def get_input_file_from_file_id( file_id: str, expected_file_type: FileType = None ) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]: try: decoded = FileId.decode(file_id) except Exception: raise ValueError(f'Failed to decode "{file_id}". The value does not represent an existing local file, ' f'HTTP URL, or valid file id.') file_type = decoded.file_type if expected_file_type is not None and file_type != expected_file_type: raise ValueError(f'Expected: "{expected_file_type}", got "{file_type}" file_id instead') if file_type in (FileType.THUMBNAIL, FileType.CHAT_PHOTO): raise ValueError(f"This file_id can only be used for download: {file_id}") if file_type in PHOTO_TYPES: return raw.types.InputPhoto( id=decoded.media_id, access_hash=decoded.access_hash, file_reference=decoded.file_reference ) if file_type in DOCUMENT_TYPES: return raw.types.InputDocument( id=decoded.media_id, access_hash=decoded.access_hash, file_reference=decoded.file_reference ) raise ValueError(f"Unknown file id: {file_id}")
def test_stringify_file_id(): file_id = "BQACAgIAAx0CAAGgr9AAAgmPX7b4UxbjNoFEO_L0I4s6wrXNJA8AAgQAA4GkuUm9FFvIaOhXWR4E" string = "{'major': 4, 'minor': 30, 'file_type': <FileType.DOCUMENT: 5>, 'dc_id': 2, " \ "'file_reference': b'\\x02\\x00\\xa0\\xaf\\xd0\\x00\\x00\\t\\x8f_\\xb6\\xf8S\\x16\\xe36\\x81D;\\xf2\\xf4#\\x8b:\\xc2\\xb5\\xcd$\\x0f', " \ "'media_id': 5312458109417947140, 'access_hash': 6437869729085068477, 'thumbnail_size': ''}" assert str(FileId.decode(file_id)) == string
async def generate_file_properties(msg: Message): error_message = "This message doesn't contain any downloadable media" available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note") if isinstance(msg, Message): for kind in available_media: media = getattr(msg, kind, None) if media is not None: break else: raise ValueError(error_message) else: media = msg if isinstance(media, str): file_id_str = media else: file_id_str = media.file_id file_id_obj = FileId.decode(file_id_str) # The below lines are added to avoid a break in routes.py setattr(file_id_obj, "file_size", getattr(media, "file_size", 0)) setattr(file_id_obj, "mime_type", getattr(media, "mime_type", "")) setattr(file_id_obj, "file_name", getattr(media, "file_name", "")) return file_id_obj
def unpack_new_file_id(new_file_id): """Return file_id, file_ref""" decoded = FileId.decode(new_file_id) file_id = encode_file_id( pack("<iiqq", int(decoded.file_type), decoded.dc_id, decoded.media_id, decoded.access_hash)) file_ref = encode_file_ref(decoded.file_reference) return file_id, file_ref
async def pyro_dl(self, file_id): file_id_obj = FileId.decode(file_id) file_type = file_id_obj.file_type mime_type = "" date = 0 file_name = "" directory, file_name = os.path.split(file_name) if not os.path.isabs(file_name): directory = self.client.PARENT_DIR / (directory or DEFAULT_DOWNLOAD_DIR) if not file_name: guessed_extension = self.client.guess_extension(mime_type) if file_type in PHOTO_TYPES: extension = ".jpg" elif file_type == FileType.VOICE: extension = guessed_extension or ".ogg" elif file_type in (FileType.VIDEO, FileType.ANIMATION, FileType.VIDEO_NOTE): extension = guessed_extension or ".mp4" elif file_type == FileType.DOCUMENT: extension = guessed_extension or ".zip" elif file_type == FileType.STICKER: extension = guessed_extension or ".webp" elif file_type == FileType.AUDIO: extension = guessed_extension or ".mp3" else: extension = ".unknown" file_name = "{}_{}_{}{}".format( FileType(file_id_obj.file_type).name.lower(), datetime.fromtimestamp( date or time.time()).strftime("%Y-%m-%d_%H-%M-%S"), self.client.rnd_id(), extension) final_file_path = os.path.abspath( re.sub("\\\\", "/", os.path.join(directory, file_name))) os.makedirs(directory, exist_ok=True) downloaderr = self.handle_download(file_id_obj, final_file_path) asyncio.get_event_loop().create_task(downloaderr) return final_file_path
async def parse_file_id(message: "Message") -> Optional[FileId]: media = get_media_from_message(message) if media: return FileId.decode(media.file_id)
def is_photo(file_id: str) -> bool: return bool(FileId.decode(file_id).file_type in PHOTO_TYPES)
async def download_media( self, message: Union["types.Message", str], file_name: str = DEFAULT_DOWNLOAD_DIR, block: bool = True, progress: callable = None, progress_args: tuple = ()) -> Optional[str]: """Download the media from a message. Parameters: message (:obj:`~pyrogram.types.Message` | ``str``): Pass a Message containing the media, the media itself (message.audio, message.video, ...) or a file id as string. file_name (``str``, *optional*): A custom *file_name* to be used instead of the one provided by Telegram. By default, all files are downloaded in the *downloads* folder in your working directory. You can also specify a path for downloading files in a custom location: paths that end with "/" are considered directories. All non-existent folders will be created automatically. block (``bool``, *optional*): Blocks the code execution until the file has been downloaded. Defaults to True. progress (``callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: ``str`` | ``None``: On success, the absolute path of the downloaded file is returned, otherwise, in case the download failed or was deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned. Raises: ValueError: if the message doesn't contain any downloadable media Example: .. code-block:: python # Download from Message app.download_media(message) # Download from file id app.download_media("CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") # Keep track of the progress while downloading def progress(current, total): print(f"{current * 100 / total:.1f}%") app.download_media(message, progress=progress) """ available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note", "new_chat_photo") if isinstance(message, types.Message): for kind in available_media: media = getattr(message, kind, None) if media is not None: break else: raise ValueError( "This message doesn't contain any downloadable media") else: media = message if isinstance(media, str): file_id_str = media else: file_id_str = media.file_id file_id_obj = FileId.decode(file_id_str) file_type = file_id_obj.file_type media_file_name = getattr(media, "file_name", "") file_size = getattr(media, "file_size", 0) mime_type = getattr(media, "mime_type", "") date = getattr(media, "date", 0) directory, file_name = os.path.split(file_name) file_name = file_name or media_file_name or "" if not os.path.isabs(file_name): directory = self.PARENT_DIR / (directory or DEFAULT_DOWNLOAD_DIR) if not file_name: guessed_extension = self.guess_extension(mime_type) if file_type in PHOTO_TYPES: extension = ".jpg" elif file_type == FileType.VOICE: extension = guessed_extension or ".ogg" elif file_type in (FileType.VIDEO, FileType.ANIMATION, FileType.VIDEO_NOTE): extension = guessed_extension or ".mp4" elif file_type == FileType.DOCUMENT: extension = guessed_extension or ".zip" elif file_type == FileType.STICKER: extension = guessed_extension or ".webp" elif file_type == FileType.AUDIO: extension = guessed_extension or ".mp3" else: extension = ".unknown" file_name = "{}_{}_{}{}".format( FileType(file_id_obj.file_type).name.lower(), datetime.fromtimestamp( date or time.time()).strftime("%Y-%m-%d_%H-%M-%S"), self.rnd_id(), extension) downloader = self.handle_download((file_id_obj, directory, file_name, file_size, progress, progress_args)) if block: return await downloader else: asyncio.get_event_loop().create_task(downloader)
async def stream_media( self, message: Union["types.Message", str], progress: callable = None, progress_args: tuple = () ) -> Optional[AsyncGenerator]: """Stream the media from a message. Parameters: message (:obj:`~pyrogram.types.Message` | ``str``): Pass a Message containing the media, the media itself (message.audio, message.video, ...) or a file id as string. progress (``callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: ``async_generator``: In case the download failed or was deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned. Raises: ValueError: if the message doesn't contain any downloadable media Example: .. code-block:: python # Stream from Message media_streaming = app.stream_media(message) async for media_bytes in media_streaming: print(f"New bytes received: {media_bytes}") # Stream from file id media_streaming = app.stream_media("CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") async for media_bytes in media_streaming: print(f"New bytes received: {media_bytes}") # Keep track of the progress while downloading def progress(current, total): print(f"{current * 100 / total:.1f}%") media_streaming = app.stream_media(message, progress=progress) async for media_bytes in media_streaming: print(f"New bytes received: {media_bytes}") """ available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note", "new_chat_photo") if isinstance(message, types.Message): for kind in available_media: media = getattr(message, kind, None) if media is not None: break else: raise ValueError( "This message doesn't contain any downloadable media") else: media = message if isinstance(media, str): file_id_str = media else: file_id_str = media.file_id file_id_obj = FileId.decode(file_id_str) media_file_name = getattr(media, "file_name", "") file_size = getattr(media, "file_size", 0) return self.get_streaming_file(file_id_obj, file_size, progress, progress_args)
def check(file_id: str, expected_file_type: FileType): decoded = FileId.decode(file_id) assert decoded.file_type == expected_file_type assert decoded.encode() == file_id
async def inline_query_handler(c: Client, iq: InlineQuery): q = iq.query res = [] if len(q.strip()) < 2: await iq.answer([]) return if q.strip().startswith('dl:'): q_res_data = await BookdlFiles().get_file_by_name( q.split(':')[1].strip(), 50) if q_res_data: for file in q_res_data: file_id_obj = FileId.decode(file['file_id']) res.append( InputBotInlineResultDocument( id=str(file['_id']), type='file', document=InputDocument( id=file_id_obj.media_id, access_hash=file_id_obj.access_hash, file_reference=file_id_obj.file_reference), send_message=InputBotInlineMessageMediaAuto( message=file['title']), title=file['title'], description=f"File Name: {file['file_name']}\n" f"File Type: {file['file_type']}", )) await BookDLBot.invoke(data=SetInlineBotResults( query_id=int(iq.id), results=res, cache_time=0)) else: await iq.answer([]) return else: if q.strip(): result = await Libgen(result_limit=50 ).search(query=q.strip(), return_fields=[ 'title', 'pages', 'language', 'publisher', 'year', 'author', 'extension', 'coverurl', 'volumeinfo', 'mirrors', 'md5' ]) if result is not None: for item in result: res.append( InlineQueryResultArticle( title=result[item]['title'], description=f"Author: {result[item]['author']}\n" f"Volume: {result[item]['volumeinfo']} Year: {result[item]['year']} Pages: {result[item]['pages']}\n" f"Language: {result[item]['language']} Extension: {result[item]['extension']}\n" f"Publisher: {result[item]['publisher']}\n", thumb_url="https://cdn3.iconfinder.com/data/icons/" "education-vol-1-34/512/15_File_files_office-256.png" if result[item]['coverurl'] is None else result[item]['coverurl'], input_message_content=InputTextMessageContent( message_text=f"MD5: {result[item]['md5']}\n" f"Title: **{result[item]['title']}**\n" f"Author: **{result[item]['author']}**"), reply_markup=None)) if res: await iq.answer(results=res, cache_time=60, is_personal=False) else: await iq.answer( results=[], cache_time=7, switch_pm_text=f'{emoji.CROSS_MARK} No results for "{q}"', switch_pm_parameter="okay", )
async def stream_media(self: "pyrogram.Client", message: Union["types.Message", str], limit: int = 0, offset: int = 0) -> Optional[Union[str, BinaryIO]]: """Stream the media from a message chunk by chunk. You can use this method to partially download a file into memory or to selectively download chunks of file. The chunk maximum size is 1 MiB (1024 * 1024 bytes). Parameters: message (:obj:`~pyrogram.types.Message` | ``str``): Pass a Message containing the media, the media itself (message.audio, message.video, ...) or a file id as string. limit (``int``, *optional*): Limit the amount of chunks to stream. Defaults to 0 (stream the whole media). offset (``int``, *optional*): How many chunks to skip before starting to stream. Defaults to 0 (start from the beginning). Returns: ``Generator``: A generator yielding bytes chunk by chunk Example: .. code-block:: python # Stream the whole media async for chunk in app.stream_media(message): print(len(chunk)) # Stream the first 3 chunks only async for chunk in app.stream_media(message, limit=3): print(len(chunk)) # Stream the rest of the media by skipping the first 3 chunks async for chunk in app.stream_media(message, offset=3): print(len(chunk)) # Stream the last 3 chunks only (negative offset) async for chunk in app.stream_media(message, offset=-3): print(len(chunk)) """ available_media = ("audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note", "new_chat_photo") if isinstance(message, types.Message): for kind in available_media: media = getattr(message, kind, None) if media is not None: break else: raise ValueError( "This message doesn't contain any downloadable media") else: media = message if isinstance(media, str): file_id_str = media else: file_id_str = media.file_id file_id_obj = FileId.decode(file_id_str) file_size = getattr(media, "file_size", 0) if offset < 0: if file_size == 0: raise ValueError( "Negative offsets are not supported for file ids, pass a Message object instead" ) chunks = math.ceil(file_size / 1024 / 1024) offset += chunks async for chunk in self.get_file(file_id_obj, file_size, limit, offset): yield chunk