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

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.2
File Size Uploaded Provenance Actions
balthon-0.1.2.tar.gz 24.3 kB Without provenance Details for balthon-0.1.2.tar.gz

Built distribution (wheel)

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

Total release size: 47.7 kB

Release files / balthon-0.1.2.tar.gz

Download URL balthon-0.1.2.tar.gz
Size 24.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c8d457901ec9e154aa47fbe03f63ea8a59dd9676074282853472e3b5374ea573
BLAKE2b-256 checksum
How to use checksums
6ffe406538390a7034c26ba8fd1ec2f96a9b9cf7213743b38aaa81ef5bc48be1
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.2-py3-none-any.whl

Download URL balthon-0.1.2-py3-none-any.whl
Size 23.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aa6d24c84283d0a6367ba566eebc3df1582eb39628ca9ddd83287068b21efb3a
BLAKE2b-256 checksum
How to use checksums
9af3ee3e5517506041cab9d416d229b4af6d570d40f0f000c7dbb8cb32523a74
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.2

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