How can I download a file which has been sent by a user in chat?
For example
I need to download the file moonloader.log
from Telegram to my local path C:text-foldermoonloader.log
and read it.
Code so far
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)
Updated Code
I tried to follow the answer of hc_dev and added the download method. But not sure how to get the File
or file_path
from message
. I tried this:
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)
But when running it raises the error:
‘Message’ object has no attribute ‘file_id’
2
Answers
Following question welcomed and explained the new
getFile
operation in Telegram Bot API:How do I download a file or photo that was sent to my Telegram bot?
In aiogram you would use
download_file
on youBot
object:As parameters you can pass the string
file_path
(path identifying the file on the telegram server) and adestination
on your local volume.The
file_path
is an attribute of antypes.File
object.If you don’t want to save files locally, you could use io.BytesIO. In my projects I am used to save files like that:
or with a context manager: