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?