From 3b869974d0513d6d0a00e2bc8dd5d13d872e05ad Mon Sep 17 00:00:00 2001 From: clarkzjw Date: Thu, 24 Nov 2022 16:29:14 -0800 Subject: bot: add telegram bot to produce square image --- .gitignore | 1 + bot.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 17 ++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 bot.py diff --git a/.gitignore b/.gitignore index be2fb47..40992df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +__pycache__/ .idea/ *.png *.jpg diff --git a/bot.py b/bot.py new file mode 100644 index 0000000..2d48783 --- /dev/null +++ b/bot.py @@ -0,0 +1,84 @@ +import logging +import os + +from telegram import __version__ as TG_VER + +try: + from telegram import __version_info__ +except ImportError: + __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment] + +if __version_info__ < (20, 0, 0, "alpha", 1): + raise RuntimeError( + f"This example is not compatible with your current PTB version {TG_VER}. To view the " + f"{TG_VER} version of this example, " + f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html" + + ) + +from telegram import ForceReply, Update, File +from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters +from telegram.constants import ParseMode +from PIL import Image, ImageFilter +from square import square_size_padding, drop_shadow + +# Enable logging + +logging.basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO +) + +logger = logging.getLogger(__name__) + + +# Define a few command handlers. These usually take the two arguments update and context. + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + """Send a message when the command /start is issued.""" + user = update.effective_user + await update.message.reply_html( + rf"Hi {user.mention_html()}!", + ) + + +async def process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + """Echo the user message.""" + filename = update.message.document.file_name + chat_id = update.message.chat_id + await context.bot.send_message(chat_id, "Processing `{}`".format(filename), + parse_mode=ParseMode.MARKDOWN_V2) + + file = await update.message.effective_attachment.get_file() + img = await file.download_to_drive(filename) + + try: + im = Image.open(img) + names = filename.split(".") + result = square_size_padding(im) + filename = "{}-result.{}".format(names[0], names[1]) + result.save(filename, quality=100) + + await context.bot.send_document(chat_id=update.message.chat_id, document=filename) + + except Exception as e: + await update.message.reply_markdown_v2(text="Error:\n```{}```".format(str(e))) + + +def main() -> None: + """Start the bot.""" + # Create the Application and pass it your bot's token. + tg_token = os.getenv("TG_TOKEN") + application = Application.builder().token(tg_token).build() + + # on different commands - answer in Telegram + application.add_handler(CommandHandler("start", start)) + + # on non command i.e message - echo the message on Telegram + application.add_handler(MessageHandler(filters.ATTACHMENT & ~filters.COMMAND, process)) + + # Run the bot until the user presses Ctrl-C + application.run_polling() + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt index a6d4d60..ac7741f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,18 @@ +anyio==3.6.2 +APScheduler==3.6.3 +cachetools==4.2.2 +certifi==2022.9.24 +h11==0.14.0 +httpcore==0.16.1 +httpx==0.23.1 +idna==3.4 Pillow==9.2.0 +python-telegram-bot==20.0a6 +pytz==2022.6 +pytz-deprecation-shim==0.1.0.post0 +rfc3986==1.5.0 +six==1.16.0 +sniffio==1.3.0 +tornado==6.1 +tzdata==2022.6 +tzlocal==4.2 -- cgit v1.2.3