English فارسی

Authentication

Client accepts three kinds of credential and picks the right code path from the string you give it. Bots and user sessions are detected automatically.

Which method should I use?

MethodCredentialGood forNeeds the app installed?
Session string"256049633:eyJ…"Servers, scripts, CIAlready logged in once
Browser importNothing — reads cookiesLocal scripts, migrating off the webYes (logged into web.bale.ai)
Phone + code"989120000000"Fresh headless deploymentsYes, to receive the SMS
Bot token"123456:ABC…"Bots, notificationsNo

Session string

The canonical form is <user_id>:<jwt>. Everything after the first colon is the token, so JWTs with dots are fine.

from balexyz import Client

client = Client("256049633:eyJhbGciOiJIUzI1NiJ9.payload.signature")
await client.start()

print(client.user_id)      # 256049633
print(client.is_user)      # True

Export it once you are logged in, and keep it somewhere safe:

token = await client.export_session()
print(token)               # "256049633:eyJhbGciOi..."
That string is a full account takeover.

Anyone holding it can read and send messages as you, including in encrypted chats. Never commit it, never log it, never paste it into an issue. The default session_dir="./sessions" writes it with mode 0o600; pass session_dir="" to keep it in memory only.

Import from a local browser

The web client stores its session in cookies. bale xyz can read them directly from the profile of an already-logged-in browser — no password, no SMS.

from balexyz import Client, Session

# Automatic: detects firefox / chrome / chromium / edge / brave / opera / vivaldi
session = Session.from_browser()

# Or be explicit
session = Session.from_firefox()                    # ~/.mozilla/firefox/...
session = Session.from_chromium("chrome")           # Windows, macOS, Linux
session = Session.from_chromium("edge", profile_path="/custom/profile")

client = Client(str(session))
await client.start()
PlatformHandled
LinuxNative ~/.config, Snap, Flatpak
Windows%APPDATA% / %LOCALAPPDATA%
macOS~/Library/Application Support
Android (Termux)~/../usr/share paths
Chromium locks its cookie database while running.

Close the browser first. If you cannot, point profile_path at a copied profile directory. On macOS the Cookies file may also be encrypted with a Keychain-held key — bale xyz does not attempt to decrypt it.

Phone number + SMS code

The flow is StartPhoneAuth → ValidateCode → (optional ValidatePassword). The client drives it for you and prompts with plain input() unless you supply callbacks.

from balexyz import Client

client = Client(
    "989120000000",
    phone_prompt=None,          # the number is already known
    code_prompt=None,           # → input("Enter verification code: ")
    password_prompt=None,       # → input("Two-factor password: ")
    session_name="work",
)
await client.start()

Driving the prompts yourself

Prompt callables may be sync or async, and can raise to abort:

import asyncio

async def ask_code(prompt: str) -> str:
    # e.g. read from Redis, a web form, or a queue
    return await asyncio.to_thread(input, prompt)


client = Client(
    "989120000000",
    phone_prompt=lambda _: "989120000000",
    code_prompt=ask_code,
    password_prompt=lambda _: "my-2fa-password",
)

The three possible outcomes

OutcomeWhat the client does
Code accepted, account existsStores the session and connects immediately
Two-factor enabledValidateCode returns no JWT; the client calls ValidatePassword with password_prompt
New numberRaises AuthError — sign-up (SignUp) is not driven automatically; call it through raw RPC
Code delivery differs by account.

StartPhoneAuth returns sentCodeType. When it is 3, the code arrives inside the Bale app rather than by SMS — the client changes the prompt text accordingly. Watch bale.auth.v1.Auth for ResendCode and CancelCode if you need retries.

Bot token

Auto-detected by the \d+:[A-Za-z0-9_-]{20,} shape:

bot = Client("123456789:AAH4x-veryLongTokenValueHere")
await bot.start()

print(bot.is_bot)     # True
print((await bot.get_me())["first_name"])

Bot mode talks to https://tapi.bale.ai only — it never opens the user WebSocket. See Bot API.

Session storage

ArgumentDefaultEffect
session_dir"./sessions"Directory for stored sessions; empty string disables persistence
session_namederived from the user idFilename inside session_dir
device_title"bale xyz"Name shown under "active sessions" in Bale
# ephemeral: nothing touches the disk
client = Client(cred, session_dir="")

# multiple accounts side by side
work = Client(cred_a, session_dir="sessions", session_name="work")
personal = Client(cred_b, session_dir="sessions", session_name="personal")

Auth errors

from balexyz import AuthError, SessionError, ClientStateError

try:
    await client.start()
except AuthError as exc:
    print("rejected:", exc.code, exc.message)       # e.g. 4401 wrong code
except SessionError as exc:
    print("cookie extraction failed:", exc)
except ClientStateError as exc:
    print("client used before connecting:", exc)
bale xyz 1.0.0 · MIT licensed · unofficial client © 2026 bale xyz contributors