43 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| 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
 |