def send_campaign(): payload = request.json try: """ Insert campaign """ camp.insert(data=payload) """ Create schedule """ cid = int(payload['campaignid']) campaign = db.select_one(table='campaigns', where=dict(campaign_id=cid)) conf_sched = conf.section(name='scheduler') retries = int(conf_sched['retries']) interval = int(conf_sched['interval']) for i in range(retries): scheduler.add_job(func=create_jobs, trigger='date', run_date=campaign['time_start'] + timedelta(seconds=(i * interval)), args=[cid], id='{0}.p{1}'.format(cid, i)) db.update(table='campaigns', where=['campaign_id'], data=dict(campaign_id=cid, status_scheduled=True)) except (CampaignError, DBError) as e: return jsonify( dict(campaignid=int(payload['campaignid']), status=0, error_msg=e.msg)), 400 else: return jsonify(dict(campaignid=int(payload['campaignid']), status=1))
def send_originate(cdrid): conf_originate = conf.section(name='originate') queue = conf_originate['queue'] extension = subprocess.check_output( 'python3.6 originate.py -q {0}'.format(queue), shell=True).strip().decode('utf-8') if extension != '': uniqueid = subprocess.check_output( 'python3.6 originate.py -o {0} {1}'.format(cdrid, extension), shell=True).strip().decode('utf-8') db.update(table='cdr', where=['id'], data=dict(id=cdrid, uniqueid=uniqueid))
def originate(cdrid, extension): conf_originate = conf.section(name='originate') conf_asterisk = conf.section(name='asterisk') job = db.select_one(table='cdr', where=dict(id=cdrid)) manager = Manager(**conf_asterisk) yield from manager.connect() action = dict(Action='Originate', Channel='{0}/{1}'.format(conf_originate['channel'], job['phone_number']), Context=conf_originate['context'], Exten=extension, Priority=conf_originate['priority'], Timeout=int(conf_originate['timeout']), WaitTime=25, CallerID=job['callerid'], Async=True) responses = yield from manager.send_action(action=action, as_list=True) manager.close() print(responses[1]['Uniqueid'])
def listener_cdr(manager, event): if not db.select_one(table='cdr', where=dict(uniqueid=event['UniqueID'])): return False fmt = "%Y-%m-%d %H:%M:%S" cdr = dict(time_start=datetime.strptime(event['StartTime'], fmt), time_end=datetime.strptime(event['EndTime'], fmt), agent=event['Destination'], station_id=event['Destination'], duration=event['Duration'], billsec=event['BillableSeconds'], disposition=event['Disposition'], uniqueid=event['UniqueID'], linkedid=event['Linkedid']) if event['RecordingFile'] != '': cdr['record_url'] = conf.section( name='originate')['record_url'] + event['RecordingFile'] if event['AnswerTime'] != '': cdr['time_answer'] = datetime.strptime(event['AnswerTime'], fmt) db.update(table='cdr', where=['uniqueid'], data=cdr) cworker.callback_cdr.delay(callid=event['UniqueID'])
def queue_status(queue): conf_asterisk = conf.section(name='asterisk') manager = Manager(**conf_asterisk) yield from manager.connect() queues_status = yield from manager.send_action({ 'Action': 'QueueStatus', 'Queue': queue }) manager.close() available_extensions = list( filter(lambda x: 'Status' in x and x['Status'] == '1', queues_status)) if len(available_extensions) == 0: print('') else: available_extensions_sorted = sorted(available_extensions, key=lambda k: k['CallsTaken']) location = available_extensions_sorted[0]['Location'] m = re.search('(?<=\/)\d{3,5}(?=@)', location) print(m.group(0))
import requests from celery import Celery from celery.utils.log import get_task_logger from klass.exceptions import DBError, CampaignError from klass import conf, db conf_redis = conf.section(name='redis') celery_app = Celery( 'cworker', broker='redis://{0}:{1}/{2}'.format(conf_redis['host'], conf_redis['port'], conf_redis['worker_db']), backend='redis://{0}:{1}/{2}'.format(conf_redis['host'], conf_redis['port'], conf_redis['worker_db'])) celery_app.config_from_object( dict(task_serializer='json', result_serializer='json', accept_content=['json'], timezone='Asia/Ho_Chi_Minh')) logger = get_task_logger(__name__) conf_callback = conf.section(name='callback') @celery_app.task() def callback_campaign(campaign_id): crm_callback = conf_callback['finish_campaign'] try: campaign = db.select_one(table='campaigns', where=dict(campaign_id=campaign_id)) status = 'RECEIVED' if campaign['status_completed']:
# -*- coding: utf-8 -*- #!/usr/bin/python3.6 import asyncio from datetime import datetime from panoramisk.manager import Manager from klass import conf, db import cworker ami = Manager(loop=asyncio.get_event_loop(), **conf.section(name='asterisk')) @ami.register_event('Cdr') def listener_cdr(manager, event): if not db.select_one(table='cdr', where=dict(uniqueid=event['UniqueID'])): return False fmt = "%Y-%m-%d %H:%M:%S" cdr = dict(time_start=datetime.strptime(event['StartTime'], fmt), time_end=datetime.strptime(event['EndTime'], fmt), agent=event['Destination'], station_id=event['Destination'], duration=event['Duration'], billsec=event['BillableSeconds'], disposition=event['Disposition'], uniqueid=event['UniqueID'], linkedid=event['Linkedid']) if event['RecordingFile'] != '': cdr['record_url'] = conf.section( name='originate')['record_url'] + event['RecordingFile'] if event['AnswerTime'] != '': cdr['time_answer'] = datetime.strptime(event['AnswerTime'], fmt)
# -*- coding: utf-8 -*- import subprocess from datetime import datetime, timedelta from flask import Flask, request, jsonify from klass.exceptions import CampaignError, DBError from klass.campaign import Campaign from klass import conf, scheduler, db import cworker """ Initial Flask """ app = Flask(__name__) """ Initial Campaign """ camp = Campaign(conf.section(name='api')) @app.route('/api/sendCampaign', methods=['POST']) def send_campaign(): payload = request.json try: """ Insert campaign """ camp.insert(data=payload) """ Create schedule """ cid = int(payload['campaignid']) campaign = db.select_one(table='campaigns', where=dict(campaign_id=cid)) conf_sched = conf.section(name='scheduler') retries = int(conf_sched['retries']) interval = int(conf_sched['interval']) for i in range(retries): scheduler.add_job(func=create_jobs, trigger='date', run_date=campaign['time_start'] +