如何在电报python bot中保存照片?

Ali*_*Ali 7 photo python-3.x python-telegram-bot telegram-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()
Run Code Online (Sandbox Code Playgroud)

请帮我解决我的问题。

dev*_*Fun 14

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

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

  • @Ali [-1] 是数组的最后一项。这就是索引在 python 中的工作方式。我建议熟悉它,因为它是非常常见的功能。您实际上不必使用最后一个项目,但根据文档,最后一个图像是最大的图像(https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#download -一份文件) (3认同)
  • 为什么我应该写“[-1]”?这是什么? (2认同)

小智 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()
Run Code Online (Sandbox Code Playgroud)