Telegram Bot: How Can I Retrieve All Photos from a Specific media_group_id in One Update?

I found myself stuck on a previous question and would like to seek further assistance. Below is my current code which aims to fetch all images sent under the same media_group_id from a Telegram bot.

async def fetch_images(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Retrieve the highest resolution images from messages in a media group."""
    images = update.message.photo
    downloaded_files = []

    if images:
        highest_res_image = images[-1].file_id
        logger.info(f'Handling image with file_id: {highest_res_image}')

        try:
            file_details = await context.bot.get_file(highest_res_image)
            image_url = file_details.file_path
            file_label = f'image_{update.message.message_id}_{images[-1].file_unique_id}.jpg'

            logger.info(f'Downloading image from: {image_url}')

            # Retrieve the image content
            response = requests.get(image_url)
            response.raise_for_status()  # Ensure the download was successful
            with open(file_label, 'wb') as file:
                file.write(response.content)
            downloaded_files.append(file_label)
            logger.info(f'Successfully retrieved image with file_id: {highest_res_image}')
        except Exception as error:
            logger.error(f'Failed to download image with file_id {highest_res_image}: {error}')

    logger.info(f'Downloaded files: {downloaded_files}')
    return downloaded_files

So far, I have managed to download only one out of two images sent. This is the log output I received:

INFO:__main__:Downloading image from: https://api.telegram.org/file/bot12800363:AAF7LWpZz79LOVevA6OmFUAMA6SjVn2esns/photos/file_42.jpg
INFO:__main__:Successfully retrieved image with file_id: AgACAgUAAxkBAAIBx2sdFpfpjbDNU4nclU_ji1AALGvDEbpJVhVl6sAQADAgADeQADNQQ
INFO:__main__:Downloaded files: ['image_455_AQADxrwxG6SVYVZ-.jpg']

I’ve had to edit the URL for compliance with site guidelines. My main concern is that while attempting to download all images, only one was successfully retrieved. It seems like the iteration through the media group in the update isn’t working correctly. Could anyone assist me in figuring out how to fix this?

In your current implementation, it looks like you are dealing with just a single element in update.message.photo, which represents one photo in a message. If you’re trying to download multiple images that belong to the same media_group_id, you should be iterating through each message that contains photos in the media_group set.

You might need to change your approach to handle all possible messages within the media_group_id. First, ensure that your bot is receiving updates with multiple messages correctly. Once confirmed, you can loop through each photo within each message using an additional message handler to manage and retrieve their file IDs. Extract the photos in a loop, and download each one just like how you’ve implemented it for a single photo. This way, all images will be processed together, and you should be able to accumulate them into your downloaded_files list effectively.

maybe check if the entire media_group is getting in one update? sometimes big media groups send multiple udpates, and then they might be split which causes issues. you can try logging all updates to make sure you see all parts coming in at once. telegram can be tricky that way!