Metadata-Version: 2.4
Name: aiogram-screens
Version: 0.1.0
Summary: Declarative, frozen message screens for aiogram 3 bots
Keywords: aiogram,telegram,telegram-bot,screens,declarative
Author: DmitryDavis
Author-email: DmitryDavis <dmitrydavis@protonmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: aiogram>=3.33.0,<4.0
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/DavisDmitry/aiogram-screens
Project-URL: Repository, https://github.com/DavisDmitry/aiogram-screens
Project-URL: Issues, https://github.com/DavisDmitry/aiogram-screens/issues
Project-URL: Changelog, https://github.com/DavisDmitry/aiogram-screens/releases
Description-Content-Type: text/markdown

# aiogram-screens

[![codecov](https://codecov.io/gh/DavisDmitry/aiogram-screens/graph/badge.svg)](https://codecov.io/gh/DavisDmitry/aiogram-screens)

Declarative screens for [aiogram 3](https://github.com/aiogram/aiogram) bots.

A **screen** is a small frozen class that describes one bot message: its fields
are the data, its `create_*()` methods and `create_reply_markup()` turn that
data into a message. A screen doesn't send anything by itself — it builds
aiogram methods (`SendMessage`, `SendPhoto`, `EditMessageText`, …) that you
return from a handler or await with a bot.

```python
from aiogram_screens import TextMessageScreen


class Welcome(TextMessageScreen[str]):
    name: str

    def create_text(self) -> str:
        return f"Hello, {self.name}!"


@router.message(CommandStart())
async def start(message: Message) -> SendMessage:
    return Welcome(name=message.from_user.full_name).send(message.chat.id)
```

## Installation

```sh
pip install aiogram-screens
```

To install the latest unreleased version from `main`, install it from GitHub:

```sh
pip install git+https://github.com/DavisDmitry/aiogram-screens.git
```

Requires Python 3.11+ and aiogram 3.33+.

## Screens

| Class | Builds | Use for |
|---|---|---|
| `TextMessageScreen[T]` | `send()` | Messages that are only sent |
| `EditableTextMessageScreen[T]` | `send()`, `edit()` → `EditMessageText` | Messages that are sent and later edited in place |
| `MediaMessageScreen[T]` | `send()` | Photo, video, animation, audio, document and live photo messages |
| `EditableMediaMessageScreen[T]` | `send()`, `edit_media()` → `EditMessageMedia` | Media messages that are sent and later edited in place |
| `WidgetScreen` | `send()` → `SendWidget` | [Widgets](https://core.telegram.org/bots/api#sendwidget) |
| `CallbackQueryAnswerScreen` | `answer()` → `AnswerCallbackQuery` | Callback query notifications and alerts |

`create_reply_markup()` is optional and returns `None` by default.

### Text and rich messages

Message screens are generic over the type `create_text()` returns, and the type
decides what `send()` builds:

| Screen | `create_text()` returns | `send()` builds |
|---|---|---|
| `TextMessageScreen[str]` | `str` | `SendMessage` |
| `TextMessageScreen[InputRichMessage]` | `InputRichMessage` | `SendRichMessage` |

```python
from aiogram.types import InputRichMessage

from aiogram_screens import TextMessageScreen


class Report(TextMessageScreen[InputRichMessage]):
    title: str

    def create_text(self) -> InputRichMessage:
        return InputRichMessage(html=f"<b>{self.title}</b>")


Report(title="Weekly").send(chat_id)  # SendRichMessage
```

Type checkers know the exact method type: `send()` of a `str` screen returns
`SendMessage`, of a rich screen `SendRichMessage`, and a `create_text()` that
doesn't match the type parameter is reported as an error. `Replacer` methods
follow the same types. The type parameter is required: there is no default, so
write `TextMessageScreen[str]`, not `TextMessageScreen`.

`parse_mode` and `link_preview_options` apply only to text messages; a rich
message carries its formatting itself.

### Media messages

Media screens follow the same idea: the screen is generic over the media type,
and the type decides what `send()` builds.

| Screen | `create_media()` returns | `send()` builds |
|---|---|---|
| `MediaMessageScreen[InputMediaPhoto]` | `InputMediaPhoto` | `SendPhoto` |
| `MediaMessageScreen[InputMediaVideo]` | `InputMediaVideo` | `SendVideo` |
| `MediaMessageScreen[InputMediaAnimation]` | `InputMediaAnimation` | `SendAnimation` |
| `MediaMessageScreen[InputMediaAudio]` | `InputMediaAudio` | `SendAudio` |
| `MediaMessageScreen[InputMediaDocument]` | `InputMediaDocument` | `SendDocument` |
| `MediaMessageScreen[InputMediaLivePhoto]` | `InputMediaLivePhoto` | `SendLivePhoto` |

`create_media()` returns an aiogram `InputMedia*` object, so the file, caption
and media metadata are declared together:

```python
from aiogram.types import (
    FSInputFile,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    InputMediaPhoto,
)

from aiogram_screens import EditableMediaMessageScreen


class Product(EditableMediaMessageScreen[InputMediaPhoto]):
    name: str
    price: int

    def create_media(self) -> InputMediaPhoto:
        return InputMediaPhoto(
            media=FSInputFile(f"products/{self.name}.jpg"),
            caption=f"<b>{self.name}</b>: {self.price} ₽",
            parse_mode="HTML",
        )

    def create_reply_markup(self) -> InlineKeyboardMarkup:
        return InlineKeyboardMarkup(
            inline_keyboard=[
                [
                    InlineKeyboardButton(
                        text="Buy", callback_data=f"buy:{self.name}"
                    )
                ]
            ]
        )


Product(name="tea", price=100).send(chat_id)  # SendPhoto
Product(name="tea", price=100).edit_media(message=message)  # EditMessageMedia
```

Like text screens, there are no separate classes per media kind: the type
parameter is the only difference, just as `TextMessageScreen[str]` and
`TextMessageScreen[InputRichMessage]` share one class.

The caption, `parse_mode`, entities and media-specific fields (`duration`,
`width`, `has_spoiler`, …) belong to the `InputMedia*` object. `send()` only
takes message-level options such as `reply_parameters`,
`disable_notification` and `business_connection_id`.

All six media types are also accepted by `EditMessageMedia`, so an editable
media screen can always edit its own message.

### Widgets

A `WidgetScreen` sends a [widget](https://core.telegram.org/bots/api#sendwidget):
an HTML page rendered by Telegram next to the chat. `create_widget()` returns a
`Widget`, and `send()` builds `SendWidget`:

```python
from aiogram_screens import Widget, WidgetScreen


class Chart(WidgetScreen):
    period: str

    def create_widget(self) -> Widget:
        return Widget(f"<b>{self.period}</b>", width=100, height=200)

    def create_chat_data(self) -> str:
        return "period"  # comes back in the widget's queries


Chart(period="week").send(chat_id)  # SendWidget
```

`width`, `height` and `allow_queries` of `Widget` are optional. `create_caption()`,
`create_chat_data()` and `create_reply_markup()` are optional methods and return
`None` by default.

The widget body is always HTML; `parse_mode` applies to the caption only. A
widget message can't be edited in place, and a widget can't be sent to a
business connection or a direct messages topic — `SendWidget` has no fields
for them.

### Fields

Screens are declared like dataclasses: annotated class attributes become
keyword-only constructor arguments, values become defaults.

```python
from typing import ClassVar

from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup

from aiogram_screens import EditableTextMessageScreen


class Counter(EditableTextMessageScreen[str]):
    title: ClassVar[str] = "Counter"  # ClassVar is not a field
    value: int = 0

    def create_text(self) -> str:
        return f"{self.title}: {self.value}"

    def create_reply_markup(self) -> InlineKeyboardMarkup:
        return InlineKeyboardMarkup(
            inline_keyboard=[
                [InlineKeyboardButton(text="+1", callback_data=f"inc:{self.value}")]
            ]
        )


Counter()  # value=0
Counter(value=5)  # value=5
Counter(valeu=5)  # TypeError: Counter() got unexpected keyword arguments: 'valeu'
```

Fields are inherited, and a subclass can re-declare a field to change its
default. Missing required fields and unknown arguments raise `TypeError`.

Mutable defaults (`items: list[str] = []`) are shared between instances, as in
plain classes — prefer immutable ones such as `tuple` or `frozenset`.

### Screens are frozen

The text and the markup are computed **once**, when the screen is created. To
keep them in sync with the fields, screens are immutable: assigning or deleting
an attribute raises `FrozenScreenError` (a subclass of `AttributeError`). To
show different data, create a new screen.

Screens must not define `__slots__` — they are generated from the fields, so
instances have no `__dict__`.

Screens must not define `__init__`. Use `__post_init__` for extra setup; it runs
after the fields are assigned and before `create_text()`. Like in frozen
dataclasses, assign attributes there with `object.__setattr__`.

Dataclass class keywords (`frozen=False`, `eq=True`, `order=True`, …) are not
supported and raise `TypeError`. Other class keywords are passed to
`__init_subclass__` as usual.

### Computed fields

`field(init=False)` excludes a field from the constructor. Give it a `default`,
or assign it in `__post_init__`; a screen that leaves such a field unset raises
`TypeError`.

```python
from aiogram_screens import TextMessageScreen, field


class Order(TextMessageScreen[str]):
    price: int
    quantity: int
    total: int = field(init=False)

    def __post_init__(self) -> None:
        object.__setattr__(self, "total", self.price * self.quantity)

    def create_text(self) -> str:
        return f"{self.quantity} × {self.price} = {self.total}"


Order(price=10, quantity=3)  # "3 × 10 = 30"
Order(price=10, quantity=3, total=1)  # TypeError
```

`field()` is a PEP 681 field specifier, so mypy and pyright understand it too:
both report `total=1` as an unexpected argument. Pass the arguments literally
(`init=False`, not `init=SOME_FLAG`) — type checkers don't evaluate expressions.

### Combining screens

A screen can inherit several bases and is then usable in every role they
provide. For example, a screen that is both an editable message and a callback
query answer shares one `create_text()`:

```python
from aiogram_screens import CallbackQueryAnswerScreen, EditableTextMessageScreen


class Saved(EditableTextMessageScreen[str], CallbackQueryAnswerScreen):
    def create_text(self) -> str:
        return "Saved!"


Saved().send(chat_id)  # SendMessage
Saved().edit(message=message)  # EditMessageText
await Saved().answer(query)  # AnswerCallbackQuery
```

`answer()` uses only the text — the reply markup of the message roles is
ignored. Bases of different kinds can't be combined: a text, media and widget
screen each disagree on what a screen holds, so only the first base in the MRO
would be used.

## Sending, editing, answering

```python
screen = Counter(value=1)

screen.send(chat_id, message_thread_id=7)  # SendMessage
screen.edit(message=message)  # EditMessageText
screen.edit(chat_id=chat_id, message_id=message_id)
screen.edit(inline_message_id=inline_message_id)
```

`send()` and `edit()` accept the usual Bot API options (`parse_mode`,
`link_preview_options`, `reply_parameters`, `business_connection_id`, …).
`edit(message=...)` takes the chat, message id and business connection from the
message.

An editable media screen has `edit_media()` with the same three targeting
forms; the media itself (including its caption) comes from the screen:

```python
screen.send(chat_id)  # SendPhoto
screen.edit_media(message=message)  # EditMessageMedia
screen.edit_media(chat_id=chat_id, message_id=message_id)
screen.edit_media(inline_message_id=inline_message_id)
```

Both edit methods accept only an inline keyboard, which is why the `Editable*`
bases narrow `create_reply_markup()` to `InlineKeyboardMarkup | None`: a type
checker rejects a reply keyboard in an editable screen. A plain
`TextMessageScreen` or `MediaMessageScreen` can still use one.

```python
from aiogram_screens import CallbackQueryAnswerScreen


class Notified(CallbackQueryAnswerScreen):
    def create_text(self) -> str:
        return "Saved!"


await Notified().answer(query, show_alert=True)  # bound to the query's bot
await bot(Notified().answer(query.id))  # a plain method, send it explicitly
```

### Returned methods are not sent

Methods built by screens are not bound to a bot. Either return them from a
handler — the dispatcher sends them — or send them explicitly:

```python
await bot(screen.send(chat_id))
```

Only `answer(query)` returns a bound method, because it uses the query's own
shortcut.

## Replacer

`Replacer` updates the conversation after a user action: it builds the next
screen in place of the message the user interacted with, keeping its chat,
thread, direct messages topic and business connection.

```python
from aiogram_screens import Replacer


@router.callback_query(F.data.startswith("inc:"))
async def increment(query: CallbackQuery) -> TelegramMethod[Any] | None:
    value = int(query.data.removeprefix("inc:")) + 1
    if query.message is None:
        return None
    return await Replacer(Counter(value=value)).edit_or_replace(query.message)
```

| Method | What happens to the old message | New message |
|---|---|---|
| `replace(message)` | Deleted; if deleting fails, its keyboard is removed instead | Sent |
| `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 |
| `new(message)` | Its keyboard is removed | Sent; with `reply_parameters=NewReplyParameters(...)` it replies to the old message |

A `WidgetScreen` is supported by all three methods. A widget message can't be
edited in place, so `edit_or_replace()` always replaces it. Because `SendWidget`
has no fields for a business connection or a direct messages topic, all three
methods raise `ValueError` when the old message belongs to one — *before* the
old message is touched.

Media screens are supported by all three methods. `edit_or_replace()` uses
`EditMessageMedia` when the screen is editable and the old message is one that
Telegram can edit into media (text, rich, photo, video, animation, audio,
document or live photo). Stickers, voice notes, video notes, widgets and
inaccessible messages are replaced instead. `replace()` and `new()` copy the
old message's business connection, thread and topic just like text screens.

> [!IMPORTANT]
> The old message is deleted (or its keyboard removed) **immediately**, when you
> call the method; the new message is only built and is sent when the
> dispatcher handles the returned method. If sending fails, the user is left
> with neither message.

The deletion uses `safe_call`, so a failure is logged, not raised.

## `safe_call`

`safe_call` awaits a bound Telegram method and returns `(True, result)` on
success or `(False, None)` on a Telegram API error:

```python
from aiogram_screens import safe_call

ok, _ = await safe_call(message.delete())
if not ok:
    ...
```

API errors are logged as `WARNING` to the `aiogram_screens.safe` logger. Other
exceptions are re-raised; pass `raise_non_api_error=False` to log them as
`ERROR` instead. `log_level_resolver` overrides the level per exception.

## `BufferInputFile`

`BufferInputFile` uploads from an already opened binary stream, reading it in
chunks instead of loading the whole file into memory:

```python
from aiogram.types import InputMediaDocument

from aiogram_screens import BufferInputFile

with open("report.pdf", "rb") as buffer:
    document = InputMediaDocument(media=BufferInputFile(buffer, filename="report.pdf"))
    await bot.send_document(chat_id, document=document)  # or screen.send(chat_id)
```

Unlike `FSInputFile` it takes an open file object rather than a path, and unlike
`BufferedInputFile` it doesn't need the file contents as `bytes`. The stream is
read from its current position and must stay open until the request is sent.

## Development

The project is managed with [uv](https://docs.astral.sh/uv/); checks run with
[nox](https://nox.thea.codes/).

```sh
uv sync                    # create .venv with the linters and tests groups
uv run pytest              # quick test run on the pinned Python (3.11)

uvx nox                    # lint + tests on Python 3.11–3.15 + combined coverage
uvx nox -s format          # ruff check --fix + ruff format
uvx nox -s lint            # ruff check, ruff format --check, mypy --strict
uvx nox -s tests-3.15      # tests on one Python version
```

## License

MIT
