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
|
import sys
import random
import time
from pprint import pprint
import telepot
import urllib.request
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")
golden_im = Image.open("golden.png")
img_size = (640, 640)
START_TIME = calendar.timegm(time.gmtime())
taulu_im.thumbnail(img_size, Image.ANTIALIAS)
golden_im.thumbnail(img_size, Image.ANTIALIAS)
def run_taulu(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/")
# 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"
if os.path.exists(finalpath):
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("Opening image for editing...")
im = Image.open(filepath)
im.thumbnail(img_size, Image.ANTIALIAS)
# every 100th image has golden borders :)
golden_chance = random.randrange(1, 100)
logging.warning("Random gold number was: {}".format(golden_chance))
if golden_chance == 1:
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)
logging.warning("Saving image...")
im.save(finalpath)
f = open(finalpath, "rb")
logging.warning("Sending photo {} to chat {}...".format(finalpath, chat_id))
bot.sendPhoto(chat_id, f)
logging.warning("Image sent succesfully.")
return
# 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]
bot = telepot.Bot(TOKEN)
logging.warning("Connected with token {}".format(TOKEN))
last_user_by_chat_id = {}
done_list = []
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.warning("New message! chat_id: {}, user_name: {}, msg_text: {}".format(chat_id, user_name, msg_text))
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
bot.notifyOnMessage(handle)
logging.warning("Listening...")
# Keep the program running.
while 1:
time.sleep(5)
|