import asyncio
import tempfile
from telethon import TelegramClient
from telethon.tl.types import MessageMediaDocument, User
async def download_media(client, dialog):
total_downloads = 0
async for message in client.iter_messages(dialog):
if isinstance(message.media, MessageMediaDocument):
with tempfile.TemporaryFile('wb') as tmp:
print(f'\rtotal downloads: {total_downloads}', end='')
await client.download_media(message, tmp.name)
process_video(tmp.name) # time consuming
total_downloads += 1
async def main():
api_id = 'API_ID'
api_hash = 'API_HASH'
client = TelegramClient('SESSION', api_id, api_hash)
await client.start(phone='PHONE')
async for dialog in client.iter_dialogs():
if isinstance(dialog.entity, User) and dialog.entity.first_name in (
'NAME1',
'NAME2',
):
await download_media(client, dialog)
if __name__ == '__main__':
asyncio.run(main())
Он работает успешно и загружает несколько файлов, но через некоторое время начинают возникать проблемы. Сначала я начинаю получать повторяющиеся сообщения вроде этого:
total downloads: 0
Server sent a very old message with ID 7350958896137580545, ignoring (see FAQ for details)
Server sent a very old message with ID 7350958902767389697, ignoring (see FAQ for details)
Server sent a very old message with ID 7350958906952594433, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959031208322049, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959159667548161, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959289209278465, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959417536965633, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959546499766273, ignoring (see FAQ for details)
Server sent a very old message with ID 7350959676516447233, ignoring (see FAQ for details)
Server sent a very old message with ID 7350963570432817153, ignoring (see FAQ for details)
Security error while unpacking a received message: Too many messages had to be ignored consecutively
Server sent a very old message with ID 7350963636540084225, ignoring (see FAQ for details)
Security error while unpacking a received message: Too many messages had to be ignored consecutively
total downloads: 1
Некоторое время он работает, файлы загружаются, затем выдается исключение и продолжает возникать, если загрузка того же сообщения повторяется.
Traceback (most recent call last):
File "/download/telegram.py", line 14, in download_video
await client.download_media(
File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 422, in download_media
return await self._download_document(
File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 895, in _download_document
result = await self._download_file(
File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 545, in _download_file
async for chunk in self._iter_download(
File "/usr/local/lib/python3.10/dist-packages/telethon/requestiter.py", line 74, in __anext__
if await self._load_next_chunk():
File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 66, in _load_next_chunk
cur = await self._request()
File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 76, in _request
result = await self.client._call(self._sender, self.request)
File "/usr/local/lib/python3.10/dist-packages/telethon/client/users.py", line 87, in _call
result = await future
telethon.errors.rpcerrorlist.FileReferenceExpiredError: The file reference has expired and is no longer valid or it belongs to self-destructing media and cannot be resent (caused by GetFileRequest)
Изменить
Я исправил проблему, заменив telethon клиентом telethon.sync и получив сообщения по идентификатору на основе ответа Лонами.
просмотры: [code]python: 3.10.12 telethon: 1.34.0 [/code] Ниже загружаются медиафайлы из Telegram. [code]import asyncio import tempfile
from telethon import TelegramClient from telethon.tl.types import MessageMediaDocument, User
async def download_media(client, dialog): total_downloads = 0 async for message in client.iter_messages(dialog): if isinstance(message.media, MessageMediaDocument): with tempfile.TemporaryFile('wb') as tmp: print(f'\rtotal downloads: {total_downloads}', end='') await client.download_media(message, tmp.name) process_video(tmp.name) # time consuming total_downloads += 1
async def main(): api_id = 'API_ID' api_hash = 'API_HASH' client = TelegramClient('SESSION', api_id, api_hash) await client.start(phone='PHONE') async for dialog in client.iter_dialogs(): if isinstance(dialog.entity, User) and dialog.entity.first_name in ( 'NAME1', 'NAME2', ): await download_media(client, dialog)
if __name__ == '__main__': asyncio.run(main()) [/code] Он работает успешно и загружает несколько файлов, но через некоторое время начинают возникать проблемы. Сначала я начинаю получать повторяющиеся сообщения вроде этого: [code]total downloads: 0 Server sent a very old message with ID 7350958896137580545, ignoring (see FAQ for details) Server sent a very old message with ID 7350958902767389697, ignoring (see FAQ for details) Server sent a very old message with ID 7350958906952594433, ignoring (see FAQ for details) Server sent a very old message with ID 7350959031208322049, ignoring (see FAQ for details) Server sent a very old message with ID 7350959159667548161, ignoring (see FAQ for details) Server sent a very old message with ID 7350959289209278465, ignoring (see FAQ for details) Server sent a very old message with ID 7350959417536965633, ignoring (see FAQ for details) Server sent a very old message with ID 7350959546499766273, ignoring (see FAQ for details) Server sent a very old message with ID 7350959676516447233, ignoring (see FAQ for details) Server sent a very old message with ID 7350963570432817153, ignoring (see FAQ for details) Security error while unpacking a received message: Too many messages had to be ignored consecutively Server sent a very old message with ID 7350963636540084225, ignoring (see FAQ for details) Security error while unpacking a received message: Too many messages had to be ignored consecutively total downloads: 1 [/code] Некоторое время он работает, файлы загружаются, затем выдается исключение и продолжает возникать, если загрузка того же сообщения повторяется. [code]Traceback (most recent call last): File "/download/telegram.py", line 14, in download_video await client.download_media( File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 422, in download_media return await self._download_document( File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 895, in _download_document result = await self._download_file( File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 545, in _download_file async for chunk in self._iter_download( File "/usr/local/lib/python3.10/dist-packages/telethon/requestiter.py", line 74, in __anext__ if await self._load_next_chunk(): File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 66, in _load_next_chunk cur = await self._request() File "/usr/local/lib/python3.10/dist-packages/telethon/client/downloads.py", line 76, in _request result = await self.client._call(self._sender, self.request) File "/usr/local/lib/python3.10/dist-packages/telethon/client/users.py", line 87, in _call result = await future telethon.errors.rpcerrorlist.FileReferenceExpiredError: The file reference has expired and is no longer valid or it belongs to self-destructing media and cannot be resent (caused by GetFileRequest) [/code] [b]Изменить[/b] Я исправил проблему, заменив telethon клиентом telethon.sync и получив сообщения по идентификатору на основе ответа Лонами.