Ejemplo n.º 1
0
 def sync_cm_list(sender, instance=None, created=False, **kwargs):
     """On Group Add:
             if group name does not exist on C. M,
                 add a list to C. M.
             add an entry to listmap
             
         On Group Edit:
             if group exists on C. M.,
                 if list.name <> group.name,
                     update list name
             else:
                 add a list on C. M.
                 add an entry to listmap
     """
     
     cl = Client(cm_client_id)
     lists = cl.lists()
     list_ids = [list.ListID for list in lists]
     list_names = [list.Name for list in lists]
     list_ids_d = dict(zip(list_names, list_ids))
     list_d = dict(zip(list_ids, lists))
     
     if created:
         if instance.name in list_names:
             list_id = list_ids_d[instance.name]
             
         else:
             list_id = get_or_create_cm_list(cm_client_id, instance)
         
         if list_id:
             # add an entry to the listmap
             listmap_insert(instance, list_id)
             
         
     else:   # update
         try:
             # find the entry in the listmap
             list_map = ListMap.objects.get(group=instance)
             list_id = list_map.list_id
         except ListMap.DoesNotExist:
             if instance.name in list_names:
                 list_id = list_ids_d[instance.name]
             else:
                 # hasn't be created on C. M. yet. create one
                 list_id = get_or_create_cm_list(cm_client_id, instance)
                     
               
             if list_id:  
                 listmap_insert(instance, list_id)
                 
         
         # if the list title doesn't match with the group name, update the list title
         if list_id and list_id in list_ids:
             list = list_d[list_id]
             if instance.name != list.Name:
                 list = List(list_id)
                 list.update(instance.name, "", False, "")
Ejemplo n.º 2
0
 def handle_noargs(self, **options):
     client = CSClient(auth=settings.CREDENTIALS, client_id=settings.CLIENT_ID)
     lists = client.lists()
     for list_id in lists:
         list = CSList(list_id)
         import pdb; pdb.set_trace()
         data = list.list_id # WTF?!
         List.objects.create(
             cm_id=data.ListID,
             title=data.Name,
         )
 def handle_noargs(self, **options):
     CreateSend.api_key = settings.API_KEY
     client = CSClient(client_id=settings.CLIENT_ID)
     lists = client.lists()
     for list_id in lists:
         list = CSList(list_id)
         import pdb; pdb.set_trace()
         data = list.list_id # WTF?!
         List.objects.create(
             cm_id=data.ListID,
             title=data.Name,
         )
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.profiles.models import Profile
        from tendenci.apps.campaign_monitor.models import (ListMap, setup_custom_fields)
        from tendenci.apps.campaign_monitor.utils import sync_campaigns, sync_templates
        from createsend import (Client, List, Subscriber,
            BadRequest, Unauthorized)

        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']

        def subscribe_to_list(subscriber_obj, list_id, name, email, custom_data):
            # check if this user has already subscribed, if not, subscribe it
            try:
                subscriber = subscriber_obj.get(list_id, email)
                if str(subscriber.State).lower() == 'active':
                    print(name, email, ' - UPDATED')
                    subscriber = subscriber_obj.update(email, name, custom_data, True)
            except BadRequest as br:
                print(br)
                try:
                    subscriber_obj.add(list_id, email, name, custom_data, True)  # Returns email_address
                    if verbosity >=2:
                        print("%s (%s)" % (name, email))
                except BadRequest as br:
                    print(name, email, ' - NOT ADDED: %s' % br)

        api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
        client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None)
        #CreateSend.api_key = api_key
        auth = {'api_key': api_key}
        cl = Client(auth, client_id)

        lists = cl.lists()
        list_ids = [list.ListID for list in lists]
        list_names = [list.Name for list in lists]
        list_ids_d = dict(zip(list_names, list_ids))

        groups = Group.objects.filter(status=1, status_detail='active', sync_newsletters=1)
        listmaps = ListMap.objects.filter(group__sync_newsletters=1)
        syncd_groups = [listmap.group for listmap in listmaps]
        cm_list = List(auth)

        print("Starting to sync groups with campaign monitor...")
        print()

        for group in groups:
            if group not in syncd_groups:
                # get the list id or create a list if not exists
                # campaing monitor requires the list title
                if group.name in list_names:
                    list_id = list_ids_d[group.name]
                else:
                    # add group to the campaign monitor
                    list_id = cm_list.create(client_id, group.name, "", False, "")
                    print("Added group '%s' to the C.M. list." % group.name)
                    print()

                # insert to the listmap
                list_map = ListMap(group=group,
                           list_id=list_id)
                list_map.save()
            else:
                list_map = ListMap.objects.filter(group=group)[0]
                list_id = list_map.list_id

            # if a previous added list is deleted on campaign monitor, add it back
            # TODO: we might need a setting to decide whether we want to add it back or not.

            a_list = List(auth, list_id)
            try:
                #list_stats = a_list.stats()
                # set up custom fields
                print("Setting up custom fields...")
                setup_custom_fields(a_list)
                #num_unsubscribed = list_stats.TotalUnsubscribes
                #if num_unsubscribed > 0:
                #    # a list of all unsubscribed
                #    unsubscribed_obj = a_list.unsubscribed('2011-5-1')
                #    unsubscribed_emails = [res.EmailAddress for res in unsubscribed_obj.Results]
                #    unsubscribed_names = [res.Name for res in unsubscribed_obj.Results]
                #   unsubscribed_list = zip(unsubscribed_emails, unsubscribed_names)
            except Unauthorized as e:
                if 'Invalid ListID' in e:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = cm_list.create(client_id, group.name, "", False, "")
                    # update the list_map
                    list_map.list_id = list_id
                    list_map.save()

            # sync subscribers in this group
            print("Subscribing users to the C.M. list '%s'..." % group.name)
            members = group.members.all()
            for i, member in enumerate(members, 1):
                # Append custom fields from the profile
                try:
                    profile = member.profile
                except Profile.DoesNotExist:
                    profile = None
                custom_data = []
                if profile:
                    fields = ['city', 'state', 'zipcode', 'country', 'sex', 'member_number']
                    for field in fields:
                        data = {}
                        data['Key'] = field
                        data['Value'] = getattr(profile, field)
                        if not data['Value']:
                            data['Clear'] = True
                        custom_data.append(data)
                email = member.email
                name = member.get_full_name()
                subscriber_obj = Subscriber(auth, list_id, email)
                subscribe_to_list(subscriber_obj, list_id, name, email, custom_data)

        print('Done')

        print('Starting to sync campaigns with campaign monitor...')
        sync_campaigns()
        print("Done")

        print('Syncing templates...')
        sync_templates()
        print("Done")
 def setup_cm_account(password=''):
     # check if already setup
     client_id =  getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', '')
     if not client_id or client_id == '[CAMPAIGNMONITOR_API_CLIENT_ID]':
         cs = CreateSend()
         company_name = get_setting('site', 'global', 'sitedisplayname')
         #contact_name = get_setting('site', 'global', 'admincontactname')
         #contact_email = get_setting('site', 'global', 'admincontactemail')
         contact_name = "Schipul Client"
         contact_email = get_contact_email()
         if not contact_email:
             raise ValueError("Invalid Email address.")
         #timezone = get_setting('site', 'global', 'defaulttimezone')
         # country - must exist on campaign monitor
         country = 'United States of America'
         
         # timezone - must use the format specified by campaign monitor
         timezone = "(GMT-06:00) Central Time (US & Canada)"
         
         api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None) 
         CreateSend.api_key = api_key
         
         # check if this company already exists on campaign monitor
         # if it does, raise an error
         
         clients = cs.clients()
         cm_client_id = None
         
         for cl in clients:
             if cl.Name == company_name:
                 #cm_client_id = cl.ClientID
                 #break
                 raise ValueError('Company name "%s" already exists on campaign monitor.' % company_name)
             
         if not cm_client_id:
             # 1) Create an account
             cl = Client()
             cm_client_id = cl.create(company_name, contact_name, contact_email, timezone, country)
             cl = Client(cm_client_id)
             
             # 2) Set access with username and password
             # access level = 63  full access
             username = company_name.replace(' ', '')
             if not password:
                 # generate a random password with 6 in length
                 allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789()#$%'
                 password = User.objects.make_random_password(length=6, allowed_chars=allowed_chars)
             
             cl.set_access(username, password, 63)
             
             # 3) Set up billing - client will pay monthly
             #cl.set_payg_billing('USD', True, True, 0)
             cl.set_monthly_billing('USD', True, 0)
             
             # send an email to [email protected]
             now = datetime.now()
             now_str = now.strftime('%m/%d/%Y %H:%M')
             sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
             recipient = '*****@*****.**'
             subject = 'Campaign Monitor New client Account "%s" Created' % company_name
             email_body = """Company Name: %s
                             \n\nContact Name: %s
                             \n\nContact Email: %s
                             \n\n\nThanks,\n%s\n
                         """ % (company_name, contact_name, contact_email, now_str)
             send_mail(subject, email_body, sender, [recipient], fail_silently=True)
             
                             
         
         # add/update the client_id in the local_settings.py
         local_setting_file = os.path.join(getattr(settings, 'PROJECT_ROOT'), 'settings.py')
         f = open(local_setting_file, 'r')
         content = f.read()
         if client_id == '[CAMPAIGNMONITOR_API_CLIENT_ID]':
             content = content.replace('[CAMPAIGNMONITOR_API_CLIENT_ID]', cm_client_id)
         else:
             content = "%s\nCAMPAIGNMONITOR_API_CLIENT_ID='%s'\n" % (content, cm_client_id)
         f.close()
         f = open(local_setting_file, 'w')
         f.write(content)
         f.close()
         
         print('Success!')
         
     else:
         print('Already has a campaign monitor account')
Ejemplo n.º 6
0
    def sync_cm_list(sender, instance=None, created=False, **kwargs):
        """Check if sync_newsletters. Do nothing if false.
            On Group Add:
                if group name does not exist on C. M,
                    add a list to C. M.
                add an entry to listmap

            On Group Edit:
                if group exists on C. M.,
                    if list.name <> group.name,
                        update list name
                else:
                    add a list on C. M.
                    add an entry to listmap
        """

        cl = Client(auth, cm_client_id)
        lists = cl.lists()
        list_ids = [alist.ListID for alist in lists]
        list_names = [alist.Name for alist in lists]
        list_ids_d = dict(zip(list_names, list_ids))
        list_d = dict(zip(list_ids, lists))

        if created and instance.sync_newsletters:
            if instance.name in list_names:
                list_id = list_ids_d[instance.name]

            else:
                list_id = get_or_create_cm_list(cm_client_id, instance)

            if list_id:
                # add an entry to the listmap
                listmap_insert(instance, list_id)

                # custom fields setup
                cm_list = List(auth, list_id)
                setup_custom_fields(cm_list)

        elif instance.sync_newsletters:  # update
            try:
                # find the entry in the listmap
                list_map = ListMap.objects.get(group=instance)
                list_id = list_map.list_id
            except ListMap.DoesNotExist:
                if instance.name in list_names:
                    list_id = list_ids_d[instance.name]
                else:
                    # hasn't be created on C. M. yet. create one
                    list_id = get_or_create_cm_list(cm_client_id, instance)

                if list_id:
                    listmap_insert(instance, list_id)

            if list_id and list_id in list_ids:
                alist = list_d[list_id]
                cm_list = List(auth, list_id)
                # setup custom fields
                setup_custom_fields(cm_list)
                # if the list title doesn't match with the group name, update the list title
                if instance.name != alist.Name:
                    try:
                        # trap the error for now
                        # TODO: update only if the list title does not exist
                        # within a client.
                        cm_list.update(instance.name, "", False, "")
                    except:
                        pass
Ejemplo n.º 7
0
    def handle(self, *args, **options):
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.profiles.models import Profile
        from tendenci.apps.subscribers.models import GroupSubscription as GS, SubscriberData as SD
        from tendenci.apps.subscribers.utils import get_subscriber_name_email
        from tendenci.addons.campaign_monitor.models import ListMap, Campaign, Template, setup_custom_fields
        from tendenci.addons.campaign_monitor.utils import sync_campaigns, sync_templates
        from createsend import CreateSend, Client, List, Subscriber, BadRequest, Unauthorized

        verbosity = 1
        if "verbosity" in options:
            verbosity = options["verbosity"]

        def subscribe_to_list(subscriber_obj, list_id, name, email, custom_data):
            # check if this user has already subscribed, if not, subscribe it
            try:
                subscriber = subscriber_obj.get(list_id, email)
                if str(subscriber.State).lower() == "active":
                    print name, email, " - UPDATED"
                    subscriber = subscriber_obj.update(email, name, custom_data, True)
            except BadRequest as br:
                print br
                try:
                    email_address = subscriber_obj.add(list_id, email, name, custom_data, True)
                    if verbosity >= 2:
                        print "%s (%s)" % (name, email)
                except BadRequest as br:
                    print name, email, " - NOT ADDED: %s" % br

        api_key = getattr(settings, "CAMPAIGNMONITOR_API_KEY", None)
        client_id = getattr(settings, "CAMPAIGNMONITOR_API_CLIENT_ID", None)
        # CreateSend.api_key = api_key
        auth = {"api_key": api_key}
        cl = Client(auth, client_id)

        lists = cl.lists()
        list_ids = [list.ListID for list in lists]
        list_names = [list.Name for list in lists]
        list_ids_d = dict(zip(list_names, list_ids))

        groups = Group.objects.filter(status=1, status_detail="active", sync_newsletters=1)
        listmaps = ListMap.objects.filter(group__sync_newsletters=1)
        syncd_groups = [listmap.group for listmap in listmaps]
        cm_list = List(auth)

        print "Starting to sync groups with campaign monitor..."
        print

        for group in groups:
            if group not in syncd_groups:
                # get the list id or create a list if not exists
                # campaing monitor requires the list title
                if group.name in list_names:
                    list_id = list_ids_d[group.name]
                else:
                    # add group to the campaign monitor
                    list_id = cm_list.create(client_id, group.name, "", False, "")
                    print "Added group '%s' to the C.M. list." % group.name
                    print

                # insert to the listmap
                list_map = ListMap(group=group, list_id=list_id)
                list_map.save()
            else:
                list_map = ListMap.objects.filter(group=group)[0]
                list_id = list_map.list_id

            # if a previous added list is deleted on campaign monitor, add it back
            # TODO: we might need a setting to decide whether we want to add it back or not.

            a_list = List(list_id)
            try:
                list_stats = a_list.stats()
                # set up custom fields
                print "Setting up custom fields..."
                setup_custom_fields(a_list)
                # num_unsubscribed = list_stats.TotalUnsubscribes
                # if num_unsubscribed > 0:
                #    # a list of all unsubscribed
                #    unsubscribed_obj = a_list.unsubscribed('2011-5-1')
                #    unsubscribed_emails = [res.EmailAddress for res in unsubscribed_obj.Results]
                #    unsubscribed_names = [res.Name for res in unsubscribed_obj.Results]
                #   unsubscribed_list = zip(unsubscribed_emails, unsubscribed_names)
            except Unauthorized as e:
                if "Invalid ListID" in e:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = cm_list.create(client_id, group.name, "", False, "")
                    # update the list_map
                    list_map.list_id = list_id
                    list_map.save()

            # sync subscribers in this group
            print "Subscribing users to the C.M. list '%s'..." % group.name
            members = group.members.all()
            for i, member in enumerate(members, 1):
                # Append custom fields from the profile
                try:
                    profile = member.profile
                except Profile.DoesNotExist:
                    profile = None
                custom_data = []
                if profile:
                    fields = ["city", "state", "zipcode", "country", "sex", "member_number"]
                    for field in fields:
                        data = {}
                        data["Key"] = field
                        data["Value"] = getattr(profile, field)
                        if not data["Value"]:
                            data["Clear"] = True
                        custom_data.append(data)
                email = member.email
                name = member.get_full_name()
                subscriber_obj = Subscriber(auth, list_id, email)
                subscribe_to_list(subscriber_obj, list_id, name, email, custom_data)

            # sync subscribers in this group's subscription
            gss = GS.objects.filter(group=group)
            for gs in gss:
                if gs.subscriber:
                    form_entry = gs.subscriber
                    (name, email) = form_entry.get_name_email()
                else:
                    gs_data = SD.objects.filter(subscription=gs)
                    (name, email) = get_subscriber_name_email(gs_data)

                if email:
                    subscriber_obj = Subscriber(auth, list_id, email)
                    subscribe_to_list(subscriber_obj, list_id, name, email, [])

        print "Done"

        print "Starting to sync campaigns with campaign monitor..."
        sync_campaigns()
        print "Done"

        print "Syncing templates..."
        sync_templates()
        print "Done"
Ejemplo n.º 8
0
import shutil

from django.conf import settings
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

from createsend import CreateSend, Client, Subscriber
from createsend.createsend import BadRequest

from tendenci.addons.campaign_monitor.models import Campaign, Template

api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
api_password = getattr(settings, 'CAMPAIGNMONITOR_API_PASSWORD', None)
client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None)
CreateSend.api_key = api_key
cl = Client(client_id)


def random_string(n=32):
    return ''.join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase +
                      string.digits) for x in range(n))


def temporary_id():
    exists = True
    while (exists):
        id = random_string()
        if not Template.objects.filter(template_id=id).exists():
            exists = False
    return id
        def setup_cm_account(password=''):
            # check if already setup
            client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', '')
            if not client_id or client_id == '[CAMPAIGNMONITOR_API_CLIENT_ID]':
                cs = CreateSend()
                company_name = get_setting('site', 'global', 'sitedisplayname')
                #contact_name = get_setting('site', 'global', 'admincontactname')
                #contact_email = get_setting('site', 'global', 'admincontactemail')
                contact_name = "Schipul Client"
                contact_email = get_contact_email()
                if not contact_email:
                    raise ValueError("Invalid Email address.")
                #timezone = get_setting('site', 'global', 'defaulttimezone')
                # country - must exist on campaign monitor
                country = 'United States of America'

                # timezone - must use the format specified by campaign monitor
                timezone = "(GMT-06:00) Central Time (US & Canada)"

                api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
                CreateSend.api_key = api_key

                # check if this company already exists on campaign monitor
                # if it does, raise an error

                clients = cs.clients()
                cm_client_id = None

                for cl in clients:
                    if cl.Name == company_name:
                        #cm_client_id = cl.ClientID
                        #break
                        raise ValueError(
                            'Company name "%s" already exists on campaign monitor.'
                            % company_name)

                if not cm_client_id:
                    # 1) Create an account
                    cl = Client()
                    cm_client_id = cl.create(company_name, contact_name,
                                             contact_email, timezone, country)
                    cl = Client(cm_client_id)

                    # 2) Set access with username and password
                    # access level = 63  full access
                    username = company_name.replace(' ', '')
                    if not password:
                        # generate a random password with 6 in length
                        allowed_chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789()#$%'
                        password = User.objects.make_random_password(
                            length=6, allowed_chars=allowed_chars)

                    cl.set_access(username, password, 63)

                    # 3) Set up billing - client will pay monthly
                    #cl.set_payg_billing('USD', True, True, 0)
                    cl.set_monthly_billing('USD', True, 0)

                    # send an email to [email protected]
                    now = datetime.now()
                    now_str = now.strftime('%m/%d/%Y %H:%M')
                    sender = get_setting('site', 'global',
                                         'siteemailnoreplyaddress'
                                         ) or settings.DEFAULT_FROM_EMAIL
                    recipient = '*****@*****.**'
                    subject = 'Campaign Monitor New client Account "%s" Created' % company_name
                    email_body = """Company Name: %s
                                    \n\nContact Name: %s
                                    \n\nContact Email: %s
                                    \n\n\nThanks,\n%s\n
                                """ % (company_name, contact_name,
                                       contact_email, now_str)
                    send_mail(subject,
                              email_body,
                              sender, [recipient],
                              fail_silently=True)

                # add/update the client_id in the local_settings.py
                local_setting_file = os.path.join(
                    getattr(settings, 'PROJECT_ROOT'), 'settings.py')
                f = open(local_setting_file, 'r')
                content = f.read()
                if client_id == '[CAMPAIGNMONITOR_API_CLIENT_ID]':
                    content = content.replace(
                        '[CAMPAIGNMONITOR_API_CLIENT_ID]', cm_client_id)
                else:
                    content = "%s\nCAMPAIGNMONITOR_API_CLIENT_ID='%s'\n" % (
                        content, cm_client_id)
                f.close()
                f = open(local_setting_file, 'w')
                f.write(content)
                f.close()

                print('Success!')

            else:
                print('Already has a campaign monitor account')
Ejemplo n.º 10
0
from django.core.files.base import ContentFile
from django.contrib import messages
from django.shortcuts import redirect

from createsend import CreateSend, Client, Subscriber
from createsend.createsend import BadRequest
from createsend import Template as CST

from tendenci.addons.campaign_monitor.models import Campaign, Template
from tendenci.core.site_settings.utils import get_setting

api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
api_password = getattr(settings, 'CAMPAIGNMONITOR_API_PASSWORD', None)
client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None)
auth = {'api_key': api_key}
cl = Client(auth, client_id)


def random_string(n=32):
    return ''.join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase +
                      string.digits) for x in range(n))


def temporary_id():
    exists = True
    while (exists):
        id = random_string()
        if not Template.objects.filter(template_id=id).exists():
            exists = False
    return id
Ejemplo n.º 11
0
    def sync_cm_list(sender, instance=None, created=False, **kwargs):
        """Check if sync_newsletters. Do nothing if false.
            On Group Add:
                if group name does not exist on C. M,
                    add a list to C. M.
                add an entry to listmap

            On Group Edit:
                if group exists on C. M.,
                    if list.name <> group.name,
                        update list name
                else:
                    add a list on C. M.
                    add an entry to listmap
        """

        cl = Client(auth, cm_client_id)
        lists = cl.lists()
        list_ids = [alist.ListID for alist in lists]
        list_names = [alist.Name for alist in lists]
        list_ids_d = dict(zip(list_names, list_ids))
        list_d = dict(zip(list_ids, lists))

        if created and instance.sync_newsletters:
            if instance.name in list_names:
                list_id = list_ids_d[instance.name]

            else:
                list_id = get_or_create_cm_list(cm_client_id, instance)

            if list_id:
                # add an entry to the listmap
                listmap_insert(instance, list_id)

                # custom fields setup
                cm_list = List(auth, list_id)
                setup_custom_fields(cm_list)

        elif instance.sync_newsletters:  # update
            try:
                # find the entry in the listmap
                list_map = ListMap.objects.get(group=instance)
                list_id = list_map.list_id
            except ListMap.DoesNotExist:
                if instance.name in list_names:
                    list_id = list_ids_d[instance.name]
                else:
                    # hasn't be created on C. M. yet. create one
                    list_id = get_or_create_cm_list(cm_client_id, instance)

                if list_id:
                    listmap_insert(instance, list_id)

            if list_id and list_id in list_ids:
                alist = list_d[list_id]
                cm_list = List(auth, list_id)
                # setup custom fields
                setup_custom_fields(cm_list)
                # if the list title doesn't match with the group name, update the list title
                if instance.name != alist.Name:
                    try:
                        # trap the error for now
                        # TODO: update only if the list title does not exist
                        # within a client.
                        cm_list.update(instance.name, "", False, "")
                    except:
                        pass
Ejemplo n.º 12
0
    def handle(self, *args, **options):
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.profiles.models import Profile
        from tendenci.apps.campaign_monitor.models import (ListMap, Campaign,
                                                           Template,
                                                           setup_custom_fields)
        from tendenci.apps.campaign_monitor.utils import sync_campaigns, sync_templates
        from createsend import (CreateSend, Client, List, Subscriber,
                                BadRequest, Unauthorized)

        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']

        def subscribe_to_list(subscriber_obj, list_id, name, email,
                              custom_data):
            # check if this user has already subscribed, if not, subscribe it
            try:
                subscriber = subscriber_obj.get(list_id, email)
                if str(subscriber.State).lower() == 'active':
                    print name, email, ' - UPDATED'
                    subscriber = subscriber_obj.update(email, name,
                                                       custom_data, True)
            except BadRequest as br:
                print br
                try:
                    email_address = subscriber_obj.add(list_id, email, name,
                                                       custom_data, True)
                    if verbosity >= 2:
                        print "%s (%s)" % (name, email)
                except BadRequest as br:
                    print name, email, ' - NOT ADDED: %s' % br

        api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
        client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None)
        #CreateSend.api_key = api_key
        auth = {'api_key': api_key}
        cl = Client(auth, client_id)

        lists = cl.lists()
        list_ids = [list.ListID for list in lists]
        list_names = [list.Name for list in lists]
        list_ids_d = dict(zip(list_names, list_ids))

        groups = Group.objects.filter(status=1,
                                      status_detail='active',
                                      sync_newsletters=1)
        listmaps = ListMap.objects.filter(group__sync_newsletters=1)
        syncd_groups = [listmap.group for listmap in listmaps]
        cm_list = List(auth)

        print "Starting to sync groups with campaign monitor..."
        print

        for group in groups:
            if group not in syncd_groups:
                # get the list id or create a list if not exists
                # campaing monitor requires the list title
                if group.name in list_names:
                    list_id = list_ids_d[group.name]
                else:
                    # add group to the campaign monitor
                    list_id = cm_list.create(client_id, group.name, "", False,
                                             "")
                    print "Added group '%s' to the C.M. list." % group.name
                    print

                # insert to the listmap
                list_map = ListMap(group=group, list_id=list_id)
                list_map.save()
            else:
                list_map = ListMap.objects.filter(group=group)[0]
                list_id = list_map.list_id

            # if a previous added list is deleted on campaign monitor, add it back
            # TODO: we might need a setting to decide whether we want to add it back or not.

            a_list = List(auth, list_id)
            try:
                list_stats = a_list.stats()
                # set up custom fields
                print "Setting up custom fields..."
                setup_custom_fields(a_list)
                #num_unsubscribed = list_stats.TotalUnsubscribes
                #if num_unsubscribed > 0:
                #    # a list of all unsubscribed
                #    unsubscribed_obj = a_list.unsubscribed('2011-5-1')
                #    unsubscribed_emails = [res.EmailAddress for res in unsubscribed_obj.Results]
                #    unsubscribed_names = [res.Name for res in unsubscribed_obj.Results]
                #   unsubscribed_list = zip(unsubscribed_emails, unsubscribed_names)
            except Unauthorized as e:
                if 'Invalid ListID' in e:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = cm_list.create(client_id, group.name, "", False,
                                             "")
                    # update the list_map
                    list_map.list_id = list_id
                    list_map.save()

            # sync subscribers in this group
            print "Subscribing users to the C.M. list '%s'..." % group.name
            members = group.members.all()
            for i, member in enumerate(members, 1):
                # Append custom fields from the profile
                try:
                    profile = member.profile
                except Profile.DoesNotExist:
                    profile = None
                custom_data = []
                if profile:
                    fields = [
                        'city', 'state', 'zipcode', 'country', 'sex',
                        'member_number'
                    ]
                    for field in fields:
                        data = {}
                        data['Key'] = field
                        data['Value'] = getattr(profile, field)
                        if not data['Value']:
                            data['Clear'] = True
                        custom_data.append(data)
                email = member.email
                name = member.get_full_name()
                subscriber_obj = Subscriber(auth, list_id, email)
                subscribe_to_list(subscriber_obj, list_id, name, email,
                                  custom_data)

        print 'Done'

        print 'Starting to sync campaigns with campaign monitor...'
        sync_campaigns()
        print "Done"

        print 'Syncing templates...'
        sync_templates()
        print "Done"
Ejemplo n.º 13
0
#
# client_details = my_client.details()
#
# print(client_details.ApiKey)

#print(a_test_client_auth)

# #print("hello world")
#
# my_subscriber = Subscriber(a_test_client_auth)
#
# my_custom_fields = [{"Key": "Favorite Cuisine", "Value": "Pizza"},{'Key': 'Hobby', "Value": "Football"}]
#
# my_subscriber.add("5926ac888cffa2665144bae9127a89a5", "*****@*****.**", "Subscriber", my_custom_fields, True, "yes")
#
my_client = Client(account_auth, client_id="9cde80d058d8e4955a076d33b6ec2294")
results = my_client.lists()
list_names_ids = {}
list_names = []
for r in results:
    list_names_ids[r.Name] = r.ListID
    list_names.append(r.Name)

print(list_names)
if 'Main List' not in list_names:
    print("its not there")
else:
    print("It exists!")
#
#
# print(type(dir(results[0])))
Ejemplo n.º 14
0
    def send(self):
        if getattr(settings, 'DRIP_USE_CREATESEND', False):

            template_name = self.drip_model.template_name
            segment_name = 'Drip Segment %s' % self.drip_model.name.replace("'",'').replace('"','')
            from createsend import Campaign, Segment,  CreateSend, BadRequest, Client

            CreateSend.api_key = settings.CREATESEND_API

            client = Client(settings.CREATESEND_CLIENT_ID)

            template_id = None
            for template in client.templates():
                if template.Name == template_name:
                    template_id = template.TemplateID

            if template_id is None:
                raise Exception("Template with the name '%s' does not exist" % template_name)

            segment_id = None
            for segment in client.segments():
                if segment.Title == segment_name and segment.ListID == settings.CREATESEND_LIST_ID:
                    segment_id = segment.SegmentID

            rules = []
            count = 0

            qs = self.get_queryset()
            clauses = []

            for user in qs:
                clauses.append("EQUALS %s" % user.email)
                count += 1
            rules = [{
                    
                    'Subject' : 'EmailAddress',
                    'Clauses' : clauses,
                    }]


            if count:
                if segment_id is not None:
                    segment = Segment(segment_id)
                    segment.clear_rules()
                    segment.update(segment_name, rules)
                else:
                    segment_id = Segment().create(settings.CREATESEND_LIST_ID, segment_name, rules)
                    segment = Segment(segment_id)

                subject = Template(self.subject_template).render(Context())
                body = Template(self.body_template).render(Context())
                name    = 'Drip Campaign %s %s' % (self.drip_model.name, datetime.now().isoformat())

                from_address = getattr(settings, 'DRIP_FROM_EMAIL', settings.EMAIL_HOST_USER)

                template_content = {
                    "Multilines" : [{
                        'Content': body,
                        },],
                    }


                campaign_id = Campaign().create_from_template(settings.CREATESEND_CLIENT_ID, 
                                                              subject, 
                                                              name, 
                                                              from_address, 
                                                              from_address, 
                                                              from_address, 
                                                              [], 
                                                              [segment.details().SegmentID], 
                                                              template_id, 
                                                              template_content,
                                                              )
                campaign = Campaign(campaign_id)
                failed = False
                try:
                    campaign.send(settings.CREATESEND_CONFIRMATION_EMAIL)
                except BadRequest as br:
                    print "ERROR: Could not send Drip %s: %s" % (self.drip_model.name, br)
                    failed = True
                
                if not failed:
                    for user in qs:
                        sd = SentDrip.objects.create(
                            drip=self.drip_model,
                            user=user,
                            subject=subject,
                            body=body
                            )

            return count

            

        else:
            """
            Send the email to each user on the queryset.

            Add that user to the SentDrip.

            Returns a list of created SentDrips.
            """

            count = 0
            for user in self.get_queryset():
                msg = self.build_email(user, send=True)
                count += 1

            return count