【问题标题】:how save photo in telegram python bot?如何在电报python bot中保存照片?
【发布时间】:2018-10-27 13:03:46
【问题描述】:

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

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

请帮我解决我的问题。

【问题讨论】:

    标签: python-3.x photo telegram-bot python-telegram-bot


    【解决方案1】:

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

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

    【讨论】:

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

    这是我的代码

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

    【讨论】:

      【解决方案3】:

      与公认的答案不同,您实际上并不需要 bot 对象来获取文件:

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

      然后下载文件:

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

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-06
          • 1970-01-01
          • 2017-01-27
          • 2013-08-16
          • 1970-01-01
          相关资源
          最近更新 更多