Skip to content

Commit 9bccbda

Browse files
committed
Added ability to filter by username
1 parent e18ebd0 commit 9bccbda

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

telegram/ext/filters.py

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,27 +328,60 @@ class user(BaseFilter):
328328
"""Filters messages to allow only those which are from specified user ID
329329
330330
Args:
331-
user_id(int): which user ID to allow through
331+
user_id(Optional[int]): which user ID to allow through. Required if username is not
332+
specified
333+
username(Optional[str]): which username to allow through. Required if user_id is not
334+
specified
335+
336+
Raises:
337+
ValueError
332338
"""
333339

334-
def __init__(self, user_id):
340+
def __init__(self, user_id=None, username=None):
341+
if (user_id is None and username is None) or (bool(user_id) and bool(username)):
342+
raise ValueError('You must specify either user_id or username')
343+
if username is not None and username.startswith('@'):
344+
self.username = username[1:]
345+
else:
346+
self.username = username
335347
self.user_id = user_id
336348

337349
def filter(self, message):
338-
return bool(message.from_user and message.from_user.id == self.user_id)
350+
if self.user_id is not None:
351+
return bool(message.from_user and message.from_user.id == self.user_id)
352+
else:
353+
# self.username is not None
354+
return bool(message.from_user and message.from_user.username and
355+
message.from_user.username == self.username)
339356

340357
class chat(BaseFilter):
341358
"""Filters messages to allow only those which are from specified chat ID
342359
343360
Args:
344-
chat_id(int): which chat ID to allow through
361+
chat_id(Optional[int]): which chat ID to allow through. Required if username is not
362+
specified
363+
username(Optional[str]): which username to allow through. Required if chat_id is not
364+
specified
365+
366+
Raises:
367+
ValueError
345368
"""
346369

347-
def __init__(self, chat_id):
370+
def __init__(self, chat_id=None, username=None):
371+
if (chat_id is None and username is None) or (bool(chat_id) and bool(username)):
372+
raise ValueError('You must specify either chat_id or username')
373+
if username is not None and username.startswith('@'):
374+
self.username = username[1:]
375+
else:
376+
self.username = username
348377
self.chat_id = chat_id
349378

350379
def filter(self, message):
351-
return bool(message.chat_id == self.chat_id)
380+
if self.chat_id is not None:
381+
return message.chat_id == self.chat_id
382+
else:
383+
# self.username is not None
384+
return bool(message.chat.username and message.chat.username == self.username)
352385

353386
class _Invoice(BaseFilter):
354387

0 commit comments

Comments
 (0)