From 352b312afb2fc247979132a8d7c749453ec40e94 Mon Sep 17 00:00:00 2001 From: Stan James Date: Thu, 22 Feb 2018 15:38:02 -0800 Subject: [PATCH] Disable checks for admins --- bot.py | 11 +++++++++-- mwt.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 mwt.py diff --git a/bot.py b/bot.py index f94bf86..bb87013 100644 --- a/bot.py +++ b/bot.py @@ -17,7 +17,7 @@ from model import User, Message, MessageHide, UserBan, session from time import strftime import re import unidecode - +from mwt import MWT class TelegramMonitorBot: @@ -55,6 +55,11 @@ class TelegramMonitorBot: self.ban_name_feedback_message = "You have been banned from this group for having a misleading username." self.hide_feedback_message = "Your last message was deleted for having prohibited content." + @MWT(timeout=60*60) + def get_admin_ids(self, bot, chat_id): + """Returns a list of admin IDs for a given chat. Results are cached for 1 hour.""" + return [admin.user.id for admin in bot.get_chat_administrators(chat_id)] + def ban_user(self, update): """ Ban user """ kick_success = update.message.chat.kick_member(update.message.from_user.id) @@ -209,10 +214,12 @@ class TelegramMonitorBot: update.message.text.encode('utf-8')) ) - if not update.message.from_user.id in self.safe_user_ids: + if update.message.from_user.id not in self.get_admin_ids(bot, update.message.chat_id): # Security checks self.security_check_username(bot, update) self.security_check_message(bot, update) + else: + print("Skipping checks. User is admin: {}".format(user.id)) except Exception as e: print("Error: {}".format(e)) diff --git a/mwt.py b/mwt.py new file mode 100644 index 0000000..c936b90 --- /dev/null +++ b/mwt.py @@ -0,0 +1,38 @@ +import time + +class MWT(object): + """Memoize With Timeout""" + _caches = {} + _timeouts = {} + + def __init__(self,timeout=2): + self.timeout = timeout + + def collect(self): + """Clear cache of results which have timed out""" + for func in self._caches: + cache = {} + for key in self._caches[func]: + if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: + cache[key] = self._caches[func][key] + self._caches[func] = cache + + def __call__(self, f): + self.cache = self._caches[f] = {} + self._timeouts[f] = self.timeout + + def func(*args, **kwargs): + kw = sorted(kwargs.items()) + key = (args, tuple(kw)) + try: + v = self.cache[key] + print("cache") + if (time.time() - v[1]) > self.timeout: + raise KeyError + except KeyError: + print("new") + v = self.cache[key] = f(*args,**kwargs),time.time() + return v[0] + func.func_name = f.__name__ + + return func