Hello, I’m trying to originate a call with AMI and catch Hangup event for this call using python with the asterisk-ami module.
I wrote a script on python that makes call and listen events.
Making a call works totally fine but listening is working from time to time.
Sometimes it catches events, sometimes not.
Maybe I’m missing something.
There is my script.
Asterisk 20.4.0
import sys
from asterisk.ami import AMIClient, SimpleAction, EventListener
import argparse
import time
import re
import jsonclient = AMIClient(address=“127.0.0.1”, port=5038)
result = {}parser = argparse.ArgumentParser(description=‘Args for call to gate’)
parser.add_argument(‘-ch’,‘–channel’, help=‘specify channel to call througth.’, required=True)
parser.add_argument(‘-n’,‘–number’, help=‘specify number to call to.’, required=True)def event_listener(event,**kwargs):
result[“event_result”] = event.keys
if event.keys[‘ChannelStateDesc’] == ‘Ringing’:
result[‘status’] = “OK”
else:
result[‘status’] = “ERROR”def make_call(channel, number, client):
try:
client.login(username=“myUser”, secret=“123”)
action = SimpleAction(
“Originate”,
Channel=f’SIP/{channel}/8{number}',
Application=‘Hangup’,
CallerID=‘My_Gate_Calling’,
Timeout=10000
)
future = client.send_action(action)
response = future.response
if response:
result[“command_response”] = response.keys[“Message”]
if result[“command_response”] == “Originate failed”:
result[“status”] = “ERROR”
except Exception as e:
result[“Exception”] = efinally:
client.logoff()
client.disconnect()def start_listen_events(client):
try:
client.login(username=“myUser”, secret=“123”)client.add_event_listener(
on_Hangup=event_listener,
white_list=re.compile(‘.*’),
CallerIDName=re.compile(‘My_Gate_Calling’),
)
timeout = 0;
while True:
time.sleep(1)
if ‘status’ in result or timeout == 20:
if timeout == 20:
result[“status”] = “NoEvent”
break
timeout += 1except Exception as e:
result[“Exception”] = e
finally:
client.logoff()
client.disconnect()if name == ‘main’:
args = vars(parser.parse_args())
channel = args[‘channel’]
number = args[‘number’]
result[‘input’] = {}
result[‘input’][“channel”] = f’{channel}’
result[‘input’][“number”] = f’{number}’
make_call(channel, number, client)
start_listen_events(client)
print(result)