示例#1
0
文件: views.py 项目: BoB1Edition/lk
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
示例#3
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()
示例#4
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()
示例#5
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))
示例#6
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)
示例#7
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
示例#8
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
示例#9
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()
示例#10
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
示例#11
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)
示例#12
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)
示例#13
0
文件: callapp.py 项目: tcpzix/webcall
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)
示例#14
0
文件: parsednd.py 项目: kt351b/monast
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()
示例#15
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
示例#16
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()
示例#17
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)
示例#18
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
示例#19
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
#add formatter to the handler
#formatter = logging.Formatter('Python: { "loggerName":"%(name)s", "asciTime":"%(asctime)s", "pathName":"%(pathname)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}')

formatter = logging.Formatter(
    '%(name)s: [%(created)f] %(levelname)s %(message)s')

handler.formatter = formatter
ablogger.addHandler(handler)

ASTUSER = "******"
ASTSECRET = "admin"

client = AMIClient(address="127.0.0.1", port=5038)
AutoReconnect(client)
client.login(username=ASTUSER, secret=ASTSECRET)
adapter = AMIClientAdapter(client)

EventCollection = {}


@methods.add
def ConfbridgeListRooms():
    def event_listener(event, **kwargs):
        global EventCollection, client, adapter
        EventCollection[event.keys['ActionID']].append(event)

    myactionid = str(uuid.uuid4())
    EventCollection[myactionid] = []
    mylistener1 = client.add_event_listener(
        event_listener,
示例#21
0
class AsteriskStatus():
    isconnected = False
    client = None

    def __init__(self):
        self.config = ReadConfig()
        self.mqttc = mqtt.Client()

    def logout(self):
        self.client.logoff()

    # Gets the Caller ID

    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 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 cid_listener(self, event, **kwargs):
        if event.name == 'DBGetResponse':
            self.cid_response = event['Val']

    # Starts the main program

    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)

    def get_cid(self, cid):
        ass = AsteriskStatus()
        return ass.cid_start(cid)

    def sendaction_status(self):
        try:
            action = SimpleAction('Status')
            future = self.client.send_action(action)
        except Exception as e:
            print(e)

    def connection_listener(self, event, **kwargs):
        try:
            if event.name not in [
                    'PeerStatus', 'RTCPSent', 'VarSet', 'Registry'
            ]:
                print(f"callback: {event.name}")
            if event.name == 'FullyBooted':
                #print("---===Started===---")
                self.isconnected = True
            elif event.name == 'Shutdown':
                #print("This is shuting down!!!")
                self.isconnected = False
            elif event.name == 'Status':
                self.tmp_events.append(event)
            elif event.name == 'StatusComplete':
                for num, event in enumerate(self.tmp_events):
                    self.tmp_events[num]['chan_re'] = event['Channel']
                    ass = re.match(r'\w*\/(\S*)-\w*', event['Channel'])
                    if ass is not None:
                        self.tmp_events[num]['chan_re'] = ass.group(1)
                self.events = self.link_events(self.tmp_events)
                self.tmp_events = []
            elif event.name in [
                    'Newstate', 'HangupRequest', 'DialEnd', 'Hangup',
                    'SoftHangupRequest'
            ]:
                self.sendaction_status()
        except Exception as e:
            print(e)

    def link_events(self, events):
        try:
            filtered_events = [
                event for event in events
                if event['Uniqueid'] == event['Linkedid']
            ]
            linked_events = [
                event for event in events
                if event['Uniqueid'] != event['Linkedid']
            ]
            all_event_prints = []

            for filtered_event in filtered_events:
                lines_status = []
                linked = [
                    event for event in linked_events
                    if event['Linkedid'] == filtered_event['Uniqueid']
                ]

                cid_from = self.get_cid(filtered_event['CallerIDNum'])
                cid_to = self.get_cid(filtered_event['Exten'])
                lines_status.append(
                    f"{filtered_event['chan_re']} ({filtered_event['ChannelStateDesc']})"
                )
                for link in linked:
                    lines_status.append(
                        f"{link['chan_re']} ({link['ChannelStateDesc']})")

                cid_from_txt = cid_from if cid_from is not None else filtered_event[
                    'CallerIDNum']
                cid_to_txt = cid_to if cid_to is not None else filtered_event[
                    'Exten']
                lines_status_txt = ', '.join(lines_status)

                out_print = f"{cid_from_txt}->{cid_to_txt} [{lines_status_txt}]"
                all_event_prints.append(out_print)

            if len(all_event_prints) > 0:
                topublish = ', '.join(all_event_prints)
            else:
                topublish = 'idle'
            print(topublish)
            self.mqttc.publish(self.config['mqtt']['topic'],
                               topublish,
                               retain=True)

        except Exception as e:
            print(e)

        return events
        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):
    mqtt_client.disconnect()
    ami_client.logoff()
示例#23
0
class AsteriskLogger():
    def __init__(self, host, port, username, secret):
        self.creds = [host, port, username, secret]
        self.plugin_name = "asterisk"
        self.checking_status = False
        self.local_logfile = {}
        self.local_logfile["asterisk-systemstatus"] = {}
        self.init()

    def reinit(self):
        self.init()

    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()

    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_logfile(self):
        if "running-asterisk-version" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("running-asterisk-version", "-")
        if "running-manager-version" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("running-manager-version", "-")
        if "act-current-calls" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("act-current-calls", "-")
        if "last-core-reload" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("last-core-reload", "-")
        if "last-core-restart" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("last-core-restart", "-")

        return self.local_logfile

    def create_timestamp_from_strings(self, date, time):
        date_parts = date.split("-")
        time_parts = time.split(":")
        return datetime.datetime(int(date_parts[0]), int(date_parts[1]),
                                 int(date_parts[2]), int(time_parts[0]),
                                 int(time_parts[1]),
                                 int(time_parts[2])).timestamp()

    def callback_response_status(self, response):
        reload_time = response.keys.get("CoreReloadTime", None)
        reload_date = response.keys.get("CoreReloadDate", None)
        if reload_date is not None and reload_time is not None:
            self.push_to_logfile_system_state(
                "last-core-reload",
                self.create_timestamp_from_strings(reload_date, reload_time))

        startup_time = response.keys.get("CoreStartupTime", None)
        startup_date = response.keys.get("CoreStartupDate", None)
        if startup_time is not None and startup_date is not None:
            self.push_to_logfile_system_state(
                "last-core-restart",
                self.create_timestamp_from_strings(startup_date, startup_time))

        current_calls = response.keys.get("CoreCurrentCalls", None)
        if current_calls is not None:
            self.push_to_logfile_system_state("act-current-calls",
                                              current_calls)

    def callback_response_settings(self, response):
        version = response.keys.get("AsteriskVersion", None)
        if version is not None:
            self.push_to_logfile_system_state("running-asterisk-version",
                                              version)

        ami_version = response.keys.get("AMIversion", None)
        if ami_version is not None:
            self.push_to_logfile_system_state("running-manager-version",
                                              ami_version)

    def push_to_logfile_trunk(self, trunkname, user, state):
        self.local_logfile["timestamp"] = time.time()
        if self.local_logfile["trunk-status"].get(trunkname + "-" + user,
                                                  None) is None:
            self.local_logfile["trunk-status"][trunkname + "-" + user] = {}
        if state == "Registered":
            self.local_logfile["trunk-status"][trunkname + "-" +
                                               user]["status"] = 1
        else:
            self.local_logfile["trunk-status"][trunkname + "-" +
                                               user]["status"] = 0

        self.local_logfile["trunk-status"][trunkname + "-" +
                                           user]["trunkname"] = trunkname
        self.local_logfile["trunk-status"][trunkname + "-" +
                                           user]["user"] = user

    def push_to_logfile_system_state(self, varname, state):
        self.local_logfile["timestamp"] = time.time()
        self.local_logfile["asterisk-systemstatus"][varname] = state

    def push_to_logfile_user(self, exten, status, hint):
        self.local_logfile["timestamp"] = time.time()
        if self.local_logfile["trunk-status"].get(exten, None) is None:
            self.local_logfile["asterisk-user-status"][exten] = {}
        self.local_logfile["asterisk-user-status"][exten]["status"] = status
        self.local_logfile["asterisk-user-status"][exten]["hint"] = hint

    def event_listener_registry(self, event, **kwargs):
        trunk_domain = event.keys.get("Domain", None)
        trunk_user = event.keys.get("Username", None)
        trunk_status = event.keys.get("State", None)
        if trunk_domain is not None and trunk_user is not None and trunk_status is not None:
            self.push_to_logfile_trunk(trunk_domain, trunk_user, trunk_status)

    def event_listener_extension_status(self, event, **kwargs):
        status = event.keys.get("Status", None)
        exten = event.keys.get("Exten", None)
        hint = event.keys.get("Hint", None)
        if status is not None and exten is not None and hint is not None:
            self.push_to_logfile_user(exten, status, hint)

    def general_debug_eventlistener(self, event, **kwargs):
        return
示例#24
0
def make_call_auto():
    client = AMIClient(address=AMI_ADDRESS, port=AMI_PORT)
    future = client.login(username=AMI_USER, secret=AMI_SECRET)

    id = request.args.get('id', '')
    exten = request.args.get('exten', '')
    file = request.args.get('file', '')
    action_id = request.args.get('action_id', '')

    exten = '8' + exten

    d = {}

    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)

    channel = f'Local/{exten}@ng_ext_autodial_speech_to_text'
    d['channel'] = channel

    variable = FILE_NAMES[file]

    res_call = do_call_without_oper(adapter, channel, DATA, APP, action_id,
                                    variable, exten)

    client.logoff()

    d = {}

    d['Действия'] = 'Asterisk_AutoCall_Event'
    d['Данные'] = {}
    d['Данные']['name'] = 'init'
    d['Данные']['id_ext'] = id_ext
    d['Данные']['event_date'] = datetime.now()
    d['Данные']['status'] = 'ok'
    d['Данные']['callerid'] = exten
    d['Данные']['id'] = id.upper()

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

    auto_call_event(jdata)

    AUTO_CALLS[channel] = {
        'id_ext': id_ext,
        'id': id,
        'channel': channel,
        'exten': exten,
        'callerid': exten
    }

    #period =  datetime.now()
    #source = id.upper()
    #status = 'init'
    #value = id_ext
    #comment = res

    #var = Statuses_AutoCall.create(period=period, source=source, status=status, value=value, comment=comment)

    return jdata, 200, HEADERS
示例#25
0
        }
        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):
    mqtt_client.disconnect()
    ami_client.logoff()
示例#26
0
import pyperclip
import os
import re
from asterisk.ami import AMIClient, SimpleAction
from unidecode import unidecode

username = "******"
password = "******"
astsrv = "asterisk-ip-address"
agent = 602
port = 5038
area_code = '0604'
country_code = '+1'

sip = AMIClient(address=astsrv, port=port)
sip.login(username=username, secret=password)


def normalize(dst):
    # Normalize Destination number remove non digit charachters
    # and remove Country code followed by '+'
    if dst.startswith(country_code):
        dst = ('0' + dst[3:]).replace(" ", "")
    dst = re.sub("[^0-9]", "", dst)
    return dst


def call_to(dst):
    call = SimpleAction(
        'Originate',
        Channel="SIP/" + str(agent),
示例#27
0
#!/usr/bin/python
import os
import time
from settings import login, connection

from asterisk.ami import AMIClient
from asterisk.ami import EventListener


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(
    EventListener(on_event=event_notification,
                  white_list='Newstate',
                  ChannelStateDesc='Ringing'))

try:
    while True:
        time.sleep(10)
except (KeyboardInterrupt, SystemExit):
    client.logoff()
示例#28
0
        "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)
    for num in numbers:
示例#29
0
import requests



def event_notification(source, event):
    binado = ( event['ConnectedLineNum'] )
    ext = ( event['Exten'])
    os.system("curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{call: {src: '%s', dst: '%s'}}' http://10.254.254.208:8887/api/voip/events" % (binado, ext))

    print (binado, ext)



client = AMIClient(address="127.0.0.1")
future = client.login(username="******", secret="cxmanager*con")
client.add_event_listener(EventListener(on_event=event_notification, black_list='Exten = 100', white_list='Newstate', ChannelStateDesc='Up'))



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


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

示例#30
0
    pass


def json_serial(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()

    if isinstance(obj, decimal.Decimal):
        return float(obj)
    pass


app = Flask(__name__)

producer = KafkaProducer(bootstrap_servers=['192.168.5.131:9092'])

CORS(app, support_credentials=True)

import server.views

from asterisk.ami import AMIClient, AMIClientAdapter, AutoReconnect
from server.conf import *

client = AMIClient(address=AMI_ADDRESS, port=AMI_PORT)
AutoReconnect(client)

future = client.login(username=AMI_USER, secret=AMI_SECRET)

client.add_event_listener(event_listener)
示例#31
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)

#!/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()