【问题标题】:Download a file from Telegram using aiogram bot-framework in Python在 Python 中使用 aiogram bot-framework 从 Telegram 下载文件
【发布时间】:2021-11-06 08:45:27
【问题描述】:

如何下​​载用户在聊天中发送的文件?

例如

我需要从 Telegram 下载文件 moonloader.log 到我的本地路径 C:\text-folder\moonloader.log 并阅读它。

到目前为止的代码

def checkFile(path):
    if os.path.isfile(path):
        f = open(path, 'r')
        log = f.read()
        print('начинаю проверку...')
        # check log
        result = re.search('MoonLoader v.(.+) loaded.', log)
        if result:
            moonlog_version = result.group(1)
            print('• Версия moonloader: ' + moonlog_version)
            for err in range(0, len(errors)):
                for i in errors[err]:
                    print('   • Ошибка: ' + errors[err][i])

# ON RECEIVE FILE 
@dp.message_handler(content_types=types.ContentType.DOCUMENT)
async def fileHandle(message: types.File):
    await message.reply(text='файл получен, начинаю поиск ошибок...')
    ## LOAD FILE CODE
    checkFile(LOADED FILE PATH)

更新代码

我尝试关注answer of hc_dev并添加了下载方法。但不确定如何从message 获取Filefile_path。我试过这个:

def download_file(file: types.File):
    file_path = file.file_path 
    destination = r'C:\\Users\\admin\\Desktop\\moonlog inspector\\download'
    destination_file = bot.download_file(file_path, destination) # ON RECEIVE FILE 

@dp.message_handler(content_types=types.ContentType.DOCUMENT)
async def fileHandle(message: types.Document):
    await message.reply(text='файл получен, начинаю поиск ошибок...')
    ## LOAD FILE CODE
    download_file(message.file_id)

但是运行时会报错:

'Message' 对象没有属性 'file_id'

【问题讨论】:

标签: python file download telegram-bot aiogram


【解决方案1】:

以下问题欢迎并解释了 Telegram Bot API 中的新 getFile 操作: How do I download a file or photo that was sent to my Telegram bot?

aiogram 中,您将在您的 Bot 对象上使用 download_file: 作为参数,您可以传递字符串file_path(在电报服务器上标识文件的路径)和本地卷上的destination

file_pathtypes.File 对象的属性。

bot = # your_bot accessing Telegram's API

def download_file(file: types.File):
     file_path = file.file_path
     destination = r"C:\folder\file.txt"
     destination_file = bot.download_file(file_path, destination)

【讨论】:

  • 但是我怎样才能得到 file_path?你能帮助我吗? ``` def download_file(file: types.File): file_path = file.file_path destination = r'C:\\Users\\admin\\Desktop\\moonlog inspector\\download'destination_file = bot.download_file(file_path, destination ) # 接收文件@dp.message_handler(content_types=types.ContentType.DOCUMENT) async def fileHandle(message: types.Document): await message.reply(text='файл получен, начинаю поиск ошибок...') ##加载文件代码 download_file(message.file_id) ``` 'Message' 对象没有属性 'file_id'
猜你喜欢
  • 2016-01-10
  • 1970-01-01
  • 2016-10-11
  • 2018-11-19
  • 2020-02-28
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多