电报将png图片发送到电报将其转换为jpg

时间:2020-02-23 18:52:20

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

为什么当我将png图片发送到电报bot,然后下载该图片时,它变成jpg?如何避免呢?

MY_USER_ID = 012345
MY_TOKEN = "12345"
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

from telegram.ext import Updater, MessageHandler, Filters, CommandHandler

updater = Updater(token=MY_TOKEN, use_context=True)

updater.start_polling()

dispatcher = updater.dispatcher


def create_sticker_set(update, context):

    update_dict = update.to_dict()

    sticker_file_id = update_dict["message"]["photo"][-1]["file_id"]

    print("sticker_file_id=", sticker_file_id)

    file = context.bot.get_file(update_dict["message"]["photo"][-1]["file_id"])
    filename = file.download() # it is jpg, and it must be png

    context.bot.add_sticker_to_set(MY_USER_ID, "lala_by_ibodi_bot", open(filename, "rb"), "???")


msghandler = MessageHandler(Filters.photo, create_sticker_set)
dispatcher.add_handler(msghandler)

此代码创建一个处理程序,该处理程序接收图片并将其添加到贴纸集中。我想保留图片的扩展名,以使图片的透明部分在贴纸集中保持透明。并将其转换为jpg可使透明的地方变成白色。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。当我发送文件时,我应该选择“发送为文件”而不是“发送为照片”,它不会将png转换为jpg。

enter image description here

上面提供的代码必须进行一些更改:

# we put 
msghandler = MessageHandler(Filters.document, create_sticker_set)
# instead of instead of
msghandler = MessageHandler(Filters.photo, create_sticker_set)

# we put 
file = context.bot.get_file(update_dict["message"]["document"]["file_id"])
# instead of 
file = context.bot.get_file(update_dict["message"]["photo"][-1]["file_id"])