Asterisk Manager API Python interface for programmatically controlling and monitoring Asterisk PBX systems
—
Comprehensive exception classes for different error conditions in Manager API communication, authentication, action execution, and configuration management.
class BaseException(Exception):
"""
Base class for all py-Asterisk exceptions.
Attributes:
_prefix: Error message prefix for this exception type
_error: Specific error message
"""
def __init__(error: str):
"""Initialize with specific error message."""
def __str__() -> str:
"""Return formatted error message: '{_prefix}: {_error}'"""class AuthenticationFailure(BaseException):
"""
Raised when authentication to the PBX instance fails.
Usually indicates incorrect username/password or insufficient privileges.
"""class CommunicationError(BaseException):
"""
Raised when the PBX responds in an unexpected manner.
Indicates protocol-level communication problems.
"""
def __init__(packet: dict, msg: str = None):
"""
Initialize with problematic packet and optional message.
Args:
packet: The Manager API packet that caused the error
msg: Additional error description
"""class GoneAwayError(BaseException):
"""
Raised when the Manager connection becomes closed unexpectedly.
Usually indicates network issues or Asterisk restart.
"""class ActionFailed(BaseException):
"""
Raised when a PBX action fails.
The Manager API returned an error response for the requested action.
"""
class PermissionDenied(BaseException):
"""
Raised when connection is not permitted to perform requested action.
User lacks necessary Manager API privileges.
"""class InternalError(BaseException):
"""
Raised when an error occurs within a Manager object.
Indicates a problem in the py-Asterisk library itself.
"""class ConfigurationError(BaseException):
"""
Raised when there is a problem with configuration.
Could be missing files, invalid format, or bad values.
"""class SubscriptionError(BaseException):
"""
Raised when attempt to register the same (event, handler) tuple twice.
Prevents duplicate event subscriptions.
"""
class ArgumentsError(BaseException):
"""
Raised for bad command-line arguments in CLI functions.
"""from Asterisk.Manager import Manager, AuthenticationFailure, CommunicationError
try:
manager = Manager(('127.0.0.1', 5038), 'baduser', 'wrongpass')
except AuthenticationFailure as e:
print(f"Login failed: {e}")
# Handle authentication error - check credentials
except CommunicationError as e:
print(f"Communication problem: {e}")
# Handle protocol errors - check Asterisk configurationfrom Asterisk.Manager import (
Manager, AuthenticationFailure, CommunicationError,
GoneAwayError, ActionFailed, PermissionDenied
)
def robust_manager_operation():
manager = None
try:
# Connect
manager = Manager(('127.0.0.1', 5038), 'admin', 'secret')
# Execute action
result = manager.ShowChannels()
return result
except AuthenticationFailure:
print("Authentication failed - check username/password")
return None
except PermissionDenied:
print("Permission denied - user needs 'call' privilege")
return None
except ActionFailed as e:
print(f"Action failed: {e}")
return None
except CommunicationError as e:
print(f"Communication error: {e}")
# Could retry with exponential backoff
return None
except GoneAwayError:
print("Connection lost - Asterisk may have restarted")
# Could attempt reconnection
return None
finally:
if manager:
try:
manager.Logoff()
except:
pass # Connection may already be deadfrom Asterisk.Manager import Manager, ActionFailed
manager = Manager(('127.0.0.1', 5038), 'admin', 'secret')
try:
# Try to hang up a channel
channel = manager.get_channel('SIP/1001-00000001')
channel.Hangup()
except ActionFailed as e:
if 'No such channel' in str(e):
print("Channel already hung up or doesn't exist")
else:
print(f"Hangup failed: {e}")from Asterisk.Config import Config, ConfigurationError
try:
config = Config('/etc/asterisk/py-asterisk.conf')
except ConfigurationError as e:
print(f"Configuration error: {e}")
# Fall back to default configuration or prompt user
config = Nonefrom Asterisk.Util import EventCollection, SubscriptionError
events = EventCollection()
def my_handler(event):
print(f"Got event: {event}")
try:
events.subscribe('Hangup', my_handler)
events.subscribe('Hangup', my_handler) # Duplicate!
except SubscriptionError as e:
print(f"Subscription error: {e}")
# Handler already subscribedfrom Asterisk.CLI import command_line, ArgumentsError
try:
command_line(['py-asterisk', 'action']) # Missing action name
except ArgumentsError as e:
print(f"Invalid arguments: {e}")
# Show usage informationCommunicationError: Protocol-level problemsGoneAwayError: Connection lostAuthenticationFailure: Login failedPermissionDenied: Insufficient Manager API privilegesActionFailed: Action not allowed or failedConfigurationError: Config file problemsArgumentsError: Bad CLI argumentsSubscriptionError: Duplicate event subscriptionsInternalError: Library bugs or unexpected statesInstall with Tessl CLI
npx tessl i tessl/pypi-py-asterisk