import sys import time from pprint import pprint import telepot import urllib.request import time from PIL import Image import os import calendar final_path = "photo/final.png" taulu_im = Image.open("taulu.png") img_size = (640, 640) START_TIME = calendar.timegm(time.gmtime()) 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...") bot.sendMessage(chat_id, "Vitun taulu, hommaa kuva!") return True print("Looking up picture...") pic = photos["photos"][0][-1] file_id = pic["file_id"] if not os.path.exists("photo/"): os.makedirs("photo/") filepath = "photo/" + file_id + ".jpg" print("Downloading picture...") bot.downloadFile(file_id, filepath) time.sleep(2) print("Downloaded!") 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)) f = open(final_path, "rb") print("Sending photo {} to chat {}...".format(final_path, chat_id)) bot.sendPhoto(chat_id, f) print("Done. Returning...") return True # 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 ...') last_user_in_chat = {} done_list = [] def is_taulu_command(text): return "/taulu" in text.strip() # Keep the program running. offset_id = 0 while 1: time.sleep(5) res = bot.getUpdates() if len(res) == 0: continue for r in res: try: date = int(r["message"]["date"]) if (date < START_TIME): continue chat_id = r["message"]["chat"]["id"] user_id = r["message"]["from"]["id"] msg_id = r["message"]["message_id"] text = r["message"]["text"] except: print("Broken text") continue 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