Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how save photo in telegram python bot?

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.

like image 844
Ali Akhtari Avatar asked May 17 '18 09:05

Ali Akhtari


People also ask

How do I download a file or photo that was sent to my Telegram bot?

Any file can be downloaded by calling upload. getFile.

Can Telegram bot send files?

Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. See sendDocument official docs for a list of supported parameters and other info.


2 Answers

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.

like image 143
dev4Fun Avatar answered Oct 11 '22 12:10

dev4Fun


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()
like image 4
Himanshu Tekade Avatar answered Oct 11 '22 11:10

Himanshu Tekade