-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailchimp.py
86 lines (75 loc) · 2.29 KB
/
mailchimp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Import packages
from settings import *
'''
Method: instantiate_mailchimp_api()
Summary: Instantiates Mailchimp API
'''
def instantiate_mailchimp_api():
return MailChimp(
os.environ["mailchimp_api_key"],
os.environ["mailchimp_username"],
)
'''
Method: get_student_status()
Summary: Retrieves the subscription status for a specific user
'''
def get_student_status(
client,
list_id,
student_email,
):
# If the student is already in Mailchimp, retrieve their status
try:
return client.lists.members.get(
list_id = list_id,
subscriber_hash = student_email
)['status']
# If the student is not in Mailchimp, return 'subscribed'
except mailchimp3.Mailchimp.MailChimpError:
return 'subscribed'
'''
Method: add_student()
Summary: Adds or updates a student information in Mailchimp
'''
def add_student(
student_data,
):
# Instantiate MailChimp API
client = instantiate_mailchimp_api()
# Get list_id to add member to
list_id = os.environ['mailchimp_list_id']
# Get student 'status' if student is already in Mailchimp
status = get_student_status(
client,
list_id,
student_data['student_email']
)
# Create data payload for member
member_data = {
'email_address': student_data['student_email'],
'status_if_new': status,
'status': status,
'merge_fields': {
'FNAME': student_data['student_first_name'] or '',
'LNAME': student_data['student_last_name'] or '',
'NEXTDESC': student_data["next_lecture_description"] or '',
'NEXTMINS': student_data["next_lecture_minutes"] or '',
'NEXTLINK': student_data["next_lecture_link"] or '',
'COURSENAME': student_data["course_name"] or '',
'LSTLCTDATE': student_data["last_lecture_date"] or '',
}
}
# Add student data to Mailchimp
client.lists.members.create_or_update(
list_id = list_id,
subscriber_hash = student_data['student_email'],
data = member_data,
)
# Add tags to student
client.lists.members.tags.update(
list_id = list_id,
subscriber_hash = student_data['student_email'],
data = {
'tags': student_data["tags"],
},
)