Long Distance or Local Python AGI

AGI/CGI Script for Asterisk to tell the difference between Long Distance and Local Calling


In this example I will give you a python script that you can put in your AGI folder for asterisk and execute from the
Dial Plan to tell if the number being dialed is long distance or not. Also I will give you an example of how the Dial Plan
might look if you want to use the information correctly. This AGI Logs into a webpage called localcallingguide.com and
checks to see if the first 6 digits being "dialed to" and the first six digits being "dialed from" equals a local call.

Before this script will work you must have the python binary in your environment's path in linux see line 1 in the python script

As well Please do not just paste this from windows thinking it will work. Line feeds from windows are different than linux and the first line that
executes Python for you will not work and cause you many hours of head scratching if you didn't already know that..

PYTHON SCRIPT
Save this Script to a file named /var/lib/asterisk/agi-bin/agi-pyld.agi

(UPDATE: The following has been modified from the original script to store the lookups already used in a local flat file)


#!/usr/bin/env python
import urllib,sys,re

def StripTags(text):
    finished = False
    while not finished:
        finished = True
        # check if there is an open tag left
        start = text.find("<")
        if start >= 0:
            # if there is, check if the tag gets closed
            stop = text[start:].find(">")
            if stop >= 0:
                # if it does, strip it, and continue loop
                text = text[:start] + text[start+stop+1:]
                finished = False
    return text

def readFile(filename,searchstring):
  try:
    df=open(filename,'r')
  except:
    df=open(filename,'w')
    df.close()
    df=open(filename,'r')
  for line in df:
    if line.startswith(searchstring):
      df.close()
      return line

def writeFile(filename,writestring):
  try:
    df=open(filename,'a')
  except:
    df=open(filename,'w')
  df.write(writestring+"\n")
  df.close()

localNum = sys.argv[1]
phoneNum = sys.argv[2]
printit=-1
res=readFile('/var/lib/asterisk/agi-bin/local_ld.dat',localNum[0:3]+localNum[3:6]+'|'+phoneNum[0:3]+phoneNum[3:6])
if res is not None:
  g=res.split("|")
  if g[2].replace('\n','')=="0":line="N"
  else:line="Y"
  printit=1
  print "SET VARIABLE LOCALCALL " + line + " \n"
else:
  sock = urllib.urlopen("http://www.localcallingguide.com/lca_rcdist.php?npa1=" + localNum[0:3] + "&nxx1=" + localNum[3:6] + "&npa2=" + phoneNum[0:3] + "&nxx2=" + phoneNum[3:6])
  htmlSource = sock.read()
  printit=-1
  startPos=5
  sock.close()
  for line in htmlSource.split("\n"):
  # print line
  found_string = line.find('Local call+')
  if found_string!=-1:
    printit=1
  if printit >=1:
    if startPos>= printit:
      line = line.replace('Local call+','')
      line = line.replace('&#039;',"'")
      line = line.replace('\n','  ')
      line = line.replace('\r','  ')
      line = StripTags(line)
      line = line.rstrip(' ')
      if line!="":
        print "SET VARIABLE LOCALCALL " + line + " \n"
        if line=="N":dbrec=0
        else:dbrec=1
        writeFile('/var/lib/asterisk/agi-bin/local_ld.dat',localNum[0:3]+localNum[3:6]+'|'+phoneNum[0:3]+phoneNum[3:6]+'|'+str(dbrec))
    printit-=1
if printit==-1: print "SET VARIABLE LOCALCALL E"


A couple of things about how the above code works. If this code cannot find the information that it should be getting it will return the letter "E" if it is a local call this code will return the letter "Y" and if it is a long distance call the code will return "N". These are then stored in asterisk as the variable LOCALCALL

"E" Error
"N" Not a local Call
"Y" Is a local Call

Here is a simple example of a dial plan that you may use with this AGI

We will say you have two SIP Trunks. And lets say you want to pass all your local calls through gatewayA and all your longdistance calls through sipA and
we will say your local number at this server is 9995551212

[globals]
LOCALNUMBER=9995551212
LOCALNAME=MyName
LOCALSIPTRUNK=gatewayA
LDSIPTRUNK=sipA

[outbound]
exten => _1NXXNXXXXXX, 1, AGI(agi-pyld.agi|${LOCALNUMBER}|${EXTEN:1})
exten => _1NXXNXXXXXX, 2, GotoIf($[["${LOCALCALL}" = "Y"]?107)
exten => _1NXXNXXXXXX, 3, Set(CALLERID(number)=${LOCALNUMBER})
exten => _1NXXNXXXXXX, 4, Set(CALLERID(name)=${LOCALNAME})
exten => _1NXXNXXXXXX, 5, Dial(SIP/${EXTEN}@${LDSIPTRUNK})
exten => _1NXXNXXXXXX, 6, Hangup()
exten => _1NXXNXXXXXX, 107, Set(CALLERID(number)=${LOCALNUMBER})
exten => _1NXXNXXXXXX, 108, Set(CALLERID(name)=${LOCALNAME})
exten => _1NXXNXXXXXX, 109, Dial(SIP/${EXTEN:1}@${LOCALSIPTRUNK})
exten => _1NXXNXXXXXX, 110, Hangup()

exten => _NXXNXXXXXX, 1, AGI(agi-pyld.agi|${LOCALNUMBER}|${EXTEN})
exten => _NXXNXXXXXX, 2, GotoIf($[["${LOCALCALL}" = "N"]?107)
exten => _NXXNXXXXXX, 3, Set(CALLERID(number)=${LOCALNUMBER})
exten => _NXXNXXXXXX, 4, Set(CALLERID(name)=${LOCALNAME})
exten => _NXXNXXXXXX, 5, Dial(SIP/${EXTEN}@${LOCALSIPTRUNK})
exten => _NXXNXXXXXX, 6, Hangup()
exten => _NXXNXXXXXX, 107, Set(CALLERID(number)=${LOCALNUMBER})
exten => _NXXNXXXXXX, 108, Set(CALLERID(name)=${LOCALNAME})
exten => _NXXNXXXXXX, 109, Dial(SIP/1${EXTEN}@${LDSIPTRUNK})
exten => _NXXNXXXXXX, 110, Hangup()

^

In the above Dial Plan it would not matter if the person dialed a 1 thinking it was long distance and it really wasn't or they didnt
dial a 1 thinking it was local. It would take the one off or add it as needed.

Please Note that if you do not change the LOCALNUMBER to a valid phone number this script will already return "E" for Error because 9995551212 could never exists

Thanks
you can email me at schapman1974@gmail.com if you have any questions.

15721 Views

See also

AGI/CGI Script for Asterisk to tell the difference between Long Distance and Local Calling


In this example I will give you a python script that you can put in your AGI folder for asterisk and execute from the
Dial Plan to tell if the number being dialed is long distance or not. Also I will give you an example of how the Dial Plan
might look if you want to use the information correctly. This AGI Logs into a webpage called localcallingguide.com and
checks to see if the first 6 digits being "dialed to" and the first six digits being "dialed from" equals a local call.

Before this script will work you must have the python binary in your environment's path in linux see line 1 in the python script

As well Please do not just paste this from windows thinking it will work. Line feeds from windows are different than linux and the first line that
executes Python for you will not work and cause you many hours of head scratching if you didn't already know that..

PYTHON SCRIPT
Save this Script to a file named /var/lib/asterisk/agi-bin/agi-pyld.agi

(UPDATE: The following has been modified from the original script to store the lookups already used in a local flat file)


#!/usr/bin/env python
import urllib,sys,re

def StripTags(text):
    finished = False
    while not finished:
        finished = True
        # check if there is an open tag left
        start = text.find("<")
        if start >= 0:
            # if there is, check if the tag gets closed
            stop = text[start:].find(">")
            if stop >= 0:
                # if it does, strip it, and continue loop
                text = text[:start] + text[start+stop+1:]
                finished = False
    return text

def readFile(filename,searchstring):
  try:
    df=open(filename,'r')
  except:
    df=open(filename,'w')
    df.close()
    df=open(filename,'r')
  for line in df:
    if line.startswith(searchstring):
      df.close()
      return line

def writeFile(filename,writestring):
  try:
    df=open(filename,'a')
  except:
    df=open(filename,'w')
  df.write(writestring+"\n")
  df.close()

localNum = sys.argv[1]
phoneNum = sys.argv[2]
printit=-1
res=readFile('/var/lib/asterisk/agi-bin/local_ld.dat',localNum[0:3]+localNum[3:6]+'|'+phoneNum[0:3]+phoneNum[3:6])
if res is not None:
  g=res.split("|")
  if g[2].replace('\n','')=="0":line="N"
  else:line="Y"
  printit=1
  print "SET VARIABLE LOCALCALL " + line + " \n"
else:
  sock = urllib.urlopen("http://www.localcallingguide.com/lca_rcdist.php?npa1=" + localNum[0:3] + "&nxx1=" + localNum[3:6] + "&npa2=" + phoneNum[0:3] + "&nxx2=" + phoneNum[3:6])
  htmlSource = sock.read()
  printit=-1
  startPos=5
  sock.close()
  for line in htmlSource.split("\n"):
  # print line
  found_string = line.find('Local call+')
  if found_string!=-1:
    printit=1
  if printit >=1:
    if startPos>= printit:
      line = line.replace('Local call+','')
      line = line.replace('&#039;',"'")
      line = line.replace('\n','  ')
      line = line.replace('\r','  ')
      line = StripTags(line)
      line = line.rstrip(' ')
      if line!="":
        print "SET VARIABLE LOCALCALL " + line + " \n"
        if line=="N":dbrec=0
        else:dbrec=1
        writeFile('/var/lib/asterisk/agi-bin/local_ld.dat',localNum[0:3]+localNum[3:6]+'|'+phoneNum[0:3]+phoneNum[3:6]+'|'+str(dbrec))
    printit-=1
if printit==-1: print "SET VARIABLE LOCALCALL E"


A couple of things about how the above code works. If this code cannot find the information that it should be getting it will return the letter "E" if it is a local call this code will return the letter "Y" and if it is a long distance call the code will return "N". These are then stored in asterisk as the variable LOCALCALL

"E" Error
"N" Not a local Call
"Y" Is a local Call

Here is a simple example of a dial plan that you may use with this AGI

We will say you have two SIP Trunks. And lets say you want to pass all your local calls through gatewayA and all your longdistance calls through sipA and
we will say your local number at this server is 9995551212

[globals]
LOCALNUMBER=9995551212
LOCALNAME=MyName
LOCALSIPTRUNK=gatewayA
LDSIPTRUNK=sipA

[outbound]
exten => _1NXXNXXXXXX, 1, AGI(agi-pyld.agi|${LOCALNUMBER}|${EXTEN:1})
exten => _1NXXNXXXXXX, 2, GotoIf($[["${LOCALCALL}" = "Y"]?107)
exten => _1NXXNXXXXXX, 3, Set(CALLERID(number)=${LOCALNUMBER})
exten => _1NXXNXXXXXX, 4, Set(CALLERID(name)=${LOCALNAME})
exten => _1NXXNXXXXXX, 5, Dial(SIP/${EXTEN}@${LDSIPTRUNK})
exten => _1NXXNXXXXXX, 6, Hangup()
exten => _1NXXNXXXXXX, 107, Set(CALLERID(number)=${LOCALNUMBER})
exten => _1NXXNXXXXXX, 108, Set(CALLERID(name)=${LOCALNAME})
exten => _1NXXNXXXXXX, 109, Dial(SIP/${EXTEN:1}@${LOCALSIPTRUNK})
exten => _1NXXNXXXXXX, 110, Hangup()

exten => _NXXNXXXXXX, 1, AGI(agi-pyld.agi|${LOCALNUMBER}|${EXTEN})
exten => _NXXNXXXXXX, 2, GotoIf($[["${LOCALCALL}" = "N"]?107)
exten => _NXXNXXXXXX, 3, Set(CALLERID(number)=${LOCALNUMBER})
exten => _NXXNXXXXXX, 4, Set(CALLERID(name)=${LOCALNAME})
exten => _NXXNXXXXXX, 5, Dial(SIP/${EXTEN}@${LOCALSIPTRUNK})
exten => _NXXNXXXXXX, 6, Hangup()
exten => _NXXNXXXXXX, 107, Set(CALLERID(number)=${LOCALNUMBER})
exten => _NXXNXXXXXX, 108, Set(CALLERID(name)=${LOCALNAME})
exten => _NXXNXXXXXX, 109, Dial(SIP/1${EXTEN}@${LDSIPTRUNK})
exten => _NXXNXXXXXX, 110, Hangup()

^

In the above Dial Plan it would not matter if the person dialed a 1 thinking it was long distance and it really wasn't or they didnt
dial a 1 thinking it was local. It would take the one off or add it as needed.

Please Note that if you do not change the LOCALNUMBER to a valid phone number this script will already return "E" for Error because 9995551212 could never exists

Thanks
you can email me at schapman1974@gmail.com if you have any questions.

15721 Views

See also

Created by: schapman, Last modification: Thu 06 of Sep, 2012 (00:34 UTC) by admin
Please update this page with new information, just login and click on the "Edit" or "Discussion" tab. Get a free login here: Register Thanks! - Find us on Google+