-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimiter.py
More file actions
40 lines (34 loc) · 1.03 KB
/
Copy pathlimiter.py
File metadata and controls
40 lines (34 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import time
#TO DO limiter
class RateLimiter:
"""
chat_id => [last_send_time, last_minute_time, msg_count]
"""
def __init__(self):
self.users = {}
def can_send_to(self, chat_id):
now = time.time()
if not chat_id in self.users:
self.users[chat_id] = [now, now, 0]
return True
# 1 message per second case
diff = now - self.users[chat_id][0]
if diff <= 1:
return False
self.users[chat_id][0] = now
# 20 messages per minute case
diff = now - self.users[chat_id][1]
if diff <= 60:
msg_count = self.users[chat_id][2]
if msg_count < 20:
return True
else:
return False
else:
self.users[chat_id][1] = now
self.users[chat_id][2] = 0
return True
def send_to(self, chat_id):
if not chat_id in self.users:
raise Exception("invalid usage of rate limiter")
self.users[chat_id][2] += 1