CallbackData

Strongly-typed, versioned callback data — no more raw strings. v0.5.0

Defining a payload

callbacks.py
from kurigram_addons import CallbackData

class Page(CallbackData, prefix="pg"):
    num:   int
    total: int

class Action(CallbackData, prefix="act"):
    name: str

Building buttons

keyboards.py
from kurigram_addons import InlineKeyboard

kb = InlineKeyboard(row_width=2)

# .button(text) returns an InlineButton with callback_data already packed
for i in range(1, 6):
    kb.add(Page(num=i, total=5).button(f"Page {i}"))

# Page(num=3, total=5).button("Page 3").callback_data == "pg:3:5"

Decoding in handlers

handlers.py
@router.on_callback_query(Page.filter())
async def any_page(client, query):
    obj = Page.unpack(query.data)
    await query.answer(f"Page {obj.num} of {obj.total}")

# Filter for a specific field value
@router.on_callback_query(Page.filter(num=1))
async def first_page(client, query):
    await query.answer("That's the first page!")

Supported field types

Fields are colon-separated in the encoded string. Supported types:

Python typeEncoding example
str"hello"
int"42"
float"3.14"
bool"1" / "0"

pack() raises ValueError if the encoded string exceeds Telegram's 64-byte limit.

API reference

MethodDescription
instance.button(text)Returns an InlineButton with packed callback data
instance.pack()Returns the raw encoded string
Class.unpack(data)Decode a raw string back to an instance
Class.filter(**kwargs)Returns a Pyrogram filter (optionally match specific field values)