Bale API

The Bale adapter provides the typed asynchronous client and Bale-specific request/response models. The generated reference below recursively discovers the restructured types and methods packages.

Client

Bale platform public API.

Shared client methods

Bale and Telegram inherit a small set of proven platform-neutral request methods. They are documented here as part of each platform reference so the complete public client surface is discoverable from either page.

Shared transport-facing mechanics for Telegram-shaped bot clients.

This module contains the shared request/retry/envelope mechanics plus the M1-confirmed A-level public methods migrated in M3 and M5. M1 found that most same-named public methods remain semantically different, so only identical-logic methods are promoted here.

class peyk.platforms._telegram_like.base_client.TelegramLikeClient(token: str, session: Session | None = None, *, retry_policy: RetryPolicy | None = None, logger: object = None, base_url: str | None = None, rate_limit: object = None)[source]

Bases: Generic[UserT, WebhookInfoT, FileT, ChatT, ChatMemberT]

Base for Bale/Telegram clients sharing request mechanics.

Only behavior proven identical by the architecture audit belongs here; platform-specific methods remain on their concrete clients.

base_url: str
max_callback_data_bytes: int = 64
user_model: type[_FromDictModel[UserT]]
webhook_info_model: type[_FromDictModel[WebhookInfoT]]
file_model: type[_FromDictModel[FileT]]
chat_model: type[_FromDictModel[ChatT]]
chat_member_parser: Callable[[dict | None], ChatMemberT | None]
chat_member_count_method: str
string_media_form_encoded: bool = False

Send string media references (file_id/URL) form-urlencoded, not as JSON.

Bale’s media methods answer 400 malformed request to a JSON body whose media value is a plain string, but accept the same fields as application/x-www-form-urlencoded (hand-verified against sendAnimation). Telegram accepts JSON, so the default stays False.

rate_limit_default: bool = False

True turns the limiter on with rate_limit_preset. Off here; Bale and Telegram turn it on.

Type:

Used when rate_limit=None is passed

rate_limit_preset: Callable[[], RateLimitConfig] | None = None

Factory for this platform’s default RateLimitConfig.

property rate_limiter: RateLimiter | None

The outbound rate limiter, or None when rate limiting is off.

Toggle at runtime with client.rate_limiter.enabled = False.

property token: str

Return the bot token this client was created with (read-only).

async close() → None[source]

Close only a transport session created by this client.

Returns:

The operation result (None).

async get_me() → UserT[source]

Return the authenticated bot user using the platform’s user model.

Returns:

The concrete user model configured by the subclass.

async get_webhook_info() → WebhookInfoT[source]

Return webhook status using the platform’s webhook-info model.

Returns:

The concrete webhook-info model configured by the subclass.

async get_file(file_id: str) → FileT[source]

Fetch the platform’s file descriptor for file_id.

Parameters:

file_id – Platform-specific file identifier.

Returns:

The concrete file model configured by the subclass.

async delete_message(chat_id: int | str, message_id: int) → bool[source]

Removes message through the shared Telegram-like API.

Parameters:
  • chat_id – Identifier of the target chat.

  • message_id – Identifier of the target message.

Returns:

Result produced by the shared Telegram-like operation.

async unban_chat_member(chat_id: int | str, user_id: int, *, only_if_banned: bool | None = None) → bool[source]

Performs the unban chat member operation for the shared Telegram-like client.

Parameters:
  • chat_id – Identifier of the target chat.

  • user_id – Identifier of the target user.

  • only_if_banned – Value used by this operation.

Returns:

Result produced by the shared Telegram-like operation.

async unpin_all_chat_messages(chat_id: int | str) → bool[source]

Performs the unpin all chat messages operation for the shared Telegram-like client.

Parameters:

chat_id – Identifier of the target chat.

Returns:

Result produced by the shared Telegram-like operation.

async leave_chat(chat_id: int | str) → bool[source]

Performs the leave chat operation for the shared Telegram-like client.

Parameters:

chat_id – Identifier of the target chat.

Returns:

Result produced by the shared Telegram-like operation.

async get_chat(chat_id: int | str) → ChatT[source]

Return chat information using the platform’s chat model.

Parameters:

chat_id – Integer or string identifier accepted by the platform.

Returns:

The concrete chat model configured by the subclass.

async get_chat_member(chat_id: int | str, user_id: int) → ChatMemberT[source]

Return a member record parsed by the concrete platform adapter.

Parameters:
  • chat_id – Integer or string chat identifier.

  • user_id – User identifier whose membership should be fetched.

Returns:

The concrete chat-member type configured by the subclass.

async set_chat_title(chat_id: int | str, title: str) → bool[source]

Updates chat title through the shared Telegram-like API.

Parameters:
  • chat_id – Identifier of the target chat.

  • title – Title to apply to the target resource.

Returns:

Result produced by the shared Telegram-like operation.

async delete_chat_photo(chat_id: int | str) → bool[source]

Removes chat photo through the shared Telegram-like API.

Parameters:

chat_id – Identifier of the target chat.

Returns:

Result produced by the shared Telegram-like operation.

classmethod validate_callback_data(data: str) → None[source]

Performs the validate callback data operation for the shared Telegram-like client.

Parameters:

data – Value used by this operation.

Types and methods

peyk.platforms.bale.types

Bale API types, one file per type.

peyk.platforms.bale.methods

Bale client methods, one module per method.

Supporting modules

Bale application-level API errors.

Every Bale response is a JSON envelope with an ok flag. On ok: false, Bale still returns a plain HTTP 200 – the failure is encoded in the JSON body (description + error_code + optional parameters), not in the HTTP status line. That makes it an application-level failure, distinct from peyk.transport’s transport-level errors (HTTPStatusError, NetworkError, TimeoutError_, RateLimitedError), which are raised from transport-level facts only (connection failures, timeouts, non-2xx status codes).

BaleAPIError subclasses peyk.transport.errors.TransportError so it can still be caught alongside transport errors by callers that want a single “something about this Bale call failed” catch-all – but it is deliberately not included in peyk.transport.retry.DEFAULT_RETRYABLE, and BaleClient never passes it through run_with_retry in the first place (see client.py): a run_with_retry-wrapped call to Session.request() already returns successfully (HTTP 200, valid JSON) before BaleClient ever looks at the ok flag, so the retry layer never even sees a BaleAPIError to (correctly) decline to retry.

exception peyk.platforms.bale.errors.BaleAPIError(message: str, *, error_code: int, description: str, parameters: object | None = None)[source]

Bases: TransportError

Raised when a Bale API response has ok: false.

Variables:
  • error_code – Bale’s error_code integer from the response body.

  • description – Bale’s human-readable description string.

  • parameters – The optional parameters object Bale sometimes includes alongside an error (e.g. retry hints for specific error codes). None when absent.

Mini App helpers and ble.ir links

Server-side helpers for Bale Mini Apps and ble.ir deep links.

A Mini App sends Bale.WebApp.initData (a URL-encoded query string) to your bot’s backend. Never trust it before verifying the signature: use verify_init_data() (raises) or validate_init_data() (returns bool).

Signature algorithm (Bale docs, identical to the Telegram scheme):

data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(fields) if k != "hash")
secret_key        = HMAC_SHA256(key="WebAppData", message=bot_token)
hash              = hex(HMAC_SHA256(key=secret_key, message=data_check_string))

Example

from peyk.platforms.bale.miniapp import verify_init_data

data = verify_init_data(request_init_data, BOT_TOKEN, max_age=3600)
user_id = data.user["id"]
exception peyk.platforms.bale.miniapp.InvalidInitDataError[source]

Bases: ValueError

initData is malformed, unsigned, forged or expired.

class peyk.platforms.bale.miniapp.MiniAppInitData(fields: ~typing.Dict[str, str] = <factory>, user: ~typing.Dict[str, object] | None = None, receiver: ~typing.Dict[str, object] | None = None, chat: ~typing.Dict[str, object] | None = None, auth_date: int | None = None, query_id: str | None = None, start_param: str | None = None, chat_type: str | None = None, chat_instance: str | None = None, hash: str | None = None)[source]

Bases: object

Parsed (and, when produced by verify_init_data(), verified) initData.

Variables:
  • fields (Dict[str, str]) – Every decoded query field, including hash.

  • user (Dict[str, object] | None) – Decoded user JSON object, if present.

  • receiver (Dict[str, object] | None) – Decoded receiver JSON object, if present.

  • chat (Dict[str, object] | None) – Decoded chat JSON object, if present.

  • auth_date (int | None) – Unix time the data was signed at.

  • query_id (str | None) – query_id field, if present.

  • start_param (str | None) – The startapp value the Mini App was opened with.

  • chat_instance (chat_type /) – Launch-context fields, if present.

  • hash (str | None) – The signature that came with the data.

fields: Dict[str, str]
user: Dict[str, object] | None = None
receiver: Dict[str, object] | None = None
chat: Dict[str, object] | None = None
auth_date: int | None = None
query_id: str | None = None
start_param: str | None = None
chat_type: str | None = None
chat_instance: str | None = None
hash: str | None = None
peyk.platforms.bale.miniapp.parse_init_data(init_data: str) → MiniAppInitData[source]

Parse initData without checking the signature.

peyk.platforms.bale.miniapp.sign_init_data(fields: Mapping[str, str], bot_token: str) → str[source]

Build a signed initData string (for tests and local tooling).

peyk.platforms.bale.miniapp.validate_init_data(init_data: str, bot_token: str, *, max_age: int | None = None) → bool[source]

Return True when verify_init_data() accepts the data.

peyk.platforms.bale.miniapp.verify_init_data(init_data: str, bot_token: str, *, max_age: int | None = None, now: float | None = None) → MiniAppInitData[source]

Verify the signature (and optionally the age) and return the parsed data.

Parameters:
  • init_data – The raw Bale.WebApp.initData string sent by the Mini App.

  • bot_token – Token of the bot that owns the Mini App.

  • max_age – Reject data whose auth_date is older than this many seconds.

  • now – Override the current time (tests).

Raises:

InvalidInitDataError – Malformed, forged, missing hash or expired.

https://ble.ir/<bot>?start=<payload>: the user’s tap sends /start <payload>.

Link that opens the bot’s main Mini App directly (?startapp).

The user does not need to have started the bot. start_param arrives in the Mini App as the start_param field of initData; mode is the display mode (for example "compact").

https://ble.ir/share?url=...&text=...: opens the user’s chat list to share.

Link to a specific message of a public chat: ble.ir/<username>/<message_id>/<date>.