Skip to content

Commit 09d01d0

Browse files
committed
add cached admin check
1 parent 63bf9e4 commit 09d01d0

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed

bot.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
add_no_game, add_not_started, add_other_cards, add_pass,
3333
add_card)
3434
from user_setting import UserSetting
35-
from utils import display_name
35+
from utils import display_name, get_admin_ids
3636
import card as c
3737
from errors import (NoGameInChatError, LobbyClosedError, AlreadyJoinedError,
3838
NotEnoughPlayersError, DeckEmptyError)
@@ -117,7 +117,7 @@ def kill_game(bot, update):
117117

118118
game = games[-1]
119119

120-
if user.id in game.owner:
120+
if user.id in game.owner or user.id in get_admin_ids(bot, chat.id):
121121

122122
try:
123123
gm.end_game(chat, user)

mwt.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python
2+
# Source: http://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1
3+
4+
import time
5+
6+
class MWT(object):
7+
"""Memoize With Timeout"""
8+
_caches = {}
9+
_timeouts = {}
10+
11+
def __init__(self,timeout=2):
12+
self.timeout = timeout
13+
14+
def collect(self):
15+
"""Clear cache of results which have timed out"""
16+
for func in self._caches:
17+
cache = {}
18+
for key in self._caches[func]:
19+
if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
20+
cache[key] = self._caches[func][key]
21+
self._caches[func] = cache
22+
23+
def __call__(self, f):
24+
self.cache = self._caches[f] = {}
25+
self._timeouts[f] = self.timeout
26+
27+
def func(*args, **kwargs):
28+
kw = sorted(kwargs.items())
29+
key = (args, tuple(kw))
30+
try:
31+
v = self.cache[key]
32+
print("cache")
33+
if (time.time() - v[1]) > self.timeout:
34+
raise KeyError
35+
except KeyError:
36+
print("new")
37+
v = self.cache[key] = f(*args,**kwargs),time.time()
38+
return v[0]
39+
func.func_name = f.__name__
40+
41+
return func

utils.py

+7
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from telegram.ext.dispatcher import run_async
2424

2525
from internationalization import _, __
26+
from mwt import MWT
2627

2728
logger = logging.getLogger(__name__)
2829

@@ -102,3 +103,9 @@ def answer_async(bot, *args, **kwargs):
102103
bot.answerInlineQuery(*args, **kwargs)
103104
except Exception as e:
104105
error(None, None, e)
106+
107+
108+
@MWT(timeout=60*60)
109+
def get_admin_ids(bot, chat_id):
110+
"""Returns a list of admin IDs for a given chat. Results are cached for 1 hour."""
111+
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)]

0 commit comments

Comments
 (0)