示例#1
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))
示例#2
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
示例#3
0
    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:
        #get channel from event
        event = EventListener(getChannel,
                              white_list=['ConfbridgeList'],
                              CallerIDNum=num)
        client.add_event_listener(event)
        #call main
        main(client, num, command)
        client.remove_event_listener(event)
示例#4
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
示例#5
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()

示例#6
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()
示例#7
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()
示例#8
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
示例#9
0
        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


if __name__ == "__main__":

    def callback_response(event, **kwargs):
        print(event)

    client = AMIClient(address='192.168.0.213', port=5038)
    client.login(username='******', secret='amisecret')

    client.add_event_listener(callback_response,
                              white_list=['CoreShowChannel'])

    action = SimpleAction('CoreShowChannels')
    future = client.send_action(action, callback=callback_response)

    while True:
        time.sleep(1)

    #action = SimpleAction('SIPshowregistry')
    #future = client.send_action(action, callback=callback_response)

    #action = SimpleAction('ExtensionStateList')
    #future = client.send_action(action, callback=callback_response)

#Interessante:
# CoreStatus, CoreSettings
        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()
示例#11
0
文件: Worker.py 项目: BoB1Edition/lk
class Worker(object):

    events = []
    PBXClient = None

    def waitEvent(self, timewait=5):
        while not self.events:
            timewait -= 1
            if timewait == 0:
                break
            time.sleep(1)

    def QueryStat(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('QueueStatus', )
        #print('hi')
        self.PBXClient.add_event_listener(self.listener,
                                          white_list=['QueueParams'])
        #self.events = ['QueryStat']
        self.PBXClient.send_action(action)
        self.waitEvent()
        self.PBXClient.logoff()
        return self.events

    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 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 GetQuery(self):
        servers = settings.JSON_SETTINGS['MemcachedServers']
        cServers = []
        for server in servers:
            tmp = server.split(':')
            cServers += [(tmp[0], int(tmp[1]))]
        cl = HashClient(cServers)
        q = cl.get('queue')
        if q is None:
            self.QueryStat()
            queue = []
            for event in self.events:
                queue += [event['Queue']]
            cl.set('queue', ','.join(queue),
                   settings.JSON_SETTINGS['MemcachedExpire'])
            return queue
        else:
            return q.decode("utf-8").split(',')

    def listener(self, event, **kwargs):
        #print(event)
        self.events += [event]

    def __del__(self):
        #print("__del__")
        if not self.PBXClient is None:
            self.PBXClient.logoff()
示例#12
0
            active = {}
        active[event.keys['CallerIDNum']] = event.keys

def run(client):
    action = SimpleAction(
        'PJSIPShowEndpoints'
    )

    client.send_action(action)

    action = SimpleAction(
        'CoreShowChannels'
    )
    client.send_action(action)

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

client.add_event_listener(event_notification, white_list=[
    'EndpointList',
    'CoreShowChannel'
])

try:
    while True:
        run(client)
        time.sleep(3)
except (KeyboardInterrupt, SystemExit):
    client.logoff()
示例#13
0
        '{accountCode: "%s", zoneCode: 001, eventCode: "%s",  priority: 3,  join: false}'
        % (binadoxx, binado))
    response = requests.post('http://10.254.254.72:8080/api/remote-events',
                             headers=headers,
                             data=data,
                             verify=False)
    print(data)


#Login no AMI (Asterisk Manager) e escutando os "novos" eventos "Ringing", a fila "Exten" e um membro dentro da fila
#Por enquanto restringi ao Exten='100' e CallerIDName pra enviar apenas 1 evento, ja que a fila gera n eventos que sao os membros da fila + a discagem pra esses membros

client = AMIClient(address="127.0.0.1")
future = client.login(username="******", secret="cxmanager*con")
client.add_event_listener(
    EventListener(on_event=event_notification,
                  white_list='Newstate',
                  ChannelStateDesc='Ringing',
                  Exten='100',
                  CallerIDName='Supervisao Atendimento'))
#client.add_event_listener(EventListener(on_event=event_notification, white_list='Newstate', ChannelStateDesc='Ringing'))

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

try:
    while True:
        sleep(10)
except (KeyboardInterrupt, SystemExit):
    client.logoff()
#!/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()