Python Telegram API 下载图片

4
我按照他们简要的教程下载图像,但遇到了异常:
telegram.photosize.PhotoSize object at ... is not JSON serializable

捕获图像的函数如下所示:
def photo(bot, update):
    file_id = update.message.photo[-1]
    newFile = bot.getFile(file_id)
    newFile.download('test.jpg')
    bot.sendMessage(chat_id=update.message.chat_id, text="download succesfull")

photo_handler = MessageHandler(Filters.photo, photo)
dispatcher.add_handler(photo_handler)

目前我不知道自己做错了什么,也在网络上找不到任何解决方案。

3个回答

7
原来我误解了数据形式。我最初认为update.message.photo集合仅包含文件ID。这使我在尝试通过ID获取文件时传递了错误类型的对象。为了提取文件ID,我需要从最后一张照片中获取file_id
file_id = update.message.photo[-1].file_id

请查看我可以回答自己的问题吗?,两天后再回来确认已解决。但是请为其他用户添加一些信息。 - help-info.de
1
newFile = bot.getFile(file_id)。我无法获取getFile,错误显示bot对象没有'getFile'属性... 你能帮帮我吗? - Nilanj
@Nilanj,尝试像这样编写 `bot = context.bot getFile = bot.getFile(update.message.photo[-1].file_id)`。 - KbiR

0
# Download Image Python Telegram 
@bot.message_handler(content_types=['photo'])
def download_image(message):
    fileID = message.photo[-1].file_id
    file_info = bot.get_file(fileID)
    downloaded_file = bot.download_file(file_info.file_path)
    # guardamos en la carpeta del proyecto
    with open("image.jpg", 'wb') as new_file:
        new_file.write(downloaded_file)
    bot.reply_to(message, "Image Downloaded type: " + fileID)

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0
我的下载版本现在是:
async def get_image(self, update, context):
    img_path = f'images/img.jpg'

    await (await context.bot.getFile(update.message.photo[-1].file_id)).download_to_drive(img_path)

在现代版本中,telegram.File的方法已经更名。特别是现在有File.download_to_memoryFile.download_to_drive,但不再有File.download
来源:https://stackoverflow.com/a/74941101/14715428

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接