Builder API
Fluent, chainable keyboard construction with KeyboardBuilder. Supports validation hooks, button transforms, and programmatic row control.
Basic Usage
from pykeyboard import InlineButton, KeyboardBuilder
kb = (
KeyboardBuilder()
.add_button(InlineButton(text="Home", callback_data="home"))
.add_button(InlineButton(text="Settings", callback_data="settings"))
.new_row()
.add_button(InlineButton(text="Help", callback_data="help"))
.build_inline()
)
await message.reply("Menu:", reply_markup=kb)Methods
| Method | Returns | Description |
|---|---|---|
add_button(button) | self | Add a button to the current row |
add_row(*buttons) | self | Add a complete row of buttons |
new_row() | self | Start a new row |
build_inline() | InlineKeyboard | Build as inline keyboard |
build_reply(**kwargs) | ReplyKeyboard | Build as reply keyboard |
add_pre_build_hook(fn) | self | Hook called before build |
add_post_build_hook(fn) | self | Hook called after build |
add_button_transform(fn) | self | Transform applied to each button on build |
Validation Hooks
def validate_no_empty(builder):
"""Reject keyboards with no buttons."""
if not builder.rows:
raise ValueError("Keyboard cannot be empty")
def add_prefix(button):
"""Add emoji prefix to all buttons."""
button.text = "→ " + button.text
return button
kb = (
KeyboardBuilder()
.add_pre_build_hook(validate_no_empty)
.add_button_transform(add_prefix)
.add_button(InlineButton(text="Click me", callback_data="x"))
.build_inline()
)