aboutsummaryrefslogblamecommitdiff
path: root/bot.py
blob: 2d48783a9c252621da7e82195a7067a64cf6af69 (plain) (tree)



















































































                                                                                              
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()
Powered by cgit v1.2.3 (git 2.41.0)