How to download multiple images from Telegram bot messages?

I’m having trouble with my Telegram bot code. It’s supposed to download multiple images from a message, but it’s not working right. Here’s what’s happening:

When I send multiple images, the bot only downloads the first one several times instead of getting all the different images. It renames and saves the same image multiple times.

I’ve tried using a loop to go through the photos in the message, but it’s not picking up the other images. Here’s a simplified version of what I’m doing:

def get_telegram_photos(message):
    for photo in message.photos:
        file_name = f'image_{photo.id}.jpg'
        download_url = f'https://api.telegram.org/file/bot{TOKEN}/{photo.file_path}'
        response = requests.get(download_url)
        with open(file_name, 'wb') as f:
            f.write(response.content)

Can anyone help me figure out how to correctly download all the images from a Telegram message? I’m not sure if I’m missing something in how Telegram sends multiple images or if there’s a problem with my code. Thanks!

hey, i had a similar issue. i found that telegram sends only the first image as a photo, others as documents. so try looping over message.photo and message.document, checking if the mime starts with ‘image’, then download. hope it works

I encountered a similar problem while working on Telegram bots. The issue often arises because Telegram sends the first image as a photo and treats the remaining images as documents. In my experience, checking whether the message is part of a media group and processing each item accordingly can resolve the problem. Instead of simply looping over photos, it is important to verify if additional files are being sent as documents. Calling the Telegram API’s getFile method to obtain the correct file path for every image is a step that has proven effective for me.

I’ve dealt with this exact issue before, and it can be frustrating. The key is understanding how Telegram handles multiple images. When you send a group of photos, only the first one is treated as a ‘photo’ object. The rest are actually sent as ‘document’ objects with a photo mime type.

To fix this, you need to check for both photos and documents in the message. Here’s a rough idea of how I approached it:

def get_telegram_photos(message):
    if message.media_group_id:
        for item in message.document:
            if item.mime_type.startswith('image'):
                # Download logic here
    else:
        for photo in message.photo:
            # Download logic here

This way, you’ll catch all the images, whether they’re sent as photos or documents. It took me a while to figure this out, but it’s worked reliably since. Hope this helps!