Telebot: отправка боту изображения от пользователя с последующим сохранением

Хочу получить изображение от пользователя, чтобы потом сохранить в папку. В документации нашел лишь вот это:

TOKEN = '<token_string>'
tb = telebot.TeleBot(TOKEN)

# getFile
# Downloading a file is straightforward
# Returns a File object
import requests
file_info = tb.get_file(file_id)

file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))

Собственно вопроса два: как "достать" file_id из присланного сообщения? message.file_id выкидывает ошибку. Само сообщение выглядит так:

{'content_type': 'photo', 'message_id': 3368, 'from_user': {'id': 894674930, 'is_bot': False, 'first_name': 'Arthur', 'username': 'sprsnc', 'last_name': None, 'language_code': 'ru'}, 'date': 1591976807, 'chat': {'type': 'private', 'last_name': None, 'first_name': 'Arthur', 'username': 'sprsnc', 'id': 894674930, 'title': None, 'all_members_are_administrators': None, 'photo': None, 'description': None, 'invite_link': None, 'pinned_message': None, 'sticker_set_name': None, 'can_set_sticker_set': None}, 'forward_from_chat': None, 'forward_from_message_id': None, 'forward_from': None, 'forward_date': None, 'reply_to_message': None, 'edit_date': None, 'media_group_id': None, 'author_signature': None, 'text': None, 'entities': None, 'caption_entities': None, 'audio': None, 'document': None, 'photo': [<telebot.types.PhotoSize object at 0x000002683197D460>, <telebot.types.PhotoSize object at 0x000002683197DEE0>, <telebot.types.PhotoSize object at 0x000002683197D2B0>], 'sticker': None, 'video': None, 'video_note': None, 'voice': None, 'caption': None, 'contact': None, 'location': None, 'venue': None, 'animation': None, 'new_chat_member': None, 'new_chat_members': None, 'left_chat_member': None, 'new_chat_title': None, 'new_chat_photo': None, 'delete_chat_photo': None, 'group_chat_created': None, 'supergroup_chat_created': None, 'channel_chat_created': None, 'migrate_to_chat_id': None, 'migrate_from_chat_id': None, 'pinned_message': None, 'invoice': None, 'successful_payment': None, 'connected_website': None, 'json': {'message_id': 3368, 'from': {'id': 894674930, 'is_bot': False, 'first_name': 'Arthur', 'username': 'sprsnc', 'language_code': 'ru'}, 'chat': {'id': 894674930, 'first_name': 'Arthur', 'username': 'sprsnc', 'type': 'private'}, 'date': 1591976807, 'photo': [{'file_id': 'AgACAgIAAxkBAAINKF7jo2eOLzxXk5NSsHCg7KGiatqBAALUrzEbiOoYS3fCaPLyQiTQILCelS4AAwEAAwIAA20AA_ROAAIaBA', 'file_unique_id': 'AQADILCelS4AA_ROAAI', 'file_size': 21659, 'width': 213, 'height': 320}, {'file_id': 'AgACAgIAAxkBAAINKF7jo2eOLzxXk5NSsHCg7KGiatqBAALUrzEbiOoYS3fCaPLyQiTQILCelS4AAwEAAwIAA3gAA_JOAAIaBA', 'file_unique_id': 'AQADILCelS4AA_JOAAI', 'file_size': 114477, 'width': 533, 'height': 800}, {'file_id': 'AgACAgIAAxkBAAINKF7jo2eOLzxXk5NSsHCg7KGiatqBAALUrzEbiOoYS3fCaPLyQiTQILCelS4AAwEAAwIAA3kAA_FOAAIaBA', 'file_unique_id': 'AQADILCelS4AA_FOAAI', 'file_size': 153310, 'width': 640, 'height': 960}]}}

Второе, что за API_TOKEN подразумевается? file_path как я понимаю обычный путь к папке


Ответы (2 шт):

Автор решения: D. Violet
@bot.message_handler(content_types=['document'])
def handle_docs_photo(message):
try:
    chat_id = message.chat.id

    file_info = bot.get_file(message.document.file_id)
    downloaded_file = bot.download_file(file_info.file_path)

    src = 'C:/Python/Project/tg_bot/files/received/' + message.document.file_name;
    with open(src, 'wb') as new_file:
        new_file.write(downloaded_file)

    bot.reply_to(message, "Пожалуй, я сохраню это")
except Exception as e:
    bot.reply_to(message, e)

Принятие всех типов файлов, сохранение в указанную директорию и ответ от бота в виде цитаты последнего сообщения и подписи "Пожалуй, я сохраню это"

вы можете использовать и другие content_types

UPD:

для фото:

def handle_docs_photo(message):
    file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
    downloaded_file = bot.download_file(file_info.file_path)

    src = 'files/' + file_info.file_path
    with open(src, 'wb') as new_file:
        new_file.write(downloaded_file)

    bot.reply_to(message, "Пожалуй, я сохраню это")

не забудьте создать каталог files, а внутри него photos

→ Ссылка
Автор решения: Дмитрий

file_id = message.photo[0].file_id

→ Ссылка