aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorclarkzjw <[email protected]>2022-11-24 17:00:49 -0800
committerclarkzjw <[email protected]>2022-11-24 17:00:49 -0800
commit7451d6229a8fcb0442adaa9be2af26173b9c363b (patch)
tree68d0cf13abccb8c9d1afa83adc4d357fa48e515d
parent3b869974d0513d6d0a00e2bc8dd5d13d872e05ad (diff)
downloadSquare-7451d6229a8fcb0442adaa9be2af26173b9c363b.tar.gz
bot: process images in memory
-rw-r--r--bot.py52
1 files changed, 29 insertions, 23 deletions
diff --git a/bot.py b/bot.py
index 2d48783..bf19588 100644
--- a/bot.py
+++ b/bot.py
@@ -1,5 +1,7 @@
1import io
1import logging 2import logging
2import os 3import os
4import traceback
3 5
4from telegram import __version__ as TG_VER 6from telegram import __version__ as TG_VER
5 7
@@ -19,8 +21,8 @@ if __version_info__ < (20, 0, 0, "alpha", 1):
19from telegram import ForceReply, Update, File 21from telegram import ForceReply, Update, File
20from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters 22from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
21from telegram.constants import ParseMode 23from telegram.constants import ParseMode
22from PIL import Image, ImageFilter 24from PIL import Image
23from square import square_size_padding, drop_shadow 25from square import square_size_padding
24 26
25# Enable logging 27# Enable logging
26 28
@@ -31,52 +33,56 @@ logging.basicConfig(
31logger = logging.getLogger(__name__) 33logger = logging.getLogger(__name__)
32 34
33 35
34# Define a few command handlers. These usually take the two arguments update and context.
35
36async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: 36async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
37 """Send a message when the command /start is issued.""" 37 await update.message.reply_text("This is a bot to output image in square shape")
38 user = update.effective_user
39 await update.message.reply_html(
40 rf"Hi {user.mention_html()}!",
41 )
42 38
43 39
44async def process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: 40async def process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
45 """Echo the user message."""
46 filename = update.message.document.file_name
47 chat_id = update.message.chat_id 41 chat_id = update.message.chat_id
42
43 filename = update.message.document.file_name
44 names = filename.split(".")
45
46 if str.upper(names[1]) in ("JPG", "JPEG"):
47 save_format = "JPEG"
48 elif str.upper(names[1]) in ("PNG",):
49 save_format = str.upper(names[1])
50 else:
51 await context.bot.send_message(chat_id, "Image extension `{}` not supported".format(names[1]),
52 parse_mode=ParseMode.MARKDOWN_V2)
53 return
54
48 await context.bot.send_message(chat_id, "Processing `{}`".format(filename), 55 await context.bot.send_message(chat_id, "Processing `{}`".format(filename),
49 parse_mode=ParseMode.MARKDOWN_V2) 56 parse_mode=ParseMode.MARKDOWN_V2)
50 57
51 file = await update.message.effective_attachment.get_file() 58 file = await update.message.effective_attachment.get_file()
52 img = await file.download_to_drive(filename) 59 img = io.BytesIO()
60 await file.download_to_memory(img)
53 61
54 try: 62 try:
55 im = Image.open(img) 63 im = Image.open(img)
56 names = filename.split(".")
57 result = square_size_padding(im) 64 result = square_size_padding(im)
58 filename = "{}-result.{}".format(names[0], names[1])
59 result.save(filename, quality=100)
60 65
61 await context.bot.send_document(chat_id=update.message.chat_id, document=filename) 66 output = io.BytesIO()
67 result.save(output, format=save_format, quality=100)
68
69 await update.message.reply_markdown_v2(text="Sending processed result")
70
71 await context.bot.send_document(chat_id=update.message.chat_id,
72 filename="{}-result.{}".format(names[0], names[1]),
73 document=output.getvalue())
62 74
63 except Exception as e: 75 except Exception as e:
64 await update.message.reply_markdown_v2(text="Error:\n```{}```".format(str(e))) 76 await update.message.reply_markdown_v2(text="Error:\n```{}```".format(traceback.format_exc()))
65 77
66 78
67def main() -> None: 79def main() -> None:
68 """Start the bot."""
69 # Create the Application and pass it your bot's token.
70 tg_token = os.getenv("TG_TOKEN") 80 tg_token = os.getenv("TG_TOKEN")
71 application = Application.builder().token(tg_token).build() 81 application = Application.builder().token(tg_token).build()
72 82
73 # on different commands - answer in Telegram
74 application.add_handler(CommandHandler("start", start)) 83 application.add_handler(CommandHandler("start", start))
75
76 # on non command i.e message - echo the message on Telegram
77 application.add_handler(MessageHandler(filters.ATTACHMENT & ~filters.COMMAND, process)) 84 application.add_handler(MessageHandler(filters.ATTACHMENT & ~filters.COMMAND, process))
78 85
79 # Run the bot until the user presses Ctrl-C
80 application.run_polling() 86 application.run_polling()
81 87
82 88
Powered by cgit v1.2.3 (git 2.41.0)