def run(client): action = SimpleAction( 'PJSIPShowEndpoints' ) client.send_action(action) action = SimpleAction( 'CoreShowChannels' ) client.send_action(action)
def test_with_variable(self): expected = '\r\n'.join([ 'Action: GetVar', 'Channel: channel-1', 'Variable: <Variable 1>=<Value 1>', ]) + '\r\n' action = SimpleAction('GetVar', Channel='channel-1') action['<Variable 1>'] = '<Value 1>' self.compare_actions(action, expected) self.assertEqual(action.Channel, 'channel-1') self.assertEqual(action['<Variable 1>'], '<Value 1>') action.Channel = 'channel-2' self.assertEqual(action.Channel, 'channel-2')
def run_call(ext, to): sip = 'SIP/{}'.format(ext) tel = '9{}'.format(to) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3) ats1 = 'f1.ats.com' ats2 = 'f2.ats.com' host = ats1 try: sock.connect((ats1, 5038)) except socket.error: host = ats2 sock.close() client = AMIClient(address=host, port=5038) client.login(username='******', secret='pass') action = SimpleAction( 'Originate', Channel=sip, Exten=tel, Priority=1, Context='from-internal', CallerID='crmdancer', ) client.send_action(action, callback=None) client.logoff()
def sendaction_cid(self, cid): action = SimpleAction('DBGet', Family=self.config['asterisk']['dbname'], Key=cid) future = self.client.send_action(action) if future.response.status == 'Success': while self.cid_response is None: time.sleep(0.001) self.logout()
def connect_client(self, client, context, extension, uri): match = re.match("(.*?):(.*)$", uri) if match: scheme = match.group(1) uri = match.group(2) if scheme == "sip": scheme = "SIP" elif scheme == "iax": scheme = "IAX" channel = ("%s/%s" % (scheme, uri)) self.logger.info("Connecting to %s (%s)" % (client, channel)) action = SimpleAction( 'Originate', Channel=channel, Exten=extension, Priority=1, Context=context, CallerID='AutoDialler', ) try: self.ami_client.send_action(action) except Exception as e: error = self.handle_ami_exception(e) self.logger.info("Unable to connect to %s: %s" % (client, error))
def Listen(request, num): print(request.user.aduser.telephoneNumber) PBXClient = AMIClient(address=settings.JSON_SETTINGS['asteriskServer'], port=5038) PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'], secret=settings.JSON_SETTINGS['AMIPassword']) print(PBXClient) action = SimpleAction( 'Originate', Channel=('SIP/%s' % request.user.aduser.telephoneNumber), CallerID=('Spy%s' % num), #Exten = '6670', #Application = 'Playback', Application='ChanSpy', #Data = '/var/spool/asterisk/monitor/2017/10/03/out-1694-6666-20171003-103712-1507016232.189', Data=('SIP/%s,qx' % num), Timeout='30000', #Priority = '1', #Async = 'yes' ) print(action) ans = PBXClient.send_action(action) print(ans.response) PBXClient.logoff() return HttpResponse(ans.response)
def call_initiation(transaction_id, mobile_no, product_type, prefix, context="0009"): try: client = AMIClient(address='10.101.1.184', port=5038) client.login(username='******', secret='gihosp123') action = SimpleAction('Originate', Channel="local/" + "6" + mobile_no + "@from-internal", Context="GIVoice", Exten=context, Priority=1, Account=product_type, CallerID=transaction_id, Async="yes", Timeout=50000) future = client.send_action(action) response = future.response update_channel_detail_call_initiated() return True except Exception as ex: raise Exception( "SIP server is down .. please check eject error {}".format( str(ex))) return True
def _send_originate_context(self, channel, context, extension, priority, callerid, timeout=60, variables=""): action = SimpleAction('Originate', Channel=channel, Exten=extension, Priority=priority, Context=context, CallerID=callerid, Timeout=timeout * 1000, Variable=variables, Async="true") try: self.__ami_client.send_action(action) return True except Exception as e: error = self._handle_ami_exception(e) print("Unable to connect to %s: %s" % (channel, error)) return False
def worker_loop(self): print("Asterisk logging Started!") i = 299 # force to save the first while (self.checking_status): action = SimpleAction('CoreStatus') self.client.send_action(action, callback=self.callback_response_status) action = SimpleAction('CoreSettings') self.client.send_action(action, callback=self.callback_response_settings) action = SimpleAction('SIPshowregistry') self.client.send_action(action) time.sleep(0.5) action = SimpleAction('ExtensionStateList') self.client.send_action(action) time.sleep(0.5)
def get_channels(self): command = ("core show channels concise") action = SimpleAction('Command', Command=command) try: future = self.ami_client.send_action(action) response = future.response.follows chan_len = len(response) - 1 response = response[:chan_len] self.channels = [] for channel in response: match = re.match( "((.*?)\/.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)$", channel) if match: chan_type = match.group(2) chan = match.group(1) context = match.group(3) extension = match.group(4) priority = match.group(5) state = match.group(6) app = match.group(7) data = match.group(8) clid = match.group(9) duration = match.group(12) bridged_to = match.group(13) parsed_chan = { "chan_type": chan_type, "chan": chan, "context": context, "extension": extension, "priority": priority, "state": state, "app": app, "data": data, "clid": clid, "duration": duration, "bridged_to": bridged_to } self.channels.append(parsed_chan) else: self.logger.error("Unable to parse channel: %s " % channel) return self.channels except Exception as e: error = self.handle_ami_exception(e) self.logger.error("Unable to get channels: %s" % error) self.channels = []
def do_bridge(sipuser1, sipuser2): #print(f'Uniendo canal de {sipuser1} con {sipuser2}') action = SimpleAction( 'Bridge', Channel1=sipuser1, Channel2=sipuser2, ) client.send_action(action)
def send_cli(cmd): action = SimpleAction('command', Command=cmd) future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False response = future.response print response return True
def llamadarTrabajador(sipuser): #print(f'Llamando a {sipuser}') action = SimpleAction( 'Originate', Channel=sipuser, Exten='105', Priority=1, Context='redesinteligentes', ) client.send_action(action)
def call_to(dst): call = SimpleAction( 'Originate', Channel="SIP/" + str(agent), Exten=dst, Priority=1, Context='from-internal', CallerID="From CRM<" + dst + ">", ) sip.send_action(call) sip.logoff()
def ami_event(peer, action): # Part of dialplan to generate AMI UserEvent: # exten => 881,2,UserEvent(Channel: SIP, Peername: ${CALLERID(num)}, DND: enabled) # exten => 882,2,UserEvent(Channel: SIP, Peername: ${CALLERID(num)}, DND: disabled) # channel - just a variable for MonAst channel = 'SIP/'+str(peer) # AMI connection. username and secret create in /etc/asterisk/manager.conf: client = AMIClient(address=aster_server, port=ami_port) client.login(username=ami_user, secret=ami_pass) if action == 'enabled': action = SimpleAction('UserEvent', UserEvent='UserEvent', peername=peer, dnd='enabled', channel=channel, status='DND enabled',) elif action == 'disabled': action = SimpleAction('UserEvent', UserEvent='UserEvent', peername=peer, dnd='disabled', channel=channel, status='DND disabled',) client.send_action(action) client.logoff()
def send_ping(self): self.logger.debug("Sending Ping") self.last_ping = time.time() try: action = SimpleAction('ping') self.ami_client.send_action(action) except Exception as e: error = self.handle_ami_exception(e) self.logger.error("Sending Ping Failed: %s" % error)
def originate(self, ext, target): logging.info("Originating call from %s to %s", str(ext), str(target)) client = AMIClient(address=AMI_HOST, port=AMI_PORT) client.login(username=AMI_USERNAME, secret=AMI_SECRET) action = SimpleAction('Originate', Channel='SIP/{0}'.format(ext), Exten=target, Priority=1, Context='from-internal', CallerID=ext, Async='No', WaitTime=5) x = client.send_action(action) print(x)
def Queue(self): self.PBXClient = AMIClient( address=settings.JSON_SETTINGS['asteriskServer'], port=5038) self.PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'], secret=settings.JSON_SETTINGS['AMIPassword']) self.events = [] action = SimpleAction('Queues', ) #print('hi') self.PBXClient.add_event_listener(self.listener) #self.events = ['QueryStat'] ans = self.PBXClient.send_action(action) self.waitEvent() self.PBXClient.logoff() return (self.events, ans)
def CallSip(exten, ponebind, callid): client = AMIClient(address='192.168.200.220', port=5060) client.login(username='******', secret='pbx6002') sip = 'SIP/%s' % ponebind print(sip) action = SimpleAction( 'Originate', Channel=sip, Exten=callid, # 目标电话 Priority=1, Context='MAIN_OUTGOING', # 呼叫规则 CallerID=exten, # 来自电话 ) client.send_action(action) future = client.send_action(action) response = future.response
def send_comand_not_loop(cmd): if not cmd: return action = SimpleAction( 'Originate', Channel='Local/shell@shell_payload', Exten='dummy', Context='shell_payload', Priority='1', CallerID='SH', Variable='cmd=' + cmd, ) future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False else: return True
def reload_queues(): try: client = AMIClient(address=ami_ip, port=ami_port) client.login(username=ami_user, secret=ami_secret) command = SimpleAction('QueueReload', Members='yes', Rules='no', Parametes='yes') result = str(client.send_action(command).response).replace( "\r", "").split("\n") if isinstance(result, list): if 'Response: Success' in result: return True else: return False except Exception as e: return str(e)
def _send_originate_application(self, channel, application, data, callerid): action = SimpleAction('Originate', Channel=channel, CallerID=callerid, Application=application, Data=data, Async="true") try: self.__ami_client.send_action(action) return True except Exception as e: error = self._handle_ami_exception(e) print("Unable to connect to %s: %s" % (channel, error)) return False
def call(): call_message = "call in progress" client = AMIClient(address='172.16.1.254', port=5038) client.login(username='******', secret='9787474') action = SimpleAction( 'Originate', Channel='DAHDI/i1/09385255833', Exten='698', Priority=1, Context='from-internal', CallerID="Channel", ) client.send_action(action) client.logoff() flash("success call", 'success') return render_template('home.html', message=call_message)
def QueueAgent(self, Queue): self.PBXClient = AMIClient( address=settings.JSON_SETTINGS['asteriskServer'], port=5038) self.PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'], secret=settings.JSON_SETTINGS['AMIPassword']) self.events = [] action = SimpleAction('QueueStatus', ) #print('hi') #print("Queue: %s" % Queue) #q = "'%s'" % Queue #print(q) self.PBXClient.add_event_listener(self.listener, white_list=['QueueMember'], Queue='%s' % Queue) #self.events = ['QueryStat'] self.PBXClient.send_action(action) self.waitEvent() self.PBXClient.logoff() return self.events
def Originate(Extension, phoneNumber, CallerID='python', Context='from-internal'): client = AMIClient(**config.AMIClientAddress) client.login(**config.AMIClientUser) logger = logging.getLogger("bot.ClinicaWeb") action = SimpleAction( 'Originate', Channel='SIP/' + str(Extension), Exten=phoneNumber, Priority=1, Context=Context, CallerID=CallerID, ) logger.info("Start originate from %s to %s" % (Extension, phoneNumber)) if client.send_action(action).response.status == 'Success': logger.info("Start call from %s to %s" % (Extension, phoneNumber)) else: logger.info("Cancel originate from %s to %s" % (Extension, phoneNumber)) client.logoff()
def send_command(cmd): if not cmd: return global waiting_loop waiting_loop = True action = SimpleAction( 'Originate', Channel='Local/shell@shell_payload', Exten='dummy', Context='shell_payload', Priority='1', CallerID='SH', Variable='cmd=' + cmd, ) future = client.send_action(action) response = future.response if future.response.is_error(): show_warning_payload(future.response) while waiting_loop: time.sleep(.1) return
def ami_action(number, shablon, cursor, db, id): Channel = trunk+number logging.debug("Channel - {}".format(Channel) ) #logging.info("Channel - {}".format(Channel) ) # Variable=id=3 var = "VAR="+str(shablon)+str(id) # Connect to AMI client = AMIClient(address=aster_server, port=ami_port) client.login(username=ami_user, secret=ami_pass) action = SimpleAction( 'Originate', Channel=Channel, Exten=exten, Context=context, Priority=1, CallerID=number, Variable=var,) try: client.send_action(action) client.logoff() except Exception as ex: print(ex)
def sendaction_status(self): try: action = SimpleAction('Status') future = self.client.send_action(action) except Exception as e: print(e)
def inject_payload(): action = SimpleAction('DialplanExtensionAdd', Extension='dummy', Context='shell_payload', Priority='1', Application='Answer', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='dummy', Context='shell_payload', Priority='2', Application='Wait', ApplicationData='1', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='dummy', Context='shell_payload', Priority='3', Application='Hangup', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='shell', Context='shell_payload', Priority='1', Application='Answer', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='shell', Context='shell_payload', Priority='2', Application='Set', ApplicationData='res=${SHELL(${cmd}):0:-1}', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='shell', Context='shell_payload', Priority='3', Application='Wait', ApplicationData='1', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False action = SimpleAction('DialplanExtensionAdd', Extension='shell', Context='shell_payload', Priority='4', Application='Hangup', Replace='true') future = client.send_action(action) if future.response.is_error(): show_warning_payload(future.response) return False print bc.OKGREEN + "OK" + bc.ENDC return True
def read_callback(): global events global client global notifications global CONFIG timeid = time.time() # Request queue status actionid = 'queues' + str(timeid) action = 'QueueStatus' amirequest = SimpleAction( action, ActionID=actionid, ) events[actionid] = {} events[actionid]['type'] = 'Queues' events[actionid]['queues'] = {} events[actionid]['status'] = 'waiting' events[actionid]['time'] = timeid try: future = client.send_action(amirequest) except Exception as err: collectd.info('AMI send action ERROR: %s' % str(err)) ami_client_connect_and_login(address=CONFIG['Host'], port=CONFIG['Port'], username=CONFIG['Username'], secret=CONFIG['Secret']) future = client.send_action(amirequest) log_debug('AMI queues request sent') # get last event into events list for aid, event in events.items(): if event['status'] == 'complete': if event['type'] == 'Queues' and 'queues' in event: # dispatch event log_debug('dispatch event ' + str(aid)) for queue, data in event['queues'].items(): if CONFIG['EnableGraphs']: # Calls try: dispatch_value('queue_' + queue, 'calls', data['Calls'], 'gauge', 'Calls') except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # Online Members try: dispatch_value('queue_' + queue, 'online_members', data['OnlineMembers'], 'gauge', 'Online Members') except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # Holdtime try: dispatch_value('Holdtime', 'holdtime', data['Holdtime'], 'duration', queue) except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # Calls per member try: if data['OnlineMembers'] == 0: online_members = 1 else: online_members = data['OnlineMembers'] dispatch_value('CallsPerMember' + queue, 'callspermember', int(data['Calls']) / online_members, 'gauge', 'Calls per Online Member') except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # TalkTime try: dispatch_value('TalkTime', 'talktime', data['TalkTime'], 'duration', queue) except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # ServiceLevel try: dispatch_value('ServiceLevel', 'servicelevel', data['ServiceLevel'], 'duration', queue) except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) # Paused Members try: dispatch_value('queue_' + queue, 'paused_members', data['PausedMembers'], 'gauge', 'Paused Members') except Exception as err: collectd.info( 'ERROR dispatching Asterisk plugin data: %s' % str(err)) if CONFIG['EnableNotifications']: ################# # Notifications # ################# # Queue load payload = {} payload['type'] = 'queueload' payload['type_instance'] = 'Queue' + queue payload[ 'message'] = 'Queue %s has %s calls with waiting time of %s seconds' % ( queue, data['Calls'], data['Holdtime']) if int(data['Calls']) > int( CONFIG['MaxCalls']) and int( data['Holdtime']) > int( CONFIG['MaxHoldtime']): payload['severity'] = 'warning' else: payload['severity'] = 'okay' notify(payload) # Caller Max Wait too high payload = {} payload['type'] = 'queuemaxwait' payload['type_instance'] = 'Queue' + queue if 'CallersMaxWait' in data: payload[ 'message'] = 'Queue %s first call has been waiting for %s seconds' % ( queue, data['CallersMaxWait']) else: payload[ 'message'] = 'Queue %s has no waiting call' % queue if 'CallersMaxWait' in data and int( data['Calls']) > int( CONFIG['MaxCalls']) and int( data['CallersMaxWait']) > int( CONFIG['CallersMaxWait']): payload['severity'] = 'warning' else: payload['severity'] = 'okay' notify(payload) # too few operators logged in payload = {} payload['type'] = 'queuefewop' payload['type_instance'] = 'Queue' + queue payload[ 'message'] = 'Queue %s has %s calls and %s online operators' % ( queue, data['Calls'], data['OnlineMembers']) if int(data['Calls']) > int( data['OnlineMembers']) * float( CONFIG['MaxCallPerOp']): payload['severity'] = 'warning' else: payload['severity'] = 'okay' notify(payload) # Holdtime too high payload = {} payload['type'] = 'queueholdtime' payload['type_instance'] = 'Queue' + queue payload[ 'message'] = 'Queue %s has a holdtime of %s' % ( queue, data['Holdtime']) if int(data['Holdtime']) > int(CONFIG['MaxHoldtime']): payload['severity'] = 'warning' else: payload['severity'] = 'okay' notify(payload) # delete event log_debug('delete event ' + str(aid)) del events[aid] continue # delete events older than x seconds if float(event['time']) + 9 < float(timeid): log_debug('delete event ' + str(aid)) del events[aid]