summaryrefslogtreecommitdiffstats
path: root/taulubot.py
blob: 27f3b1bc86d0c822c0e77bf41dd84cf257485d45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import random
import time
from pprint import pprint
from telepot import Bot
from telepot.loop import MessageLoop
import time
from PIL import Image
import os
import calendar
import logging

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 = 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"]

    if not os.path.exists("photo/"):
        logging.warning("No 'photo' directory in working directory, creating one...")
        os.makedirs("photo/")

    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"

    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)
    )
    im = 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["text"]
    logging.debug(
        "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

    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)