Asterisk Management Interface (AMI)

The AMI interface consists primarily of a number of action classes that are sent to Asterisk to ellicit responses. Additionally, a number of event classes are defined to provide convenience processing on the various messages Asterisk generates.

All of these concepts are bound together by the ami.Manager class, which provides facilities for sending actions and serving callback handlers when events are received.


All of the following objects should be accessed as part of the ami namespace, regardless of the modules in which they are defined.


Aside, perhaps, from the “GENERIC” values, to be matched against responses, these constants are largely unnecessary outside of internal module usage, but they’re exposed for convenience’s sake.


A header-value provided as a surrogate for unidentifiable responses


A header-value provided as a surrogate for unidentifiable unsolicited events


The header key used to identify an action being requested of Asterisk


The header key used to hold the ActionID of a request, for matching with responses


The header key used to hold the event-name of a response


The header key used to hold the event-name of a request


class ami.Manager(debug=False, logger=None, aggregate_timeout=5, orphaned_response_timeout=5)

Release all resources associated with this manager and ensure that all threads have stopped.

This function is automatically invoked when garbage-collected.

connect(host, port=5038, timeout=5)

Establishes a connection to the specified Asterisk manager, closing any existing connection first.

timeout specifies the number of seconds to allow Asterisk to go between producing lines of a response; it differs from the timeout that may be set on individual requests and exists primarily to avoid having a thread stay active forever, to allow for clean shutdowns.

If the connection fails, ManagerSocketError is raised.


Gracefully closes a connection to the Asterisk manager.

If not connected, this is a no-op.


Provides the name and version of Asterisk as a tuple of strings.

If not connected, None is returned.


Returns the current _SynchronisedSocket in use by the active connection, or None if no manager is attached.

This function is exposed for debugging purposes and should not be used by normal applications that do not have very special reasons for interacting with Asterisk directly.


Indicates whether the manager is connected.


Spawns a thread that watches the AMI connection to indicate a disruption when the connection goes down.

interval is the number of seconds to wait between automated Pings to see if Asterisk is still alive; defaults to 2.5.

register_callback(event, function)

Registers a callback for an Asterisk event identified by event, which may be a string for exact matches or a reference to the specific event class.

function is the callable to be invoked whenever a matching _Event is emitted; it must accept the positional arguments “event” and “manager”, with “event” being the _Event object and “manager” being a reference to generating instance of this class.

Registering the same function twice for the same event will unset the first callback, placing the new one at the end of the list.

Registering against the special event None will cause the given function to receive all responses not associated with a request, which normally shouldn’t exist, but may be observed in practice. Events will not be included.

Registering against the empty string will cause the given function to receive every event, suitable for logging purposes.

Callbacks are executed in the order in which they were registered.

send_action(request, action_id=None, **kwargs)

Sends a command, contained in request, a _Request, to the Asterisk manager, referred to interchangeably as “actions”. Any additional keyword arguments are added directly into the request command as though they were native headers, though the original object is unaffected.

action_id is an optional Asterisk ActionID to use; if unspecified, whatever is in the request, keyed at ‘ActionID’, is used with the output of id_generator being a fallback.

Asterisk’s response is returned as a named tuple of the following form, or None if the request timed out:

  • result: The processed response from Asterisk, nominally the same as response; see the specific _Request subclass for details in case it provides additional processing
  • response: The formatted, but unprocessed, response from Asterisk
  • request: The _Request object supplied when the request was placed; not a copy of the original
  • action_id: The ‘ActionID’ sent with this request
  • success: A boolean value indicating whether the request was met with success
  • time: The number of seconds, as a float, that the request took to be serviced
  • events: A dictionary containing related events if the request is synchronous or None otherwise
  • events_timeout: Whether the request timed out while waiting for events

For forward-compatibility reasons, elements of the tuple should be accessed by name, rather than by index.

Raises ManagerError if the manager is not connected.

Raises ManagerSocketError if the socket is broken during transmission.

This function is thread-safe.

unregister_callback(event, function)

Unregisters a previously bound callback.

A boolean value is returned, indicating whether anything was removed.

Internal classes

The following classes are not meant to be worked with directly, but are important for other parts of the system, with members that are worth knowing about.

class ami.ami._MessageTemplate

An abstract base-class for all message-types, including aggregates.


The Asterisk Action-ID associated with this message, or None if undefined, as is the case with unsolicited events.

class ami.ami._Aggregate(action_id)

Bases: ami.ami._MessageTemplate, dict

Provides, as a dictionary, access to all events that make up the aggregation, keyed by event-class. Repeatable event-types are exposed as lists, while others are direct references to the event itself.


Indicates whether the aggregate is consistent with Asterisk’s protocol.


If valid is False, this will offer a string explaining why validation failed.

class ami.ami._Event(response)

Bases: ami.ami._Message

The base-class of any event received from Asterisk, either unsolicited or as part of an extended response-chain.


Provides a tuple containing a copy of all headers as a dictionary and a copy of all response lines. The value of this data is negligible, but subclasses may apply further processing, replacing the values of headers with Python types or making the data easier to work with.

class ami.ami._Message(response)

Bases: ami.ami._MessageTemplate, dict

The common base-class for both replies and events, this is any structured response received from Asterisk.

All message headers are exposed as dictionary items on this object directly.


A series of lines containing the message’s payload from Asterisk.


A reference to a dictionary containing all headers associated with this message. Simply treating the message itself as a dictionary for headers is preferred, however; the two methods are equivalent.


The raw response from Asterisk as a series of lines, provided for applications that need access to the original data.

class ami.ami._Request(action)

Provides a generic container for assembling AMI requests, the basis of all actions.

Subclasses may override __init__ and define any additional behaviours they may need, as well as override process_response() to specially format the data to be returned after a request has been served.


If True (False by default), an aggregate-event will be generated after the list of independent events generated by this request.

This only has an effect with requests that generate lists of events to begin with and will be ignored in other cases.


If True (False by default), any events generated by this request will be collected and returned in the response.

Synchronous requests will suppress generation of associated asynchronous events and aggregates.


The number of seconds to wait before considering this request timed out, defaulting to 5; may be a float.

Indefinite waiting is not supported, but arbitrarily large values may be provided.

A request that has timed out may still be serviced by Asterisk, with the notification being treated as an orphaned event.

Changing the timeout value of the request object has no effect on any previously-sent instances of the request object, since the value is copied at dispatch-time.

class ami.ami._Response

The action-ID associated with the request that led to the creation of this response.


If the corresponding request was synchronous, this is a dictionary containing any events emitted in response. If not, this is None.

The dictionary will contain references to either the events themselves or lists of events, depending on what is appropriate, keyed by the event’s class-object and its friendly name as a string, like pystrix.ami.core_events.CoreShowChannels and “CoreShowChannels”.


A boolean value indicating whether any events were still unreceived when the response was returned. This is meaningful only if the reqyest had synchronous set.


The response from Asterisk, without any post-processing applied. You will generally want to use result instead, unless you need to see exactly what Asterisk returned.


The request object that led to this response. This will be None if the response is an orhpan, which may happen when a request times out, but a response is generated anyway, if multiple AMI clients are working with the same Asterisk instance (they won’t know each other’s action-IDs), or when working with buggy or experimental versions of Asterisk.


The response from Asterisk, with post-processing applied to make it easier to work with in Python. This is the attribute about which you will likely care most.


A boolean value that indicates whether the response appears to indicate that the request succeeded.


The amount of time, as a UNIX timestamp, that elapsed while waiting for a response.


exception ami.Error

Bases: exceptions.Exception

The base exception from which all errors native to this module inherit.

exception ami.ManagerError

Bases: pystrix.ami.ami.Error

Represents a generic error involving the Asterisk manager.

exception ami.ManagerSocketError

Bases: pystrix.ami.ami.Error

Represents a generic error involving the Asterisk connection.