import requests from mixpanel import Mixpanel from django.conf import settings from django.contrib.auth import get_user_model from project.celery import app from project.sengrid import get_sendgrid_client @app.task def user_to_mixpanel(user_id, email, phone, first_name, last_name, date_joined, role, subscriptions): mix = Mixpanel(settings.MIX_TOKEN) mix.people_set( user_id, { '$email': email, '$phone': phone, '$first_name': first_name, '$last_name': last_name, '$created': date_joined, 'role': role, 'subscriptions': subscriptions, } ) @app.task def users_to_roistat(): User = get_user_model() users_queryset = User.objects.all() users = [ { 'id': str(user.id), 'name': user.get_full_name(), 'phone': str(user.phone), 'email': user.email, 'birth_date': user.birthday.strftime('%d%m%Y') if user.birthday else None, } for user in users_queryset ] project = settings.ROISTAT_PROJECT key = settings.ROISTAT_KEY url = settings.ROISTAT_API_URL + f'/project/clients/import?key={key}&project={project}' resp = requests.post(url, json=users) @app.task def subscribers_to_sendgrid(): from apps.user.models import EmailSubscription list_id = None list_name = 'subscribed' sg = get_sendgrid_client() # берем все списки response = sg.client.contactdb.lists.get() if response.status_code != 200: print('Cannot get list of lists') return # ищем нужный список for sg_list in response.to_dict.get('lists'): if sg_list.get('name') == list_name: list_id = sg_list.get('id') break # не нашли - создаем if not list_id: response = sg.client.contactdb.lists.post(request_body={'name': list_name}) if response.status_code != 201: print('List was not created') return list_id = response.to_dict.get('id') for subscriber in EmailSubscription.objects.filter(sendgrid_sent=False): print('Adding subscriber %s ...' % subscriber.email, end=' ') # добавляем получателя response = sg.client.contactdb.recipients.patch(request_body=[{ 'email': subscriber.email, }]) if response.status_code != 201 or not response.to_dict.get('persisted_recipients'): print('Cannot update recipients') continue recipient_id = response.to_dict.get('persisted_recipients')[0] # добавляем получателя в отдельный список response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).post() if response.status_code != 201: print('Cannot add recipient to list') else: print('OK') subscriber.sendgrid_sent = True subscriber.save()