Export image to Json with Python

Viewed 46

be patient, I'm new to both python and bots, I'm building a bot for Telegram and I'd like to save and retrieve an image from Json. As you can see from the code I load the image that someone messages in a buffer, I save it in a dictionary and later I send it. I would like to be able to export the image and import it if needed, but as per the code, it doesn't work for coding reasons, I think, does anyone have any ideas? Thank you

file=context.bot.getFile(file_id=update.message.photo[1].file_id)
image=BytesIO(initial_bytes=file.download_as_bytearray())
caption=update.message.caption
image.seek(0)
context.dispatcher.chat_data[update.message.chat.id][‘photo’]={'image':image, ’caption’:caption}
context.bot.send_photo(chat_id=update.message.from_user.id, photo=context.dispatcher.chat_data[update.message.chat.id][‘photo’]['image'], caption= context.dispatcher.chat_data[update.message.chat.id][‘photo’]['caption'])

this works perfectly with text but not with images, it gives me an error on exporting

name_file='a.json'
buffer= BytesIO()
buffer.write(json.dumps(obj=context.dispatcher.chat_data[update.message.chat.id][‘photo’], indent=2, sort_keys=True))
buffer.seek(0)
buffer.close()
context.bot.send_document(chat_id=update.message.chat.id, document=buffer, filename=name_file)

TypeError: Object of type BytesIO is not JSON serializable

Of course after:

file=context.bot.getFile(file_id=update.message.document.file_id)
buffer=StringIO(initial_bytes=file.download_as_bytearray())
buffer.seek(0)
context.dispatcher.chat_data[update.message.chat.id][‘photo’]=json.load(fp=buffer)

However, even the load with StringIO I don't think goes well with images. As I said everything works with text but not with images, it's too advanced for me, how to solve?

0 Answers
Related