def setup_active_settings(): client = facade._client facade._client = Client(API_URL, 'some key') # https://medium.com/@rishabhsrao/testing-lru-cache-functions-in-python-with-pytest-33dd5757d11c facade._get_lists.cache_clear() yield facade._client facade._client = client
def sync_automations(ac_academy): client = Client(ac_academy.ac_url, ac_academy.ac_key) response = client.automations.list_all_automations(limit=100) if 'automations' not in response: print("Invalid automations incoming from AC") return False automations = response['automations'] count = 0 while len(response['automations']) == 100: count = count + 100 response = client.tags.list_all_tags(limit=100, offset=count) automations = automations + response['automations'] for auto in automations: a = Automation.objects.filter(acp_id=auto['id'], ac_academy=ac_academy).first() if a is None: a = Automation( acp_id=auto['id'], ac_academy=ac_academy, ) a.name = auto['name'] a.entered = auto['entered'] a.exited = auto['exited'] a.status = auto['status'] a.save() return response
def sync_tags(ac_academy): client = Client(ac_academy.ac_url, ac_academy.ac_key) response = client.tags.list_all_tags(limit=100) if 'tags' not in response: logger.error("Invalid tags incoming from AC") return False tags = response['tags'] count = 0 while len(response['tags']) == 100: count = count + 100 response = client.tags.list_all_tags(limit=100, offset=count) tags = tags + response['tags'] for tag in tags: t = Tag.objects.filter(slug=tag['tag'], ac_academy=ac_academy).first() if t is None: t = Tag( slug=tag['tag'], acp_id=tag['id'], ac_academy=ac_academy, ) t.subscribers = tag['subscriber_count'] t.save() return response
def add_to_active_campaign(contact, academy_id: int, automation_id: int): if not ActiveCampaignAcademy.objects.filter( academy__id=academy_id).count(): raise Exception(f"No academy found with id {academy_id}") active_campaign_academy_values = [ 'ac_url', 'ac_key', 'event_attendancy_automation__id' ] ac_url, ac_key, event_attendancy_automation_id = ActiveCampaignAcademy.objects.filter( academy__id=academy_id).values_list( *active_campaign_academy_values).first() logger.debug("ready to send contact with following details") logger.debug(contact) old_client = AC_Old_Client(ac_url, ac_key) response = old_client.contacts.create_contact(contact) contact_id = response['subscriber_id'] if 'subscriber_id' not in response: logger.error("error adding contact", response) raise APIException('Could not save contact in CRM') client = Client(ac_url, ac_key) if event_attendancy_automation_id != automation_id: message = 'Automation doesn\'t exist for this AC Academy' logger.debug(message) raise Exception(message) acp_id = Automation.objects.filter(id=automation_id).values_list( 'acp_id', flat=True).first() if not acp_id: message = 'Automation acp_id doesn\'t exist' logger.debug(message) raise Exception(message) data = { "contactAutomation": { "contact": contact_id, "automation": acp_id, } } response = client.contacts.add_a_contact_to_an_automation(data) if 'contacts' not in response: logger.error(f"error triggering automation with id {str(acp_id)}", response) raise APIException('Could not add contact to Automation') else: logger.debug(f"Triggered automation with id {str(acp_id)}", response)
def setUp(self): self.client = Client(os.environ.get('host'), os.environ.get('api_key'))
from functools import lru_cache from activecampaign.client import Client from activecampaign.exception import ActiveCampaignError from django.conf import settings _client = Client(settings.ACTIVE_CAMPAIGN_URL, settings.ACTIVE_CAMPAIGN_KEY) _roles_cache = None _LEAD = 'lead' _CLIENT = 'client' _MEMBER = 'member' _ROLES = {_LEAD, _CLIENT, _MEMBER} def create_or_update_with_no_role(name: str, email: str, *tags, id='0'): return _create_or_update(name, email, '', *tags, id=id) def create_or_update_lead(name: str, email: str, *tags, id='0'): return _create_or_update(name, email, _LEAD, *tags, id=id) def create_or_update_client(name: str, email: str, *tags, id='0'): return _create_or_update(name, email, _CLIENT, *tags, id=id) def create_or_update_member(name: str, email: str, *tags, id='0'): return _create_or_update(name, email, _MEMBER, *tags, id=id)
def setUp(self): self.host = os.environ.get('host') self.api_key = os.environ.get('api_key') self.client = Client(self.host, self.api_key)
def test_ac_connection(ac_academy): client = Client(ac_academy.ac_url, ac_academy.ac_key) response = client.tags.list_all_tags(limit=1) return response
def register_new_lead(form_entry=None): if form_entry is None: raise Exception('You need to specify the form entry data') if 'location' not in form_entry or form_entry['location'] is None: raise Exception('Missing location information') ac_academy = ActiveCampaignAcademy.objects.filter( academy__slug=form_entry['location']).first() if ac_academy is None: raise Exception(f"No academy found with slug {form_entry['location']}") automations = get_lead_automations(ac_academy, form_entry) if automations: logger.debug("found automations") logger.debug(automations) else: logger.debug("automations not found") tags = get_lead_tags(ac_academy, form_entry) logger.debug("found tags") logger.debug(set(t.slug for t in tags)) LEAD_TYPE = tags[0].tag_type if (automations is None or len(automations) == 0) and len(tags) > 0: if tags[0].automation is None: raise Exception( 'No automation was specified and the the specified tag has no automation either' ) automations = [tags[0].automation.acp_id] if not 'email' in form_entry: raise Exception('The email doesn\'t exist') if not 'first_name' in form_entry: raise Exception('The first name doesn\'t exist') if not 'last_name' in form_entry: raise Exception('The last name doesn\'t exist') if not 'phone' in form_entry: raise Exception('The phone doesn\'t exist') if not 'id' in form_entry: raise Exception('The id doesn\'t exist') contact = { "email": form_entry["email"], "first_name": form_entry["first_name"], "last_name": form_entry["last_name"], "phone": form_entry["phone"] } contact = set_optional(contact, 'utm_url', form_entry) contact = set_optional(contact, 'utm_location', form_entry, "location") contact = set_optional(contact, 'course', form_entry) contact = set_optional(contact, 'utm_language', form_entry, "language") contact = set_optional(contact, 'utm_country', form_entry, "country") contact = set_optional(contact, 'client_comments', form_entry, "client_comments") contact = set_optional(contact, 'gclid', form_entry) contact = set_optional(contact, 'referral_key', form_entry) entry = FormEntry.objects.filter(id=form_entry['id']).first() if not entry: raise Exception('FormEntry not found (id: ' + str(form_entry['id']) + ')') # save geolocalization info # save_get_geolocal(entry, form_enty) if 'contact-us' == tags[0].slug: send_email_message( 'new_contact', ac_academy.academy.marketing_email, { "subject": f"New contact from the website {form_entry['first_name']} {form_entry['last_name']}", "full_name": form_entry['first_name'] + " " + form_entry['last_name'], "client_comments": form_entry['client_comments'], "data": { **form_entry }, # "data": { **form_entry, **address }, }) # ENV Variable to fake lead storage if SAVE_LEADS == 'FALSE': logger.debug( "Ignoring leads because SAVE_LEADS is FALSE on the env variables") return form_entry logger.debug("ready to send contact with following details: ", contact) old_client = AC_Old_Client(ac_academy.ac_url, ac_academy.ac_key) response = old_client.contacts.create_contact(contact) contact_id = response['subscriber_id'] if 'subscriber_id' not in response: logger.error("error adding contact", response) raise APIException('Could not save contact in CRM') client = Client(ac_academy.ac_url, ac_academy.ac_key) if automations: for automation_id in automations: data = { "contactAutomation": { "contact": contact_id, "automation": automation_id } } response = client.contacts.add_a_contact_to_an_automation(data) if 'contacts' not in response: logger.error( f"error triggering automation with id {str(automation_id)}", response) raise APIException('Could not add contact to Automation') else: logger.debug( f"Triggered automation with id {str(automation_id)}", response) auto = Automation.objects.filter( acp_id=automation_id, ac_academy=ac_academy).first() entry.automation_objects.add(auto) for t in tags: data = {"contactTag": {"contact": contact_id, "tag": t.acp_id}} response = client.contacts.add_a_tag_to_contact(data) if 'contacts' in response: entry.tag_objects.add(t.id) entry.storage_status = 'PERSISTED' entry.save() form_entry['storage_status'] = 'PERSISTED' return entry
from activecampaign.client import Client from settings import ACTIVE_CAMPAIGN_URL, ACTIVE_CAMPAIGN_KEY client = Client(ACTIVE_CAMPAIGN_URL, ACTIVE_CAMPAIGN_KEY)
This module takes care of starting the API Server, Loading the DB and Adding the endpoints """ import os from flask import Flask, request, jsonify, url_for from flask_migrate import Migrate from flask_swagger import swagger from flask_cors import CORS from utils import APIException, generate_sitemap from models import db, Customer, Queries, Products, Orders, Cart from activecampaign.client import Client from flask_jwt_simple import (JWTManager, jwt_required, create_jwt, get_jwt_identity) #from models import Person client = Client('https://libertyexpress.api-us1.com', os.environ.get('AC_KEY')) app = Flask(__name__) app.url_map.strict_slashes = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['JWT_SECRET_KEY'] = 'secret-key' # Change this! jwt = JWTManager(app) MIGRATE = Migrate(app, db) db.init_app(app) CORS(app) # Handle/serialize errors like a JSON object @app.errorhandler(APIException) def handle_invalid_usage(error): return jsonify(error.to_dict()), error.status_code
from activecampaign.client import Client client = Client(URL, API_KEY)
import os, re from itertools import chain from .models import FormEntry, Tag, Automation from schema import Schema, And, Use, Optional, SchemaError from rest_framework.exceptions import APIException, ValidationError, PermissionDenied from activecampaign.client import Client from .utils import AC_Old_Client client = Client(os.getenv('ACTIVE_CAMPAIGN_URL'), os.getenv('ACTIVE_CAMPAIGN_KEY')) old_client = AC_Old_Client(os.getenv('ACTIVE_CAMPAIGN_URL'), os.getenv('ACTIVE_CAMPAIGN_KEY')) acp_ids = { # "strong": "49", # "soft": "48", # "newsletter_list": "3", "utm_url": "15", "utm_location": "18", "course": "2", "utm_language": "16", "utm_country": "19", "gclid": "26", "referral_key": "27", } def set_optional(contact, key, data, custom_key=None): if custom_key is None: custom_key = key if custom_key in data: