aiogram-screens
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.