Skip to main content

aiogram-screens

codecov

Declarative screens for aiogram 3 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.

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

pip install aiogram-screens

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

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
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
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:

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: an HTML page rendered by Telegram next to the chat. create_widget() returns a Widget, and send() builds SendWidget:

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.

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.

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():

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

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:

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.

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:

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.

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.

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:

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:

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; checks run with nox.

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

Metadata

Release files for aiogram-screens 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiogram-screens 0.1.0
File Size Uploaded Provenance Actions
aiogram_screens-0.1.0.tar.gz 18.3 kB With provenance Details for aiogram_screens-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiogram-screens 0.1.0
File Interpreter ABI Platform Actions
aiogram_screens-0.1.0-py3-none-any.whl Python 3 none any Details for aiogram_screens-0.1.0-py3-none-any.whl

Total release size: 37.6 kB

Release files / aiogram_screens-0.1.0.tar.gz

Download URL aiogram_screens-0.1.0.tar.gz
Size 18.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e811080271144d68cde13bbef0b498d3817f83e8c069ec66a859b4755b7092f3
BLAKE2b-256 checksum
How to use checksums
44717127aa57a4c8f399024869b7aa1445179c178573828651ccdbf57d7a861a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / aiogram_screens-0.1.0-py3-none-any.whl

Download URL aiogram_screens-0.1.0-py3-none-any.whl
Size 19.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9a1c8b2a7d245c65521c1a17c88ae1ef152d1852f07cc252b639039dc5e22da0
BLAKE2b-256 checksum
How to use checksums
87668f2ba82ef576c078f2619ea3b2fa07415470667258d47abef3fb529e6596
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for aiogram-screens 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for aiogram_screens-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page