Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Integraciones con Asterisk PBX

Integraciones con Asterisk PBX

En esta presentación podrás encontrar como integrar tus desarrollos con Asterisk PBX utilizando su API y AMI para realizar requests y consumir sus servicios.

Gabriel Covarrubias

June 21, 2017
Tweet

More Decks by Gabriel Covarrubias

Other Decks in Programming

Transcript

  1. Hola! Mi nombre es Gabriel Y soy un n00b en

    Python Empecé a migrar de PHP para evitar el bullying en redes sociales
  2. Esto no es un charla sobre Asterisk ◎ Les puedo

    compartir slides de una charla sobre Asterisk.
  3. Asterisk PBX - The Future of Telephony Asterisk es un

    servidor de telefonía que ejecuta las funciones de un conmutador tradicional. Es Software Libre…. YAY!!!!
  4. Conceptos Básicos Call Flow - El flujo de una llamada

    desde que se origina hasta que termina. Dialplan - Configuración mediante patrones para programar el “call flow”
  5. AGI - Asterisk Gateway Interface Un AGI es un script

    que puede ejecutarse en cualquier momento del Call Flow desde el dialplan. En estos casos Asterisk ejecuta el Script.
  6. AGI - Lista de funciones answer: Asserts answer asyncagi break:

    Break Async AGI loop channel status: Returns status of the connected channel control stream file: Send the given file, allowing playback to be controlled by the given digits, if any. exec: Executes a given get data: Gets data on a channel hangup: Hangup the current channel noop: Does nothing receive char: Receives one character from channels supporting it receive text: Receives text from channels supporting it record file: Records to a given file say alpha: Says a given character string say date: Say a date say datetime: Say a formatted date and time
  7. AGI - Lista de funciones set extension: Changes channel extension

    set music: Enable/Disable Music on hold generator, example "SET MUSIC ON default" set priority: Prioritizes the channel stream file: Sends audio file on channel verbose: Logs a message to the asterisk verbose log wait for digit: Waits for a digit to be pressed say digits: Says a given digit string say number: Says a given number say phonetic: Say the given character string. say time: Say a time send image: Sends images to channels supporting it send text: Sends text to channels supporting it set callerid: Sets callerid for the current channel set context: Sets channel context
  8. AGI - Ejemplo #!/usr/bin/env python import urllib2 import xml.etree.ElementTree as

    ET import sys from asterisk.agi import * agi = AGI() # for a complete list of US cities, go to # http://www.weather.gov/xml/current_obs/ weatherURL = [] weatherURL.append("http://w1.weather.gov/xml/current_ob s/KNYC.xml") #NYC weatherURL.append("http://w1.weather.gov/xml/current_ob s/KJFK.xml") #JFK weatherURL.append("http://w1.weather.gov/xml/current_ob s/KART.xml") #Watertown, NY weatherURL.append("http://w1.weather.gov/xml/current_ob s/KBGM.xml") #Binghamton
  9. AGI - Ejemplo while True: agi.stream_file('vm-extension') result = agi.wait_for_digit(-1) if

    result.isdigit(): request = urllib2.Request(weatherURL[int(result)], headers={"Accept" : "application/xml"}) xml = urllib2.urlopen(request) tree = ET.parse(xml) root = tree.getroot() temp_f = root.find('temp_f').text agi.say_number(temp_f) else: sys.exit()
  10. AMI - Asterisk Manager Interface Asterisk cuenta con un protocolo

    de red, que permite enviar y recibir instrucciones de administrador. En estos casos el Script se conecta con Asterisk
  11. AGI - Seguridad Siendo AMI un protocolo que permite ejecutar

    comandos de forma remota en Asterisk, la seguridad es un factor esencial /etc/asterisk/manager.conf [general] enabled = yes port = 5038 bindaddr = 127.0.0.1 debug = on [python] secret = PythonTijuana deny=0.0.0.0/0.0.0.0 permit=127.0.0.1/255.255.255.255 read = system,call,log,verbose,command,agent,user write = system,call,log,verbose,command,agent,user,originate
  12. AGI - Seguridad system - General information about the system

    and ability to run system management commands, such as Shutdown, Restart, and Reload. call - Information about channels and ability to set information in a running channel. log - Logging information. Read-only. verbose - Verbose information. Read-only. agent - Information about queues and agents and ability to add queue members to a queue. user - Permission to send and receive UserEvent. config - Ability to read and write configuration files. command - Permission to run CLI commands. Write-only. dtmf - Receive DTMF events. Read-only. reporting - Ability to get information about the system. cdr - Output of cdr_manager, if loaded. Read-only. dialplan - Receive NewExten and VarSet events. Read-only. originate - Permission to originate new calls. Write-only.
  13. import asterisk.manager import sys manager = asterisk.manager.Manager() try: try: manager.connect('localhost')

    manager.login('user', 'secret') response = manager.status() print(response) response = manager.command('core show channels concise') print(response.data) manager.logoff() except asterisk.manager.ManagerSocketException as e: print "Error connecting to the manager: %s" % e.strerror sys.exit(1) except asterisk.manager.ManagerAuthException as e: print "Error logging in to the manager: %s" % e.strerror sys.exit(1) except asterisk.manager.ManagerException as e: print "Error: %s" % e.strerror sys.exit(1) finally: manager.close() AMI - Ejemplo
  14. ARI - Asterisk REST Interface Esta última Interfaz es una

    fusión de AGI y AMI, pero a través de WebSockets con un API REST, disponible desde Asterisk 12.
  15. ARI - Configuraciones /etc/asterisk/http.conf [general] enabled = yes bindaddr =

    0.0.0.0 bindport=8080 /etc/asterisk/ari.conf [general] enabled = yes pretty = yes [asterisk] type = user read_only = no password = asterisk
  16. Call Files - Archivos de llamadas Está es la integración

    más “sencilla”, consiste en generar archivos con un formato definido, que después Asterisk utiliza para ejecutar sus instrucciones
  17. Call Files - Ejemplo from pycall import CallFile, Call, Application

    call = Call('SIP/flowroute/18882223333') action = Application('Playback', 'hello-world') c = CallFile(call, action) c.spool()
  18. “ Resumen AGI - Asterisk Ejecuta Python AMI - Python

    Ejecuta Asterisk ARI - Python Consume REST Call Files - Python crea archivos, Asterisk los ejecuta