Actual hangup call event with AMI (python)

Hi guys!

I would like to make python script to handle AMI hangup (terminated call) event.

Script receives arguments:

–callerid ( Callerid(num) )
–masterchannel ( Uniqueid generated in very first call )
Script is started and handling events.
I need to do some action like rabbitMQ queue charge when this particular call is actually terminated (regardless of the reason)

I will mention that dialplan has some custom destination, queues and others.
Now script does work great when i terminate call relatively short time after its start. The deeper into the dialplan, the longer the ami returns the termination event.

Strategy i adopted is to define handle_event function to check if Hangup event occured with callerid and uniquid (linkedID).
Is any better way to handle actual hangup channel? 30 second from terminated call to handle event is not acceptable for this project :upside_down_face:

My script:

#!/usr/bin/env python3

import asterisk.manager
import argparse
import os
import threading
#import time

def handle_event(event, manager):
    if == 'Hangup' and callerid in event.headers.get('CallerIDNum', '') and masterchannel in event.headers.get('Uniqueid', ''):
# here do somethink else...
        # Exit from program

# Parse input arguments
parser = argparse.ArgumentParser(description='Monitor a call with specified callerid and masterchannel.')
parser.add_argument('--callerid', help='The callerid of the call to monitor.', required=True)
parser.add_argument('--masterchannel', help='The masterchannel of the call to monitor.', required=True)
args = parser.parse_args()
callerid = args.callerid
masterchannel = args.masterchannel

manager = asterisk.manager.Manager()

    # Connect to the manager
    # Log in
    manager.login('python', 'password')
    print("Logged in successfully")

    # Register a callback for the hangup event
    manager.register_event('Hangup', handle_event)

    # Wait forever for events to come in
    while True:
        # This loop will block, so you might want to run it in a separate thread
except asterisk.manager.ManagerSocketException as e:
    print("An error occurred: %s" % e.strerror)
except asterisk.manager.ManagerAuthException as e:
    print("An error occurred: %s" % e.strerror)
except asterisk.manager.ManagerException as e:
    print("An error occurred: %s" % e.strerror)
    # Remember to always log out and close the connection when finished

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.