Skip to main content

bale xyz

CI Docs Python License

A complete Python client for the Bale (بله) messenger — user sessions, bot tokens, conferences and every one of the 683 internal RPCs, all in one library.

📖 Full documentation — 40 pages in English and Persian (مستندات فارسی), covering the protocol, the client API, all 52 services, auth, messaging, calls and the CLI.

pip install bale-xyz            # core
pip install "bale-xyz[voice]"   # + LiveKit rooms for calls

What makes it different

Most Bale libraries either wrap the small Bot API or hack at the private web endpoints. bale xyz does both, in one client, with real typed protobuf.

Capability bale xyz
Bot API (tapi.bale.ai) ✅ every method, plus call() for new ones
User sessions ✅ phone login, session strings, browser cookie import
Internal RPCs ✅ 683 across 52 services
Typed protobuf ✅ rebuilt at import time from the official protocol AST
Conferences / meetings ✅ voice-first, all 30 call RPCs wrapped
LiveKit integration ✅ returns ready-to-connect room credentials
Events & filters ✅ Telethon-style dispatcher
FSM ✅ state machine with pluggable storage

The schema layer is the heart of it: rather than shipping thousands of generated _pb2.py files, bale xyz reconstructs every codec at runtime as a genuine FileDescriptorProto. All 683 request and response types — including deeply nested unions like Message.textMessage.ext — behave like real protobuf messages: SerializeToString, ParseFromString, reflection and JSON conversion all work.


Quick start

Bot token

import asyncio
from balexyz import BotApi

async def main():
    bot = BotApi("123456789:AAF...")
    me = await bot.get_me()
    await bot.send_message(chat_id=me["id"], text="hello from bale xyz")

asyncio.run(main())

User session

import asyncio
from balexyz import Client

async def main():
    async with Client("989120000000") as client:   # phone → prompts for code
        print(client.me)

asyncio.run(main())

Reuse a session instead of logging in again:

client = Client("123456789:eyJhbGciOi...")          # <user_id>:<jwt>
client = Client(session_name="work")                # from ./sessions/work.session

Or lift it straight out of your browser:

from balexyz import Session

session = Session.from_browser("firefox")   # or "chrome", "edge", "auto"
print(session)                              # 123456789:eyJ...

Conferences and calls

This is the part most libraries get wrong. bale xyz treats voice as the default and lets you opt into video. All 30 bale.meet.v1.Meet RPCs have a typed wrapper, and the payloads are verified byte-for-byte against a real browser capture (see tests/test_meet_capture.py).

No chat needed — this is the standalone room with a shareable URL:

meeting = await client.create_meet_link(title="Team sync", is_public=True)
print(meeting["link"])        # https://meet.bale.ai/i/zfqw-52pog-g5o5
print(meeting["expires_in"])  # 10800  (3 hours)

Behind the scenes that is GenerateCallLink → optional SetLinkTitle.

Create a conference bound to a group

result = await client.create_conference(
    "987654321|2",          # group peer
    voice=True,             # ← audio-only; pass False for video
    mode="group",
)
call = result["group_call"]
print(call["id"], call["room"], call["voice"])

# with a join link in one shot
result = await client.create_conference(
    "987654321|2", public=True, title="Standup"
)
print(result["group_call"]["link"])

Modes: "group" (2), "multi_peer" (3), "channel_live" (4).

Join a conference and actually connect

conn = await client.join_conference(call_id, name="Alice", connect=True)
room = await conn.connect()            # livekit.rtc.Room
print(conn.server_url, conn.permissions.can_publish)

Private one-to-one calls

await client.start_call("555|1", voice=True)     # ringing
await client.receive_call(call_id)               # mark as ringing
await client.accept_call(call_id)                # answer
await client.discard_call(call_id)               # hang up

Moderate a live room

await client.mute_participant(call_id, "111|1", muted=True)
await client.remove_from_call(call_id, identity="spammer", block=True)
await client.raise_hand(call_id, "identity-42")
await client.lower_hand(call_id, "identity-42")
await client.send_call_reaction(call_id, "❤️")
await client.update_call_layout(call_id, "grid")

# approval flow for locked rooms
await client.ask_to_join_call(call_id, name="Bob")
await client.answer_join_request(call_id, "req-7", allow=True)

Record, stream, inspect

await client.start_call_recording(call_id, quality="high")
await client.stop_call_recording(call_id)

key = await client.start_call_stream("555|1", rtmp_server="rtmp://...")
await client.delete_call_stream("555|1")

await client.get_call("987654321|2")       # active call for a chat
await client.get_ongoing_calls()           # every live call
await client.get_call_logs(limit=20)
await client.delete_call_logs([call_id])
await client.submit_call_feedback(call_id, rate=5, opinion="clear audio")

Escape hatch

Any RPC without a wrapper is still one call away:

await client.call("bale.meet.v1.Meet", "GetCallState", {"callId": 123})

Messaging

await client.send_message("555|1", "hello")
await client.send_message("555|1", "reply", reply_to=42, silent=True)
await client.edit_message("555|1", 42, "edited")
await client.delete_messages("555|1", [42, 43])

await client.send_typing("555|1", "typing")
history = await client.get_history("555|1", limit=50)
dialogs = await client.get_dialogs(limit=100)

Files and media

Bale has no single "send file" RPC — the browser reserves a slot, PUTs the bytes, then sends a message referencing the file id. All three steps are exposed, plus one-call shortcuts.

# one call: upload + send
await client.send_photo("555|1", "cat.jpg", caption="look", width=1280, height=960)
await client.send_video("555|1", "clip.mp4", duration=12)
await client.send_voice("555|1", "note.ogg", duration=7)
await client.send_audio("555|1", "track.mp3")
await client.send_document("555|1", "invoice.pdf",
                           mime_type="application/pdf")

# or step by step
info = await client.upload_file("report.pdf", mime_type="application/pdf")
print(info["file_id"], info["duplicate"])   # duplicate → Bale already had it

# download
data = await client.download_file(info["file_id"])
url  = await client.get_file_url(info["file_id"])

Command line

The package ships a read-only protocol explorer — no credentials, no network.

$ bale-xyz info
bale-xyz 1.0.0
  services        : 52
  RPC methods     : 683
  wire codecs     : 1960
  index release   : web@5.5.1+169491

$ bale-xyz methods -s bale.meet.v1.Meet
$ bale-xyz search upload
$ bale-xyz describe bale.meet.v1.Meet StartGroupCall

Documentation

A complete guide lives in docs/ — 40 pages (20 English + 20 Persian), searchable, no build step. Open docs/index.html in a browser, or serve it:

cd docs && python -m http.server 8000

English pages are at the root, Persian pages under docs/fa/ with a right-to-left layout, translated navigation, per-locale search and hreflang tags. The site is plain HTML/CSS/JS and is also published via GitHub Pages.

Events

from balexyz import Client, NewMessage, filters

async def main():
    async with Client("989120000000") as client:

        @client.on_message(filters.text & filters.private)
        async def handler(message):
            print(message.text)
            await client.send_message(message.chat.id, "got it")

        @client.on_event(NewMessage)
        async def everything(event):
            print(event.name)

        async for event in client.iter_events():
            ...

asyncio.run(main())

Raw frames are always available if you prefer:

async for update in client.iter_updates():
    print(update)

Calling any RPC

All 683 methods are addressable three ways.

# 1. Friendly high-level methods (above)

# 2. By name, with a plain dict
await client.call("bale.users.v1.Users", "LoadUsers", {"users": [...]})

# 3. Attribute proxy
users = client.api("bale.users.v1.Users")
await users.GetMe()

# Discovery
client.methods()                       # ['bale.auth.v1.Auth.ChangeLanguage', ...]
client.find("call")                    # every call-related RPC
print(client.describe("bale.meet.v1.Meet", "StartGroupCall"))
# bale.meet.v1.Meet.StartGroupCall(peer: message, randomId: int64, video: bool,
#   mode: int32, invitees: list[message]) -> {groupCall: message, seq: int32}

Payloads are validated against the real schema:

>>> await client.call("bale.messaging.v2.Messaging", "SendMessage", {"nope": 1})
TypeError: Message has no field 'nope'; available: bankMessage, ...

Bots and users in one client

bot = Client("123456789:AAF...")        # detected as a token
await bot.bot.send_message("42|1", "via Bot API")

me = Client("989120000000")             # detected as a phone
await me.send_message("42|1", "via user session")

client.is_bot and client.is_user tell you which mode is active. In bot mode, send_message, get_chat, delete_messages and send_typing route through the Bot API automatically.


Architecture

balexyz/
├── dynamic.py        runtime protobuf synthesis (the schema engine)
├── client.py         unified Client: user sessions + bot tokens
├── botapi.py         Bot API (tapi.bale.ai) with automatic error mapping
├── rpc.py            RPC driver + attribute-style service proxy
├── transports/
│   ├── websocket.py  wss://next-ws.bale.ai — multiplexed, index-matched
│   └── grpc.py       gRPC-web for login and one-shot calls
├── proto/            vendored envelope types + generated index.json
├── peers.py          Peer parsing ("123|2", ints, @usernames)
├── session.py        session strings + browser/browserless cookie import
├── rtc.py            LiveKit credential parsing → livekit.rtc.Room
├── events.py         typed updates
├── filters.py        composable filters
├── fsm.py            finite state machine
├── dispatcher.py     handler routing
├── keyboards.py      inline keyboards
├── models.py         Message, Chat, User wrappers
└── types/            dataclass-based models

The schema engine

scripts/build_protocol_index.py distils the 2.5 MB official protocol AST into a 688 KB index.json (52 services → 683 methods → 1960 codecs). At import time dynamic.py groups codecs by their originating webpack module, topo-sorts the module graph (verified acyclic) and registers each module as one .proto file with real import statements. Cross-module references then resolve through ordinary protobuf symbol lookup — no inlining, no arbitrary nesting depth, no cycles.

Every field of all 1960 codecs is fully typed. The only fields left as raw bytes are the 30 that genuinely are bytes in the protocol.

Cost: ~0.08 s to materialise all 683 request/response classes.


Development

git clone <this repo> && cd bale_xyz
pip install -e ".[dev]"
python scripts/build_protocol_index.py     # regenerate index.json
python -m pytest tests/ -q                 # 73 tests
python scripts/check_docs.py                # docs must match the code
python scripts/build_docs.py                # rebuild docs/

The index is deterministic; rebuild it only when you bump the protocol release.

scripts/check_docs.py is the important one: it verifies that every client.something() mentioned in the documentation still exists, that internal links and anchors resolve, and that the headline numbers (683 RPCs, 52 services, test count) are still true. A pull request that renames a public method will fail CI until the docs are updated.


Notes and limits

  • Bale's internal RPCs are unofficial and may change without notice. The protocol index is pinned to web release 5.5.1.
  • Session strings grant full account access — treat them like passwords. SessionStorage writes files with mode 0o600.
  • Rate limits surface as RpcError with code 429; catch FloodWait to read seconds.
  • Media upload uses Nasim URLs returned by Bale; GrpcTransport.upload() handles the PUT.
  • LiveKit room control needs the optional voice extra.
  • The authenticated paths were verified by construction and by live handshake (the socket rejects a bad token with code 4401, gRPC-web returns a real transactionHash), not by a full logged-in session. Run await client.start() with your own credentials before relying on it.
  • The protocol index is pinned to web build 5.5.1. When Bale changes an endpoint, calls fail loudly rather than corrupting payloads silently.

License

MIT.

Metadata

Release files for bale-xyz 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bale-xyz 1.0.0
File Size Uploaded Provenance Actions
bale_xyz-1.0.0.tar.gz 647.7 kB Without provenance Details for bale_xyz-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bale-xyz 1.0.0
File Interpreter ABI Platform Actions
bale_xyz-1.0.0-py3-none-any.whl Python 3 none any Details for bale_xyz-1.0.0-py3-none-any.whl

Total release size: 1.1 MB

Release files / bale_xyz-1.0.0.tar.gz

Download URL bale_xyz-1.0.0.tar.gz
Size 647.7 kB
Tags Source
SHA-256 checksum
How to use checksums
eb4330598313a77c05f73f81374a91812f0b9a7044e294ee643c33db97564bb5
BLAKE2b-256 checksum
How to use checksums
cdf0b1bdea5dd3d42ae84cf189e2a710b3225f95afb75e2e29ec9bd199fd169e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.1

Release files / bale_xyz-1.0.0-py3-none-any.whl

Download URL bale_xyz-1.0.0-py3-none-any.whl
Size 413.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
58439da7be2b29027cd41028e8d27b155c3cf0c15e40471253044c88e1d4d8fa
BLAKE2b-256 checksum
How to use checksums
1b2dc014f43a8fb948ec90464c6394011a6b6a9d33ae31edb53d8734796eb434
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.1

Security for bale-xyz 1.0.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A 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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page