6

I'm working on telethon download_media and _download_document methods for downloading media from telegram. My code is something like this:

from telethon import TelegramClient

api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)

async def main():
    async for message in client.iter_messages('me'):
        print(message.id, message.text)

        # You can download media from messages, too!
        # The method will return the path where the file was saved.
        if message.photo:
            path = await message.download_media()
            print('File saved to', path)  # printed after download is done

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

But this code cannot download the media to a specific path, and How Can I get the name of file that saved

2 Answers2

10

Docs of telethon shows that download_media method accepts argument named file, which is

The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten. If file is the type bytes, it will be downloaded in-memory as a bytestring (e.g. file=bytes).

I do not have ability to test it, but something like replacing

message.download_media()

with

message.download_media(file="path/to/downloads_dir")

should work.

Daweo
  • 31,313
  • 3
  • 12
  • 25
3

You Can get File name by Using message.file.name, Here is Code

from telethon import TelegramClient

api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)

async def main():
    async for message in client.iter_messages('me'):
        print(message.id, message.text)
        if message.photo:
            print('File Name :' + str(message.file.name))
            path = await client.download_media(message.media, "youranypathhere")
            print('File saved to', path)  # printed after download is done

with client:
    client.loop.run_until_complete(main())
WarnerStark
  • 172
  • 11