How to get image bytes from telegram message using Telethon

Question:

I’m trying to locate bytes of image contained in the message I’m downloading from telegram channels I’m following. However, I keep getting errors that MessageMediaPhoto does not have attribute bytes. Below is the relevant snipped of code:

  if event.photo:
            id = event.message.to_id
            chat_username = client.get_entity(id)
            usr = chat_username.username
            image_base = event.message.media
            image_bytes = image_base.photo.bytes
            message = event.message.id
            url = ("https://t.me/" + str(usr) + "/" + str(message))
            print(url)
            print(image_bytes)
Asked By: Matthew

||

Answers:

you have to download the image first using the download_media method first in order to do that. a simple Message object does not have that information.

Answered By: painor

This ended up working for me:

photo_1 = Image.open(photo)
image_buf = BytesIO()
photo_1.save(image_buf, format="JPEG")
image = image_buf.getvalue()
Answered By: Matthew

We can use BytesIO from python’s io library.

from io import BytesIO

image_bytes = BytesIO()
event.message.download_media(image_bytes)

Then, we get the image bytes of the message in image_bytes.

Answered By: Richard Zhao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.