如何将媒体下载到 Telethon 上的特定路径

Jai*_*ith 6 python file telegram telegram-bot telethon

我正在研究 telethon download_media 和 _download_document 方法,用于从电报下载媒体。我的代码是这样的:

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())
Run Code Online (Sandbox Code Playgroud)

但是此代码无法将媒体下载到特定路径,并且如何获取保存的文件的名称

Daw*_*weo 12

telethon 的文档显示该download_media方法接受名为 的参数file,即

输出文件路径、目录或类似流的对象。如果路径存在并且是一个文件,它将被覆盖。如果文件是字节类型,它将作为字节串下载到内存中(例如文件=字节)。

我没有能力测试它,但类似替换

message.download_media()
Run Code Online (Sandbox Code Playgroud)

message.download_media(file="path/to/downloads_dir")
Run Code Online (Sandbox Code Playgroud)

应该管用。