【问题标题】:Opening a photo with tempfile in Telegram bot在 Telegram bot 中使用临时文件打开照片
【发布时间】:2021-08-09 02:28:59
【问题描述】:

我正在尝试处理客户发送给我的 Telegram 机器人的照片。为此,我愿意使用 tempfile 来简化过程而不是填充磁盘。我正在使用python-telegram-bot

代码如下所示:

def get_exif(update: Update, context: CallbackContext):
    with tempfile.NamedTemporaryFile() as f:
        update.message.photo[-1].get_file().download(out=f)
        f.seek(0)

        print(exifread.process_file(f))

这会打印一个空字典,尽管我很确定该文件有 exif 信息。如果我看不到的其他任何内容有问题,我使用以下代码进行了调试。以下内容运行良好:

# the same file with the telegram code
with open(filename, 'rb') as f:
    exifread.process_file(f)

或者:

# I tried this to see if something wrong with my
# usage of tempfile. may look stupid
with open(p, 'rb') as f:
    with tempfile.NamedTemporaryFile() as tf:
        tf.write(f.read())
        tf.seek(0)
        exifread.process_file(tf)

我在这里错过了什么?

编辑 1: 我正在分享完整的代码,您只需将机器人的令牌粘贴到 TOKEN 即可。

"""
Module for keep telegram bot and related functions.

This is the main script to run telegram bot.
"""
import tempfile
from os import getenv
from pprint import pformat
from typing import Tuple

import dotenv
from PIL import Image
from telegram import Update
from telegram.ext import (CallbackContext, Dispatcher, Filters, MessageHandler,
                          Updater)
import exifread


TOKEN = ""


def get_exif(update: Update, context: CallbackContext):
    """Get the photo with largest size from message and send exif info."""
    # with tempfile.TemporaryFile('wb+') as f:
    with tempfile.NamedTemporaryFile() as f:
        update.message.photo[-1].get_file().download()

        print(exifread.process_file(
            f, stop_tag='EXIF', details=False, auto_seek=True))


def set_updater() -> Tuple[Updater, Dispatcher]:
    """Set updaters."""
    updater = Updater(token=TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    image_handler = MessageHandler(
        Filters.photo & (~Filters.command), get_exif)
    dispatcher.add_handler(image_handler)

    return updater, dispatcher


if __name__ == '__main__':
    updater, _ = set_updater()

    updater.start_polling()

编辑 2:
我正在使用 Ubuntu。当我右键单击图像以查看其属性时,我可以看到其中的详细信息。但是我在下载的临时文件(/tmp)中或在 Telegram 界面中“将图像另存为”时都看不到它们。

所以我们可以说当你在电报中发送照片时细节丢失了吗?有可能吗?

【问题讨论】:

  • 所以在第二个示例中,您要将您从update.message.photo[-1].get_file().download(...) 获得的照片保存到filename?你在 Telegram 使用什么库?添加一个完整的minimal reproducible example 一个非常简单的机器人来重现问题会有所帮助。
  • 您好,我已编辑问题以添加代码。我正在使用github.com/python-telegram-bot/python-telegram-bot

标签: python telegram python-telegram-bot


【解决方案1】:

这可能无法回答您的实际问题,但下载telegram.File 无需写入磁盘即可

【讨论】:

    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2015-11-24
    • 2016-07-09
    • 2017-06-06
    • 2021-10-03
    相关资源
    最近更新 更多