aiogram-screens 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DmitryDavis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,483 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiogram-screens
3
+ Version: 0.1.0
4
+ Summary: Declarative, frozen message screens for aiogram 3 bots
5
+ Keywords: aiogram,telegram,telegram-bot,screens,declarative
6
+ Author: DmitryDavis
7
+ Author-email: DmitryDavis <dmitrydavis@protonmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: aiogram>=3.33.0,<4.0
21
+ Requires-Python: >=3.11
22
+ Project-URL: Homepage, https://github.com/DavisDmitry/aiogram-screens
23
+ Project-URL: Repository, https://github.com/DavisDmitry/aiogram-screens
24
+ Project-URL: Issues, https://github.com/DavisDmitry/aiogram-screens/issues
25
+ Project-URL: Changelog, https://github.com/DavisDmitry/aiogram-screens/releases
26
+ Description-Content-Type: text/markdown
27
+
28
+ # aiogram-screens
29
+
30
+ [![codecov](https://codecov.io/gh/DavisDmitry/aiogram-screens/graph/badge.svg)](https://codecov.io/gh/DavisDmitry/aiogram-screens)
31
+
32
+ Declarative screens for [aiogram 3](https://github.com/aiogram/aiogram) bots.
33
+
34
+ A **screen** is a small frozen class that describes one bot message: its fields
35
+ are the data, its `create_*()` methods and `create_reply_markup()` turn that
36
+ data into a message. A screen doesn't send anything by itself — it builds
37
+ aiogram methods (`SendMessage`, `SendPhoto`, `EditMessageText`, …) that you
38
+ return from a handler or await with a bot.
39
+
40
+ ```python
41
+ from aiogram_screens import TextMessageScreen
42
+
43
+
44
+ class Welcome(TextMessageScreen[str]):
45
+ name: str
46
+
47
+ def create_text(self) -> str:
48
+ return f"Hello, {self.name}!"
49
+
50
+
51
+ @router.message(CommandStart())
52
+ async def start(message: Message) -> SendMessage:
53
+ return Welcome(name=message.from_user.full_name).send(message.chat.id)
54
+ ```
55
+
56
+ ## Installation
57
+
58
+ ```sh
59
+ pip install aiogram-screens
60
+ ```
61
+
62
+ To install the latest unreleased version from `main`, install it from GitHub:
63
+
64
+ ```sh
65
+ pip install git+https://github.com/DavisDmitry/aiogram-screens.git
66
+ ```
67
+
68
+ Requires Python 3.11+ and aiogram 3.33+.
69
+
70
+ ## Screens
71
+
72
+ | Class | Builds | Use for |
73
+ |---|---|---|
74
+ | `TextMessageScreen[T]` | `send()` | Messages that are only sent |
75
+ | `EditableTextMessageScreen[T]` | `send()`, `edit()` → `EditMessageText` | Messages that are sent and later edited in place |
76
+ | `MediaMessageScreen[T]` | `send()` | Photo, video, animation, audio, document and live photo messages |
77
+ | `EditableMediaMessageScreen[T]` | `send()`, `edit_media()` → `EditMessageMedia` | Media messages that are sent and later edited in place |
78
+ | `WidgetScreen` | `send()` → `SendWidget` | [Widgets](https://core.telegram.org/bots/api#sendwidget) |
79
+ | `CallbackQueryAnswerScreen` | `answer()` → `AnswerCallbackQuery` | Callback query notifications and alerts |
80
+
81
+ `create_reply_markup()` is optional and returns `None` by default.
82
+
83
+ ### Text and rich messages
84
+
85
+ Message screens are generic over the type `create_text()` returns, and the type
86
+ decides what `send()` builds:
87
+
88
+ | Screen | `create_text()` returns | `send()` builds |
89
+ |---|---|---|
90
+ | `TextMessageScreen[str]` | `str` | `SendMessage` |
91
+ | `TextMessageScreen[InputRichMessage]` | `InputRichMessage` | `SendRichMessage` |
92
+
93
+ ```python
94
+ from aiogram.types import InputRichMessage
95
+
96
+ from aiogram_screens import TextMessageScreen
97
+
98
+
99
+ class Report(TextMessageScreen[InputRichMessage]):
100
+ title: str
101
+
102
+ def create_text(self) -> InputRichMessage:
103
+ return InputRichMessage(html=f"<b>{self.title}</b>")
104
+
105
+
106
+ Report(title="Weekly").send(chat_id) # SendRichMessage
107
+ ```
108
+
109
+ Type checkers know the exact method type: `send()` of a `str` screen returns
110
+ `SendMessage`, of a rich screen `SendRichMessage`, and a `create_text()` that
111
+ doesn't match the type parameter is reported as an error. `Replacer` methods
112
+ follow the same types. The type parameter is required: there is no default, so
113
+ write `TextMessageScreen[str]`, not `TextMessageScreen`.
114
+
115
+ `parse_mode` and `link_preview_options` apply only to text messages; a rich
116
+ message carries its formatting itself.
117
+
118
+ ### Media messages
119
+
120
+ Media screens follow the same idea: the screen is generic over the media type,
121
+ and the type decides what `send()` builds.
122
+
123
+ | Screen | `create_media()` returns | `send()` builds |
124
+ |---|---|---|
125
+ | `MediaMessageScreen[InputMediaPhoto]` | `InputMediaPhoto` | `SendPhoto` |
126
+ | `MediaMessageScreen[InputMediaVideo]` | `InputMediaVideo` | `SendVideo` |
127
+ | `MediaMessageScreen[InputMediaAnimation]` | `InputMediaAnimation` | `SendAnimation` |
128
+ | `MediaMessageScreen[InputMediaAudio]` | `InputMediaAudio` | `SendAudio` |
129
+ | `MediaMessageScreen[InputMediaDocument]` | `InputMediaDocument` | `SendDocument` |
130
+ | `MediaMessageScreen[InputMediaLivePhoto]` | `InputMediaLivePhoto` | `SendLivePhoto` |
131
+
132
+ `create_media()` returns an aiogram `InputMedia*` object, so the file, caption
133
+ and media metadata are declared together:
134
+
135
+ ```python
136
+ from aiogram.types import (
137
+ FSInputFile,
138
+ InlineKeyboardButton,
139
+ InlineKeyboardMarkup,
140
+ InputMediaPhoto,
141
+ )
142
+
143
+ from aiogram_screens import EditableMediaMessageScreen
144
+
145
+
146
+ class Product(EditableMediaMessageScreen[InputMediaPhoto]):
147
+ name: str
148
+ price: int
149
+
150
+ def create_media(self) -> InputMediaPhoto:
151
+ return InputMediaPhoto(
152
+ media=FSInputFile(f"products/{self.name}.jpg"),
153
+ caption=f"<b>{self.name}</b>: {self.price} ₽",
154
+ parse_mode="HTML",
155
+ )
156
+
157
+ def create_reply_markup(self) -> InlineKeyboardMarkup:
158
+ return InlineKeyboardMarkup(
159
+ inline_keyboard=[
160
+ [
161
+ InlineKeyboardButton(
162
+ text="Buy", callback_data=f"buy:{self.name}"
163
+ )
164
+ ]
165
+ ]
166
+ )
167
+
168
+
169
+ Product(name="tea", price=100).send(chat_id) # SendPhoto
170
+ Product(name="tea", price=100).edit_media(message=message) # EditMessageMedia
171
+ ```
172
+
173
+ Like text screens, there are no separate classes per media kind: the type
174
+ parameter is the only difference, just as `TextMessageScreen[str]` and
175
+ `TextMessageScreen[InputRichMessage]` share one class.
176
+
177
+ The caption, `parse_mode`, entities and media-specific fields (`duration`,
178
+ `width`, `has_spoiler`, …) belong to the `InputMedia*` object. `send()` only
179
+ takes message-level options such as `reply_parameters`,
180
+ `disable_notification` and `business_connection_id`.
181
+
182
+ All six media types are also accepted by `EditMessageMedia`, so an editable
183
+ media screen can always edit its own message.
184
+
185
+ ### Widgets
186
+
187
+ A `WidgetScreen` sends a [widget](https://core.telegram.org/bots/api#sendwidget):
188
+ an HTML page rendered by Telegram next to the chat. `create_widget()` returns a
189
+ `Widget`, and `send()` builds `SendWidget`:
190
+
191
+ ```python
192
+ from aiogram_screens import Widget, WidgetScreen
193
+
194
+
195
+ class Chart(WidgetScreen):
196
+ period: str
197
+
198
+ def create_widget(self) -> Widget:
199
+ return Widget(f"<b>{self.period}</b>", width=100, height=200)
200
+
201
+ def create_chat_data(self) -> str:
202
+ return "period" # comes back in the widget's queries
203
+
204
+
205
+ Chart(period="week").send(chat_id) # SendWidget
206
+ ```
207
+
208
+ `width`, `height` and `allow_queries` of `Widget` are optional. `create_caption()`,
209
+ `create_chat_data()` and `create_reply_markup()` are optional methods and return
210
+ `None` by default.
211
+
212
+ The widget body is always HTML; `parse_mode` applies to the caption only. A
213
+ widget message can't be edited in place, and a widget can't be sent to a
214
+ business connection or a direct messages topic — `SendWidget` has no fields
215
+ for them.
216
+
217
+ ### Fields
218
+
219
+ Screens are declared like dataclasses: annotated class attributes become
220
+ keyword-only constructor arguments, values become defaults.
221
+
222
+ ```python
223
+ from typing import ClassVar
224
+
225
+ from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
226
+
227
+ from aiogram_screens import EditableTextMessageScreen
228
+
229
+
230
+ class Counter(EditableTextMessageScreen[str]):
231
+ title: ClassVar[str] = "Counter" # ClassVar is not a field
232
+ value: int = 0
233
+
234
+ def create_text(self) -> str:
235
+ return f"{self.title}: {self.value}"
236
+
237
+ def create_reply_markup(self) -> InlineKeyboardMarkup:
238
+ return InlineKeyboardMarkup(
239
+ inline_keyboard=[
240
+ [InlineKeyboardButton(text="+1", callback_data=f"inc:{self.value}")]
241
+ ]
242
+ )
243
+
244
+
245
+ Counter() # value=0
246
+ Counter(value=5) # value=5
247
+ Counter(valeu=5) # TypeError: Counter() got unexpected keyword arguments: 'valeu'
248
+ ```
249
+
250
+ Fields are inherited, and a subclass can re-declare a field to change its
251
+ default. Missing required fields and unknown arguments raise `TypeError`.
252
+
253
+ Mutable defaults (`items: list[str] = []`) are shared between instances, as in
254
+ plain classes — prefer immutable ones such as `tuple` or `frozenset`.
255
+
256
+ ### Screens are frozen
257
+
258
+ The text and the markup are computed **once**, when the screen is created. To
259
+ keep them in sync with the fields, screens are immutable: assigning or deleting
260
+ an attribute raises `FrozenScreenError` (a subclass of `AttributeError`). To
261
+ show different data, create a new screen.
262
+
263
+ Screens must not define `__slots__` — they are generated from the fields, so
264
+ instances have no `__dict__`.
265
+
266
+ Screens must not define `__init__`. Use `__post_init__` for extra setup; it runs
267
+ after the fields are assigned and before `create_text()`. Like in frozen
268
+ dataclasses, assign attributes there with `object.__setattr__`.
269
+
270
+ Dataclass class keywords (`frozen=False`, `eq=True`, `order=True`, …) are not
271
+ supported and raise `TypeError`. Other class keywords are passed to
272
+ `__init_subclass__` as usual.
273
+
274
+ ### Computed fields
275
+
276
+ `field(init=False)` excludes a field from the constructor. Give it a `default`,
277
+ or assign it in `__post_init__`; a screen that leaves such a field unset raises
278
+ `TypeError`.
279
+
280
+ ```python
281
+ from aiogram_screens import TextMessageScreen, field
282
+
283
+
284
+ class Order(TextMessageScreen[str]):
285
+ price: int
286
+ quantity: int
287
+ total: int = field(init=False)
288
+
289
+ def __post_init__(self) -> None:
290
+ object.__setattr__(self, "total", self.price * self.quantity)
291
+
292
+ def create_text(self) -> str:
293
+ return f"{self.quantity} × {self.price} = {self.total}"
294
+
295
+
296
+ Order(price=10, quantity=3) # "3 × 10 = 30"
297
+ Order(price=10, quantity=3, total=1) # TypeError
298
+ ```
299
+
300
+ `field()` is a PEP 681 field specifier, so mypy and pyright understand it too:
301
+ both report `total=1` as an unexpected argument. Pass the arguments literally
302
+ (`init=False`, not `init=SOME_FLAG`) — type checkers don't evaluate expressions.
303
+
304
+ ### Combining screens
305
+
306
+ A screen can inherit several bases and is then usable in every role they
307
+ provide. For example, a screen that is both an editable message and a callback
308
+ query answer shares one `create_text()`:
309
+
310
+ ```python
311
+ from aiogram_screens import CallbackQueryAnswerScreen, EditableTextMessageScreen
312
+
313
+
314
+ class Saved(EditableTextMessageScreen[str], CallbackQueryAnswerScreen):
315
+ def create_text(self) -> str:
316
+ return "Saved!"
317
+
318
+
319
+ Saved().send(chat_id) # SendMessage
320
+ Saved().edit(message=message) # EditMessageText
321
+ await Saved().answer(query) # AnswerCallbackQuery
322
+ ```
323
+
324
+ `answer()` uses only the text — the reply markup of the message roles is
325
+ ignored. Bases of different kinds can't be combined: a text, media and widget
326
+ screen each disagree on what a screen holds, so only the first base in the MRO
327
+ would be used.
328
+
329
+ ## Sending, editing, answering
330
+
331
+ ```python
332
+ screen = Counter(value=1)
333
+
334
+ screen.send(chat_id, message_thread_id=7) # SendMessage
335
+ screen.edit(message=message) # EditMessageText
336
+ screen.edit(chat_id=chat_id, message_id=message_id)
337
+ screen.edit(inline_message_id=inline_message_id)
338
+ ```
339
+
340
+ `send()` and `edit()` accept the usual Bot API options (`parse_mode`,
341
+ `link_preview_options`, `reply_parameters`, `business_connection_id`, …).
342
+ `edit(message=...)` takes the chat, message id and business connection from the
343
+ message.
344
+
345
+ An editable media screen has `edit_media()` with the same three targeting
346
+ forms; the media itself (including its caption) comes from the screen:
347
+
348
+ ```python
349
+ screen.send(chat_id) # SendPhoto
350
+ screen.edit_media(message=message) # EditMessageMedia
351
+ screen.edit_media(chat_id=chat_id, message_id=message_id)
352
+ screen.edit_media(inline_message_id=inline_message_id)
353
+ ```
354
+
355
+ Both edit methods accept only an inline keyboard, which is why the `Editable*`
356
+ bases narrow `create_reply_markup()` to `InlineKeyboardMarkup | None`: a type
357
+ checker rejects a reply keyboard in an editable screen. A plain
358
+ `TextMessageScreen` or `MediaMessageScreen` can still use one.
359
+
360
+ ```python
361
+ from aiogram_screens import CallbackQueryAnswerScreen
362
+
363
+
364
+ class Notified(CallbackQueryAnswerScreen):
365
+ def create_text(self) -> str:
366
+ return "Saved!"
367
+
368
+
369
+ await Notified().answer(query, show_alert=True) # bound to the query's bot
370
+ await bot(Notified().answer(query.id)) # a plain method, send it explicitly
371
+ ```
372
+
373
+ ### Returned methods are not sent
374
+
375
+ Methods built by screens are not bound to a bot. Either return them from a
376
+ handler — the dispatcher sends them — or send them explicitly:
377
+
378
+ ```python
379
+ await bot(screen.send(chat_id))
380
+ ```
381
+
382
+ Only `answer(query)` returns a bound method, because it uses the query's own
383
+ shortcut.
384
+
385
+ ## Replacer
386
+
387
+ `Replacer` updates the conversation after a user action: it builds the next
388
+ screen in place of the message the user interacted with, keeping its chat,
389
+ thread, direct messages topic and business connection.
390
+
391
+ ```python
392
+ from aiogram_screens import Replacer
393
+
394
+
395
+ @router.callback_query(F.data.startswith("inc:"))
396
+ async def increment(query: CallbackQuery) -> TelegramMethod[Any] | None:
397
+ value = int(query.data.removeprefix("inc:")) + 1
398
+ if query.message is None:
399
+ return None
400
+ return await Replacer(Counter(value=value)).edit_or_replace(query.message)
401
+ ```
402
+
403
+ | Method | What happens to the old message | New message |
404
+ |---|---|---|
405
+ | `replace(message)` | Deleted; if deleting fails, its keyboard is removed instead | Sent |
406
+ | `edit_or_replace(message)` | Edited in place if the screen matches the message: an `EditableTextMessageScreen` edits text and rich messages with `EditMessageText`, an `EditableMediaMessageScreen` edits media (or text and rich messages) with `EditMessageMedia`; otherwise as `replace` | Sent only on fallback |
407
+ | `new(message)` | Its keyboard is removed | Sent; with `reply_parameters=NewReplyParameters(...)` it replies to the old message |
408
+
409
+ A `WidgetScreen` is supported by all three methods. A widget message can't be
410
+ edited in place, so `edit_or_replace()` always replaces it. Because `SendWidget`
411
+ has no fields for a business connection or a direct messages topic, all three
412
+ methods raise `ValueError` when the old message belongs to one — *before* the
413
+ old message is touched.
414
+
415
+ Media screens are supported by all three methods. `edit_or_replace()` uses
416
+ `EditMessageMedia` when the screen is editable and the old message is one that
417
+ Telegram can edit into media (text, rich, photo, video, animation, audio,
418
+ document or live photo). Stickers, voice notes, video notes, widgets and
419
+ inaccessible messages are replaced instead. `replace()` and `new()` copy the
420
+ old message's business connection, thread and topic just like text screens.
421
+
422
+ > [!IMPORTANT]
423
+ > The old message is deleted (or its keyboard removed) **immediately**, when you
424
+ > call the method; the new message is only built and is sent when the
425
+ > dispatcher handles the returned method. If sending fails, the user is left
426
+ > with neither message.
427
+
428
+ The deletion uses `safe_call`, so a failure is logged, not raised.
429
+
430
+ ## `safe_call`
431
+
432
+ `safe_call` awaits a bound Telegram method and returns `(True, result)` on
433
+ success or `(False, None)` on a Telegram API error:
434
+
435
+ ```python
436
+ from aiogram_screens import safe_call
437
+
438
+ ok, _ = await safe_call(message.delete())
439
+ if not ok:
440
+ ...
441
+ ```
442
+
443
+ API errors are logged as `WARNING` to the `aiogram_screens.safe` logger. Other
444
+ exceptions are re-raised; pass `raise_non_api_error=False` to log them as
445
+ `ERROR` instead. `log_level_resolver` overrides the level per exception.
446
+
447
+ ## `BufferInputFile`
448
+
449
+ `BufferInputFile` uploads from an already opened binary stream, reading it in
450
+ chunks instead of loading the whole file into memory:
451
+
452
+ ```python
453
+ from aiogram.types import InputMediaDocument
454
+
455
+ from aiogram_screens import BufferInputFile
456
+
457
+ with open("report.pdf", "rb") as buffer:
458
+ document = InputMediaDocument(media=BufferInputFile(buffer, filename="report.pdf"))
459
+ await bot.send_document(chat_id, document=document) # or screen.send(chat_id)
460
+ ```
461
+
462
+ Unlike `FSInputFile` it takes an open file object rather than a path, and unlike
463
+ `BufferedInputFile` it doesn't need the file contents as `bytes`. The stream is
464
+ read from its current position and must stay open until the request is sent.
465
+
466
+ ## Development
467
+
468
+ The project is managed with [uv](https://docs.astral.sh/uv/); checks run with
469
+ [nox](https://nox.thea.codes/).
470
+
471
+ ```sh
472
+ uv sync # create .venv with the linters and tests groups
473
+ uv run pytest # quick test run on the pinned Python (3.11)
474
+
475
+ uvx nox # lint + tests on Python 3.11–3.15 + combined coverage
476
+ uvx nox -s format # ruff check --fix + ruff format
477
+ uvx nox -s lint # ruff check, ruff format --check, mypy --strict
478
+ uvx nox -s tests-3.15 # tests on one Python version
479
+ ```
480
+
481
+ ## License
482
+
483
+ MIT