Wednesday, July 15, 2009

Asterisk Manager Interface to Python

I was thinking bit strange about python String Handling and doing advanced operations. It is very hunger for strings and handle things in a neat way.

Eventhough there are python libraries available for Asterisk. Handling it in our code natively gives us more comfort.

Below is the code connects to AMI (Asterisk Manager Interface) and prints all the events which it receives from asterisk.

#!/usr/bin/env python

import socket
import sys


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1",5038))
s.settimeout(.5)
file = s.makefile("rw",8096)
file.write("Action: Login\r\nUsername: username\r\nSecret: secret\r\nEvents: On\r\n\r\n")
file.flush()
print "Starting to Receive ...\n"
AVDict = {}

while 1:
try:
data = file.readline()
results = data.strip().split(": ")

try:
AVDict[results[0]].append(results[1])
except KeyError:
AVDict[results[0]] = results[1];
except AttributeError:
continue;
except:
print "[1001] ", sys.exc_info()[0]

except IndexError:
try:
print "AVDict is:", AVDict
AVDict.clear()
continue
except:
try:
del AVDict[:]
except TypeError:
continue;
except:
print "[1003] ", sys.exc_info()[0]
continue;
except:
#print "[1004] ", sys.exc_info()[0]
continue;

file.close()




Enjoy !