下载图像Python Telegram API

问题描述 投票:0回答:3

我按照他们的简短教程下载图像,但遇到了异常:

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)

此时我不知道我做错了什么,并且在网上找不到任何解决方案。

python telegram python-telegram-bot
3个回答
7
投票

原来我误解了数据形状。我最初认为

update.message.photo
集合仅包含文件 ID。这导致我在尝试通过 ID 获取文件时传递了错误类型的对象。为了提取文件 ID,我需要去掉最后一张照片上的
file_id

file_id = update.message.photo[-1].file_id

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)

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_memory
File.download_to_drive
,但不再有
File.download

来源:https://stackoverflow.com/a/74941101/14715428

© www.soinside.com 2019 - 2024. All rights reserved.