简体   繁体   English

下载图片 Python 电报 API

[英]Download Image Python Telegram API

I followed their brief tutorial on downloading an image but I'm encountering an exception:我按照他们关于下载图像的简短教程进行操作,但遇到了异常:

telegram.photosize.PhotoSize object at ... is not JSON serializable

the function for catching the images looks like this:用于捕获图像的 function 如下所示:

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)

At this point I have no idea what I'm doing wrong and can't find any solution on the net.在这一点上,我不知道我做错了什么,在网上找不到任何解决方案。

Turns out I misunderstood the data shape. 原来我误解了数据形状。 I thought originally that the update.message.photo collection held just file IDs. 我本来以为update.message.photo集合仅包含文件ID。 This led me to pass the wrong kind of object in when trying to fetch the file by ID. 这导致我在尝试通过ID提取文件时传递了错误的对象。 In order to pull out the file ID, I needed to get the file_id off the last photo: 为了提取文件ID,我需要从上一张照片中获取file_id

file_id = update.message.photo[-1].file_id
# 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM