import calendar import logging import os import random import time import traceback from dotenv import load_dotenv from PIL import Image from telepot import Bot from telepot.loop import MessageLoop load_dotenv() logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO) BOT_TOKEN = os.getenv("BOT_TOKEN", default=None) if not BOT_TOKEN: raise Exception("BOT_TOKEN not defined in env") PHOTOS_DIR = os.getenv("PHOTOS_DIR", default="photo") wooden_im = Image.open("wooden.png") golden_im = Image.open("golden.png") img_size = (640, 640) GOLDEN_CHANCE = 1 # % START_TIME = calendar.timegm(time.gmtime()) wooden_im.thumbnail(img_size) golden_im.thumbnail(img_size) bot = Bot(BOT_TOKEN) logging.warning("Connected with token {}".format(BOT_TOKEN)) last_user_by_chat_id = {} def edit_image(unedited_path, edited_path, frame_im): if os.path.exists(edited_path): im = Image.open(edited_path) else: im = Image.open(unedited_path) im.thumbnail(img_size) im.paste(frame_im, (0, 0), frame_im) im.save(edited_path) return im def run(chat_id, user_id): photos = bot.getUserProfilePhotos(user_id) if photos["total_count"] == 0: logging.error("No pictures found, sending message...") bot.sendMessage(chat_id, "Vitun taulu, hommaa kuva!") return logging.warning("Looking up picture...") pic = photos["photos"][0][-1] file_id = pic["file_id"] os.makedirs(PHOTOS_DIR, exist_ok=True) unedited_path = os.path.join(PHOTOS_DIR, f"{file_id}.jpg") edited_path_wooden = os.path.join(PHOTOS_DIR, f"{file_id}_wooden.png") edited_path_gold = os.path.join(PHOTOS_DIR, f"{file_id}_gold.png") if os.path.exists(unedited_path): logging.info("User profile pic already found. Skipping download...") else: logging.warning(f"Downloading profile image with file_id {file_id}...") bot.download_file(file_id, unedited_path) # one image in 100 has golden borders :) golden_number = random.randrange(0, 100 - 1) logging.warning("Random gold number was: {}".format(golden_number)) is_golden = golden_number < GOLDEN_CHANCE if is_golden: bot.sendMessage( chat_id, "Onneksi olkoon! Kultainen taulu ilmestyy vain kerran tuhannessa vuodessa!", ) edited_path = edited_path_gold frame_im = golden_im else: edited_path = edited_path_wooden frame_im = wooden_im logging.warning( "Editing and sending photo {} to chat {}...".format(edited_path, chat_id) ) edit_image(unedited_path, edited_path, frame_im) with open(edited_path, "rb") as f: bot.sendPhoto(chat_id, f) logging.warning("Image sent succesfully.") return def is_taulu_command(text): return "taulu" in text.strip().lower() def handle(msg): chat_id = msg["chat"]["id"] user_id = msg["from"]["id"] user_name = msg["from"]["first_name"] msg_text = msg.get("text", None) logging.debug( "New message! chat_id: {}, user_name: {}, msg_text: {}".format( chat_id, user_name, msg_text ) ) if msg_text is not None and is_taulu_command(msg_text): logging.info("Taulu command found!") attempt, ATTEMPTS = 0, 3 while attempt < ATTEMPTS: try: taulu_id = last_user_by_chat_id[chat_id] logging.warning("Running taulu for user id {}".format(taulu_id)) run(chat_id, taulu_id) break except KeyError: logging.error( "No chat id found in chat dict. Maybe no previous messages in the chat?" ) break except: traceback.print_exc() logging.error( "Error occured during process. Retrying... (attempt {})".format( attempt ) ) attempt += 1 last_user_by_chat_id[chat_id] = user_id logging.warning("Listening...") MessageLoop(bot, handle).run_as_thread( allowed_updates=["message"], ) # Run forever while True: time.sleep(1)