Python library to talk to Asterisk

Hi guys,

I want to do some functionalities such as call recording from a Python web app to asterisk server. Please what python library can I use with Asterisk to make this work.

Thanks

Try pyst2 https://pypi.python.org/pypi/pyst2/0.4
–Satish Barot

Thank you Satish, but the documentation I found for it is not well explanatory. How do I do the following

  1. Connect to my Asterisk server
  2. Get asterisk files and many more

try:

    manager.connect('hostnameaddress')
    manager.login('username', 'password')

       # register some callbacks
    manager.register_event('Shutdown', handle_shutdown) # shutdown
    manager.register_event('*', handle_event)           # catch all

       # get a status report
    response = manager.status()

    manager.logoff()
    return "Successful connection to the manager"
except asterisk.manager.ManagerSocketException, (errno, reason):

    return "Error connecting to the manager: %s" % reason
    
except asterisk.manager.ManagerAuthException, reason:

    return "Error logging in to the manager: %s" % reason
   
except asterisk.manager.ManagerException, reason:
    return "Error: %s" % reason

I get the following error response : “Error connecting to the manager: Connection refused”

Did you change the values in manager.connect and manager.login?
Do you have Asterisk running on specified hostnameaddress and listening on 5038(if you haven’t changed the default port)?

I would say for help on any further issues you should talk to the developer of this library.

–Satish Barot

The issue is probably your manager.conf settings…

[general]
enabled = yes 
port = 5038
bindaddr = 0.0.0.0
displayconnects = yes

[username]
secret=password
deny=0.0.0.0/0.0.0.0
permit=0.0.0.0/0.0.0.0 
read = system,call,log,verbose,command,agent,user,originate
write = system,call,log,verbose,command,agent,user,originate

Yes I have done that and it now connected, but the issue I have now is I can’t get active calls.

def handle_event(event, manager):
with ctx:

if event.name == 'CoreShowChannel':

    user_id = event.message['AccountCode']
    data = {
            'user_id': user_id,
            'caller_id': event.message['CallerIDnum'],
            'channel': event.message['Channel'],
            'duration': event.message['Duration'],
            'context': event.message['Context'],
            'extension': event.message['Extension'],
            'line': event.message['ConnectedLineNum'],
            'channel_state': event.message['ChannelStateDesc'],
            }
    user = System().getUserById(user_id)
    if user:
        data.update({
                'first_name': user['first_name'],
                'last_name': user['last_name']
                })
    g.channels.append(data)
if event.name == 'CoreShowChannelsComplete':
    g.complete = True

if event.name is None:
    data = {
        "connectivity":None,
        "event-name":None
    }
    g.channels.append(data)
    g.complete = True

@app.route(’/live-calls’)
def live_calls():

g.complete = False
g.channels = []
manager = asterisk.manager.Manager()

try:

    manager.connect('hostnameaddress')
    manager.login('username', 'password')
    manager.register_event('*', handle_event)
    res = manager.send_action({'Action':'CoreShowChannels'})
    while not g.complete:

        time.sleep(0.1)

    manager.close()
    return json.dumps(g.channels)


except asterisk.manager.ManagerSocketException, (errno, reason):

    return "Error connecting to the manager: %s" % reason

except asterisk.manager.ManagerAuthException, reason:

    return "Error logging in to the manager: %s" % reason

except asterisk.manager.ManagerException, reason:
    return "Error: %s" % reason

This program returns a 502 error bad gateway.

Thank you [poing]. The connection to the Asterisk server is now successful but I ran into another problem which is fetching the incoming calls data. I have the following function.
ctx = app.app_context()
ctx.push()

def handle_event(event, manager):

with ctx:

    if event.name == 'CoreShowChannel':


        user_id = event.message['accountcode']
        data = {
                'user_id': user_id,
                'caller_id': event.message['CallerIDnum'],
                'channel': event.message['Channel'],
                'duration': event.message['Duration'],
                'context': event.message['Context'],
                'extension': event.message['Extension'],
                'line': event.message['ConnectedLineNum'],
                #'channel_state': event.message['ChannelState'],
                'channel_state': event.message['ChannelStateDesc'],
                }
        user = System().getUserById(user_id)
        if user:
            profile = {
                        'first_name': user['first_name'],
                        'last_name': user['last_name']
                    }
           
        else:
            profile = {
                        'first_name': "No firstname",
                        'last_name': "No lastname"
                    }
        data.update(profile)   
        g.channels.append(data)
    if event.name == 'CoreShowChannelsComplete':
        g.complete = True

    if not event.name:
        data = {
            "connectivity":"Not connected",
            "event-name":"No event name"
        }
        g.channels.append(data)
        g.complete = True

But when I try getting incoming calls events after registering the handle_event method but I get an empty array

@app.route(’/incoming-calls’)
def incoming_calls():
/**** I have already login and connect *****/
g.channels = []
g.complete = False
manager.register_event(’*’, handle_event)
res = manager.send_action({‘Action’:‘CoreShowChannels’})

    try:

        while not g.complete:

            time.sleep(0.5)
        manager.close()
        return json.dumps(g.channels)

When I look carefully to it, I think the CoreShowChannel event is not working.