diff options
Diffstat (limited to 'taulubot.py')
| -rw-r--r-- | taulubot.py | 180 |
1 files changed, 101 insertions, 79 deletions
diff --git a/taulubot.py b/taulubot.py index 40e6367..ae8a9b8 100644 --- a/taulubot.py +++ b/taulubot.py @@ -1,121 +1,143 @@ -import sys import random import time from pprint import pprint import telepot -import urllib.request +from telepot.loop import MessageLoop import time from PIL import Image import os import calendar import logging -logging.basicConfig(format='%(asctime)s %(message)s') -taulu_im = Image.open("taulu.png") +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") + +wooden_im = Image.open("wooden.png") golden_im = Image.open("golden.png") img_size = (640, 640) -GOLDEN_CHANCE = 2 #% +GOLDEN_CHANCE = 1 # % START_TIME = calendar.timegm(time.gmtime()) -taulu_im.thumbnail(img_size, Image.ANTIALIAS) -golden_im.thumbnail(img_size, Image.ANTIALIAS) +wooden_im.thumbnail(img_size) +golden_im.thumbnail(img_size) + +bot = telepot.Bot(BOT_TOKEN) +logging.warning("Connected with token {}".format(BOT_TOKEN)) -def run_taulu(chat_id, user_id): +last_user_by_chat_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 +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) - logging.warning("Looking up picture...") - pic = photos["photos"][0][-1] - file_id = pic["file_id"] + return im - if not os.path.exists("photo/"): - logging.warning("No 'photo' directory in working directory, creating one...") - os.makedirs("photo/") - # download to a file with user_id in the name for duplicate recognition - filepath = "photo/" + str(abs(user_id)) + ".jpg" - finalpath = "photo/" + str(abs(user_id)) + "final.png" +def run(chat_id, user_id): + photos = bot.getUserProfilePhotos(user_id) - # every 100th image has golden borders :) - golden_number= random.randrange(1, 100) - logging.warning("Random gold number was: {}".format(golden_number)) - is_golden = (golden_number < GOLDEN_CHANCE) + if photos["total_count"] == 0: + logging.error("No pictures found, sending message...") + bot.sendMessage(chat_id, "Vitun taulu, hommaa kuva!") + return - if os.path.exists(finalpath) and not is_golden: - logging.warning("User profile already found. Skipping download and edit...") - else: - logging.warning("Downloading picture...") - bot.downloadFile(file_id, filepath) - # time.sleep(2) + logging.warning("Looking up picture...") + pic = photos["photos"][0][-1] + file_id = pic["file_id"] - logging.warning("Opening image for editing...") - im = Image.open(filepath) - im.thumbnail(img_size, Image.ANTIALIAS) + if not os.path.exists("photo/"): + logging.warning("No 'photo' directory in working directory, creating one...") + os.makedirs("photo/") - if is_golden: - logging.warning("Golden taulu!") - im.paste(golden_im, (0, 0), golden_im) - bot.sendMessage(chat_id, "Onneksi olkoon! Kultainen taulu ilmestyy vain kerran tuhannessa vuodessa!") - else: - im.paste(taulu_im, (0, 0), taulu_im) + unedited_path = f"photo/{file_id}.jpg" + edited_path_wooden = f"photo/{file_id}_wooden.png" + edited_path_gold = f"photo/{file_id}_gold.png" - logging.warning("Saving image...") - im.save(finalpath) + 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) - f = open(finalpath, "rb") - logging.warning("Sending photo {} to chat {}...".format(finalpath, chat_id)) - bot.sendPhoto(chat_id, f) + # 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 - logging.warning("Image sent succesfully.") - return + 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 -# Getting the token from command-line is better than embedding it in code, -# because tokens are supposed to be kept secret. -TOKEN = sys.argv[1] + logging.warning( + "Editing and sending photo {} to chat {}...".format(edited_path, chat_id) + ) + im = edit_image(unedited_path, edited_path, frame_im) + with open(edited_path, "rb") as f: + bot.sendPhoto(chat_id, f) -bot = telepot.Bot(TOKEN) -logging.warning("Connected with token {}".format(TOKEN)) + logging.warning("Image sent succesfully.") + return -last_user_by_chat_id = {} -done_list = [] def is_taulu_command(text): - return "taulu" in text.strip().lower() + 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["text"] + logging.debug( + "New message! chat_id: {}, user_name: {}, msg_text: {}".format( + chat_id, user_name, msg_text + ) + ) - chat_id = msg["chat"]["id"] - user_id = msg["from"]["id"] - user_name = msg["from"]["first_name"] - msg_text = msg["text"] - logging.warning("New message! chat_id: {}, user_name: {}, msg_text: {}".format(chat_id, user_name, msg_text)) + if 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: + logging.error( + "Error occured during process. Retrying... (attempt {})".format( + attempt + ) + ) + attempt += 1 - if is_taulu_command(msg_text): - logging.warning("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_taulu(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: - logging.error("Error occured during process. Retrying... (attempt {})".format(attempt)) - attempt += 1 + last_user_by_chat_id[chat_id] = user_id - last_user_by_chat_id[chat_id] = user_id -bot.notifyOnMessage(handle) logging.warning("Listening...") +MessageLoop(bot, handle).run_as_thread() # Keep the program running. while 1: - time.sleep(5) + time.sleep(1) |
