-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
filters.py
2704 lines (1988 loc) · 89.7 KB
/
filters.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2023
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""
This module contains filters for use with :class:`telegram.ext.MessageHandler`,
:class:`telegram.ext.CommandHandler`, or :class:`telegram.ext.PrefixHandler`.
.. versionchanged:: 20.0
#. Filters are no longer callable, if you're using a custom filter and are calling an existing
filter, then switch to the new syntax: ``filters.{filter}.check_update(update)``.
#. Removed the ``Filters`` class. The filters are now directly attributes/classes of the
:mod:`~telegram.ext.filters` module.
#. The names of all filters has been updated:
* Filter classes which are ready for use, e.g ``Filters.all`` are now capitalized, e.g
``filters.ALL``.
* Filters which need to be initialized are now in CamelCase. E.g. ``filters.User(...)``.
* Filters which do both (like ``Filters.text``) are now split as ready-to-use version
``filters.TEXT`` and class version ``filters.Text(...)``.
"""
__all__ = (
"ALL",
"ANIMATION",
"ATTACHMENT",
"AUDIO",
"CAPTION",
"CHAT",
"COMMAND",
"CONTACT",
"FORWARDED",
"GAME",
"HAS_MEDIA_SPOILER",
"HAS_PROTECTED_CONTENT",
"INVOICE",
"IS_AUTOMATIC_FORWARD",
"IS_TOPIC_MESSAGE",
"LOCATION",
"PASSPORT_DATA",
"PHOTO",
"POLL",
"PREMIUM_USER",
"REPLY",
"STORY",
"SUCCESSFUL_PAYMENT",
"TEXT",
"USER",
"USER_ATTACHMENT",
"VENUE",
"VIA_BOT",
"VIDEO",
"VIDEO_NOTE",
"VOICE",
"BaseFilter",
"Caption",
"CaptionEntity",
"CaptionRegex",
"Chat",
"ChatType",
"Command",
"Dice",
"Document",
"Entity",
"ForwardedFrom",
"Language",
"Mention",
"MessageFilter",
"Regex",
"SenderChat",
"StatusUpdate",
"Sticker",
"SuccessfulPayment",
"Text",
"UpdateFilter",
"UpdateType",
"User",
"ViaBot",
)
import mimetypes
import re
from abc import ABC, abstractmethod
from typing import (
Collection,
Dict,
FrozenSet,
Iterable,
List,
Match,
NoReturn,
Optional,
Pattern,
Sequence,
Set,
Tuple,
Union,
cast,
)
from telegram import Chat as TGChat
from telegram import Message, MessageEntity, Update
from telegram import User as TGUser
from telegram._utils.types import SCT
from telegram.constants import DiceEmoji as DiceEmojiEnum
from telegram.ext._utils.types import FilterDataDict
class BaseFilter:
"""Base class for all Filters.
Filters subclassing from this class can combined using bitwise operators:
And::
filters.TEXT & filters.Entity(MENTION)
Or::
filters.AUDIO | filters.VIDEO
Exclusive Or::
filters.Regex('To Be') ^ filters.Regex('Not 2B')
Not::
~ filters.COMMAND
Also works with more than two filters::
filters.TEXT & (filters.Entity("url") | filters.Entity("text_link"))
filters.TEXT & (~ filters.FORWARDED)
Note:
Filters use the same short circuiting logic as python's :keyword:`and`, :keyword:`or` and
:keyword:`not`. This means that for example::
filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')
With ``message.text == 'x'``, will only ever return the matches for the first filter,
since the second one is never evaluated.
If you want to create your own filters create a class inheriting from either
:class:`MessageFilter` or :class:`UpdateFilter` and implement a ``filter()``
method that returns a boolean: :obj:`True` if the message should be
handled, :obj:`False` otherwise.
Note that the filters work only as class instances, not actual class objects (so remember to
initialize your filter classes).
By default, the filters name (what will get printed when converted to a string for display)
will be the class name. If you want to overwrite this assign a better name to the :attr:`name`
class variable.
.. versionadded:: 20.0
Added the arguments :attr:`name` and :attr:`data_filter`.
Args:
name (:obj:`str`): Name for this filter. Defaults to the type of filter.
data_filter (:obj:`bool`): Whether this filter is a data filter. A data filter should
return a dict with lists. The dict will be merged with
:class:`telegram.ext.CallbackContext`'s internal dict in most cases
(depends on the handler).
"""
__slots__ = ("_data_filter", "_name")
def __init__(self, name: Optional[str] = None, data_filter: bool = False):
self._name = self.__class__.__name__ if name is None else name
self._data_filter = data_filter
def __and__(self, other: "BaseFilter") -> "BaseFilter":
"""Defines `AND` bitwise operator for :class:`BaseFilter` object.
The combined filter accepts an update only if it is accepted by both filters.
For example, ``filters.PHOTO & filters.CAPTION`` will only accept messages that contain
both a photo and a caption.
Returns:
:obj:`BaseFilter`
"""
return _MergedFilter(self, and_filter=other)
def __or__(self, other: "BaseFilter") -> "BaseFilter":
"""Defines `OR` bitwise operator for :class:`BaseFilter` object.
The combined filter accepts an update only if it is accepted by any of the filters.
For example, ``filters.PHOTO | filters.CAPTION`` will only accept messages that contain
photo or caption or both.
Returns:
:obj:`BaseFilter`
"""
return _MergedFilter(self, or_filter=other)
def __xor__(self, other: "BaseFilter") -> "BaseFilter":
"""Defines `XOR` bitwise operator for :class:`BaseFilter` object.
The combined filter accepts an update only if it is accepted by any of the filters and
not both of them. For example, ``filters.PHOTO ^ filters.CAPTION`` will only accept
messages that contain photo or caption, not both of them.
Returns:
:obj:`BaseFilter`
"""
return _XORFilter(self, other)
def __invert__(self) -> "BaseFilter":
"""Defines `NOT` bitwise operator for :class:`BaseFilter` object.
The combined filter accepts an update only if it is accepted by any of the filters.
For example, ``~ filters.PHOTO`` will only accept messages that do not contain photo.
Returns:
:obj:`BaseFilter`
"""
return _InvertedFilter(self)
def __repr__(self) -> str:
"""Gives name for this filter.
.. seealso::
:meth:`name`
Returns:
:obj:`str`:
"""
return self.name
@property
def data_filter(self) -> bool:
""":obj:`bool`: Whether this filter is a data filter."""
return self._data_filter
@data_filter.setter
def data_filter(self, value: bool) -> None:
self._data_filter = value
@property
def name(self) -> str:
""":obj:`str`: Name for this filter."""
return self._name
@name.setter
def name(self, name: str) -> None:
self._name = name
def check_update(self, update: Update) -> Optional[Union[bool, FilterDataDict]]:
"""Checks if the specified update should be handled by this filter.
Args:
update (:class:`telegram.Update`): The update to check.
Returns:
:obj:`bool`: :obj:`True` if the update contains one of
:attr:`~telegram.Update.channel_post`, :attr:`~telegram.Update.message`,
:attr:`~telegram.Update.edited_channel_post` or
:attr:`~telegram.Update.edited_message`, :obj:`False` otherwise.
"""
if ( # Only message updates should be handled.
update.channel_post
or update.message
or update.edited_channel_post
or update.edited_message
):
return True
return False
class MessageFilter(BaseFilter):
"""Base class for all Message Filters. In contrast to :class:`UpdateFilter`, the object passed
to :meth:`filter` is :obj:`telegram.Update.effective_message`.
Please see :class:`BaseFilter` for details on how to create custom filters.
.. seealso:: :wiki:`Advanced Filters <Extensions---Advanced-Filters>`
"""
__slots__ = ()
def check_update(self, update: Update) -> Optional[Union[bool, FilterDataDict]]:
"""Checks if the specified update should be handled by this filter by passing
:attr:`~telegram.Update.effective_message` to :meth:`filter`.
Args:
update (:class:`telegram.Update`): The update to check.
Returns:
:obj:`bool` | Dict[:obj:`str`, :obj:`list`] | :obj:`None`: If the update should be
handled by this filter, returns :obj:`True` or a dict with lists, in case the filter
is a data filter. If the update should not be handled by this filter, :obj:`False` or
:obj:`None`.
"""
if super().check_update(update):
return self.filter(update.effective_message) # type: ignore[arg-type]
return False
@abstractmethod
def filter(self, message: Message) -> Optional[Union[bool, FilterDataDict]]:
"""This method must be overwritten.
Args:
message (:class:`telegram.Message`): The message that is tested.
Returns:
:obj:`dict` or :obj:`bool`
"""
class UpdateFilter(BaseFilter):
"""Base class for all Update Filters. In contrast to :class:`MessageFilter`, the object
passed to :meth:`filter` is an instance of :class:`telegram.Update`, which allows to create
filters like :attr:`telegram.ext.filters.UpdateType.EDITED_MESSAGE`.
Please see :class:`telegram.ext.filters.BaseFilter` for details on how to create custom
filters.
"""
__slots__ = ()
def check_update(self, update: Update) -> Optional[Union[bool, FilterDataDict]]:
"""Checks if the specified update should be handled by this filter.
Args:
update (:class:`telegram.Update`): The update to check.
Returns:
:obj:`bool` | Dict[:obj:`str`, :obj:`list`] | :obj:`None`: If the update should be
handled by this filter, returns :obj:`True` or a dict with lists, in case the filter
is a data filter. If the update should not be handled by this filter, :obj:`False` or
:obj:`None`.
"""
return self.filter(update) if super().check_update(update) else False
@abstractmethod
def filter(self, update: Update) -> Optional[Union[bool, FilterDataDict]]:
"""This method must be overwritten.
Args:
update (:class:`telegram.Update`): The update that is tested.
Returns:
:obj:`dict` or :obj:`bool`.
"""
class _InvertedFilter(UpdateFilter):
"""Represents a filter that has been inverted.
Args:
f: The filter to invert.
"""
__slots__ = ("inv_filter",)
def __init__(self, f: BaseFilter):
super().__init__()
self.inv_filter = f
def filter(self, update: Update) -> bool:
return not bool(self.inv_filter.check_update(update))
@property
def name(self) -> str:
return f"<inverted {self.inv_filter}>"
@name.setter
def name(self, name: str) -> NoReturn:
raise RuntimeError("Cannot set name for combined filters.")
class _MergedFilter(UpdateFilter):
"""Represents a filter consisting of two other filters.
Args:
base_filter: Filter 1 of the merged filter.
and_filter: Optional filter to "and" with base_filter. Mutually exclusive with or_filter.
or_filter: Optional filter to "or" with base_filter. Mutually exclusive with and_filter.
"""
__slots__ = ("and_filter", "base_filter", "or_filter")
def __init__(
self,
base_filter: BaseFilter,
and_filter: Optional[BaseFilter] = None,
or_filter: Optional[BaseFilter] = None,
):
super().__init__()
self.base_filter = base_filter
if self.base_filter.data_filter:
self.data_filter = True
self.and_filter = and_filter
if (
self.and_filter
and not isinstance(self.and_filter, bool)
and self.and_filter.data_filter
):
self.data_filter = True
self.or_filter = or_filter
if self.or_filter and not isinstance(self.and_filter, bool) and self.or_filter.data_filter:
self.data_filter = True
@staticmethod
def _merge(base_output: Union[bool, Dict], comp_output: Union[bool, Dict]) -> FilterDataDict:
base = base_output if isinstance(base_output, dict) else {}
comp = comp_output if isinstance(comp_output, dict) else {}
for k in comp:
# Make sure comp values are lists
comp_value = comp[k] if isinstance(comp[k], list) else []
try:
# If base is a list then merge
if isinstance(base[k], list):
base[k] += comp_value
else:
base[k] = [base[k], *comp_value]
except KeyError:
base[k] = comp_value
return base
# pylint: disable=too-many-return-statements
def filter(self, update: Update) -> Union[bool, FilterDataDict]:
base_output = self.base_filter.check_update(update)
# We need to check if the filters are data filters and if so return the merged data.
# If it's not a data filter or an or_filter but no matches return bool
if self.and_filter:
# And filter needs to short circuit if base is falsy
if base_output:
comp_output = self.and_filter.check_update(update)
if comp_output:
if self.data_filter:
merged = self._merge(base_output, comp_output)
if merged:
return merged
return True
elif self.or_filter:
# Or filter needs to short circuit if base is truthy
if base_output:
if self.data_filter:
return base_output
return True
comp_output = self.or_filter.check_update(update)
if comp_output:
if self.data_filter:
return comp_output
return True
return False
@property
def name(self) -> str:
return (
f"<{self.base_filter} {'and' if self.and_filter else 'or'} "
f"{self.and_filter or self.or_filter}>"
)
@name.setter
def name(self, name: str) -> NoReturn:
raise RuntimeError("Cannot set name for combined filters.")
class _XORFilter(UpdateFilter):
"""Convenience filter acting as wrapper for :class:`MergedFilter` representing the an XOR gate
for two filters.
Args:
base_filter: Filter 1 of the merged filter.
xor_filter: Filter 2 of the merged filter.
"""
__slots__ = ("base_filter", "merged_filter", "xor_filter")
def __init__(self, base_filter: BaseFilter, xor_filter: BaseFilter):
super().__init__()
self.base_filter = base_filter
self.xor_filter = xor_filter
self.merged_filter = (base_filter & ~xor_filter) | (~base_filter & xor_filter)
def filter(self, update: Update) -> Optional[Union[bool, FilterDataDict]]:
return self.merged_filter.check_update(update)
@property
def name(self) -> str:
return f"<{self.base_filter} xor {self.xor_filter}>"
@name.setter
def name(self, name: str) -> NoReturn:
raise RuntimeError("Cannot set name for combined filters.")
class _All(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return True
ALL = _All(name="filters.ALL")
"""All Messages."""
class _Animation(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return bool(message.animation)
ANIMATION = _Animation(name="filters.ANIMATION")
"""Messages that contain :attr:`telegram.Message.animation`."""
class _Attachment(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return bool(message.effective_attachment)
ATTACHMENT = _Attachment(name="filters.ATTACHMENT")
"""Messages that contain :meth:`telegram.Message.effective_attachment`.
.. versionadded:: 13.6"""
class _Audio(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return bool(message.audio)
AUDIO = _Audio(name="filters.AUDIO")
"""Messages that contain :attr:`telegram.Message.audio`."""
class Caption(MessageFilter):
"""Messages with a caption. If a list of strings is passed, it filters messages to only
allow those whose caption is appearing in the given list.
Examples:
``MessageHandler(filters.Caption(['PTB rocks!', 'PTB']), callback_method_2)``
.. seealso::
:attr:`telegram.ext.filters.CAPTION`
Args:
strings (List[:obj:`str`] | Tuple[:obj:`str`], optional): Which captions to allow. Only
exact matches are allowed. If not specified, will allow any message with a caption.
"""
__slots__ = ("strings",)
def __init__(self, strings: Optional[Union[List[str], Tuple[str, ...]]] = None):
self.strings: Optional[Sequence[str]] = strings
super().__init__(name=f"filters.Caption({strings})" if strings else "filters.CAPTION")
def filter(self, message: Message) -> bool:
if self.strings is None:
return bool(message.caption)
return message.caption in self.strings if message.caption else False
CAPTION = Caption()
"""Shortcut for :class:`telegram.ext.filters.Caption()`.
Examples:
To allow any caption, simply use ``MessageHandler(filters.CAPTION, callback_method)``.
"""
class CaptionEntity(MessageFilter):
"""
Filters media messages to only allow those which have a :class:`telegram.MessageEntity`
where their :class:`~telegram.MessageEntity.type` matches `entity_type`.
Examples:
``MessageHandler(filters.CaptionEntity("hashtag"), callback_method)``
Args:
entity_type (:obj:`str`): Caption Entity type to check for. All types can be found as
constants in :class:`telegram.MessageEntity`.
"""
__slots__ = ("entity_type",)
def __init__(self, entity_type: str):
self.entity_type: str = entity_type
super().__init__(name=f"filters.CaptionEntity({self.entity_type})")
def filter(self, message: Message) -> bool:
return any(entity.type == self.entity_type for entity in message.caption_entities)
class CaptionRegex(MessageFilter):
"""
Filters updates by searching for an occurrence of :paramref:`~CaptionRegex.pattern` in the
message caption.
This filter works similarly to :class:`Regex`, with the only exception being that
it applies to the message caption instead of the text.
Examples:
Use ``MessageHandler(filters.PHOTO & filters.CaptionRegex(r'help'), callback)``
to capture all photos with caption containing the word 'help'.
Note:
This filter will not work on simple text messages, but only on media with caption.
Args:
pattern (:obj:`str` | :func:`re.Pattern <re.compile>`): The regex pattern.
"""
__slots__ = ("pattern",)
def __init__(self, pattern: Union[str, Pattern[str]]):
if isinstance(pattern, str):
pattern = re.compile(pattern)
self.pattern: Pattern[str] = pattern
super().__init__(name=f"filters.CaptionRegex({self.pattern})", data_filter=True)
def filter(self, message: Message) -> Optional[Dict[str, List[Match[str]]]]:
if message.caption and (match := self.pattern.search(message.caption)):
return {"matches": [match]}
return {}
class _ChatUserBaseFilter(MessageFilter, ABC):
__slots__ = (
"_chat_id_name",
"_chat_ids",
"_username_name",
"_usernames",
"allow_empty",
)
def __init__(
self,
chat_id: Optional[SCT[int]] = None,
username: Optional[SCT[str]] = None,
allow_empty: bool = False,
):
super().__init__()
self._chat_id_name: str = "chat_id"
self._username_name: str = "username"
self.allow_empty: bool = allow_empty
self._chat_ids: Set[int] = set()
self._usernames: Set[str] = set()
self._set_chat_ids(chat_id)
self._set_usernames(username)
@abstractmethod
def _get_chat_or_user(self, message: Message) -> Union[TGChat, TGUser, None]: ...
@staticmethod
def _parse_chat_id(chat_id: Optional[SCT[int]]) -> Set[int]:
if chat_id is None:
return set()
if isinstance(chat_id, int):
return {chat_id}
return set(chat_id)
@staticmethod
def _parse_username(username: Optional[SCT[str]]) -> Set[str]:
if username is None:
return set()
if isinstance(username, str):
return {username[1:] if username.startswith("@") else username}
return {chat[1:] if chat.startswith("@") else chat for chat in username}
def _set_chat_ids(self, chat_id: Optional[SCT[int]]) -> None:
if chat_id and self._usernames:
raise RuntimeError(
f"Can't set {self._chat_id_name} in conjunction with (already set) "
f"{self._username_name}s."
)
self._chat_ids = self._parse_chat_id(chat_id)
def _set_usernames(self, username: Optional[SCT[str]]) -> None:
if username and self._chat_ids:
raise RuntimeError(
f"Can't set {self._username_name} in conjunction with (already set) "
f"{self._chat_id_name}s."
)
self._usernames = self._parse_username(username)
@property
def chat_ids(self) -> FrozenSet[int]:
return frozenset(self._chat_ids)
@chat_ids.setter
def chat_ids(self, chat_id: SCT[int]) -> None:
self._set_chat_ids(chat_id)
@property
def usernames(self) -> FrozenSet[str]:
"""Which username(s) to allow through.
Warning:
:attr:`usernames` will give a *copy* of the saved usernames as :obj:`frozenset`. This
is to ensure thread safety. To add/remove a user, you should use :meth:`add_usernames`,
and :meth:`remove_usernames`. Only update the entire set by
``filter.usernames = new_set``, if you are entirely sure that it is not causing race
conditions, as this will complete replace the current set of allowed users.
Returns:
frozenset(:obj:`str`)
"""
return frozenset(self._usernames)
@usernames.setter
def usernames(self, username: SCT[str]) -> None:
self._set_usernames(username)
def add_usernames(self, username: SCT[str]) -> None:
"""
Add one or more chats to the allowed usernames.
Args:
username(:obj:`str` | Collection[:obj:`str`]): Which username(s) to
allow through. Leading ``'@'`` s in usernames will be discarded.
"""
if self._chat_ids:
raise RuntimeError(
f"Can't set {self._username_name} in conjunction with (already set) "
f"{self._chat_id_name}s."
)
parsed_username = self._parse_username(username)
self._usernames |= parsed_username
def _add_chat_ids(self, chat_id: SCT[int]) -> None:
if self._usernames:
raise RuntimeError(
f"Can't set {self._chat_id_name} in conjunction with (already set) "
f"{self._username_name}s."
)
parsed_chat_id = self._parse_chat_id(chat_id)
self._chat_ids |= parsed_chat_id
def remove_usernames(self, username: SCT[str]) -> None:
"""
Remove one or more chats from allowed usernames.
Args:
username(:obj:`str` | Collection[:obj:`str`]): Which username(s) to
disallow through. Leading ``'@'`` s in usernames will be discarded.
"""
if self._chat_ids:
raise RuntimeError(
f"Can't set {self._username_name} in conjunction with (already set) "
f"{self._chat_id_name}s."
)
parsed_username = self._parse_username(username)
self._usernames -= parsed_username
def _remove_chat_ids(self, chat_id: SCT[int]) -> None:
if self._usernames:
raise RuntimeError(
f"Can't set {self._chat_id_name} in conjunction with (already set) "
f"{self._username_name}s."
)
parsed_chat_id = self._parse_chat_id(chat_id)
self._chat_ids -= parsed_chat_id
def filter(self, message: Message) -> bool:
chat_or_user = self._get_chat_or_user(message)
if chat_or_user:
if self.chat_ids:
return chat_or_user.id in self.chat_ids
if self.usernames:
return bool(chat_or_user.username and chat_or_user.username in self.usernames)
return self.allow_empty
return False
@property
def name(self) -> str:
return (
f"filters.{self.__class__.__name__}("
f"{', '.join(str(s) for s in (self.usernames or self.chat_ids))})"
)
@name.setter
def name(self, name: str) -> NoReturn:
raise RuntimeError(f"Cannot set name for filters.{self.__class__.__name__}")
class Chat(_ChatUserBaseFilter):
"""Filters messages to allow only those which are from a specified chat ID or username.
Examples:
``MessageHandler(filters.Chat(-1234), callback_method)``
Warning:
:attr:`chat_ids` will give a *copy* of the saved chat ids as :class:`frozenset`. This
is to ensure thread safety. To add/remove a chat, you should use :meth:`add_chat_ids`, and
:meth:`remove_chat_ids`. Only update the entire set by ``filter.chat_ids = new_set``,
if you are entirely sure that it is not causing race conditions, as this will complete
replace the current set of allowed chats.
Args:
chat_id(:obj:`int` | Collection[:obj:`int`], optional):
Which chat ID(s) to allow through.
username(:obj:`str` | Collection[:obj:`str`], optional):
Which username(s) to allow through.
Leading ``'@'`` s in usernames will be discarded.
allow_empty(:obj:`bool`, optional): Whether updates should be processed, if no chat
is specified in :attr:`chat_ids` and :attr:`usernames`. Defaults to :obj:`False`.
Attributes:
chat_ids (set(:obj:`int`)): Which chat ID(s) to allow through.
allow_empty (:obj:`bool`): Whether updates should be processed, if no chat
is specified in :attr:`chat_ids` and :attr:`usernames`.
Raises:
RuntimeError: If ``chat_id`` and ``username`` are both present.
"""
__slots__ = ()
def _get_chat_or_user(self, message: Message) -> Optional[TGChat]:
return message.chat
def add_chat_ids(self, chat_id: SCT[int]) -> None:
"""
Add one or more chats to the allowed chat ids.
Args:
chat_id(:obj:`int` | Collection[:obj:`int`]): Which chat ID(s) to allow
through.
"""
return super()._add_chat_ids(chat_id)
def remove_chat_ids(self, chat_id: SCT[int]) -> None:
"""
Remove one or more chats from allowed chat ids.
Args:
chat_id(:obj:`int` | Collection[:obj:`int`]): Which chat ID(s) to
disallow through.
"""
return super()._remove_chat_ids(chat_id)
class _Chat(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return bool(message.chat)
CHAT = _Chat(name="filters.CHAT")
"""This filter filters *any* message that has a :attr:`telegram.Message.chat`.
.. deprecated:: NEXT.VERSION
This filter has no effect since :attr:`telegram.Message.chat` is always present.
"""
class ChatType: # A convenience namespace for Chat types.
"""Subset for filtering the type of chat.
Examples:
Use these filters like: ``filters.ChatType.CHANNEL`` or
``filters.ChatType.SUPERGROUP`` etc.
Caution:
``filters.ChatType`` itself is *not* a filter, but just a convenience namespace.
"""
__slots__ = ()
class _Channel(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return message.chat.type == TGChat.CHANNEL
CHANNEL = _Channel(name="filters.ChatType.CHANNEL")
"""Updates from channel."""
class _Group(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return message.chat.type == TGChat.GROUP
GROUP = _Group(name="filters.ChatType.GROUP")
"""Updates from group."""
class _Groups(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return message.chat.type in [TGChat.GROUP, TGChat.SUPERGROUP]
GROUPS = _Groups(name="filters.ChatType.GROUPS")
"""Update from group *or* supergroup."""
class _Private(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return message.chat.type == TGChat.PRIVATE
PRIVATE = _Private(name="filters.ChatType.PRIVATE")
"""Update from private chats."""
class _SuperGroup(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return message.chat.type == TGChat.SUPERGROUP
SUPERGROUP = _SuperGroup(name="filters.ChatType.SUPERGROUP")
"""Updates from supergroup."""
class Command(MessageFilter):
"""
Messages with a :attr:`telegram.MessageEntity.BOT_COMMAND`. By default, only allows
messages `starting` with a bot command. Pass :obj:`False` to also allow messages that contain a
bot command `anywhere` in the text.
Examples:
``MessageHandler(filters.Command(False), command_anywhere_callback)``
.. seealso::
:attr:`telegram.ext.filters.COMMAND`.
Note:
:attr:`telegram.ext.filters.TEXT` also accepts messages containing a command.
Args:
only_start (:obj:`bool`, optional): Whether to only allow messages that `start` with a bot
command. Defaults to :obj:`True`.
"""
__slots__ = ("only_start",)
def __init__(self, only_start: bool = True):
self.only_start: bool = only_start
super().__init__(f"filters.Command({only_start})" if not only_start else "filters.COMMAND")
def filter(self, message: Message) -> bool:
if not message.entities:
return False
first = message.entities[0]
if self.only_start:
return bool(first.type == MessageEntity.BOT_COMMAND and first.offset == 0)
return bool(any(e.type == MessageEntity.BOT_COMMAND for e in message.entities))
COMMAND = Command()
"""Shortcut for :class:`telegram.ext.filters.Command()`.
Examples:
To allow messages starting with a command use
``MessageHandler(filters.COMMAND, command_at_start_callback)``.
"""
class _Contact(MessageFilter):
__slots__ = ()
def filter(self, message: Message) -> bool:
return bool(message.contact)
CONTACT = _Contact(name="filters.CONTACT")
"""Messages that contain :attr:`telegram.Message.contact`."""
class _Dice(MessageFilter):