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