Skip to main content

Balthon

Balthon is an asynchronous Python library for building bots for the Bale messenger.

It provides an async client, update handlers, filters, message and user models, keyboard helpers, state management, and methods for interacting with the Bale Bot API.

Features

  • Asynchronous API client built on httpx
  • Long-polling support
  • Optional built-in webhook server
  • Update handlers and composable filters
  • Message, user, chat, callback-query, and media models
  • Reply and inline keyboard helpers
  • Per-user update queues and rate limiting
  • Lightweight state manager with expiration
  • Bale API operations for messages, chats, files, members, stickers, and payments

Requirements

  • Python 3.9 or newer
  • An active Bale bot token

Installation

Install the package from PyPI:

pip install balthon

For webhook mode, install the optional dependencies:

pip install "balthon[webhook]"

Quick start

Create a bot in Bale and obtain its token. Then create a Python file:

from balthon import BotClient, filters

bot = BotClient("YOUR_BOT_TOKEN")


@bot.on_update(filters.command("start"))
async def start_handler(update):
    await bot.reply("Hello! Welcome to my bot.")


bot.run()

Replace YOUR_BOT_TOKEN with your bot token.

Handling updates

Register handlers with on_update. You can pass one or more filters to decide which updates a handler receives.

from balthon import BotClient, filters

bot = BotClient("YOUR_BOT_TOKEN")


@bot.on_update(filters.text())
async def text_handler(update):
    await bot.reply(f"You sent: {update.text}")


@bot.on_update(filters.photo())
async def photo_handler(update):
    await bot.reply("I received a photo!")


bot.run()

The library includes filters for common update types and conditions, including text, commands, private chats, groups, channels, photos, documents, audio, video, voice messages, stickers, callbacks, contacts, locations, membership status, user IDs, chat IDs, and state checks.

Filters can be combined with & (AND), | (OR), and ~ (NOT).

@bot.on_update(filters.private() & filters.text())
async def private_text_handler(update):
    await bot.reply("This is a private text message.")

Keyboards

Balthon provides helpers for reply and inline keyboards.

from balthon import BotClient, Button, KeyBoard, KeyBoardRow

bot = BotClient("YOUR_BOT_TOKEN")


@bot.on_update(filters.command("menu"))
async def menu_handler(update):
    keyboard = KeyBoard(
        KeyBoardRow(Button("Option 1"), Button("Option 2")),
        resize=True,
    )
    await bot.reply("Choose an option:", markup=keyboard)


bot.run()

For inline keyboards:

from balthon import InlineButton, InLineRow, InLineKeyboard

keyboard = InLineKeyboard(
    InLineRow(InlineButton("Open Bale", url="https://bale.ai"))
)

State management

Use StateManager to store temporary state for a user. States expire after the configured number of seconds.

from balthon import BotClient, StateManager, filters

bot = BotClient("YOUR_BOT_TOKEN")
states = StateManager()


@bot.on_update(filters.command("begin"))
async def begin(update):
    await states.set_state_for(update, "waiting_for_name", expire=60)
    await bot.reply("What is your name?")


@bot.on_update(filters.at_state(states, "waiting_for_name"))
async def receive_name(update):
    name = update.text
    await bot.reply(f"Nice to meet you, {name}!")
    await states.clear_state_for(update)


bot.run()

Webhook mode

Webhook mode uses FastAPI and Uvicorn. Install the optional dependencies first:

pip install "balthon[webhook]"

Then start the client with use_webhook=True:

from balthon import BotClient, filters

bot = BotClient("YOUR_BOT_TOKEN", use_webhook=True)

@bot.on_update(filters.text())
async def text_handler(update):
    await bot.reply(update.text)

bot.run(host="0.0.0.0", port=8000, webhook_path="/webhook")

Configure your Bale bot webhook to point to the publicly reachable endpoint for your server. Make sure your deployment, network, and webhook URL are configured appropriately.

Async applications

If your application already runs an asyncio event loop, use await bot.start() instead of bot.run():

import asyncio
from balthon import BotClient

bot = BotClient("YOUR_BOT_TOKEN")


async def main():
    await bot.start()


asyncio.run(main())

API overview

The package exports the main client as BotClient (also available as Client and BotConnect), along with:

  • filters and Filter
  • StateManager
  • Keyboard and button helpers
  • Update, message, user, chat, media, and payment models
  • Bale API response models
  • ActionsEnum
  • Balthon-specific exception classes

See the source code and exported names in balthon/__init__.py for the complete public API.

Error handling

Balthon defines exception classes for common client and API errors, including:

  • BalthonError
  • BaleError
  • APIError
  • NetworkError
  • InvalidTokenError
  • AuthenticationError
  • RateLimitError
  • InvalidRequestError
  • UpdateError
  • HandlerError
  • FilterError
  • StateError

You can import these directly from balthon:

from balthon import APIError, NetworkError

try:
    # Call a Balthon API method here.
    pass
except NetworkError as error:
    print(f"Network error: {error}")
except APIError as error:
    print(f"Bale API error: {error}")

License

This project is licensed under the MIT License. See LICENSE for details.

Metadata

Release files for balthon 0.1.1

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

Source distribution (sdist)

Source distribution for balthon 0.1.1
File Size Uploaded Provenance Actions
balthon-0.1.1.tar.gz 3.9 kB Without provenance Details for balthon-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for balthon 0.1.1
File Interpreter ABI Platform Actions
balthon-0.1.1-py3-none-any.whl Python 3 none any Details for balthon-0.1.1-py3-none-any.whl

Total release size: 7.3 kB

Release files / balthon-0.1.1.tar.gz

Download URL balthon-0.1.1.tar.gz
Size 3.9 kB
Tags Source
SHA-256 checksum
How to use checksums
150e8dbd7e38dc1edb9015e85a8d28642f1dae01affad2c5d2e8b93a1d821b57
BLAKE2b-256 checksum
How to use checksums
0d8acafe8db009e965e2da147cfc621853bc8a29de1dfc266d7233fcf43e3855
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / balthon-0.1.1-py3-none-any.whl

Download URL balthon-0.1.1-py3-none-any.whl
Size 3.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c66d5acc742525855c3590a8c4d57c48653c80ad7e594472bff1191bc9efe84
BLAKE2b-256 checksum
How to use checksums
5b08134d00245ec2a85eafaa6f650a911e942afe928d36dcaaf82b4d8577079e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for balthon 0.1.1

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.

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