Python Telethon,如何恢复下载媒体

Python Telethon, how to resume a download media

目前正在下载我正在使用的文件

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()


但有时我会失去联系,因为我的网络或电报disconnection.Or可能是因为我需要重新启动...这是一个日志。

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" 是我使用 logging.info(....)

写的消息

真恶心...文件进度99%,但连接失败,必须从零开始重新下载。

阅读文档我发现了这个client.iter_download 我试过了:

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)

但如果我停止脚本,结果相同,下载从零开始

iter_download是正确的方法,但是,您需要手动指定恢复偏移量(并且您应该以追加模式打开文件):

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)