telegram_bots/bots/modules/stickers.py

50 lines
1.9 KiB
Python
Raw Normal View History

2021-08-27 17:03:11 +00:00
import tempfile
from PIL import Image
from telegram import Update
from telegram.ext import Dispatcher, CallbackContext, MessageHandler, Filters
from bots.models import TelegramBotModuleConfig
class StickersBotModuleConfig(TelegramBotModuleConfig):
MODULE_NAME = 'Stickers'
def resize_image(self, update: Update, ctx: CallbackContext):
doc = update.message.document
if update.message.photo:
with tempfile.NamedTemporaryFile(suffix='.jpg') as f:
f.write(update.message.photo[-1].get_file().download_as_bytearray())
f.seek(0)
im = Image.open(f).convert('RGBA')
else:
if doc.mime_type == 'image/png':
suffix = '.png'
elif doc.mime_type == 'image/jpeg':
suffix = '.jpg'
else:
return
with tempfile.NamedTemporaryFile(suffix=suffix) as f:
f.write(doc.get_file().download_as_bytearray())
f.seek(0)
im = Image.open(f).convert('RGBA')
width, height = im.size
2023-05-12 13:42:12 +00:00
long_dimension = max(width, height)
scale_ratio = 512 / long_dimension
target_width = int(width * scale_ratio)
target_height = int(height * scale_ratio)
if long_dimension == width:
target_width = 512
else:
target_height = 512
2023-05-12 13:47:38 +00:00
im = im.resize((target_width, target_height), Image.ANTIALIAS)
2023-07-26 10:38:23 +00:00
with tempfile.NamedTemporaryFile(suffix='.webp') as f:
im.save(f, 'webp')
2021-08-27 17:03:11 +00:00
f.seek(0)
update.message.reply_document(f, caption=f'{width}x{height} -> {target_width}x{target_height}')
def build_dispatcher(self, dispatcher: Dispatcher):
dispatcher.add_handler(MessageHandler(Filters.document, self.resize_image))
dispatcher.add_handler(MessageHandler(Filters.photo, self.resize_image))
return dispatcher