Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - When Telethon download media files, it fails because of FILE_REFERENCE_EXPIRED. How to download it again?

The code works only for two hours . I have a low bandwidth Internet connection I can't do very much. I found this on doc I hope will be useful. based on doc https://core.telegram.org/api/file_reference

if this happens, the context info must be used to refetch the object that contained the file reference: in this example, the peer info and the message ID have to be used with channels.getMessages or messages.getMessages to refetch the message, recache the file reference and use it in a new file download request.

If I understood correctly, I have to do :

  1. refetch the message relative to this error code
  2. Download the media using this new message object

This is my code simplified:

async def Download():
      channel = await client(functions.messages.CheckChatInviteRequest(hash=channel))
async for message in client.iter_messages(channel.chat,filter=InputMessagesFilterDocument):
       if message.media is not None:
            #FileReferenceExpiredError
            try:  
                await message.download_media(file_path,progress_callback=callback) 
            except errors.FileReferenceExpiredError:

That is a simplified version but it only runs for two hours. When it catches the error

  1. I have to refetch the message and here I dont know how to refetch message inside iter_message I tried like this:

    result = client(functions.channels.GetMessagesRequest( channel=channel, id=message.id ))

AND

  1. Download the media using this new message object so I have to call again i.e . download_media (result......) ?

I'm aware that message object contains File reference , How Do I use it?

Thank for any tips

EDIT : I've been able to catch the exception.

fout = open(file_path + message.file_name, 'wb')
try:
    await download_file(client, message.media.document, fout, progress_callback=callback)
except errors.FileReferenceExpiredError:
    fout.close()
    fout = open(file_path + "fetch-" + message.file.name, 'wb')
    refetch = await client.get_messages(channel.chat, ids=message.id)
    await download_file(client, refetch.media.document, fout, progress_callback=callback)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...