Search code examples
pythontelegramtelethon

Python Telethon, how to resume a download media


Currently to download file i'm using

from telethon import TelegramClient

client = TelegramClient('anon', api_id, api_hash)


async def main():
        async for dialog in client.iter_messages(entity=peer_channel):
          await dialog.download_media("file....")


def bot():
    with client:
        client.loop.run_until_complete(main())

    client.start()
    client.run_until_disconnected()

if __name__ == "__main__":
    bot()


But sometimes I lost connection, because of my net or telegram disconnection.Or maybe because I need to restart... Here a log.

INFO:root:Download total: 99% 1048.50 mb/1057.82 mb tmp/Evil/2x12 Evil.rar
INFO:telethon.network.mtprotosender:Disconnecting from xxx.xxx.xxx.xxx:443/TcpFull...
INFO:telethon.network.mtprotosender:Disconnection from xxx.xxx.xxx.xxx:443/TcpFull complete!
INFO:telethon.network.mtprotosender:Connecting to xxx.xxx.xxx.xxx:443/TcpFull...
INFO:telethon.network.mtprotosender:Connection to xxx.xxx.xxx.xxx:443/TcpFull complete!
INFO:root:[DEBUG] DOWNLOADING /export/nasty/tmp/Evil/2x12 Evil.rar
INFO:telethon.client.downloads:Starting direct file download in chunks of 524288 at 0, stride 524288

"INFO:root" are messages writed by me using logging.info(....)

It's disgusting... file was at 99% but connection failed and must to restart download from zero.

Reading documentation I found this client.iter_download I tried:

async def main():
    async for dialog in client.iter_messages(entity=peer_channel):
# Filename should be generated by dialog.media, is a example
        with open('file.rar', 'wb') as fd:
            async for chunk in client.iter_download(dialog.media):
                fd.write(chunk)

But same result if I stop script, download start from zero


Solution

  • iter_download is the correct way, however, you need to manually specify the resume offset (and you should open the file in append mode):

    import os
    
    file = 'file.rar'
    
    try:
        offset = os.path.getsize(file)
    except OSError:
        offset = 0
    
    with open(file, 'ab') as fd:
        #            ^ append
        async for chunk in client.iter_download(dialog.media, offset=offset):
            #                                                 ^~~~~~~~~~~~~ resume from offset
            fd.write(chunk)