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

how save photo in telegram python bot?

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

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()

请帮我解决我的问题。

update.message.photo 是一组照片尺寸(PhotoSize 对象)。

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

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

与接受的答案所暗示的不同,您实际上不需要 bot 对象来获取文件:

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

然后下载文件:

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

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

这是我的代码

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()