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/fsm.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""FSM: dialogue states and data, in the spirit of aiogram 3."""
|
|
2
|
+
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FSMStorage(Protocol):
|
|
7
|
+
"""Storage for dialogue state and data.
|
|
8
|
+
|
|
9
|
+
The interface is synchronous: in a running bot these are local Redis
|
|
10
|
+
operations without blocking reads.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def get_state(self, key): ...
|
|
14
|
+
def set_state(self, key, state, ttl=None): ...
|
|
15
|
+
def clear_state(self, key): ...
|
|
16
|
+
def get_data(self, key): ...
|
|
17
|
+
def update_data(self, key, values, ttl=None): ...
|
|
18
|
+
def clear_data(self, key): ...
|
|
19
|
+
def claim(self, key, token, ttl=None): ...
|
|
20
|
+
def complete_claim(self, key, token): ...
|
|
21
|
+
def clear(self, key): ...
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class State(str):
|
|
25
|
+
"""A state value. Compares like a string."""
|
|
26
|
+
|
|
27
|
+
def __new__(cls, value):
|
|
28
|
+
return super().__new__(cls, str(value))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class StatesGroup:
|
|
32
|
+
"""A group of states: ``State`` attributes are collected automatically."""
|
|
33
|
+
|
|
34
|
+
def __init_subclass__(cls, **kwargs):
|
|
35
|
+
super().__init_subclass__(**kwargs)
|
|
36
|
+
cls.__states__ = {
|
|
37
|
+
name: value
|
|
38
|
+
for name, value in vars(cls).items()
|
|
39
|
+
if isinstance(value, State)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class FSMContext:
|
|
44
|
+
"""State and data for one user in one chat.
|
|
45
|
+
|
|
46
|
+
``key`` is a ``(chat_id, user_id)`` pair.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, storage: "FSMStorage | None", key):
|
|
50
|
+
self.storage = storage
|
|
51
|
+
self.key = key
|
|
52
|
+
|
|
53
|
+
def get_state(self):
|
|
54
|
+
if self.storage is None:
|
|
55
|
+
return None
|
|
56
|
+
return self.storage.get_state(self.key)
|
|
57
|
+
|
|
58
|
+
def set_state(self, state, ttl=None):
|
|
59
|
+
if self.storage is None:
|
|
60
|
+
return
|
|
61
|
+
self.storage.set_state(self.key, state, ttl=ttl)
|
|
62
|
+
|
|
63
|
+
def clear_state(self):
|
|
64
|
+
if self.storage is not None:
|
|
65
|
+
self.storage.clear_state(self.key)
|
|
66
|
+
|
|
67
|
+
def get_data(self):
|
|
68
|
+
if self.storage is None:
|
|
69
|
+
return {}
|
|
70
|
+
return self.storage.get_data(self.key)
|
|
71
|
+
|
|
72
|
+
def update_data(self, values=None, ttl=None, **kwargs):
|
|
73
|
+
payload = dict(values or {})
|
|
74
|
+
payload.update(kwargs)
|
|
75
|
+
if self.storage is None:
|
|
76
|
+
return payload
|
|
77
|
+
return self.storage.update_data(self.key, payload, ttl=ttl)
|
|
78
|
+
|
|
79
|
+
def clear_data(self):
|
|
80
|
+
if self.storage is not None:
|
|
81
|
+
self.storage.clear_data(self.key)
|
|
82
|
+
|
|
83
|
+
def claim(self, token, ttl=None):
|
|
84
|
+
"""Atomically bind a one-shot action to this event."""
|
|
85
|
+
if self.storage is None:
|
|
86
|
+
return False
|
|
87
|
+
return self.storage.claim(self.key, str(token), ttl=ttl)
|
|
88
|
+
|
|
89
|
+
def complete(self, token):
|
|
90
|
+
"""Clear the state only when this event owns the claim."""
|
|
91
|
+
if self.storage is None:
|
|
92
|
+
return False
|
|
93
|
+
return self.storage.complete_claim(self.key, str(token))
|
|
94
|
+
|
|
95
|
+
def clear(self):
|
|
96
|
+
"""Drop both state and data."""
|
|
97
|
+
if self.storage is not None:
|
|
98
|
+
self.storage.clear(self.key)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class MemoryStorage:
|
|
102
|
+
"""In-memory storage for tests and local scenarios."""
|
|
103
|
+
|
|
104
|
+
def __init__(self):
|
|
105
|
+
self.records = {}
|
|
106
|
+
|
|
107
|
+
def _record(self, key, create=False):
|
|
108
|
+
record = self.records.get(key)
|
|
109
|
+
if record is None and create:
|
|
110
|
+
record = {"state": None, "claim": None, "data": {}}
|
|
111
|
+
self.records[key] = record
|
|
112
|
+
return record
|
|
113
|
+
|
|
114
|
+
def get_state(self, key):
|
|
115
|
+
record = self._record(key)
|
|
116
|
+
return record["state"] if record else None
|
|
117
|
+
|
|
118
|
+
def set_state(self, key, state, ttl=None):
|
|
119
|
+
record = self._record(key, create=True)
|
|
120
|
+
record["state"] = str(state)
|
|
121
|
+
record["claim"] = None
|
|
122
|
+
|
|
123
|
+
def clear_state(self, key):
|
|
124
|
+
record = self._record(key)
|
|
125
|
+
if record is not None:
|
|
126
|
+
record["state"] = None
|
|
127
|
+
record["claim"] = None
|
|
128
|
+
|
|
129
|
+
def get_data(self, key):
|
|
130
|
+
record = self._record(key)
|
|
131
|
+
return dict(record["data"]) if record else {}
|
|
132
|
+
|
|
133
|
+
def update_data(self, key, values, ttl=None):
|
|
134
|
+
record = self._record(key, create=True)
|
|
135
|
+
record["data"].update(values)
|
|
136
|
+
return dict(record["data"])
|
|
137
|
+
|
|
138
|
+
def clear_data(self, key):
|
|
139
|
+
record = self._record(key)
|
|
140
|
+
if record is not None:
|
|
141
|
+
record["data"] = {}
|
|
142
|
+
|
|
143
|
+
def claim(self, key, token, ttl=None):
|
|
144
|
+
record = self._record(key)
|
|
145
|
+
if not record or not record.get("state"):
|
|
146
|
+
return False
|
|
147
|
+
if not record.get("claim"):
|
|
148
|
+
record["claim"] = str(token)
|
|
149
|
+
return True
|
|
150
|
+
return record["claim"] == str(token)
|
|
151
|
+
|
|
152
|
+
def complete_claim(self, key, token):
|
|
153
|
+
record = self._record(key)
|
|
154
|
+
if not record or record.get("claim") != str(token):
|
|
155
|
+
return False
|
|
156
|
+
del self.records[key]
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
def clear(self, key):
|
|
160
|
+
self.records.pop(key, None)
|
mbtk/max/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""MAX Bot API integration.
|
|
2
|
+
|
|
3
|
+
The client is optional and requires the ``max`` extra::
|
|
4
|
+
|
|
5
|
+
pip install mbtk[max]
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from .client import InvalidMediaUrlError, MaxApiClient
|
|
12
|
+
|
|
13
|
+
__all__ = ["InvalidMediaUrlError", "MaxApiClient"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def __getattr__(name):
|
|
17
|
+
if name in __all__:
|
|
18
|
+
from . import client
|
|
19
|
+
|
|
20
|
+
return getattr(client, name)
|
|
21
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
mbtk/max/client.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Asynchronous client for the MAX Bot API.
|
|
2
|
+
|
|
3
|
+
Requires the ``max`` extra::
|
|
4
|
+
|
|
5
|
+
pip install mbtk[max]
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import ssl
|
|
9
|
+
from urllib.parse import quote, urlsplit
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ..errors import RemoteServiceError
|
|
14
|
+
|
|
15
|
+
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class InvalidMediaUrlError(ValueError):
|
|
19
|
+
"""MAX returned an unsafe media URL or an unsupported image response."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MaxApiClient:
|
|
23
|
+
"""Small asynchronous client for the MAX Bot API.
|
|
24
|
+
|
|
25
|
+
``access_token`` is used as the ``Authorization`` header value. When
|
|
26
|
+
``ca_bundle`` is set, TLS verification uses that CA bundle; otherwise
|
|
27
|
+
the system default trust store is used.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
MAX_IMAGE_BYTES = MAX_IMAGE_BYTES
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
base_url,
|
|
35
|
+
access_token,
|
|
36
|
+
ca_bundle=None,
|
|
37
|
+
session=None,
|
|
38
|
+
media_hosts=None,
|
|
39
|
+
media_session=None,
|
|
40
|
+
):
|
|
41
|
+
self.base_url = base_url.rstrip("/")
|
|
42
|
+
self.api_host = urlsplit(self.base_url).hostname
|
|
43
|
+
self.ca_bundle = ca_bundle
|
|
44
|
+
self.access_token = access_token
|
|
45
|
+
self.media_hosts = {self.api_host} | {
|
|
46
|
+
str(host).strip().lower().rstrip(".")
|
|
47
|
+
for host in media_hosts or ()
|
|
48
|
+
if str(host).strip()
|
|
49
|
+
}
|
|
50
|
+
verify = (
|
|
51
|
+
ssl.create_default_context(cafile=ca_bundle) if ca_bundle else True
|
|
52
|
+
)
|
|
53
|
+
self.session = session or httpx.AsyncClient(timeout=15, verify=verify)
|
|
54
|
+
self.media_session = media_session or httpx.AsyncClient(
|
|
55
|
+
timeout=15, verify=verify
|
|
56
|
+
)
|
|
57
|
+
self.session.headers.update(
|
|
58
|
+
{"Authorization": access_token, "Accept": "application/json"}
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
async def send_message(self, chat_id, text, attachments=None):
|
|
62
|
+
body = {"text": text}
|
|
63
|
+
# MAX only understands markdown when the flag is present; without
|
|
64
|
+
# it, ``**...**`` and links stay raw in the message text.
|
|
65
|
+
body["format"] = "markdown"
|
|
66
|
+
if attachments:
|
|
67
|
+
# Attachments are always a list: MAX rejects a single object
|
|
68
|
+
# (for example, a keyboard) with a 400 "Can't deserialize body".
|
|
69
|
+
body["attachments"] = (
|
|
70
|
+
[attachments]
|
|
71
|
+
if isinstance(attachments, dict)
|
|
72
|
+
else list(attachments)
|
|
73
|
+
)
|
|
74
|
+
return await self._request(
|
|
75
|
+
"POST", "/messages", params={"chat_id": chat_id}, json=body
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
async def edit_message(self, message_id, chat_id, text, attachments=None):
|
|
79
|
+
"""Edit a message sent by the bot (for in-place screen updates)."""
|
|
80
|
+
body = {"text": text, "format": "markdown"}
|
|
81
|
+
if attachments is not None:
|
|
82
|
+
body["attachments"] = (
|
|
83
|
+
[attachments]
|
|
84
|
+
if isinstance(attachments, dict)
|
|
85
|
+
else list(attachments)
|
|
86
|
+
)
|
|
87
|
+
data = await self._request(
|
|
88
|
+
"PUT",
|
|
89
|
+
"/messages",
|
|
90
|
+
params={"message_id": message_id, "chat_id": chat_id},
|
|
91
|
+
json=body,
|
|
92
|
+
)
|
|
93
|
+
# MAX returns 200 even when the edit was not applied. Without this
|
|
94
|
+
# check the bot believes the screen is updated while the user still
|
|
95
|
+
# sees the old message.
|
|
96
|
+
if isinstance(data, dict) and data.get("success") is False:
|
|
97
|
+
raise RemoteServiceError(
|
|
98
|
+
"MAX rejected the message edit",
|
|
99
|
+
400,
|
|
100
|
+
service="MAX",
|
|
101
|
+
code="success_false",
|
|
102
|
+
)
|
|
103
|
+
return data
|
|
104
|
+
|
|
105
|
+
async def answer_callback(
|
|
106
|
+
self, callback_id, text=None, alert=False, message=None
|
|
107
|
+
):
|
|
108
|
+
"""Answer a button press: a notification and/or a message update.
|
|
109
|
+
|
|
110
|
+
MAX applies ``message`` to the message whose button was pressed, so
|
|
111
|
+
no ``mid`` is needed and a list can be updated for the whole shift.
|
|
112
|
+
The ``CallbackAnswer`` schema knows only ``message`` and
|
|
113
|
+
``notification``; the server rejects ``text``/``alert`` with a 400.
|
|
114
|
+
An empty body is rejected as well, so no request is sent when both
|
|
115
|
+
arguments are missing.
|
|
116
|
+
"""
|
|
117
|
+
body = {}
|
|
118
|
+
if text:
|
|
119
|
+
body["notification"] = text
|
|
120
|
+
if message:
|
|
121
|
+
body["message"] = message
|
|
122
|
+
if not body:
|
|
123
|
+
return None
|
|
124
|
+
data = await self._request(
|
|
125
|
+
"POST",
|
|
126
|
+
"/answers",
|
|
127
|
+
params={"callback_id": callback_id},
|
|
128
|
+
json=body,
|
|
129
|
+
)
|
|
130
|
+
# MAX returns 200 even when the answer was not applied.
|
|
131
|
+
if isinstance(data, dict) and data.get("success") is False:
|
|
132
|
+
raise RemoteServiceError(
|
|
133
|
+
"MAX rejected the callback answer",
|
|
134
|
+
400,
|
|
135
|
+
service="MAX",
|
|
136
|
+
code="success_false",
|
|
137
|
+
)
|
|
138
|
+
return data
|
|
139
|
+
|
|
140
|
+
async def get_message(self, message_id):
|
|
141
|
+
return await self._request(
|
|
142
|
+
"GET", f"/messages/{quote(str(message_id), safe='')}"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
async def download_image(self, url, max_bytes=MAX_IMAGE_BYTES):
|
|
146
|
+
parsed = self._validate_media_url(url)
|
|
147
|
+
headers = {"Accept": "image/*"}
|
|
148
|
+
if parsed.hostname.lower().rstrip(".") == self.api_host:
|
|
149
|
+
headers["Authorization"] = self.access_token
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
async with self.media_session.stream(
|
|
153
|
+
"GET", url, headers=headers, follow_redirects=False
|
|
154
|
+
) as response:
|
|
155
|
+
if 300 <= response.status_code < 400:
|
|
156
|
+
raise InvalidMediaUrlError("Redirects are not allowed")
|
|
157
|
+
response.raise_for_status()
|
|
158
|
+
content_type = response.headers.get("Content-Type", "")
|
|
159
|
+
if content_type and not content_type.lower().startswith(
|
|
160
|
+
"image/"
|
|
161
|
+
):
|
|
162
|
+
raise InvalidMediaUrlError(
|
|
163
|
+
"MAX media URL did not return an image"
|
|
164
|
+
)
|
|
165
|
+
content_length = response.headers.get("Content-Length")
|
|
166
|
+
if content_length and int(content_length) > max_bytes:
|
|
167
|
+
raise InvalidMediaUrlError(
|
|
168
|
+
"MAX image exceeds the size limit"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
chunks = []
|
|
172
|
+
total = 0
|
|
173
|
+
async for chunk in response.aiter_bytes(64 * 1024):
|
|
174
|
+
if not chunk:
|
|
175
|
+
continue
|
|
176
|
+
total += len(chunk)
|
|
177
|
+
if total > max_bytes:
|
|
178
|
+
raise InvalidMediaUrlError(
|
|
179
|
+
"MAX image exceeds the size limit"
|
|
180
|
+
)
|
|
181
|
+
chunks.append(chunk)
|
|
182
|
+
return b"".join(chunks)
|
|
183
|
+
except InvalidMediaUrlError:
|
|
184
|
+
raise
|
|
185
|
+
except (TypeError, ValueError):
|
|
186
|
+
raise InvalidMediaUrlError("Invalid MAX image response") from None
|
|
187
|
+
except httpx.HTTPError as error:
|
|
188
|
+
status = _error_status(error)
|
|
189
|
+
raise RemoteServiceError(
|
|
190
|
+
"Failed to download the MAX image", status, service="MAX"
|
|
191
|
+
) from None
|
|
192
|
+
|
|
193
|
+
def _validate_media_url(self, url):
|
|
194
|
+
if not isinstance(url, str) or len(url) > 4096:
|
|
195
|
+
raise InvalidMediaUrlError("Invalid MAX media URL")
|
|
196
|
+
try:
|
|
197
|
+
parsed = urlsplit(url)
|
|
198
|
+
port = parsed.port
|
|
199
|
+
except ValueError:
|
|
200
|
+
raise InvalidMediaUrlError("Invalid MAX media URL") from None
|
|
201
|
+
|
|
202
|
+
host = (parsed.hostname or "").lower().rstrip(".")
|
|
203
|
+
if (
|
|
204
|
+
parsed.scheme != "https"
|
|
205
|
+
or not host
|
|
206
|
+
or parsed.username
|
|
207
|
+
or parsed.password
|
|
208
|
+
or parsed.fragment
|
|
209
|
+
or port not in (None, 443)
|
|
210
|
+
or host not in self.media_hosts
|
|
211
|
+
):
|
|
212
|
+
raise InvalidMediaUrlError("Untrusted MAX media URL")
|
|
213
|
+
return parsed
|
|
214
|
+
|
|
215
|
+
async def _request(self, method, path, **kwargs):
|
|
216
|
+
try:
|
|
217
|
+
response = await self.session.request(
|
|
218
|
+
method,
|
|
219
|
+
f"{self.base_url}{path}",
|
|
220
|
+
**kwargs,
|
|
221
|
+
)
|
|
222
|
+
response.raise_for_status()
|
|
223
|
+
return response.json()
|
|
224
|
+
except httpx.HTTPStatusError as error:
|
|
225
|
+
raise RemoteServiceError(
|
|
226
|
+
"MAX API request failed",
|
|
227
|
+
error.response.status_code,
|
|
228
|
+
service="MAX",
|
|
229
|
+
code=_error_code(error.response),
|
|
230
|
+
) from None
|
|
231
|
+
except httpx.HTTPError as error:
|
|
232
|
+
raise RemoteServiceError(
|
|
233
|
+
"MAX API request failed",
|
|
234
|
+
_error_status(error),
|
|
235
|
+
service="MAX",
|
|
236
|
+
) from None
|
|
237
|
+
except ValueError:
|
|
238
|
+
raise RemoteServiceError(
|
|
239
|
+
"MAX API returned invalid JSON", service="MAX"
|
|
240
|
+
) from None
|
|
241
|
+
|
|
242
|
+
async def aclose(self):
|
|
243
|
+
"""Close HTTP sessions, without closing a shared one twice."""
|
|
244
|
+
sessions = {
|
|
245
|
+
id(self.session): self.session,
|
|
246
|
+
id(self.media_session): self.media_session,
|
|
247
|
+
}
|
|
248
|
+
for session in sessions.values():
|
|
249
|
+
await session.aclose()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _error_status(error):
|
|
253
|
+
response = getattr(error, "response", None)
|
|
254
|
+
return response.status_code if response is not None else None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _error_code(response):
|
|
258
|
+
"""Short error code from the MAX response body, without its text."""
|
|
259
|
+
try:
|
|
260
|
+
data = response.json()
|
|
261
|
+
except ValueError:
|
|
262
|
+
return None
|
|
263
|
+
if not isinstance(data, dict):
|
|
264
|
+
return None
|
|
265
|
+
code = data.get("code")
|
|
266
|
+
return str(code)[:64] if code is not None else None
|
mbtk/max/keyboards.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Builders for MAX inline keyboards and attachments."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
MAX_BUTTONS_PER_KEYBOARD = 30
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def button(text: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
10
|
+
"""Build an inline callback button."""
|
|
11
|
+
return {
|
|
12
|
+
"type": "callback",
|
|
13
|
+
"text": str(text),
|
|
14
|
+
"payload": json.dumps(
|
|
15
|
+
payload, ensure_ascii=False, separators=(",", ":")
|
|
16
|
+
),
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def keyboard(
|
|
21
|
+
rows: list[list[dict[str, Any]]],
|
|
22
|
+
limit: int = MAX_BUTTONS_PER_KEYBOARD,
|
|
23
|
+
) -> dict[str, Any]:
|
|
24
|
+
"""Build an inline keyboard from rows of buttons."""
|
|
25
|
+
return {"type": "inline_keyboard", "payload": {"buttons": rows[:limit]}}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def location_attachment(latitude, longitude) -> dict[str, Any]:
|
|
29
|
+
"""Build a location attachment."""
|
|
30
|
+
return {
|
|
31
|
+
"type": "location",
|
|
32
|
+
"latitude": latitude,
|
|
33
|
+
"longitude": longitude,
|
|
34
|
+
}
|
mbtk/max/updates.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Parse raw MAX updates into typed events."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from ..events import BotStarted, Callback, Message
|
|
7
|
+
|
|
8
|
+
SUPPORTED_UPDATES = frozenset(
|
|
9
|
+
{"message_created", "message_callback", "bot_started"}
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def event_id_for(update):
|
|
14
|
+
"""Stable event ID: ``update_id`` or a hash of the canonical JSON."""
|
|
15
|
+
supplied_id = update.get("update_id")
|
|
16
|
+
if supplied_id is not None and str(supplied_id).strip():
|
|
17
|
+
return str(supplied_id)
|
|
18
|
+
canonical = json.dumps(
|
|
19
|
+
update, sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
|
20
|
+
)
|
|
21
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_update(update, bot=None):
|
|
25
|
+
"""Turn a MAX update into an event, or return None.
|
|
26
|
+
|
|
27
|
+
Group chats and unknown update types are ignored.
|
|
28
|
+
"""
|
|
29
|
+
if not isinstance(update, dict):
|
|
30
|
+
return None
|
|
31
|
+
update_type = update.get("update_type")
|
|
32
|
+
if update_type not in SUPPORTED_UPDATES:
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
payload = _payload(update)
|
|
36
|
+
chat_id, user_id, chat_type = _identity(update_type, payload)
|
|
37
|
+
if not chat_id or not user_id or chat_type != "dialog":
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
identity = {
|
|
41
|
+
"event_id": event_id_for(update),
|
|
42
|
+
"chat_id": chat_id,
|
|
43
|
+
"user_id": user_id,
|
|
44
|
+
"chat_type": chat_type,
|
|
45
|
+
"raw": update,
|
|
46
|
+
"bot": bot,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if update_type == "message_created":
|
|
50
|
+
message = _mapping(payload.get("message"))
|
|
51
|
+
body = _mapping(message.get("body"))
|
|
52
|
+
text = str(body.get("text") or "").strip()
|
|
53
|
+
return Message(
|
|
54
|
+
text=text,
|
|
55
|
+
message_id=str(body.get("mid") or message.get("mid") or ""),
|
|
56
|
+
body=body,
|
|
57
|
+
message=message,
|
|
58
|
+
**identity,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if update_type == "message_callback":
|
|
62
|
+
callback = _mapping(payload.get("callback") or update.get("callback"))
|
|
63
|
+
callback_message = _mapping(callback.get("message"))
|
|
64
|
+
callback_body = _mapping(callback_message.get("body"))
|
|
65
|
+
callback_id = str(callback.get("callback_id") or "")
|
|
66
|
+
if callback_id:
|
|
67
|
+
identity["event_id"] = callback_id
|
|
68
|
+
return Callback(
|
|
69
|
+
callback_id=callback_id,
|
|
70
|
+
payload=_parse_callback_payload(callback.get("payload")),
|
|
71
|
+
message_id=str(
|
|
72
|
+
callback_body.get("mid") or callback_message.get("mid") or ""
|
|
73
|
+
),
|
|
74
|
+
**identity,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return BotStarted(
|
|
78
|
+
user=_mapping(payload.get("user")),
|
|
79
|
+
**identity,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _payload(update):
|
|
84
|
+
nested = update.get("payload")
|
|
85
|
+
return nested if isinstance(nested, dict) else update
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _identity(update_type, payload):
|
|
89
|
+
message = _mapping(payload.get("message"))
|
|
90
|
+
recipient = _mapping(message.get("recipient"))
|
|
91
|
+
sender = _mapping(message.get("sender"))
|
|
92
|
+
callback = _mapping(payload.get("callback"))
|
|
93
|
+
callback_message = _mapping(callback.get("message")) or message
|
|
94
|
+
callback_recipient = (
|
|
95
|
+
_mapping(callback_message.get("recipient")) or recipient
|
|
96
|
+
)
|
|
97
|
+
callback_user = _mapping(callback.get("user")) or _mapping(
|
|
98
|
+
callback.get("sender")
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if update_type == "message_created":
|
|
102
|
+
chat_id = recipient.get("chat_id")
|
|
103
|
+
max_user_id = sender.get("user_id")
|
|
104
|
+
chat_type = recipient.get("chat_type")
|
|
105
|
+
elif update_type == "message_callback":
|
|
106
|
+
chat_id = (
|
|
107
|
+
callback.get("chat_id")
|
|
108
|
+
or callback_recipient.get("chat_id")
|
|
109
|
+
or recipient.get("chat_id")
|
|
110
|
+
)
|
|
111
|
+
max_user_id = callback_user.get("user_id") or sender.get("user_id")
|
|
112
|
+
chat_type = callback_recipient.get("chat_type")
|
|
113
|
+
elif update_type == "bot_started":
|
|
114
|
+
user = _mapping(payload.get("user"))
|
|
115
|
+
chat_id = payload.get("chat_id") or recipient.get("chat_id")
|
|
116
|
+
max_user_id = user.get("user_id") or sender.get("user_id")
|
|
117
|
+
chat_type = recipient.get("chat_type") or payload.get("chat_type")
|
|
118
|
+
else:
|
|
119
|
+
return None, None, None
|
|
120
|
+
|
|
121
|
+
return _numeric_id(chat_id), _numeric_id(max_user_id), chat_type
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _numeric_id(value):
|
|
125
|
+
text = str(value or "")
|
|
126
|
+
return text if text.isdigit() and len(text) <= 32 else None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _mapping(value):
|
|
130
|
+
return value if isinstance(value, dict) else {}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _parse_callback_payload(raw):
|
|
134
|
+
"""Parse a button payload.
|
|
135
|
+
|
|
136
|
+
MAX sends the payload as a string. Messages sent by the built-in bot
|
|
137
|
+
0.9.x arrive with double encoding (a JSON string inside a JSON string),
|
|
138
|
+
so unwrap up to two levels. Otherwise buttons in old messages silently
|
|
139
|
+
stop working.
|
|
140
|
+
"""
|
|
141
|
+
data = raw
|
|
142
|
+
for _ in range(2):
|
|
143
|
+
if not isinstance(data, str):
|
|
144
|
+
break
|
|
145
|
+
try:
|
|
146
|
+
data = json.loads(data)
|
|
147
|
+
except json.JSONDecodeError:
|
|
148
|
+
return {}
|
|
149
|
+
return data if isinstance(data, dict) else {}
|
mbtk/middleware.py
ADDED
mbtk/py.typed
ADDED
|
File without changes
|