how save photo in telegram python bot? – Code Utility

[

i want to write a telegram bot that save photos .
this is my code , but its not working.
and i don’t know what is my problem?

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

pleas help me to solve my problem.

,

update.message.photo is an array of photos sizes (PhotoSize objects).

Use file = bot.getFile(update.message.photo[-1].file_id). This will get the image with biggest size available.

,

Here is my code

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

,

Unlike the accepted answer suggests, you don’t actually need the bot object to get the file:

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

and then download the file:

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

to use it for further processing or just have it on your device : )

,

@dp.message_handler(commands=’start’)
9 async def s_photo(message: types.Message):
10 “””getting str type of json file”””
11photostr = await bot.get_user_profile_photos(message.from_user.id)
12 “””parsing str to json”””
13 photojson = json.loads(photostr.as_json())
14 “””giving file unic code to get_file method”””
15 photo = await bot.get_file(photojson[‘photo’][0][0][‘file_id’])
16 “””end downloading object with download method”””
17 downloadphoto = await photo.download(‘filename’+’.jpeg’)

]