-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
filters.py
2449 lines (1894 loc) · 89.5 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-2022
# 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/].
# pylint: disable=C0112, C0103, W0221
"""This module contains the Filters for use with the MessageHandler class."""
import re
import warnings
from abc import ABC, abstractmethod
from sys import version_info as py_ver
from threading import Lock
from typing import (
Dict,
FrozenSet,
List,
Match,
Optional,
Pattern,
Set,
Tuple,
Union,
cast,
NoReturn,
)
from telegram import Chat, Message, MessageEntity, Update, User
__all__ = [
'Filters',
'BaseFilter',
'MessageFilter',
'UpdateFilter',
'InvertedFilter',
'MergedFilter',
'XORFilter',
]
from telegram.utils.deprecate import TelegramDeprecationWarning, set_new_attribute_deprecated
from telegram.utils.types import SLT
DataDict = Dict[str, list]
class BaseFilter(ABC):
"""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 `and`, `or` and `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 :meth:`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.
Attributes:
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).
"""
if py_ver < (3, 7):
__slots__ = ('_name', '_data_filter')
else:
__slots__ = ('_name', '_data_filter', '__dict__') # type: ignore[assignment]
def __new__(cls, *args: object, **kwargs: object) -> 'BaseFilter': # pylint: disable=W0613
instance = super().__new__(cls)
instance._name = None
instance._data_filter = False
return instance
@abstractmethod
def __call__(self, update: Update) -> Optional[Union[bool, DataDict]]:
...
def __and__(self, other: 'BaseFilter') -> 'BaseFilter':
return MergedFilter(self, and_filter=other)
def __or__(self, other: 'BaseFilter') -> 'BaseFilter':
return MergedFilter(self, or_filter=other)
def __xor__(self, other: 'BaseFilter') -> 'BaseFilter':
return XORFilter(self, other)
def __invert__(self) -> 'BaseFilter':
return InvertedFilter(self)
def __setattr__(self, key: str, value: object) -> None:
# Allow setting custom attributes w/o warning for user defined custom filters.
# To differentiate between a custom and a PTB filter, we use this hacky but
# simple way of checking the module name where the class is defined from.
if (
issubclass(self.__class__, (UpdateFilter, MessageFilter))
and self.__class__.__module__ != __name__
): # __name__ is telegram.ext.filters
object.__setattr__(self, key, value)
return
set_new_attribute_deprecated(self, key, value)
@property
def data_filter(self) -> bool:
return self._data_filter
@data_filter.setter
def data_filter(self, value: bool) -> None:
self._data_filter = value
@property
def name(self) -> Optional[str]:
return self._name
@name.setter
def name(self, name: Optional[str]) -> None:
self._name = name # pylint: disable=E0237
def __repr__(self) -> str:
# We do this here instead of in a __init__ so filter don't have to call __init__ or super()
if self.name is None:
self.name = self.__class__.__name__
return self.name
class MessageFilter(BaseFilter):
"""Base class for all Message Filters. In contrast to :class:`UpdateFilter`, the object passed
to :meth:`filter` is ``update.effective_message``.
Please see :class:`telegram.ext.filters.BaseFilter` for details on how to create custom
filters.
Attributes:
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__ = ()
def __call__(self, update: Update) -> Optional[Union[bool, DataDict]]:
return self.filter(update.effective_message)
@abstractmethod
def filter(self, message: Message) -> Optional[Union[bool, DataDict]]:
"""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 ``update``, which allows to create filters like
:attr:`Filters.update.edited_message`.
Please see :class:`telegram.ext.filters.BaseFilter` for details on how to create custom
filters.
Attributes:
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__ = ()
def __call__(self, update: Update) -> Optional[Union[bool, DataDict]]:
return self.filter(update)
@abstractmethod
def filter(self, update: Update) -> Optional[Union[bool, DataDict]]:
"""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__ = ('f',)
def __init__(self, f: BaseFilter):
self.f = f
def filter(self, update: Update) -> bool:
return not bool(self.f(update))
@property
def name(self) -> str:
return f"<inverted {self.f}>"
@name.setter
def name(self, name: str) -> NoReturn:
raise RuntimeError('Cannot set name for InvertedFilter')
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__ = ('base_filter', 'and_filter', 'or_filter')
def __init__(
self, base_filter: BaseFilter, and_filter: BaseFilter = None, or_filter: BaseFilter = None
):
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]) -> DataDict:
base = base_output if isinstance(base_output, dict) else {}
comp = comp_output if isinstance(comp_output, dict) else {}
for k in comp.keys():
# 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
def filter(self, update: Update) -> Union[bool, DataDict]: # pylint: disable=R0911
base_output = self.base_filter(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 falsey
if base_output:
comp_output = self.and_filter(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 truthey
if base_output:
if self.data_filter:
return base_output
return True
comp_output = self.or_filter(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 MergedFilter')
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', 'xor_filter', 'merged_filter')
def __init__(self, base_filter: BaseFilter, xor_filter: BaseFilter):
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, DataDict]]:
return self.merged_filter(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 XORFilter')
class _DiceEmoji(MessageFilter):
__slots__ = ('emoji',)
def __init__(self, emoji: str = None, name: str = None):
self.name = f'Filters.dice.{name}' if name else 'Filters.dice'
self.emoji = emoji
class _DiceValues(MessageFilter):
__slots__ = ('values', 'emoji')
def __init__(
self,
values: SLT[int],
name: str,
emoji: str = None,
):
self.values = [values] if isinstance(values, int) else values
self.emoji = emoji
self.name = f'{name}({values})'
def filter(self, message: Message) -> bool:
if message.dice and message.dice.value in self.values:
if self.emoji:
return message.dice.emoji == self.emoji
return True
return False
def __call__( # type: ignore[override]
self, update: Union[Update, List[int], Tuple[int]]
) -> Union[bool, '_DiceValues']:
if isinstance(update, Update):
return self.filter(update.effective_message)
return self._DiceValues(update, self.name, emoji=self.emoji)
def filter(self, message: Message) -> bool:
if bool(message.dice):
if self.emoji:
return message.dice.emoji == self.emoji
return True
return False
class Filters:
"""Predefined filters for use as the ``filter`` argument of
:class:`telegram.ext.MessageHandler`.
Examples:
Use ``MessageHandler(Filters.video, callback_method)`` to filter all video
messages. Use ``MessageHandler(Filters.contact, callback_method)`` for all contacts. etc.
"""
__slots__ = ('__dict__',)
def __setattr__(self, key: str, value: object) -> None:
set_new_attribute_deprecated(self, key, value)
class _All(MessageFilter):
__slots__ = ()
name = 'Filters.all'
def filter(self, message: Message) -> bool:
return True
all = _All()
"""All Messages."""
class _Text(MessageFilter):
__slots__ = ()
name = 'Filters.text'
class _TextStrings(MessageFilter):
__slots__ = ('strings',)
def __init__(self, strings: Union[List[str], Tuple[str]]):
self.strings = strings
self.name = f'Filters.text({strings})'
def filter(self, message: Message) -> bool:
if message.text:
return message.text in self.strings
return False
def __call__( # type: ignore[override]
self, update: Union[Update, List[str], Tuple[str]]
) -> Union[bool, '_TextStrings']:
if isinstance(update, Update):
return self.filter(update.effective_message)
return self._TextStrings(update)
def filter(self, message: Message) -> bool:
return bool(message.text)
text = _Text()
"""Text Messages. If a list of strings is passed, it filters messages to only allow those
whose text is appearing in the given list.
Examples:
To allow any text message, simply use
``MessageHandler(Filters.text, callback_method)``.
A simple use case for passing a list is to allow only messages that were sent by a
custom :class:`telegram.ReplyKeyboardMarkup`::
buttons = ['Start', 'Settings', 'Back']
markup = ReplyKeyboardMarkup.from_column(buttons)
...
MessageHandler(Filters.text(buttons), callback_method)
Note:
* Dice messages don't have text. If you want to filter either text or dice messages, use
``Filters.text | Filters.dice``.
* Messages containing a command are accepted by this filter. Use
``Filters.text & (~Filters.command)``, if you want to filter only text messages without
commands.
Args:
update (List[:obj:`str`] | Tuple[:obj:`str`], optional): Which messages to allow. Only
exact matches are allowed. If not specified, will allow any text message.
"""
class _Caption(MessageFilter):
__slots__ = ()
name = 'Filters.caption'
class _CaptionStrings(MessageFilter):
__slots__ = ('strings',)
def __init__(self, strings: Union[List[str], Tuple[str]]):
self.strings = strings
self.name = f'Filters.caption({strings})'
def filter(self, message: Message) -> bool:
if message.caption:
return message.caption in self.strings
return False
def __call__( # type: ignore[override]
self, update: Union[Update, List[str], Tuple[str]]
) -> Union[bool, '_CaptionStrings']:
if isinstance(update, Update):
return self.filter(update.effective_message)
return self._CaptionStrings(update)
def filter(self, message: Message) -> bool:
return bool(message.caption)
caption = _Caption()
"""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, callback_method)``
Args:
update (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.
"""
class _Command(MessageFilter):
__slots__ = ()
name = 'Filters.command'
class _CommandOnlyStart(MessageFilter):
__slots__ = ('only_start',)
def __init__(self, only_start: bool):
self.only_start = only_start
self.name = f'Filters.command({only_start})'
def filter(self, message: Message) -> bool:
return bool(
message.entities
and any(e.type == MessageEntity.BOT_COMMAND for e in message.entities)
)
def __call__( # type: ignore[override]
self, update: Union[bool, Update]
) -> Union[bool, '_CommandOnlyStart']:
if isinstance(update, Update):
return self.filter(update.effective_message)
return self._CommandOnlyStart(update)
def filter(self, message: Message) -> bool:
return bool(
message.entities
and message.entities[0].type == MessageEntity.BOT_COMMAND
and message.entities[0].offset == 0
)
command = _Command()
"""
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, command_at_start_callback)
MessageHandler(Filters.command(False), command_anywhere_callback)
Note:
``Filters.text`` also accepts messages containing a command.
Args:
update (:obj:`bool`, optional): Whether to only allow messages that `start` with a bot
command. Defaults to :obj:`True`.
"""
class regex(MessageFilter):
"""
Filters updates by searching for an occurrence of ``pattern`` in the message text.
The ``re.search()`` function is used to determine whether an update should be filtered.
Refer to the documentation of the ``re`` module for more information.
To get the groups and groupdict matched, see :attr:`telegram.ext.CallbackContext.matches`.
Examples:
Use ``MessageHandler(Filters.regex(r'help'), callback)`` to capture all messages that
contain the word 'help'. You can also use
``MessageHandler(Filters.regex(re.compile(r'help', re.IGNORECASE)), callback)`` if
you want your pattern to be case insensitive. This approach is recommended
if you need to specify flags on your pattern.
Note:
Filters use the same short circuiting logic as python's `and`, `or` and `not`.
This means that for example:
>>> Filters.regex(r'(a?x)') | Filters.regex(r'(b?x)')
With a message.text of `x`, will only ever return the matches for the first filter,
since the second one is never evaluated.
Args:
pattern (:obj:`str` | :obj:`Pattern`): The regex pattern.
"""
__slots__ = ('pattern',)
data_filter = True
def __init__(self, pattern: Union[str, Pattern]):
if isinstance(pattern, str):
pattern = re.compile(pattern)
pattern = cast(Pattern, pattern)
self.pattern: Pattern = pattern
self.name = f'Filters.regex({self.pattern})'
def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]:
"""""" # remove method from docs
if message.text:
match = self.pattern.search(message.text)
if match:
return {'matches': [match]}
return {}
class caption_regex(MessageFilter):
"""
Filters updates by searching for an occurrence of ``pattern`` in the message caption.
This filter works similarly to :class:`Filters.regex`, with the only exception being that
it applies to the message caption instead of the text.
Examples:
Use ``MessageHandler(Filters.photo & Filters.caption_regex(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` | :obj:`Pattern`): The regex pattern.
"""
__slots__ = ('pattern',)
data_filter = True
def __init__(self, pattern: Union[str, Pattern]):
if isinstance(pattern, str):
pattern = re.compile(pattern)
pattern = cast(Pattern, pattern)
self.pattern: Pattern = pattern
self.name = f'Filters.caption_regex({self.pattern})'
def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]:
"""""" # remove method from docs
if message.caption:
match = self.pattern.search(message.caption)
if match:
return {'matches': [match]}
return {}
class _Reply(MessageFilter):
__slots__ = ()
name = 'Filters.reply'
def filter(self, message: Message) -> bool:
return bool(message.reply_to_message)
reply = _Reply()
"""Messages that are a reply to another message."""
class _Audio(MessageFilter):
__slots__ = ()
name = 'Filters.audio'
def filter(self, message: Message) -> bool:
return bool(message.audio)
audio = _Audio()
"""Messages that contain :class:`telegram.Audio`."""
class _Document(MessageFilter):
__slots__ = ()
name = 'Filters.document'
class category(MessageFilter):
"""Filters documents by their category in the mime-type attribute.
Note:
This Filter only filters by the mime_type of the document,
it doesn't check the validity of the document.
The user can manipulate the mime-type of a message and
send media with wrong types that don't fit to this handler.
Example:
Filters.document.category('audio/') returns :obj:`True` for all types
of audio sent as file, for example 'audio/mpeg' or 'audio/x-wav'.
"""
__slots__ = ('_category',)
def __init__(self, category: Optional[str]):
"""Initialize the category you want to filter
Args:
category (str, optional): category of the media you want to filter
"""
self._category = category
self.name = f"Filters.document.category('{self._category}')"
def filter(self, message: Message) -> bool:
"""""" # remove method from docs
if message.document:
return message.document.mime_type.startswith(self._category)
return False
application = category('application/')
audio = category('audio/')
image = category('image/')
video = category('video/')
text = category('text/')
class mime_type(MessageFilter):
"""This Filter filters documents by their mime-type attribute
Note:
This Filter only filters by the mime_type of the document,
it doesn't check the validity of document.
The user can manipulate the mime-type of a message and
send media with wrong types that don't fit to this handler.
Example:
``Filters.document.mime_type('audio/mpeg')`` filters all audio in mp3 format.
"""
__slots__ = ('mimetype',)
def __init__(self, mimetype: Optional[str]):
self.mimetype = mimetype
self.name = f"Filters.document.mime_type('{self.mimetype}')"
def filter(self, message: Message) -> bool:
"""""" # remove method from docs
if message.document:
return message.document.mime_type == self.mimetype
return False
apk = mime_type('application/vnd.android.package-archive')
doc = mime_type('application/msword')
docx = mime_type('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
exe = mime_type('application/x-ms-dos-executable')
gif = mime_type('video/mp4')
jpg = mime_type('image/jpeg')
mp3 = mime_type('audio/mpeg')
pdf = mime_type('application/pdf')
py = mime_type('text/x-python')
svg = mime_type('image/svg+xml')
txt = mime_type('text/plain')
targz = mime_type('application/x-compressed-tar')
wav = mime_type('audio/x-wav')
xml = mime_type('application/xml')
zip = mime_type('application/zip')
class file_extension(MessageFilter):
"""This filter filters documents by their file ending/extension.
Note:
* This Filter only filters by the file ending/extension of the document,
it doesn't check the validity of document.
* The user can manipulate the file extension of a document and
send media with wrong types that don't fit to this handler.
* Case insensitive by default,
you may change this with the flag ``case_sensitive=True``.
* Extension should be passed without leading dot
unless it's a part of the extension.
* Pass :obj:`None` to filter files with no extension,
i.e. without a dot in the filename.
Example:
* ``Filters.document.file_extension("jpg")``
filters files with extension ``".jpg"``.
* ``Filters.document.file_extension(".jpg")``
filters files with extension ``"..jpg"``.
* ``Filters.document.file_extension("Dockerfile", case_sensitive=True)``
filters files with extension ``".Dockerfile"`` minding the case.
* ``Filters.document.file_extension(None)``
filters files without a dot in the filename.
"""
__slots__ = ('_file_extension', 'is_case_sensitive')
def __init__(self, file_extension: Optional[str], case_sensitive: bool = False):
"""Initialize the extension you want to filter.
Args:
file_extension (:obj:`str` | :obj:`None`):
media file extension you want to filter.
case_sensitive (:obj:bool, optional):
pass :obj:`True` to make the filter case sensitive.
Default: :obj:`False`.
"""
self.is_case_sensitive = case_sensitive
if file_extension is None:
self._file_extension = None
self.name = "Filters.document.file_extension(None)"
elif self.is_case_sensitive:
self._file_extension = f".{file_extension}"
self.name = (
f"Filters.document.file_extension({file_extension!r},"
" case_sensitive=True)"
)
else:
self._file_extension = f".{file_extension}".lower()
self.name = f"Filters.document.file_extension({file_extension.lower()!r})"
def filter(self, message: Message) -> bool:
"""""" # remove method from docs
if message.document is None:
return False
if self._file_extension is None:
return "." not in message.document.file_name
if self.is_case_sensitive:
filename = message.document.file_name
else:
filename = message.document.file_name.lower()
return filename.endswith(self._file_extension)
def filter(self, message: Message) -> bool:
return bool(message.document)
document = _Document()
"""
Subset for messages containing a document/file.
Examples:
Use these filters like: ``Filters.document.mp3``,
``Filters.document.mime_type("text/plain")`` etc. Or use just
``Filters.document`` for all document messages.
Attributes:
category: Filters documents by their category in the mime-type attribute
Note:
This Filter only filters by the mime_type of the document,
it doesn't check the validity of the document.
The user can manipulate the mime-type of a message and
send media with wrong types that don't fit to this handler.
Example:
``Filters.document.category('audio/')`` filters all types
of audio sent as file, for example 'audio/mpeg' or 'audio/x-wav'.
application: Same as ``Filters.document.category("application")``.
audio: Same as ``Filters.document.category("audio")``.
image: Same as ``Filters.document.category("image")``.
video: Same as ``Filters.document.category("video")``.
text: Same as ``Filters.document.category("text")``.
mime_type: Filters documents by their mime-type attribute
Note:
This Filter only filters by the mime_type of the document,
it doesn't check the validity of document.
The user can manipulate the mime-type of a message and
send media with wrong types that don't fit to this handler.
Example:
``Filters.document.mime_type('audio/mpeg')`` filters all audio in mp3 format.
apk: Same as ``Filters.document.mime_type("application/vnd.android.package-archive")``.
doc: Same as ``Filters.document.mime_type("application/msword")``.
docx: Same as ``Filters.document.mime_type("application/vnd.openxmlformats-\
officedocument.wordprocessingml.document")``.
exe: Same as ``Filters.document.mime_type("application/x-ms-dos-executable")``.
gif: Same as ``Filters.document.mime_type("video/mp4")``.
jpg: Same as ``Filters.document.mime_type("image/jpeg")``.
mp3: Same as ``Filters.document.mime_type("audio/mpeg")``.
pdf: Same as ``Filters.document.mime_type("application/pdf")``.
py: Same as ``Filters.document.mime_type("text/x-python")``.
svg: Same as ``Filters.document.mime_type("image/svg+xml")``.
txt: Same as ``Filters.document.mime_type("text/plain")``.
targz: Same as ``Filters.document.mime_type("application/x-compressed-tar")``.
wav: Same as ``Filters.document.mime_type("audio/x-wav")``.
xml: Same as ``Filters.document.mime_type("application/xml")``.
zip: Same as ``Filters.document.mime_type("application/zip")``.
file_extension: This filter filters documents by their file ending/extension.
Note:
* This Filter only filters by the file ending/extension of the document,
it doesn't check the validity of document.
* The user can manipulate the file extension of a document and
send media with wrong types that don't fit to this handler.
* Case insensitive by default,
you may change this with the flag ``case_sensitive=True``.
* Extension should be passed without leading dot
unless it's a part of the extension.
* Pass :obj:`None` to filter files with no extension,
i.e. without a dot in the filename.
Example:
* ``Filters.document.file_extension("jpg")``
filters files with extension ``".jpg"``.
* ``Filters.document.file_extension(".jpg")``
filters files with extension ``"..jpg"``.
* ``Filters.document.file_extension("Dockerfile", case_sensitive=True)``
filters files with extension ``".Dockerfile"`` minding the case.
* ``Filters.document.file_extension(None)``
filters files without a dot in the filename.
"""
class _Animation(MessageFilter):
__slots__ = ()
name = 'Filters.animation'
def filter(self, message: Message) -> bool:
return bool(message.animation)
animation = _Animation()
"""Messages that contain :class:`telegram.Animation`."""
class _Photo(MessageFilter):
__slots__ = ()
name = 'Filters.photo'
def filter(self, message: Message) -> bool:
return bool(message.photo)
photo = _Photo()
"""Messages that contain :class:`telegram.PhotoSize`."""
class _Sticker(MessageFilter):
__slots__ = ()
name = 'Filters.sticker'
def filter(self, message: Message) -> bool:
return bool(message.sticker)
sticker = _Sticker()
"""Messages that contain :class:`telegram.Sticker`."""
class _Video(MessageFilter):
__slots__ = ()
name = 'Filters.video'
def filter(self, message: Message) -> bool:
return bool(message.video)
video = _Video()
"""Messages that contain :class:`telegram.Video`."""
class _Voice(MessageFilter):
__slots__ = ()
name = 'Filters.voice'
def filter(self, message: Message) -> bool:
return bool(message.voice)
voice = _Voice()
"""Messages that contain :class:`telegram.Voice`."""
class _VideoNote(MessageFilter):
__slots__ = ()
name = 'Filters.video_note'
def filter(self, message: Message) -> bool:
return bool(message.video_note)
video_note = _VideoNote()
"""Messages that contain :class:`telegram.VideoNote`."""
class _Contact(MessageFilter):
__slots__ = ()
name = 'Filters.contact'
def filter(self, message: Message) -> bool:
return bool(message.contact)
contact = _Contact()
"""Messages that contain :class:`telegram.Contact`."""
class _Location(MessageFilter):
__slots__ = ()
name = 'Filters.location'