Exemplo n.º 1
0
def make_call():
    channel = request.args.get('channel', '')
    exten = request.args.get('exten', '')
    channel = '304'
    exten = '8' + exten[1:]

    user_client = AMIClient(address=ami_ip, port=ami_port)

    future = user_client.login(username=ami_user, secret=ami_secret)

    time.sleep(0.5)

    user_adapter = AMIClientAdapter(user_client)

    res = user_adapter.Originate(Channel='SIP/' + channel,
                                 Context='local',
                                 Exten=exten,
                                 ActionID=exten,
                                 Priority=1,
                                 CallerID=exten,
                                 CallerIDName=exten,
                                 Timeout='')

    time.sleep(0.2)

    user_client.logoff()

    return 'ok', 200, HEADERS
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
Exemplo n.º 3
0
    def __init__(self, logger, config):

        self.logger = logger
        self.config = config
        self.clients = self.config['clients']

        self.check_interval = config['intervals']['check_interval']
        self.reconnect_interval = config['intervals']['reconnect_interval']
        self.ping_interval = config['intervals']['ping_interval']

        self.ami_host = config['ami']['host']
        self.ami_port = int(config['ami']['port'])
        self.ami_username = config['ami']['username']
        self.ami_password = config['ami']['password']

        self.ami_client = AMIClient(address=self.ami_host, port=self.ami_port)
        self.channels = []
        self.last_check = time.time()
        self.last_ping = time.time()
        self.last_login = time.time()
        self.connected = False

        self.kill_received = False
        self.thread = threading.Thread(target=self.reconnect_loop, args=())
        self.thread.daemon = True
        self.thread.start()
Exemplo n.º 4
0
def ami_login(fuser, fpassword, fhost, fport):
    client_local = AMIClient(address=fhost, port=fport)
    res = client_local.login(username=fuser, secret=fpassword)
    if res.response.is_error():
        return False
    global client
    client = client_local
    return True
Exemplo n.º 5
0
 def cid_start(self, cid):
     self.cid_response = None
     self.client = AMIClient(address=self.config['asterisk']['ip'], port=self.config['asterisk']['port'])
     self.client.login(username=self.config['asterisk']['user'], secret=self.config['asterisk']['pass'])
     self.client.add_event_listener(self.connection_listener)
     self.client.add_event_listener(self.cid_listener)
     self.sendaction_cid(cid)
     return self.cid_response
    def __init__(self, ami_host, ami_port, ami_username, ami_password):

        self.__ami_host = ami_host
        self.__ami_port = int(ami_port)
        self.___ami_username = ami_username
        self.__ami_password = ami_password

        self.__ami_client = AMIClient(address=self.__ami_host,
                                      port=self.__ami_port)
Exemplo n.º 7
0
def test_auth(host, port=7777, user='******', secret='admin'):
    client = AMIClient(address=host, port=port)
    future = client.login(username=user, secret=secret)
    response = future.response
    if response:
        if response.is_error():
            return False
        else:
            client.logoff()
            return True
    else:
        return False
Exemplo n.º 8
0
 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)
Exemplo n.º 9
0
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()
Exemplo n.º 10
0
 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)
Exemplo n.º 11
0
 def test_start(self):
     client = AMIClient(
         **dict(zip(('address', 'port'), self.server_address)))
     client.connect()
     time.sleep(0.5)
     self.assertEqual(client._ami_version, '6.6.6')
     client.login(**login)
     client.disconnect()
Exemplo n.º 12
0
def make_call():
    client = AMIClient(address=AMI_ADDRESS, port=AMI_PORT)
    future = client.login(username=AMI_USER, secret=AMI_SECRET)

    id = request.args.get('id', '')
    channel = request.args.get('channel', '')
    exten = request.args.get('exten', '')
    caller_id = request.args.get('caller_id', '')
    caller_id_name = request.args.get('caller_id_name', '')
    user = request.args.get('user', '')
    action_id = request.args.get('action_id', '')

    d = {}

    exten = '8' + exten

    id_ext = uuid.uuid4()
    id_ext = str(id_ext)

    if future.response.is_error():
        d['status'] = 'failed'
        d['error'] = str(future.response)
        res = json.dumps(d, default=json_serial)

        return res, 200, HEADERS

    adapter = AMIClientAdapter(client)

    res_call = do_call_with_oper(adapter, channel, exten, caller_id,
                                 caller_id_name, action_id)

    client.logoff()

    d['status'] = 'ok'
    d['id_ext'] = id_ext

    res = json.dumps(d, default=json_serial)

    USER_EVENTS[user] = {
        'id_ext': id_ext,
        'id': id,
        'user': user,
        'channel': channel,
        'exten': exten,
        'caller_id': caller_id
    }

    return res, 200, HEADERS
    def _login(self):

        self.__ami_client = AMIClient(address=self.__ami_host,
                                      port=self.__ami_port)

        try:
            self.__ami_client.login(username=self.___ami_username,
                                    secret=self.__ami_password)
            print("Successfully logged into AMI")
            return True

        except Exception as e:

            error = self._handle_ami_exception(e)
            print("Unable to login to AMI: %s" % error)
            return False
Exemplo n.º 14
0
    def connection_start(self):
        try:
            self.tmp_events = []
            self.events = []

            self.client = AMIClient(address=self.config['asterisk']['ip'], port=self.config['asterisk']['port'])
            self.client.login(username=self.config['asterisk']['user'], secret=self.config['asterisk']['pass'])
            self.client.add_event_listener(self.connection_listener)

            self.mqttc.username_pw_set(self.config['mqtt']['user'], password=self.config['mqtt']['pass'])
            self.mqttc.connect(self.config['mqtt']['ip'])
            self.mqttc.loop_start()

            self.sendaction_status()
        except Exception as e:
            print(e)
Exemplo n.º 15
0
    def login(self):

        self.last_login = time.time()

        self.ami_client = AMIClient(address=self.ami_host, port=self.ami_port)

        try:
            self.ami_client.login(username=self.ami_username,
                                  secret=self.ami_password)
            self.connected = True
            self.logger.info("Successfully logged into AMI")
            return True

        except Exception as e:

            error = self.handle_ami_exception(e)
            self.logger.error("Unable to login to AMI: %s" % error)
Exemplo n.º 16
0
    def send_message(self, message="", **kwargs):
        """Send an SMS to target users."""
        from asterisk.ami import AMIClient
        from asterisk.ami.action import SimpleAction

        client = AMIClient(address=self._address, port=self._port)
        future = client.login(username=self._user, secret=self._password)
        if future.response.is_error():
            _LOGGER.error("Can't connect to Asterisk AMI: %s", " ".join(str(future.response).splitlines()))
            return

        targets = kwargs.get(ATTR_TARGET)

        if targets is None:
            _LOGGER.error("No SMS targets, as 'target' is not defined")
            return

        # TODO: add quota per day
        for target in targets:
            _LOGGER.debug("Sending SMS to %s", target)
            action = SimpleAction(
                'DongleSendSMS',
                Device=self._dongle,
                Number=target,
                Message=message,
            )
            client.send_action(action, callback=lambda r: self._on_message(target, r))
            _LOGGER.debug("SMS to %s sent", target)

        client.logoff()
Exemplo n.º 17
0
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)
Exemplo n.º 18
0
 def init(self):
     try:
         self.client = AMIClient(address=self.creds[0], port=self.creds[1])
         self.client.login(username=self.creds[2],
                           secret=self.creds[3])  # TODO: Sicherheitskonzept
         self.push_to_logfile_system_state("status", 1)
     except Exception as e:
         self.push_to_logfile_system_state("status", 0)
         print("Could not init: " + self.plugin_name, e)
         return
     self.client.add_event_listener(self.event_listener_registry,
                                    white_list=['RegistryEntry'])
     self.client.add_event_listener(self.event_listener_extension_status,
                                    white_list=['ExtensionStatus'])
     self.client.add_event_listener(self.general_debug_eventlistener)
     self.checking_status = True
     self.worker = threading.Thread(target=self.worker_loop)
     self.worker.start()
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
    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
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
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
Exemplo n.º 23
0
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()
Exemplo n.º 24
0
def ami_client_connect_and_login(address, port, username, secret):
    global client
    try:
        client = AMIClient(address=CONFIG['Host'], port=CONFIG['Port'])
        #AutoReconnect(client)
        client.login(username=CONFIG['Username'], secret=CONFIG['Secret'])
        client.add_event_listener(event_listener,
                                  white_list=[
                                      'QueueParams', 'QueueStatusComplete',
                                      'QueueMember', 'QueueEntry'
                                  ])
        log_debug('AMI client connected')
    except Exception as err:
        collectd.info('AMI client ERROR: ' % str(err))
Exemplo n.º 25
0
def dev_dial(action):
    """Function that actually makes the asterisk call."""

    try:
        client = AMIClient(address=AUTH_CREDS['address'],
                           port=AUTH_CREDS['port'])
        client.login(username=AUTH_CREDS['username'],
                     secret=AUTH_CREDS['secret'])

        future = client.send_action(action)
        if VERBOSE:
            print(future.response or "None")

        client.logoff()

    except Exception as e:
        print("Error: %s" % e.strerror)
        sys.exit(1)
Exemplo n.º 26
0
def make_call_auto(param):
    tel = kwargs_get(param, 'tel')
    file = kwargs_get(param, 'file')

    client = AMIClient(address=AMI_ADDRESS, port=AMI_PORT)
    future = client.login(username=AMI_USER, secret=AMI_SECRET)

    if future.response.is_error():
        raise Exception(str(future.response))

    adapter = AMIClientAdapter(client)

    channel = f'Local/{tel}@ng_ext_autodial'
    d['channel'] = channel

    action_id = tel

    variable = FILE_NAMES[file]

    client.add_event_listener(event_listener)

    #res_call = simple_call_without_oper(channel, data)
    res_call = simple_call_without_oper(adapter, channel, DATA, APP, action_id,
                                        variable, tel)

    while True:
        if d['status'] == 'Error':
            break
        elif d['status'] == 'ANSWER':
            break
        elif d['status'] == 'BUSY':
            break
        elif d['status'] == 'Success':
            break
        if not res_call.response is None:
            d['status'] = res_call.response.status
        time.sleep(0.2)

    client.logoff()

    #print(d['DTMF'])
    #print(d['status'])

    return d
Exemplo n.º 27
0
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)
Exemplo n.º 28
0
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()
Exemplo n.º 29
0
        "kick": actionKick,
        "lock": actionLock,
        "unlock": actionUnlock,
        "startRecord": actionStartRecord,
        "stopRecord": actionStopRecord
    }
    adapter = AMIClientAdapter(client)
    result = adapter.ConfbridgeList(Conference=confName)
    future = result.response
    time.sleep(0.01)
    command_option[command]()


if __name__ == '__main__':
    #init ami client
    client = AMIClient(address='127.0.0.1', port=5038)
    client.login(username='******', secret='for-confbridge')
    #get vars
    confNum = sys.argv[1]
    command = sys.argv[2]
    numbers = []
    if len(sys.argv) == 4:
        number = sys.argv[3]
        numbers = number.split(',')
    else:
        numbers.append(confNum)
    adapter = AMIClientAdapter(client)
    options = optionTool.Option(confNum)
    confName = options.basic["Name"]

    #print(future)
Exemplo n.º 30
0

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s\n')


def event_listener(event, **kwargs):
    logging.info('ami client -> '+str(event))


ami_ip = "192.168.5.173"
ami_port = 5038
ami_user = '' 
ami_secret=''


client = AMIClient(address=ami_ip, port=ami_port)

AutoReconnect(client)

try:
    future = client.login(username=ami_user, secret=ami_secret)
except:
    raise Exception('ami client login failed')

time.sleep(0.5)

if future.response.is_error():
    raise Exception(str(future.response))

client.add_event_listener(event_listener)
Exemplo n.º 31
-1
            self.mqtt_client.publish(self.base_topic + '/error', json.dumps(data))

    def send_response(self, response):
        data = {
            'Response': response.status,
            'follows': response.follows,
        }
        data.update(response.keys)
        self.mqtt_client.publish(self.base_topic + '/response', json.dumps(data))

    def on_event(self, event, **kwargs):
        self.mqtt_client.publish(self.base_topic + '/event/%s' % event.name, json.dumps(event.keys))


mqtt_client = mqtt.Client()
ami_client = AMIClient(**connection)
AutoReconnect(ami_client)
bridge = MqttAmiBridge('%s/%s' % (hostname, 'asterisk-ami'), mqtt_client, ami_client)

mqtt_client.on_message = bridge.mqtt_on_message
mqtt_client.on_connect = bridge.mqtt_on_connect
mqtt_client.connect(broker, 1883)
mqtt_client.loop_start()

f = ami_client.login(**login)
ami_client.add_event_listener(bridge)

try:
    while True:
        time.sleep(10)
except (KeyboardInterrupt, SystemExit):
#!/usr/bin/python
import os
import time
from settings import login, connection

from asterisk.ami import AMIClient


def event_notification(source, event):
    os.system('notify-send "%s" "%s"' % (event.name, str(event)))


client = AMIClient(**connection)
future = client.login(**login)
if future.response.is_error():
    raise Exception(str(future.response))

client.add_event_listener(event_notification)

try:
    while True:
        time.sleep(10)
except (KeyboardInterrupt, SystemExit):
    client.logoff()