如何在电报Python机器人中保存照片?

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

我想写一个保存照片的电报机器人。 这是我的代码,但它不起作用。 我不知道我的问题是什么?

def image_handler(bot, update):
    file = bot.getFile(update.message.photo.file_id)
    print ("file_id: " + str(update.message.photo.file_id))
    file.download('image.jpg')

updater.dispatcher.add_handler(MessageHandler(Filters.photo, image_handler))
updater.start_polling()
updater.idle()

请帮助我解决我的问题。

python-3.x photo telegram-bot python-telegram-bot
6个回答
18
投票

update.message.photo
是照片大小的数组(PhotoSize 对象)。

使用

file = bot.getFile(update.message.photo[-1].file_id)
。这将获得可用最大尺寸的图像。


5
投票

这是我的代码

from telegram.ext import *
import telegram

def start_command(update, context):
    name = update.message.chat.first_name
    update.message.reply_text("Hello " + name)
    update.message.reply_text("Please share your image")

def image_handler(update, context):
    file = update.message.photo[0].file_id
    obj = context.bot.get_file(file)
    obj.download()
    
    update.message.reply_text("Image received")

def main():
    print("Started")
    TOKEN = "your-token"
    updater = Updater(TOKEN, use_context = True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start_command))

    dp.add_handler(MessageHandler(Filters.photo, image_handler))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

1
投票

与接受的答案不同,您实际上并不需要

bot
对象来获取文件:

file = update.message.photo[-1].get_file()

然后下载文件:

path = file.download("output.jpg")

将其用于进一步处理或将其放在您的设备上:)


0
投票

这是一个普通的Python解决方案:

import requests
from PIL import Image

# for example, we get the last message
# update = requests.post(f'https://api.telegram.org/bot{TOKEN}/getUpdates').json()['result'][-1]

msg = update['message']

# check whether the message contains a photo
if msg.get('photo', None) == None:
  return

# get the photo id with the biggest resolution
file_id = msg['photo'][-1]['file_id']

# get URL by id
file_path = requests.get(f'https://api.telegram.org/bot{TOKEN}/getFile?file_id={file_id}').json()['result']['file_path']

# open URL with Pillow
img = Image.open(requests.get(f'https://api.telegram.org/file/bot{TOKEN}/{file_path}', stream=True).raw)

# save on the disk if needed
img.save('photo.jpg')

0
投票

为什么当我尝试下载文件时显示此错误:“coroutine”对象没有属性“download”

似乎没有下载功能 context.bot.getFile(update.message.photo[-1].file_id).download('image.jpg') 我正在使用这个版本,这个下载功能不允许,也不显示,会等待你们的回复谢谢..


-1
投票

@dp.message_handler(命令='开始')
9 异步 def s_photo(消息: types.Message):
10 """获取json文件的str类型"""
11photostr =等待bot.get_user_profile_photos(message.from_user.id)
12 """将str解析为json"""
13 photojson = json.loads(photostr.as_json())
14 """给 get_file 方法提供文件 unic 代码"""
15 照片=await bot.get_file(photojson['photo'][0][0]['file_id'])
16 """用下载方法结束下载对象"""
17 downloadphoto = wait photo.download('文件名'+'.jpeg')

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