How can I download multiple images from a Telegram bot?

I have the following code:

file_name = f'image_{update.message.message_id}_{photo.file_unique_id}.jpeg'

full_url = f'https://api.telegram.org/file/bot{BOT_TOKEN}/{download_url}'
logger.info(f'Downloading image from URL: {full_url}')
response = requests.get(full_url)
response.raise_for_status()  
with open(file_name, 'wb') as file:
    file.write(response.content)

This code is designed to retrieve the Telegram URL. However, Telegram sends images as multiple messages or updates simultaneously. I’m struggling with the logic of correctly downloading the images. Currently, the code ends up saving the same image multiple times instead of recognizing how many distinct images are present in the update. Even when I send two separate images, it only downloads the first one and renames it multiple times. Could you provide guidance on how to fix this issue?**

async def fetch_images(update: Update, context: ContextTypes.DEFAULT_TYPE):
    image_list = update.message.photo
    saved_files = []

    for img in image_list:
        unique_id = img.file_id
        logger.info(f'Processing image with unique_id: {unique_id}')  
        try:
            file_details = await context.bot.get_file(unique_id)
            path_to_download = file_details.file_path  # Directly using the file_path

            # Generate a distinct filename for each image
            unique_file_name = f'image_{update.message.message_id}_{img.file_unique_id}.jpeg'

            # Log the complete download URL
            full_url = f'https://api.telegram.org/file/bot{BOT_TOKEN}/{path_to_download}'
            logger.info(f'Downloading image from URL: {full_url}')  

            # Download the image using the complete URL
            response = requests.get(full_url)
            response.raise_for_status()  
            with open(unique_file_name, 'wb') as file:
                file.write(response.content)
            saved_files.append(unique_file_name)
            logger.info(f'Image downloaded successfully with unique_id: {unique_id}')
        except Exception as error:
            logger.error(f'Error while downloading image with unique_id {unique_id}: {error}')

    logger.info(f'All downloaded files: {saved_files}')

Hey! It might be worth checking if you’re processing the update correctly? Not all versions of telegram APIs handle photos as lists by default. Try iterating over update.message.photo to make sure each image is handled in the loop, that might be missing in your loops setup.