diff --git a/bots/modules/__init__.py b/bots/modules/__init__.py index 07b188c..15110b0 100644 --- a/bots/modules/__init__.py +++ b/bots/modules/__init__.py @@ -6,6 +6,7 @@ from .cyberlina import CyberLinaBotModuleConfig from .ping import PingBotModuleConfig from .robot import RobotBotModuleConfig from .spoiler import SpoilerBotModuleConfig +from .stickers import StickersBotModuleConfig BOT_MODULES = [EchoBotModuleConfig, ChannelHelperBotModuleConfig, OverlayBotModuleConfig, CyberLinaBotModuleConfig, - PingBotModuleConfig, SpoilerBotModuleConfig, RobotBotModuleConfig, FeedbackBotModuleConfig] + PingBotModuleConfig, SpoilerBotModuleConfig, RobotBotModuleConfig, FeedbackBotModuleConfig, StickersBotModuleConfig] diff --git a/bots/modules/stickers.py b/bots/modules/stickers.py new file mode 100644 index 0000000..8728fc3 --- /dev/null +++ b/bots/modules/stickers.py @@ -0,0 +1,42 @@ +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 + im.thumbnail((512, 512), Image.ANTIALIAS) + target_width, target_height = im.size + with tempfile.NamedTemporaryFile(suffix='.png') as f: + im.save(f, 'png') + 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