Client (astra.client)
Overview
Client is the main entrypoint for Astra. It manages lifecycle, session persistence, the bridge to WhatsApp Web, and exposes mixin-based behavioral APIs (chat, group, media, account).
- class Client(session_id='default', phone=None, headless=True, log_level=20, show_banner=True, use_cache=True)[source]
Bases:
objectThe main Astra Client.
Handles the browser engine, protocol bridge, and event system to provide a high-level API for WhatsApp automation.
- Parameters:
- __init__(session_id='default', phone=None, headless=True, log_level=20, show_banner=True, use_cache=True)[source]
Initialize the Astra Client.
- Parameters:
session_id (str) – A unique identifier for the session (affects profile caching).
phone (str | None) – The WhatsApp phone number (e.g., “919876543210”).
headless (bool) – If True, runs the browser without a visual window.
log_level (int) – Sensitivity of the internal logger.
show_banner (bool) – Whether to print the Astra banner on startup.
use_cache (bool)
- property newfn: ChatMethods
Compatibility alias for the functional core (now directed to ChatMethods).
- async send_media(*args, **kwargs)[source]
Shortcut for client.chat.send_media.
- Return type:
Message
- async send_photo(*args, **kwargs)[source]
Shortcut for client.media.send_photo.
- Return type:
Message
- async send_sticker(*args, **kwargs)[source]
Shortcut for client.media.send_sticker.
- Return type:
Message
- async send_document(*args, **kwargs)[source]
Shortcut for client.media.send_document.
- Return type:
Message
- async delete_message(chat_id, message_id, everyone=True)[source]
Shortcut for client.chat.delete_message.
- async send_file(*args, **kwargs)[source]
Backward compatibility alias for client.media.send_file.
- Return type:
- async download_media(*args, **kwargs)[source]
Shortcut for client.media.download_media.
- Return type:
- async get_contact(contact_id)[source]
Shortcut for client.api.get_contact.
- Parameters:
contact_id (str)
- Return type:
User
- async start()[source]
Launches Astra and establishes a connection to WhatsApp.
This method is asynchronous and will wait until the client is fully authenticated and ready to receive events.
- async restart()[source]
# Restart engine. Cleans up browser, processes, and locks before starting fresh.
- async run_forever()[source]
# Blocking loop. Keeps the client alive and handles auto-restarts indefinitely.
- async sync()[source]
Manually triggers a bridge-level data synchronization. Also resets the sync engine stall timer.
- Return type:
- async scan_dom(section='chats')[source]
Performs a deep DOM scan of a specific section (e.g., ‘chats’, ‘settings’).
- async generate_report(section='chats')[source]
Generates a detailed text report of stable selectors in a section.
- async send_message(to, text, reply_to=None, **kwargs)[source]
Sends a text message to a chat.
- Parameters:
to (str) – The recipient’s JID (e.g. ‘12345@c.us’).
text (str) – The message content.
reply_to (str | None) – Optional message ID to quote.
**kwargs – Additional options like ‘mentions’.
- Return type:
Message
- on(event, criteria=None)[source]
Decorator to register an event handler.
Example:
@client.on("message", Filters.text_contains("hi")) async def on_hi(msg): await msg.reply("Hello!")
- on_message(criteria=None)[source]
Decorator for handling new messages. Supports both instance (@client.on_message) and class (@Client.on_message).
- Parameters:
criteria (Any | None)
- on_reaction(criteria=None)[source]
Decorator for handling reactions. Supports both instance (@client.on_reaction) and class (@Client.on_reaction).
- Parameters:
criteria (Any | None)
- async get_entity(jid)[source]
Resolves a JID into a hydrated Chat or User object. Supported by a local cache to minimize bridge overhead.
- Parameters:
jid (str | JID)
- Return type:
Chat | User
- conversation(chat_id, timeout=60.0)[source]
Creates a stateful conversation context for interactive flows.
- Parameters:
- Return type:
- async fetch_messages(chat_id, **kwargs)[source]
Shortcut for client.chat.fetch_messages. Fetches messages from a chat with advanced filters.
- async export_session()[source]
Exports the current session state (cookies + localStorage). Can be used to migrate the session to another instance or server.
- Return type:
- async import_session(state)[source]
Imports a previously exported session state. This should be called BEFORE calling client.start().
- Parameters:
state (dict)
- load_plugins(root)[source]
Recursively loads event handlers from a directory.
Handlers in the target directory should use the @Client.on_… decorators (if implemented) or be registered via other mechanisms.
- async run_until_disconnected()[source]
Starts the client and blocks until the connection is lost or the process is terminated.
- run_forever_sync()[source]
Main blocking entry point. Runs the client until the event loop is stopped or an unrecoverable error occurs.
- Environment Variables:
TRACE_ERROR (bool): If true, prints full Python stack traces on failure. Defaults to False (shows clean error + hint).
- property cache: SessionStore
Direct access to the local SQLite cache.
Conversation helper
- class Conversation(client, chat_id, timeout=120.0)[source]
Conversation manager.
Provides an imperative interface for interactive message flows.
Example
- async with client.conversation(chat_id) as conv:
await conv.send_message(“What’s your name?”) name_msg = await conv.get_response() await conv.send_message(f”Hello, {name_msg.text}!”)
- async send_message(text, **kwargs)[source]
Sends a message to the current conversation chat.
- Parameters:
text (str)
- Return type:
Message
Quick usage example
from astra import Client, Filters
client = Client(session_id="bot-01")
@client.on("message", Filters.command("hello"))
async def hello(ctx):
await ctx.reply("Hi — I'm Astra")
Notes on async/await
start/stop/ engine calls are asynchronous — call them from an async context or userun_forever()for a simple blocking loop.Handler functions should be
async defunless performing trivial sync work.
Advanced snippet: waiting for a result
Sometimes you need to wait for a particular event outside of a handler. Use
client.wait_for combined with filters:
async def wait_for_reply(client):
# send a message and wait for the first reply in the same chat
sent = await client.chat.send_message(jid, "what's up?")
reply = await client.wait_for(
"message",
criteria=(Filters.reply & Filters.chat_id(jid)),
timeout=30,
)
return reply
Decorator shorthands
Client offers convenience decorators for common events, e.g. on_message
on_reaction and on_ready; they can be used at the class level to
register global handlers in plugin modules.
from astra import Client
@Client.on_message(Filters.command(".announce"))
async def announce(msg):
...