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

新手上路,请多包涵

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

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

请帮我解决我的问题。

原文由 Ali Akhtari 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

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

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

原文由 dev4Fun 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我的代码

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

原文由 Himanshu Tekade 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进