mbtk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mbtk/__init__.py +39 -0
- mbtk/bot.py +38 -0
- mbtk/clock.py +15 -0
- mbtk/di.py +28 -0
- mbtk/dispatcher.py +168 -0
- mbtk/errors.py +35 -0
- mbtk/events.py +82 -0
- mbtk/filters.py +210 -0
- mbtk/fsm.py +160 -0
- mbtk/max/__init__.py +21 -0
- mbtk/max/client.py +266 -0
- mbtk/max/keyboards.py +34 -0
- mbtk/max/updates.py +149 -0
- mbtk/middleware.py +6 -0
- mbtk/py.typed +0 -0
- mbtk/router.py +79 -0
- mbtk/storage/__init__.py +1 -0
- mbtk/storage/redis.py +139 -0
- mbtk-0.1.0.dist-info/METADATA +190 -0
- mbtk-0.1.0.dist-info/RECORD +22 -0
- mbtk-0.1.0.dist-info/WHEEL +4 -0
- mbtk-0.1.0.dist-info/licenses/LICENSE +21 -0
mbtk/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""A small async toolkit for MAX messenger bots.
|
|
2
|
+
|
|
3
|
+
The design follows aiogram 3: typed events, routers, composable filters,
|
|
4
|
+
middleware, dependency injection, and finite state machines. The core has
|
|
5
|
+
no runtime dependencies. Optional extras::
|
|
6
|
+
|
|
7
|
+
pip install mbtk[max] # HTTP client for the MAX Bot API
|
|
8
|
+
pip install mbtk[redis] # Redis-backed FSM storage
|
|
9
|
+
pip install mbtk[all]
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .di import inject
|
|
13
|
+
from .dispatcher import Dispatcher
|
|
14
|
+
from .errors import PermanentError, RemoteServiceError, SkipHandler
|
|
15
|
+
from .events import BotStarted, Callback, Event, Message
|
|
16
|
+
from .fsm import FSMContext, MemoryStorage, State, StatesGroup
|
|
17
|
+
from .max.updates import event_id_for, parse_update
|
|
18
|
+
from .middleware import BaseMiddleware
|
|
19
|
+
from .router import Router
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"BaseMiddleware",
|
|
23
|
+
"BotStarted",
|
|
24
|
+
"Callback",
|
|
25
|
+
"Dispatcher",
|
|
26
|
+
"Event",
|
|
27
|
+
"FSMContext",
|
|
28
|
+
"MemoryStorage",
|
|
29
|
+
"Message",
|
|
30
|
+
"PermanentError",
|
|
31
|
+
"RemoteServiceError",
|
|
32
|
+
"Router",
|
|
33
|
+
"SkipHandler",
|
|
34
|
+
"State",
|
|
35
|
+
"StatesGroup",
|
|
36
|
+
"event_id_for",
|
|
37
|
+
"inject",
|
|
38
|
+
"parse_update",
|
|
39
|
+
]
|
mbtk/bot.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The MAX client protocol seen by events and handlers.
|
|
2
|
+
|
|
3
|
+
Method names match :class:`mbtk.max.client.MaxApiClient` and test fakes,
|
|
4
|
+
so any object with the same methods can be used as a bot.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Protocol
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Bot(Protocol):
|
|
11
|
+
"""Minimal interface the dispatcher needs from a MAX client."""
|
|
12
|
+
|
|
13
|
+
async def send_message(
|
|
14
|
+
self,
|
|
15
|
+
chat_id: str,
|
|
16
|
+
text: str,
|
|
17
|
+
attachments: Any = None,
|
|
18
|
+
) -> dict: ...
|
|
19
|
+
|
|
20
|
+
async def edit_message(
|
|
21
|
+
self,
|
|
22
|
+
message_id: str,
|
|
23
|
+
chat_id: str,
|
|
24
|
+
text: str,
|
|
25
|
+
attachments: Any = None,
|
|
26
|
+
) -> dict: ...
|
|
27
|
+
|
|
28
|
+
async def answer_callback(
|
|
29
|
+
self,
|
|
30
|
+
callback_id: str,
|
|
31
|
+
text: str | None = None,
|
|
32
|
+
alert: bool = False,
|
|
33
|
+
message: dict | None = None,
|
|
34
|
+
) -> dict: ...
|
|
35
|
+
|
|
36
|
+
async def get_message(self, message_id: str) -> dict: ...
|
|
37
|
+
|
|
38
|
+
async def download_image(self, url: str) -> bytes: ...
|
mbtk/clock.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Clock abstraction for TTL caches and tests without real delays."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Protocol
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Clock(Protocol):
|
|
8
|
+
def now(self) -> float: ...
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SystemClock:
|
|
12
|
+
"""Monotonic clock used by runtime caches."""
|
|
13
|
+
|
|
14
|
+
def now(self) -> float:
|
|
15
|
+
return time.monotonic()
|
mbtk/di.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Dependency injection into handlers by argument name."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def inject(callback, data, skip=0):
|
|
7
|
+
"""Pass a handler only the arguments it declares.
|
|
8
|
+
|
|
9
|
+
``skip`` is the number of leading positional arguments the dispatcher
|
|
10
|
+
passes itself (the event or the error).
|
|
11
|
+
"""
|
|
12
|
+
try:
|
|
13
|
+
parameters = list(inspect.signature(callback).parameters.values())
|
|
14
|
+
except (TypeError, ValueError):
|
|
15
|
+
return {}
|
|
16
|
+
|
|
17
|
+
result = {}
|
|
18
|
+
for index, parameter in enumerate(parameters):
|
|
19
|
+
if index < skip:
|
|
20
|
+
continue
|
|
21
|
+
if parameter.kind not in (
|
|
22
|
+
parameter.POSITIONAL_OR_KEYWORD,
|
|
23
|
+
parameter.KEYWORD_ONLY,
|
|
24
|
+
):
|
|
25
|
+
continue
|
|
26
|
+
if parameter.name in data:
|
|
27
|
+
result[parameter.name] = data[parameter.name]
|
|
28
|
+
return result
|
mbtk/dispatcher.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Dispatcher: accepts an update and routes it through routers."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from .di import inject
|
|
6
|
+
from .errors import PermanentError, SkipHandler
|
|
7
|
+
from .events import BotStarted, Callback, Message
|
|
8
|
+
from .fsm import FSMContext
|
|
9
|
+
from .max.updates import parse_update
|
|
10
|
+
from .router import Router
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
EVENT_OBSERVERS = {
|
|
15
|
+
Message: "message",
|
|
16
|
+
Callback: "callback_query",
|
|
17
|
+
BotStarted: "bot_started",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Dispatcher(Router):
|
|
22
|
+
"""Root router and the ``feed_update`` entry point.
|
|
23
|
+
|
|
24
|
+
A handler is always awaited, so a queue can acknowledge the event only
|
|
25
|
+
after the handler succeeds.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, bot=None, storage=None, context=None):
|
|
29
|
+
super().__init__("dispatcher")
|
|
30
|
+
self.bot = bot
|
|
31
|
+
self.storage = storage
|
|
32
|
+
self.context = dict(context or {})
|
|
33
|
+
self.outer_middlewares = []
|
|
34
|
+
|
|
35
|
+
def outer(self, middleware):
|
|
36
|
+
self.outer_middlewares.append(middleware)
|
|
37
|
+
return middleware
|
|
38
|
+
|
|
39
|
+
async def feed_update(self, update):
|
|
40
|
+
event = parse_update(update, bot=self.bot)
|
|
41
|
+
if event is None:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
data = dict(self.context)
|
|
45
|
+
data.update(
|
|
46
|
+
event=event,
|
|
47
|
+
bot=self.bot,
|
|
48
|
+
dispatcher=self,
|
|
49
|
+
storage=self.storage,
|
|
50
|
+
)
|
|
51
|
+
data["state"] = FSMContext(self.storage, (event.chat_id, event.user_id))
|
|
52
|
+
observer_name = EVENT_OBSERVERS[type(event)]
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
handled = await self._run_outer(
|
|
56
|
+
event,
|
|
57
|
+
data,
|
|
58
|
+
lambda: self._propagate(self, event, data, observer_name, []),
|
|
59
|
+
)
|
|
60
|
+
except PermanentError as error:
|
|
61
|
+
data["error_handled"] = True
|
|
62
|
+
await self._notify(event, error.text, alert=error.alert)
|
|
63
|
+
handled = True
|
|
64
|
+
except Exception as error:
|
|
65
|
+
if not await self._propagate_error(event, error, data):
|
|
66
|
+
raise
|
|
67
|
+
data["error_handled"] = True
|
|
68
|
+
handled = True
|
|
69
|
+
|
|
70
|
+
if (
|
|
71
|
+
isinstance(event, Callback)
|
|
72
|
+
and not event.answered
|
|
73
|
+
and not data.get("error_handled")
|
|
74
|
+
):
|
|
75
|
+
await self._answer(event)
|
|
76
|
+
return handled
|
|
77
|
+
|
|
78
|
+
async def _run_outer(self, event, data, final):
|
|
79
|
+
async def step(index):
|
|
80
|
+
if index >= len(self.outer_middlewares):
|
|
81
|
+
return await final()
|
|
82
|
+
middleware = self.outer_middlewares[index]
|
|
83
|
+
return await middleware(event, data, lambda: step(index + 1))
|
|
84
|
+
|
|
85
|
+
return await step(0)
|
|
86
|
+
|
|
87
|
+
async def _propagate(self, router, event, data, name, chain):
|
|
88
|
+
observer = router.observer(name)
|
|
89
|
+
local = list(chain)
|
|
90
|
+
local.extend(router.middlewares)
|
|
91
|
+
local.extend(observer.middlewares)
|
|
92
|
+
|
|
93
|
+
for handler in observer.handlers:
|
|
94
|
+
if not await handler.matches(event, data):
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
await self._call_handler(handler, local, event, data)
|
|
98
|
+
return True
|
|
99
|
+
except SkipHandler:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
for child in router.routers:
|
|
103
|
+
if await self._propagate(child, event, data, name, local):
|
|
104
|
+
return True
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
async def _call_handler(self, handler, middlewares, event, data):
|
|
108
|
+
async def final():
|
|
109
|
+
kwargs = inject(handler.callback, data, skip=1)
|
|
110
|
+
return await handler.callback(event, **kwargs)
|
|
111
|
+
|
|
112
|
+
async def step(index):
|
|
113
|
+
if index >= len(middlewares):
|
|
114
|
+
return await final()
|
|
115
|
+
middleware = middlewares[index]
|
|
116
|
+
return await middleware(event, data, lambda: step(index + 1))
|
|
117
|
+
|
|
118
|
+
return await step(0)
|
|
119
|
+
|
|
120
|
+
async def _propagate_error(self, event, error, data):
|
|
121
|
+
return await self._walk_error(self, event, error, data)
|
|
122
|
+
|
|
123
|
+
async def _walk_error(self, router, event, error, data):
|
|
124
|
+
for handler in router.error.handlers:
|
|
125
|
+
try:
|
|
126
|
+
await handler.callback(
|
|
127
|
+
event,
|
|
128
|
+
error,
|
|
129
|
+
**inject(handler.callback, data, skip=2),
|
|
130
|
+
)
|
|
131
|
+
return True
|
|
132
|
+
except SkipHandler:
|
|
133
|
+
continue
|
|
134
|
+
for child in router.routers:
|
|
135
|
+
if await self._walk_error(child, event, error, data):
|
|
136
|
+
return True
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
async def _notify(self, event, text, alert=False):
|
|
140
|
+
if not text:
|
|
141
|
+
return
|
|
142
|
+
if isinstance(event, Callback):
|
|
143
|
+
await self._answer(event, text, alert)
|
|
144
|
+
return
|
|
145
|
+
if self.bot is None:
|
|
146
|
+
return
|
|
147
|
+
await self.bot.send_message(event.chat_id, text)
|
|
148
|
+
|
|
149
|
+
async def _answer(self, event, text=None, alert=False):
|
|
150
|
+
"""Close the button spinner without breaking the handler.
|
|
151
|
+
|
|
152
|
+
The handler has already sent its messages, and a queue
|
|
153
|
+
acknowledges the event only after success. Raising here would leave
|
|
154
|
+
the event in the queue, and a retry would send the same screens
|
|
155
|
+
again, looping the bot.
|
|
156
|
+
"""
|
|
157
|
+
try:
|
|
158
|
+
await event.answer(text, alert=alert)
|
|
159
|
+
except Exception as error:
|
|
160
|
+
# Status and code are enough for debugging: 400 with
|
|
161
|
+
# ``proto.payload`` means a bad request body, 403 means the bot
|
|
162
|
+
# lost access to the chat. Never log the response body or chat ID.
|
|
163
|
+
logger.warning(
|
|
164
|
+
"MAX callback answer failed (%s status=%s code=%s)",
|
|
165
|
+
type(error).__name__,
|
|
166
|
+
getattr(error, "status", None) or "unknown",
|
|
167
|
+
getattr(error, "code", None) or "unknown",
|
|
168
|
+
)
|
mbtk/errors.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Exceptions raised by the toolkit."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class FrameworkError(Exception):
|
|
5
|
+
"""Base error for the toolkit."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SkipHandler(FrameworkError):
|
|
9
|
+
"""The handler does not apply: pass the event to the next one."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PermanentError(FrameworkError):
|
|
13
|
+
"""An error the user must see; retrying is pointless."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, text, alert=False):
|
|
16
|
+
super().__init__(text)
|
|
17
|
+
self.text = text
|
|
18
|
+
self.alert = alert
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RemoteServiceError(Exception):
|
|
22
|
+
"""A remote API failure with a status and a safe user-facing text."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self, message, status=None, service=None, code=None, text=None
|
|
26
|
+
):
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.status = status
|
|
29
|
+
self.service = service
|
|
30
|
+
# Short API error code (``proto.payload`` for MAX), useful for log
|
|
31
|
+
# analysis. The response body itself is never stored.
|
|
32
|
+
self.code = code
|
|
33
|
+
# Human-readable business error text from the remote service. It is
|
|
34
|
+
# safe to show to the user; the rest of the response is not.
|
|
35
|
+
self.text = text
|
mbtk/events.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Typed MAX events."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
from .bot import Bot
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Event:
|
|
10
|
+
"""Common fields of any dialogue event."""
|
|
11
|
+
|
|
12
|
+
event_id: str
|
|
13
|
+
chat_id: str
|
|
14
|
+
user_id: str
|
|
15
|
+
chat_type: str
|
|
16
|
+
raw: dict = field(repr=False)
|
|
17
|
+
bot: Bot | None = field(default=None, repr=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Message(Event):
|
|
22
|
+
"""An incoming message."""
|
|
23
|
+
|
|
24
|
+
text: str = ""
|
|
25
|
+
message_id: str = ""
|
|
26
|
+
body: dict = field(default_factory=dict, repr=False)
|
|
27
|
+
message: dict = field(default_factory=dict, repr=False)
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def attachments(self) -> list:
|
|
31
|
+
value = self.body.get("attachments")
|
|
32
|
+
return value if isinstance(value, list) else []
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def command(self) -> str:
|
|
36
|
+
"""First command token without ``@bot``, lowercased."""
|
|
37
|
+
if not self.text:
|
|
38
|
+
return ""
|
|
39
|
+
token = self.text.split(maxsplit=1)[0]
|
|
40
|
+
return token.split("@", 1)[0].lower()
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def arguments(self) -> str:
|
|
44
|
+
"""Everything after the command token, case preserved."""
|
|
45
|
+
parts = self.text.split(maxsplit=1)
|
|
46
|
+
return parts[1].strip() if len(parts) > 1 else ""
|
|
47
|
+
|
|
48
|
+
async def answer(self, text, attachments=None):
|
|
49
|
+
if self.bot is None:
|
|
50
|
+
raise RuntimeError("The event has no attached bot")
|
|
51
|
+
return await self.bot.send_message(self.chat_id, text, attachments)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Callback(Event):
|
|
56
|
+
"""An inline button press."""
|
|
57
|
+
|
|
58
|
+
callback_id: str = ""
|
|
59
|
+
payload: dict = field(default_factory=dict)
|
|
60
|
+
message_id: str = ""
|
|
61
|
+
answered: bool = field(default=False, repr=False)
|
|
62
|
+
|
|
63
|
+
async def answer(self, text=None, alert=False, message=None):
|
|
64
|
+
if self.bot is None or not self.callback_id:
|
|
65
|
+
return None
|
|
66
|
+
result = await self.bot.answer_callback(
|
|
67
|
+
self.callback_id, text, alert, message
|
|
68
|
+
)
|
|
69
|
+
self.answered = True
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class BotStarted(Event):
|
|
75
|
+
"""The user pressed Start in the bot dialogue."""
|
|
76
|
+
|
|
77
|
+
user: dict = field(default_factory=dict, repr=False)
|
|
78
|
+
|
|
79
|
+
async def answer(self, text, attachments=None):
|
|
80
|
+
if self.bot is None:
|
|
81
|
+
raise RuntimeError("The event has no attached bot")
|
|
82
|
+
return await self.bot.send_message(self.chat_id, text, attachments)
|
mbtk/filters.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Event filters that compose into trees with ``&`` and ``|``."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from .events import BotStarted, Callback, Message
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Filter:
|
|
10
|
+
"""Base filter. Returns True when the event matches."""
|
|
11
|
+
|
|
12
|
+
def __call__(self, event, data):
|
|
13
|
+
raise NotImplementedError
|
|
14
|
+
|
|
15
|
+
def __and__(self, other):
|
|
16
|
+
return AllOf(self, other)
|
|
17
|
+
|
|
18
|
+
def __or__(self, other):
|
|
19
|
+
return AnyOf(self, other)
|
|
20
|
+
|
|
21
|
+
def __invert__(self):
|
|
22
|
+
return Not(self)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FuncFilter(Filter):
|
|
26
|
+
def __init__(self, func):
|
|
27
|
+
self.func = func
|
|
28
|
+
|
|
29
|
+
def __call__(self, event, data):
|
|
30
|
+
return self.func(event, data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AllOf(Filter):
|
|
34
|
+
def __init__(self, *filters):
|
|
35
|
+
self.filters = normalize_all(filters)
|
|
36
|
+
|
|
37
|
+
def __call__(self, event, data):
|
|
38
|
+
return all(item(event, data) for item in self.filters)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AnyOf(Filter):
|
|
42
|
+
def __init__(self, *filters):
|
|
43
|
+
self.filters = normalize_all(filters)
|
|
44
|
+
|
|
45
|
+
def __call__(self, event, data):
|
|
46
|
+
return any(item(event, data) for item in self.filters)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Not(Filter):
|
|
50
|
+
def __init__(self, filter_):
|
|
51
|
+
self.filter = normalize(filter_)
|
|
52
|
+
|
|
53
|
+
def __call__(self, event, data):
|
|
54
|
+
return not self.filter(event, data)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Command(Filter):
|
|
58
|
+
"""A message command: ``/link``, ``/menu``, or ``/start@bot``."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, *names, ignore_case=True):
|
|
61
|
+
self.ignore_case = ignore_case
|
|
62
|
+
self.names = {
|
|
63
|
+
self._normalize(name) for name in names if str(name).strip()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
def _normalize(self, name):
|
|
67
|
+
value = "/" + str(name).strip().lstrip("/")
|
|
68
|
+
return value.lower() if self.ignore_case else value
|
|
69
|
+
|
|
70
|
+
def __call__(self, event, data):
|
|
71
|
+
if not isinstance(event, Message) or not event.command:
|
|
72
|
+
return False
|
|
73
|
+
command = event.command.lower() if self.ignore_case else event.command
|
|
74
|
+
return command in self.names
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class CommandStart(Filter):
|
|
78
|
+
"""``/start``, the equivalent of aiogram's ``CommandStart``."""
|
|
79
|
+
|
|
80
|
+
def __call__(self, event, data):
|
|
81
|
+
return (
|
|
82
|
+
isinstance(event, Message)
|
|
83
|
+
and event.command.split("@", 1)[0] == "/start"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TextEquals(Filter):
|
|
88
|
+
def __init__(self, *texts):
|
|
89
|
+
self.texts = {str(text) for text in texts}
|
|
90
|
+
|
|
91
|
+
def __call__(self, event, data):
|
|
92
|
+
return isinstance(event, Message) and event.text in self.texts
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class TextStartswith(Filter):
|
|
96
|
+
def __init__(self, *prefixes):
|
|
97
|
+
self.prefixes = tuple(str(prefix) for prefix in prefixes)
|
|
98
|
+
|
|
99
|
+
def __call__(self, event, data):
|
|
100
|
+
return isinstance(event, Message) and event.text.startswith(
|
|
101
|
+
self.prefixes
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TextRegexp(Filter):
|
|
106
|
+
def __init__(self, pattern):
|
|
107
|
+
self.pattern = re.compile(pattern)
|
|
108
|
+
|
|
109
|
+
def __call__(self, event, data):
|
|
110
|
+
return isinstance(event, Message) and bool(
|
|
111
|
+
self.pattern.fullmatch(event.text)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class HasPhoto(Filter):
|
|
116
|
+
"""The message contains an image attachment."""
|
|
117
|
+
|
|
118
|
+
def __call__(self, event, data):
|
|
119
|
+
if not isinstance(event, Message):
|
|
120
|
+
return False
|
|
121
|
+
return any(
|
|
122
|
+
isinstance(item, dict) and item.get("type") == "image"
|
|
123
|
+
for item in event.attachments
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Payload(Filter):
|
|
128
|
+
"""A callback payload field: ``a`` (action) or any custom key."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, action=None, **fields):
|
|
131
|
+
self.fields = dict(fields)
|
|
132
|
+
if action is not None:
|
|
133
|
+
self.fields["a"] = action
|
|
134
|
+
|
|
135
|
+
def __call__(self, event, data):
|
|
136
|
+
if not isinstance(event, Callback):
|
|
137
|
+
return False
|
|
138
|
+
return all(
|
|
139
|
+
event.payload.get(key) == value
|
|
140
|
+
for key, value in self.fields.items()
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class StateIs(Filter):
|
|
145
|
+
"""The user's current FSM state is one of the listed states."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, *states):
|
|
148
|
+
self.states = {str(state) for state in states}
|
|
149
|
+
|
|
150
|
+
def __call__(self, event, data):
|
|
151
|
+
state = data.get("state")
|
|
152
|
+
return state is not None and state.get_state() in self.states
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class ChatType(Filter):
|
|
156
|
+
def __init__(self, *types):
|
|
157
|
+
self.types = {str(value) for value in types}
|
|
158
|
+
|
|
159
|
+
def __call__(self, event, data):
|
|
160
|
+
return event.chat_type in self.types
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class IsMessage(Filter):
|
|
164
|
+
def __call__(self, event, data):
|
|
165
|
+
return isinstance(event, Message)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class IsCallback(Filter):
|
|
169
|
+
def __call__(self, event, data):
|
|
170
|
+
return isinstance(event, Callback)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class IsBotStarted(Filter):
|
|
174
|
+
def __call__(self, event, data):
|
|
175
|
+
return isinstance(event, BotStarted)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Always(Filter):
|
|
179
|
+
def __call__(self, event, data):
|
|
180
|
+
return True
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def normalize(filter_):
|
|
184
|
+
if isinstance(filter_, Filter):
|
|
185
|
+
return filter_
|
|
186
|
+
if isinstance(filter_, bool):
|
|
187
|
+
return FuncFilter(lambda _event, _data: filter_)
|
|
188
|
+
if callable(filter_):
|
|
189
|
+
return FuncFilter(_with_data(filter_))
|
|
190
|
+
raise TypeError(f"Unsupported filter: {type(filter_)!r}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def normalize_all(filters):
|
|
194
|
+
return tuple(normalize(item) for item in filters)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _with_data(func):
|
|
198
|
+
"""Allow short filters such as ``lambda event: ...``."""
|
|
199
|
+
try:
|
|
200
|
+
params = inspect.signature(func).parameters.values()
|
|
201
|
+
except (TypeError, ValueError):
|
|
202
|
+
return func
|
|
203
|
+
positional = [
|
|
204
|
+
param
|
|
205
|
+
for param in params
|
|
206
|
+
if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD)
|
|
207
|
+
]
|
|
208
|
+
if len(positional) <= 1:
|
|
209
|
+
return lambda event, _data: func(event)
|
|
210
|
+
return func
|