Metadata-Version: 2.4
Name: bale-xyz
Version: 1.0.0
Summary: Complete async Python client for the Bale messenger: user sessions, bot tokens, voice-first conferences, and all 683 internal RPCs.
Author: bale xyz contributors
Maintainer: bale xyz contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/iloveforduck/bale-xyz
Project-URL: Documentation, https://github.com/iloveforduck/bale-xyz/tree/main/docs
Project-URL: Repository, https://github.com/iloveforduck/bale-xyz
Project-URL: Issues, https://github.com/iloveforduck/bale-xyz/issues
Project-URL: Changelog, https://github.com/iloveforduck/bale-xyz/blob/main/CHANGELOG.md
Keywords: bale,balemessenger,messenger,bot,api,protobuf,grpc-web,websocket,livekit,calls,conference,telethon,pyrogram
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: protobuf<8,>=7.35.1
Requires-Dist: websockets>=13.0
Requires-Dist: httpx>=0.27
Provides-Extra: voice
Requires-Dist: livekit>=0.17; extra == "voice"
Provides-Extra: media
Requires-Dist: Pillow>=10.0; extra == "media"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Provides-Extra: all
Requires-Dist: bale-xyz[media,voice]; extra == "all"
Dynamic: license-file

# bale xyz

[![CI](https://github.com/iloveforduck/bale-xyz/actions/workflows/ci.yml/badge.svg)](https://github.com/iloveforduck/bale-xyz/actions/workflows/ci.yml)
[![Docs](https://img.shields.io/badge/docs-live-brightgreen)](https://iloveforduck.github.io/bale-xyz/)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-blue)](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](https://iloveforduck.github.io/bale-xyz/)** — 40 pages in **English and
Persian** ([مستندات فارسی](https://iloveforduck.github.io/bale-xyz/fa/)), covering the protocol,
the client API, all 52 services, auth, messaging, calls and the CLI.

```bash
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

```python
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

```python
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:

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

Or lift it straight out of your browser:

```python
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`).

### Create a Meet link (the browser's "create call" button)

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

```python
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

```python
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

```python
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

```python
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

```python
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

```python
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:

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

---

## Messaging

```python
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.

```python
# 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.

```console
$ 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/`](docs/) — 40 pages (20 English + 20 Persian),
searchable, no build step. Open `docs/index.html` in a browser, or serve it:

```bash
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

```python
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:

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

---

## Calling any RPC

All 683 methods are addressable three ways.

```python
# 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:

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

---

## Bots and users in one client

```python
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

```bash
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.
