Search code examples
pythonpython-3.xpyrogram

How to partially download a telegram file in with pyrogram


Actually I need to download first few chunks of a file(video/audio/etc) for the sake of mediainfo.

pyrogram:
https://docs.pyrogram.org/api/methods/stop_transmission
https://docs.pyrogram.org/api/bound-methods/Message.download

progress fn (stops transmission when 1% of file has been downloaded)

    def prog(curr, total, client):
      print(curr * 100 / total, '%', flush=True)
      if curr * 100 / total >= 1:
        client.stop_transmission()

implementation

    tmp = msg.download(progress=prog, in_memory=True, progress_args=(client,))
    print(type(tmp), flush=True)
    with open(f'{msg.id}', 'wb') as f:
        f.write(tmp.getvalue())

What output I am getting is:

1.8244671728371091 %
<class 'NoneType'>

here


Solution

  • You can use stream_media() function to Download chunks of a file

    Here it will Download first 2 chunks of a Document

    media=message.document
    with open(media.file_name, "wb") as file:
        async for chunk in client.stream_media(message=media, limit=2):
            file.write(chunk)
    

    Here is a Complete Example https://github.com/DeekshithSH/pyro-test/blob/main/DownloadMediaChunks.py