如何使用 Telethon 从电报消息中获取图像字节

How to get image bytes from telegram message using Telethon

我正在尝试定位我正在从我关注的电报频道下载的消息中包含的图像字节。但是,我不断收到 MessageMediaPhoto 没有属性字节的错误。以下是相关的代码片段:

  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)

您必须首先使用 download_media 方法下载图像才能执行此操作。一个简单的 Message 对象没有该信息。

这最终对我有用:

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