-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.py
96 lines (67 loc) · 2.8 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
import operator
from functools import reduce
from telegram import Message
from telegram.ext.filters import BaseFilter, MessageFilter
import text
class HasNoValidPreviousMessages(MessageFilter):
MIN_PREVIOUS_MESSAGES_COUNT = 3
def filter(self, message: Message) -> bool:
if message.from_user is None:
return True
return self.has_no_valid_previous_messages(user_id=message.from_user.id, chat_id=message.chat_id)
@classmethod
def has_no_valid_previous_messages(cls, user_id: int, chat_id: int) -> bool:
from models import LogEntry
messages_count = LogEntry.select().where(
(LogEntry.user_id == user_id),
(LogEntry.chat_id == chat_id),
(LogEntry.action != 'delete'),
).count()
return messages_count < cls.MIN_PREVIOUS_MESSAGES_COUNT
class ChatMessageOnly(MessageFilter):
def filter(self, message: Message) -> bool:
return message.forward_from_message_id is None
class NotRootChatMessage(MessageFilter):
def filter(self, message: Message) -> bool:
if message.sender_chat is None:
return True
return message.sender_chat.id != message.chat.id
def with_default_filters(*filters: BaseFilter) -> BaseFilter:
"""Apply default filters to the given filter classes"""
default_filters = [
ChatMessageOnly(),
NotRootChatMessage(),
HasNoValidPreviousMessages(),
]
return reduce(operator.and_, [*default_filters, *filters]) # МАМА Я УМЕЮ ФУНКЦИОНАЛЬНО ПРОГРАММИРОВАТЬ
class IsMessageOnBehalfOfChat(MessageFilter):
def filter(self, message: Message) -> bool:
return message.sender_chat is not None and message.sender_chat.id != message.chat.id
class ContainsTelegramContact(MessageFilter):
def filter(self, message: Message) -> bool:
if message.text is None:
return False
return ' @' in message.text or message.text.startswith('@')
class ContainsLink(MessageFilter):
def filter(self, message: Message) -> bool:
if message.text is None:
return False
return any(entity.type in ('url', 'text_link') for entity in message.entities)
class ContainsThreeOrMoreEmojies(MessageFilter):
def filter(self, message: Message) -> bool:
return 'three_or_more_emojies' in text.Labels(message.text)()
class IsMedia(MessageFilter):
def filter(self, message: Message) -> bool:
if any([message.document, message.audio, message.voice, message.video_note]):
return True
if len(message.photo) > 0:
return True
return False
__all__ = [
'ChatMessageOnly',
'ContainsLink',
'ContainsTelegramContact',
'ContainsThreeOrMoreEmojies',
'IsMessageOnBehalfOfChat',
'with_default_filters',
]