You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telethon异步下载Telegram媒体遇文件引用过期及旧消息问题

Telegram媒体下载过期错误解决

版本信息

python: 3.10.12
telethon: 1.34.0

问题场景

以下代码用于从Telegram下载媒体文件:

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)  # 耗时操作
                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())

代码运行初期可正常下载少量文件,但一段时间后出现异常:

  • 重复收到「Server sent a very old message...忽略」类提示,甚至触发「Security error while unpacking...」错误
  • 继续运行后抛出telethon.errors.rpcerrorlist.FileReferenceExpiredError,重试下载同一消息仍报错

解决方法

替换为telethon.sync客户端,并通过消息ID获取消息,问题已解决。

内容的提问来源于stack exchange,提问作者nlblack323

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:15:59