From 09d01d001b10e34c8e27d74ee1db2b08ba1cabd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannes=20H=C3=B6ke?= Date: Sat, 19 Aug 2017 00:08:55 +0200 Subject: [PATCH] add cached admin check --- bot.py | 4 ++-- mwt.py | 41 +++++++++++++++++++++++++++++++++++++++++ utils.py | 7 +++++++ 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 mwt.py diff --git a/bot.py b/bot.py index 996a4ed..43deecd 100644 --- a/bot.py +++ b/bot.py @@ -32,7 +32,7 @@ from results import (add_call_bluff, add_choose_color, add_draw, add_gameinfo, add_no_game, add_not_started, add_other_cards, add_pass, add_card) from user_setting import UserSetting -from utils import display_name +from utils import display_name, get_admin_ids import card as c from errors import (NoGameInChatError, LobbyClosedError, AlreadyJoinedError, NotEnoughPlayersError, DeckEmptyError) @@ -117,7 +117,7 @@ def kill_game(bot, update): game = games[-1] - if user.id in game.owner: + if user.id in game.owner or user.id in get_admin_ids(bot, chat.id): try: gm.end_game(chat, user) diff --git a/mwt.py b/mwt.py new file mode 100644 index 0000000..40dc9b4 --- /dev/null +++ b/mwt.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# Source: http://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1 + +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 \ No newline at end of file diff --git a/utils.py b/utils.py index 2c5f288..2d41bc9 100644 --- a/utils.py +++ b/utils.py @@ -23,6 +23,7 @@ import logging from telegram.ext.dispatcher import run_async from internationalization import _, __ +from mwt import MWT logger = logging.getLogger(__name__) @@ -102,3 +103,9 @@ def answer_async(bot, *args, **kwargs): bot.answerInlineQuery(*args, **kwargs) except Exception as e: error(None, None, e) + + +@MWT(timeout=60*60) +def get_admin_ids(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)] \ No newline at end of file