forked from test/mau_mau_bot
add cached admin check
This commit is contained in:
parent
63bf9e4035
commit
09d01d001b
3 changed files with 50 additions and 2 deletions
4
bot.py
4
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)
|
||||
|
|
41
mwt.py
Normal file
41
mwt.py
Normal file
|
@ -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
|
7
utils.py
7
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)]
|
Loading…
Reference in a new issue