summaryrefslogtreecommitdiffstats
path: root/taulubot.py
diff options
context:
space:
mode:
authorJan Tuomi <jans.tuomi@gmail.com>2016-02-23 17:23:13 +0200
committerJan Tuomi <jans.tuomi@gmail.com>2016-02-23 17:23:13 +0200
commit2a3948f008ff8a80ca367b238c6af13a16b9fb5b (patch)
tree3fdfd15efb87cb3ccae7a0e7bc96a1eba1709860 /taulubot.py
parentb3c684ec9bb2597c55726c1ec81f86347e776663 (diff)
Rehaul polling, rewrite the whole thing
Diffstat (limited to 'taulubot.py')
-rw-r--r--taulubot.py101
1 files changed, 50 insertions, 51 deletions
diff --git a/taulubot.py b/taulubot.py
index 1f6c4e5..fad1a68 100644
--- a/taulubot.py
+++ b/taulubot.py
@@ -7,8 +7,9 @@ import time
from PIL import Image
import os
import calendar
+import logging
+logging.basicConfig(format='%(asctime)s %(message)s')
-final_path = "photo/final.png"
taulu_im = Image.open("taulu.png")
img_size = (640, 640)
START_TIME = calendar.timegm(time.gmtime())
@@ -17,84 +18,82 @@ taulu_im.thumbnail(img_size, Image.ANTIALIAS)
def run_taulu(chat_id, user_id):
- print("New taulu!")
photos = bot.getUserProfilePhotos(user_id)
if photos["total_count"] == 0:
- print("No pictures found, sending message...")
+ logging.error("No pictures found, sending message...")
bot.sendMessage(chat_id, "Vitun taulu, hommaa kuva!")
- return True
+ return
- print("Looking up picture...")
+ logging.warning("Looking up picture...")
pic = photos["photos"][0][-1]
file_id = pic["file_id"]
if not os.path.exists("photo/"):
- os.makedirs("photo/")
+ logging.warning("No 'photo' directory in working directory, creating one...")
+ os.makedirs("photo/")
- filepath = "photo/" + file_id + ".jpg"
- print("Downloading picture...")
- bot.downloadFile(file_id, filepath)
- time.sleep(2)
- print("Downloaded!")
+ # 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)
- print("Opening image for editing...")
- im = Image.open(filepath)
- im.thumbnail(img_size, Image.ANTIALIAS)
- im.paste(taulu_im, (0, 0), taulu_im)
- print("Saving image...")
- im.save(final_path)
- time.sleep(2)
- print("Saved to {}!".format(final_path))
+ logging.warning("Opening image for editing...")
+ im = Image.open(filepath)
+ im.thumbnail(img_size, Image.ANTIALIAS)
+ im.paste(taulu_im, (0, 0), taulu_im)
- f = open(final_path, "rb")
- print("Sending photo {} to chat {}...".format(final_path, chat_id))
+ 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)
- print("Done. Returning...")
- return True
+ 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)
-print('Listening ...')
+logging.warning("Connected with token {}".format(TOKEN))
+
-last_user_in_chat = {}
+last_user_by_chat_id = {}
done_list = []
def is_taulu_command(text):
- return "/taulu" in text.strip()
+ return "taulu" in text.strip().lower()
-# Keep the program running.
-offset_id = 0
-while 1:
- time.sleep(5)
- res = bot.getUpdates()
+def handle(msg):
- if len(res) == 0:
- continue
+ 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))
- for r in res:
+ if is_taulu_command(msg_text):
+ logging.warning("Taulu command found!")
try:
- date = int(r["message"]["date"])
- if (date < START_TIME):
- continue
+ 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)
+ except KeyError:
+ logging.error("No chat id found in chat dict. Maybe no previous messages in the chat?")
- chat_id = r["message"]["chat"]["id"]
- user_id = r["message"]["from"]["id"]
- msg_id = r["message"]["message_id"]
- text = r["message"]["text"]
+ last_user_by_chat_id[chat_id] = user_id
- except:
- print("Broken text")
- continue
+bot.notifyOnMessage(handle)
+logging.warning("Listening...")
- if chat_id in last_user_in_chat:
- if is_taulu_command(text) and not msg_id in done_list:
- taulu_id = last_user_in_chat[chat_id]
- run_taulu(chat_id, taulu_id)
- done_list.append(msg_id)
-
- last_user_in_chat[chat_id] = user_id
+# Keep the program running.
+while 1:
+ time.sleep(5)