You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Telegram机器人图片与JSON互存的问题求助

解决方案:图片与JSON的序列化/反序列化处理

问题核心是JSON无法直接序列化BytesIO对象,因为JSON仅支持字符串、数字、列表、字典等基础数据类型。需将图片二进制数据转换为Base64编码的字符串,才能存入JSON;读取时再将Base64字符串转回二进制数据。

步骤1:修改图片存储逻辑(存入chat_data)

不再存储BytesIO对象,提取图片二进制数据并转为Base64字符串:

import base64
from io import BytesIO

# 获取图片文件并转为Base64字符串
file = context.bot.getFile(file_id=update.message.photo[1].file_id)
image_bytes = file.download_as_bytearray()
image_base64 = base64.b64encode(image_bytes).decode('utf-8')  # 二进制转Base64字符串
caption = update.message.caption

# 存入chat_data
context.dispatcher.chat_data[update.message.chat.id]['photo'] = {
    'image_base64': image_base64,
    'caption': caption
}

# 测试发送图片(从Base64转回BytesIO)
image_buffer = BytesIO(base64.b64decode(image_base64))
context.bot.send_photo(
    chat_id=update.message.from_user.id,
    photo=image_buffer,
    caption=caption
)

步骤2:修改JSON导出逻辑

此时chat_data中的内容均为JSON可序列化类型,直接导出即可:

import json
from io import BytesIO

name_file = 'a.json'
# 获取chat_data中的图片数据
photo_data = context.dispatcher.chat_data[update.message.chat.id]['photo']
# 转为JSON字符串并写入BytesIO
json_str = json.dumps(photo_data, indent=2, sort_keys=True)
buffer = BytesIO(json_str.encode('utf-8'))  # 字符串转二进制写入缓冲区
buffer.seek(0)

# 发送JSON文档
context.bot.send_document(
    chat_id=update.message.chat.id,
    document=buffer,
    filename=name_file
)
buffer.close()

步骤3:修改JSON导入逻辑

下载文档后,读取JSON并将Base64字符串转回图片二进制数据:

import json
import base64
from io import BytesIO

# 下载文档并读取JSON内容
file = context.bot.getFile(file_id=update.message.document.file_id)
document_bytes = file.download_as_bytearray()
json_str = document_bytes.decode('utf-8')  # 二进制转字符串
photo_data = json.loads(json_str)

# 将Base64转回BytesIO并存入chat_data
image_buffer = BytesIO(base64.b64decode(photo_data['image_base64']))
context.dispatcher.chat_data[update.message.chat.id]['photo'] = {
    'image': image_buffer,
    'caption': photo_data['caption']
}

关键说明

  • Base64编码会让数据体积增加约30%,若图片较大,建议直接存储文件(本地或云存储),仅在JSON中记录文件路径/ID,避免JSON体积过大。
  • 禁止用StringIO处理二进制数据:图片是二进制格式,必须用BytesIO操作;StringIO仅用于文本数据,这是你之前加载环节的核心错误。

内容的提问来源于stack exchange,提问作者vendel68

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:53