【问题标题】:How Can I download media to specific path on Telethon如何将媒体下载到 Telethon 上的特定路径
【发布时间】:2021-05-11 23:41:34
【问题描述】:

我正在研究用于从电报下载媒体的 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())

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

【问题讨论】:

    标签: python file telegram telegram-bot telethon


    【解决方案1】:

    Docs of telethon 表明download_media 方法接受名为file 的参数,即

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

    我没有能力测试它,但是像替换

    message.download_media()
    

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

    应该可以。

    【讨论】:

      【解决方案2】:

      你可以使用message.file.name获取文件名,这里是代码

      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())
      

      【讨论】:

      • 但是当我们使用event时我们如何获取文件名
      • 更简单(更可靠)的解决方案:message.file.name.
      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多