Skip to content
target111Public

About

A batteries-included framework on top of python-telegram-bot for inline-keyboard-driven bots.

Topics

Resources

Stars

2 stars

Watchers

2 watching

Forks

Latest commit

 

History

29 Commits

Folders and files

Repository files navigation

vitrine

CI PyPI

Your handler returns a screen. vitrine does the rest.

A framework for button-driven Telegram bots on top of python-telegram-bot.

from vitrine import Bot, Button, CallbackData, Screen

bot = Bot(token="...")


class MenuCB(CallbackData, prefix="menu"):
    section: str


@bot.command("start", description="Open the menu")
async def start():
    return Screen(
        text="Welcome!", keyboard=[[Button("Shop", callback=MenuCB(section="shop"))]]
    )


@bot.callback(MenuCB)
async def menu(data: MenuCB):  # decoded, validated button data
    return Screen(text=f"Section: {data.section}")


bot.run()

Also included: dependency injection, auth, conversations, background workers, per-chat command menus and a test client. PTB stays underneath and fully accessible.

Install

uv add vitrine-tg
# or
pip install vitrine-tg

The package is named vitrine-tg on PyPI; the import name is vitrine. It needs Python 3.11 or newer.

A short tour

Screens. A handler returns a Screen (text, buttons, optional media) and vitrine sends it. A button press edits the message it came from, and a command gets a reply. Switching between text and media, re-sending uploads by file_id, and persistent reply keyboards are handled for you. Screens & delivery

Typed buttons. Button data is a pydantic model with a short prefix, so handlers get validated fields instead of strings to parse. A stale or corrupt button tells the user it has expired instead of raising an error. Callbacks

Dependency injection. Handlers ask for what they need by parameter name. Providers can be values, functions or async generators, and are resolved once per update:

bot.provide_value("db", Database(DB_URL))


@bot.provide("session")
async def session(db):  # providers can depend on other providers
    async with db.begin() as s:
        yield s  # cleaned up once the update is handled


@bot.command("orders")
async def list_orders(update, session): ...

A parameter nothing can supply fails at startup, not when a user hits it. Dependency injection

Command arguments. Arguments are declared with Arg[T], and everything else is injected. Bad input gets a usage line back:

from vitrine import Arg, Greedy


@bot.command("pay")
async def pay(wallet, amount: Arg[float], note: Greedy = ""):
    ...  # "/pay 5 thanks for lunch" gives amount=5.0, note="thanks for lunch"

Commands & /help

Auth. You define the user type and how to load it. vitrine loads it once per update, injects it, enforces bans and checks role guards:

from vitrine import Arg, Auth, Bot, requires

auth = Auth(load_user, name="user", roles=lambda u: u.roles, is_banned=lambda u: u.banned)
bot = Bot(token, auth=auth)


@bot.command("refund")
@requires("support")
async def refund(user, order_id: Arg[int]): ...

Auth

Conversations. Multi-step flows keep a dataclass of state per user and move between named states:

from dataclasses import dataclass

from vitrine import END, Conversation, Screen


@dataclass
class Order:
    item: str = ""


order = Conversation("order", Order, timeout=300)


@order.entry(command="order")
async def begin():
    return "item", Screen(text="What would you like?")


@order.state("item")
async def got_item(state: Order, update):
    state.item = update.effective_message.text
    return END, Screen(text=f"Ordered {state.item}.")


bot.conversation(order)

Each user has at most one conversation per chat, and starting one cancels the previous one. Conversations

Command menus and /help. /help is generated from your commands. Give commands a scope and map scopes to chats, and vitrine keeps each chat's Telegram command menu in sync, including clearing it when a chat drops out of every scope. Command menus

Background workers. Workers get the same injection as handlers and restart with backoff if they crash:

@bot.worker(every=60)
async def send_reminders(reminders, delivery):
    for reminder in await reminders.due():
        await delivery.send(reminder.chat_id, Screen(text=reminder.text))

Workers & lifecycle

Testing. TestClient runs your bot through PTB's real dispatcher with Telegram faked at the HTTP layer, and records every API call:

from vitrine.testing import TestClient


async def test_menu():
    async with TestClient(build_bot()) as client:
        await client.send("/start")
        await client.press(MenuCB(section="shop"))
        assert client.last_text() == "Section: shop"

Testing

Also included: middleware and error handlers, and rate limiting, pagination, a Markdown builder, structured logging and file downloads.

PTB is still there. bot.build() returns the PTB Application, so webhooks and anything else PTB supports work as usual, and bot.raw() registers plain PTB handlers. PTB integration

Examples

Documentation

Local development

uv sync          # install dependencies
uv run pytest    # run the tests
BOT_TOKEN=... uv run python examples/small_bot.py

License

MIT

About

A batteries-included framework on top of python-telegram-bot for inline-keyboard-driven bots.

Topics

Resources

Stars

2 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages