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: object

The main Astra Client.

Handles the browser engine, protocol bridge, and event system to provide a high-level API for WhatsApp automation.

Parameters:
  • session_id (str)

  • phone (str | None)

  • headless (bool)

  • log_level (int)

  • show_banner (bool)

  • use_cache (bool)

__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 is_connected: 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 send_video(chat_id, file_path, **kwargs)[source]

Sends a video file with document fallback.

Parameters:
  • chat_id (str)

  • file_path (str)

Return type:

Message

async send_audio(chat_id, file_path, **kwargs)[source]

Sends an audio file with document fallback.

Parameters:
  • chat_id (str)

  • file_path (str)

Return type:

Message

async delete_message(chat_id, message_id, everyone=True)[source]

Shortcut for client.chat.delete_message.

Parameters:
Return type:

bool

async send_file(*args, **kwargs)[source]

Backward compatibility alias for client.media.send_file.

Return type:

bool

async download_media(*args, **kwargs)[source]

Shortcut for client.media.download_media.

Return type:

str

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 stop()[source]

Gracefully shuts down the client and releases all resources.

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:

bool

async logout()[source]

Logs out the current session and clears storage.

Return type:

bool

async scan_dom(section='chats')[source]

Performs a deep DOM scan of a specific section (e.g., ‘chats’, ‘settings’).

Parameters:

section (str)

Return type:

list

async generate_report(section='chats')[source]

Generates a detailed text report of stable selectors in a section.

Parameters:

section (str)

Return type:

str

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

async react(chat_id, message_id, emoji)[source]

Adds a reaction emoji to a message.

Parameters:
Return type:

bool

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!")
Parameters:
  • event (str)

  • criteria (Any | None)

async wait_for(event, criteria=None, timeout=None)[source]

Waits for a specific event to occur.

Parameters:
  • event (str)

  • criteria (Any | None)

  • timeout (float | None)

Return type:

Any

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)

on_ready(func)[source]

Decorator for the ‘ready’ event.

Parameters:

func (Callable)

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

async get_me()[source]
Return type:

User

conversation(chat_id, timeout=60.0)[source]

Creates a stateful conversation context for interactive flows.

Parameters:
Return type:

Conversation

async fetch_messages(chat_id, **kwargs)[source]

Shortcut for client.chat.fetch_messages. Fetches messages from a chat with advanced filters.

Parameters:

chat_id (str)

Return type:

List[Message]

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:

dict

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.

Parameters:

root (str | Path) – The root directory containing plugin files.

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

get_session_info()[source]

Returns current session metadata.

Return type:

dict

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}!”)

Parameters:
async send_message(text, **kwargs)[source]

Sends a message to the current conversation chat.

Parameters:

text (str)

Return type:

Message

async get_response(timeout=None)[source]

Waits for a response message in the conversation. Skips the message if it was sent by the bot (e.g. the prompt).

Parameters:

timeout (float | None)

Return type:

Message

async ask(text, timeout=None, **kwargs)[source]

Helper to send a message and immediately wait for a response.

Parameters:
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 use run_forever() for a simple blocking loop.

  • Handler functions should be async def unless 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):
 ...