import pika import sys import os import json import datetime from pymongo import MongoClient import time from phone import phone import requests db_connection = MongoClient("mongodb://mongodb:Cc03Wz5XX3iI3uY3@mongo") db_base = db_connection["phone-dev"] coll = db_base["phone"] coll_all = db_base["phone-all"] err = db_base["err"] phoneDebug = db_base["phone-debug"] coll_userkey = db_base['userkey'] mkt_phones = ['83912051046', '83912051045'] IgnoreList = ['83919865589', '83912051046', '83912051045', '84950213944', '84951252791', '83919865589', '84951183750', '89919237009', '89919241441', '89919863883', '89919505445', '89919398228', '89919500798'] mobilon_wait = 3 # Время ожидания необходимо чтобы на стороне мобилона все улеглось # Stats: # 0 - ответили # 1 - не приняли # 2 - перезвонили успешно # 4 - Перезвонили неуспешно # LOG # 0 - выходящий вызов закончен # 1 - Вызов не принят # 2 - Перезвонили и дозвонились def main(): connection = pika.BlockingConnection(pika.ConnectionParameters( 'rabbitmq', 5672, 'mkt', pika.PlainCredentials('rabbit', 'mrl2X0jwnYuCCiKFTshG7WKyOAhfDo'))) channel = connection.channel() channel.queue_declare(queue='incoming-dev') def callback(ch, method, properties, body: bytearray): # Парсим строку ph = phone(body) # Определяем тип соединения # Если входящий print(ph.ConvertToJSON()) phoneDebug.insert_one(ph.ConvertToJSON()) if ph.GetState() == "START": ph.addStart() if ph.GetState() == "END": ph.addEnd() if ph.GetState() == "HANGUP" and ph.isCanClose() == 1: # Ждем time.sleep(mobilon_wait) t_req = "https://callinfo.services.mobilon.ru/api/call/info/1e86a98e026578eb5f6bf8c092c0c4a2/" + ph.GetUUID() try: res: dict = json.loads(requests.get(t_req).content) except: print("Get data from Mobilon", t_req) try: coll_all.insert_one(res) except: print("coll_all:", res) # В этом месте описывается логика работы программы исходя основываясь на данных мобилона if res["direction"] == "incoming": # Подмена полей res["client"] = res.pop("from") res["mkt_phone"] = res.pop("to") # 2. Удаляем пропущенные если есть coll.delete_many( {"client": {'$regex': res["client"]}, "status": "NOT_ANSWERED"}) coll.insert_one(res) if res["direction"] == "external": res["client"] = res.pop("to") res["operator"] = res.pop("from") # Совершенно непонятный костыль, откуда берется загадка res.pop("_id") if res["has_record"] == True and res["answered_duration"] > 8: res["status"] = "RECALL_TRUE" else: res["status"] = "RECALL_FALSE" t = coll.update_many({ "client": {'$regex': res["client"]}, "status": {'$in': ["NOT_ANSWERED", "RECALL_FALSE"]} }, {'$set': res, '$inc': {"count_try": 1}}) coll.update_many({"count_try": {"$gt": 2}, "client": res["client"]}, {"$set": {"status": "DELETED"}}) # ------------------------------- res.clear() channel.basic_consume( queue='incoming-dev', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)