baleRobot
کتابخانهی کامل و تایپشدهی پایتون برای API بازو (رباتساز پیامرسان بله) — هم نسخهی همزمان و هم ناهمگام، با پوشش ۱۰۰٪ مستندات رسمی.
📄 نسخهی فارسی این سند: README.fa.md
Features
- Full API coverage — every method in the official Bale Bot API docs:
messages, media, chat administration, stickers, payments, webhooks,
getUpdates, plus Bale-only methods (askReview,inquireTransaction) that Telegram libraries don't have. - Async-first, sync-friendly —
AsyncBaleClient(asyncio) andBaleClient(blocking) with identical, fully typed signatures. - Typed results — responses are parsed into dataclasses (
Message,User,ChatFullInfo,ChatMemberhierarchy,SuccessfulPayment,Transaction, …). - Smart uploads — pass a
file_id, anhttpsURL, apathlib.Path,bytesor anInputFile; media groups automatically use theattach://mechanism. - Rate-limit aware —
429becomesTooManyRequestswithretry_after; automatic, configurable retries for429/5xxand transient network errors. - Business API — one flag (
business=True) switches tohttps://tapi.bale.ai/business/bot<token>/…for bulk messaging with a separate quota. - Mini App server-side helpers — validate
initData(HMAC-SHA-256) exactly as the official docs describe. - PEP 561 — full
py.typedtype hints for excellent IDE completion.
Installation
pip install baleRobot
Requires Python 3.10+ and httpx.
Quick start
Synchronous
from baleRobot import BaleClient
with BaleClient("YOUR_TOKEN") as client:
me = client.get_me()
print(me.first_name, me.username)
keyboard = InlineKeyboardMarkup.quick([
[("درباره ما", "about"), "پشتیبانی"],
])
client.send_message(123456789, "سلام!", reply_markup=keyboard)
Asynchronous
import asyncio
from baleRobot import AsyncBaleClient, InlineKeyboardMarkup
async def main() -> None:
async with AsyncBaleClient("YOUR_TOKEN") as client:
me = await client.get_me()
await client.send_message(
123456789,
f"سلام {me.first_name}!",
reply_markup=InlineKeyboardMarkup.quick([[("تماس", "contact")]]),
)
asyncio.run(main())
Receiving updates (long polling)
from baleRobot import AsyncBaleClient, Update, run_polling
client = AsyncBaleClient("YOUR_TOKEN")
async def handle(update: Update) -> None:
message = update.effective_message
if message is None or not message.text:
return
if message.command == "start":
await client.send_message(message.chat_id, "خوش آمدید!")
elif update.callback_query is not None:
await client.answer_callback_query(update.callback_query.id, text="دریافت شد")
else:
await client.send_chat_action(message.chat_id, "typing")
await client.send_message(message.chat_id, f"گفتید: {message.text}")
await run_polling(client, handle, skip_pending=True)
Use
run_polling_sync(client, handler)with the synchronousBaleClient.
Sending files
from pathlib import Path
from baleRobot import InputFile, InputMediaPhoto, InputMediaVideo
# file_id / URL / path / bytes / InputFile — all work
await client.send_photo(chat_id, "AgACAgIAAxkBAAI...")
await client.send_photo(chat_id, "https://example.com/pic.jpg", caption="از اینترنت")
await client.send_document(chat_id, Path("report.pdf"))
await client.send_document(chat_id, InputFile.from_bytes(b"...", filename="note.txt"))
# albums (uploads are sent with the attach:// mechanism automatically)
await client.send_media_group(chat_id, [
InputMediaPhoto(Path("1.jpg"), caption="آلبوم"),
InputMediaPhoto(Path("2.jpg")),
])
# download a file (valid for ~1 hour)
info = await client.get_file(file_id)
content = await client.download_file(info)
Formatting (Bale Markdown rules)
from baleRobot import bold, italic, link, inline_note
text = f"{bold('سلام')}، شما {link('اینجا', 'https://ble.ir')} هستید {italic('همین حالا')}"
await client.send_message(chat_id, text)
# inline note: ```[متن]توضیحات```
await client.send_message(chat_id, inline_note("نکته", "این یک توضیح تکمیلی است"))
Payments (Bale wallet)
from baleRobot import LabeledPrice
invoice = await client.send_invoice(
chat_id=chat_id,
title="اشتراک ویژه",
description="یک ماه دسترسی کامل",
payload="order-42", # returned in SuccessfulPayment
provider_token="WALLET-...", # from @botfather (test: WALLET-TEST-1111111111111111)
prices=[LabeledPrice("اشتراک", 150_000)], # amounts are IRR (integer)
)
# answer pre-checkout within 10 seconds
if update.pre_checkout_query is not None:
q = update.pre_checkout_query
await client.answer_pre_checkout_query(q.id, ok=True)
# and inspect a transaction any time
tx = await client.inquire_transaction("transaction-id")
Business (bulk) API
client = AsyncBaleClient("YOUR_TOKEN", business=True)
await client.send_message(user_id, "خبرنامهی هفتگی") # /business/bot<token>/…
Mini App initData validation (server side)
from baleRobot import InvalidInitData, validate_init_data
try:
data = validate_init_data(init_data, token="YOUR_TOKEN", max_age=86400)
user_id = data.user.id
except InvalidInitData:
... # reject the request
Webhooks
from fastapi import FastAPI, Request
from baleRobot import AsyncBaleClient, parse_update
app = FastAPI()
client = AsyncBaleClient("YOUR_TOKEN")
@app.post("/webhook")
async def webhook(request: Request):
update = parse_update(await request.json())
message = update.effective_message
if message is not None and message.text == "/ping":
await client.send_message(message.chat_id, "pong")
return {"ok": True}
Error handling
import baleRobot
try:
await client.send_message(chat_id, text)
except baleRobot.TooManyRequests as e: # 429
print("retry after", e.retry_after)
except baleRobot.Forbidden as e: # 403 (e.g. bot is not admin)
print(e.description)
except baleRobot.APIError as e: # any other API error
print(e.error_code, e.description)
except baleRobot.NetworkError: # connectivity
print("network problem")
Automatic retries are enabled by default (auto_retry=True, max_retries=3); disable them
if you prefer explicit handling.
API reference (all covered methods)
| Group | Methods |
|---|---|
| Bot info | get_me |
| Messages | send_message, forward_message, copy_message, edit_message_text, edit_message_caption, edit_message_reply_markup, delete_message |
| Media | send_photo, send_audio, send_document, send_video, send_animation, send_voice, send_media_group, send_location, send_contact |
| Chat | send_chat_action, get_chat, get_chat_administrators, get_chat_members_count, get_chat_member, leave_chat, set_chat_title, set_chat_description, set_chat_photo, delete_chat_photo, create_chat_invite_link, revoke_chat_invite_link, export_chat_invite_link |
| Members | ban_chat_member, unban_chat_member, promote_chat_member |
| Pins | pin_chat_message, unpin_chat_message, unpin_all_chat_messages |
| Files | get_file, download_file, file_url |
| Callbacks | answer_callback_query |
| Bale-only | ask_review, inquire_transaction |
| Stickers | upload_sticker_file, create_new_sticker_set, add_sticker_to_set |
| Payments | send_invoice, create_invoice_link, answer_pre_checkout_query |
| Updates & webhook | get_updates, set_webhook, delete_webhook, get_webhook_info |
Every method also accepts **kwargs, so any additional (or future) API parameter can be sent
without waiting for a library update.
Running tests
pip install -e ".[test]"
pytest
Publishing (maintainers)
Releases are published to PyPI automatically through Trusted Publishing (OIDC) when a
GitHub Release is published — see .github/workflows/publish.yml.
Bump src/baleRobot/_version.py, tag the commit as vX.Y.Z, then publish the release.
License
MIT © Hamidreza (mrhamidrezam)
Metadata
Release files for baleRobot 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| balerobot-0.1.0.tar.gz | 55.2 kB | With provenance | Details for balerobot-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| balerobot-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for balerobot-0.1.0-py3-none-any.whl |
Total release size: 110.4 kB
Release files / balerobot-0.1.0.tar.gz
| Download URL | balerobot-0.1.0.tar.gz |
|---|---|
| Size | 55.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0815b524636bf77745ad75949e1034ffac3a8cc9f1cab69d0140182609896e83
|
|
BLAKE2b-256 checksum How to use checksums |
b5c08f0aea7943c74223afd59754114f07e15ec07d50770de158eadddd341b80
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logRelease files / balerobot-0.1.0-py3-none-any.whl
| Download URL | balerobot-0.1.0-py3-none-any.whl |
|---|---|
| Size | 55.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5553d69df1f2d7ee630ab86559ab4fad7a149062b72ceffc4391b6a5dd1d81f2
|
|
BLAKE2b-256 checksum How to use checksums |
abd752043264c6c428dd035dac7bf4fd6e04b3adbff2d793ae01be64f7cfd6d5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logSecurity for baleRobot 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for balerobot-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.