forked from vpetersson/py-agilecrm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagilecrm.py
More file actions
244 lines (189 loc) · 6.63 KB
/
agilecrm.py
File metadata and controls
244 lines (189 loc) · 6.63 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import requests
import json
import settings
from urlparse import urljoin
APIKEY = settings.AGILECRM_APIKEY
EMAIL = settings.AGILECRM_EMAIL
BASEURL = settings.AGILECRM_BASEURL
CONTACT_ENDPOINT = urljoin(BASEURL, '/dev/api/contacts')
CONTACT_SEARCH_ENDPOINT = urljoin(BASEURL, '/dev/api/contacts/search/email')
CONTACT_ADD_TAG_ENDPOINT = urljoin(BASEURL, '/dev/api/contacts/email/tags/add')
"""
Module for dealing with AgileCRMs API.
Documentation is available here:
https://github.com/agilecrm/rest-api
"""
def create_contact(first_name=None, last_name=None, email=None, tags=None, company=None, custom={}):
"""
Create a contact. first_name is the only required field.
Returns the ID if successful, otherwise return None and log the error.
"""
headers = {
'content-type': 'application/json',
}
tags = tags or []
payload = {
'tags': tags,
'properties': []
}
def add_element(element_id, value):
if element_id in ['first_name', 'last_name', 'company', 'email']:
payload_type = 'SYSTEM'
else:
payload_type = 'CUSTOM'
payload['properties'].append(
{
"type": payload_type,
"name": element_id,
"value": value
},
)
if first_name:
add_element('first_name', first_name)
if last_name:
add_element('last_name', last_name)
if company:
add_element('company', company)
if email:
add_element('email', email)
for key in custom:
add_element(key, custom[key])
contact = requests.post(
CONTACT_ENDPOINT,
data=json.dumps(payload),
headers=headers,
auth=(EMAIL, APIKEY)
)
# We get 200 status instead of the expected 201.
if contact.status_code in (200, 201):
result = json.loads(contact.content)
return result['id']
else:
print "Failed to create contact.\nError message:\n%s.\nError code: %i" % (contact.content, contact.status_code)
return None
def update_contact(uuid=None, first_name=None, last_name=None, email=None, tags=None, company=None, custom={}):
"""
Update a contact. email is required.
Returns the response if successful, otherwise log error and return None.
"""
headers = {
'content-type': 'application/json',
}
if uuid:
payload = get_contact_by_uuid(uuid)
else:
payload = get_contact_by_email(email)
if not payload:
print "Failed to get contact %s" % email
return None
def update_element(key, value):
new_values = set()
if key == 'email':
# Email is a special case -- the email key can appear more than once. We'll keep the existing values (deduplicated).
new_values = {d['value'] for d in payload['properties'] if d['name'] == 'email'}
new_values.add(value)
new_properties = [{"type": "SYSTEM" if key in ('first_name', 'last_name', 'company', 'email') else "CUSTOM", "name": key, "value": new_value} for new_value in new_values]
payload['properties'] = [d for d in payload['properties'] if d['name'] != key] + new_properties
tags = tags or []
if tags:
payload['tags'] = list(set(payload['tags'] + list(tags)))
if first_name:
update_element('first_name', first_name)
if last_name:
update_element('last_name', last_name)
if company:
update_element('company', company)
if email:
update_element('email', email)
for key in custom:
update_element(key, custom[key])
contact = requests.put(
CONTACT_ENDPOINT,
data=json.dumps(payload),
headers=headers,
auth=(EMAIL, APIKEY)
)
# We get 200 status instead of the expected 201.
if contact.status_code not in (200, 201):
print "Failed to update contact.\nError message:\n%s.\nError code: %i" % (contact.content, contact.status_code)
return None
return json.loads(contact.content)
def get_contact_by_email(email):
"""
Returns a user object in JSON format if successful.
Otherwise return None and log the error.
From docs:
$ curl https://{domain}.agilecrm.com/dev/api/contacts/search/email -H "Accept: application/json"
-H "Content-Type :application/x-www-form-urlencoded"
-d 'email_ids=["notifications@basecamp.com"]'
-v -u {email}:{apikey} -X POST
"""
payload = "email_ids=[%s]" % email
headers = {
'content-type': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
}
contact = requests.post(
CONTACT_SEARCH_ENDPOINT,
data=payload,
headers=headers,
auth=(EMAIL, APIKEY)
)
if contact.status_code != 200:
print "Failed to get contact.\nError message:\n%s.\nError code: %i" % (contact.content, contact.status_code)
return None
return json.loads(contact.content)[0]
def get_contact_by_uuid(uuid):
"""
Returns a user object in JSON format if successful.
Otherwise return None and log the error.
From docs:
$ curl https://{domain}.agilecrm.com/dev/api/contacts/{id} \
-H "Accept :application/xml" \
-v -u {email}:{apikey}
"""
headers = {
'Accept': 'application/json',
}
contact = requests.get(
'%s/%s' % (CONTACT_ENDPOINT, uuid),
headers=headers,
auth=(EMAIL, APIKEY)
)
if contact.status_code != 200:
print "Failed to get contact.\nError message:\n%s.\nError code: %i" % (contact.content, contact.status_code)
return None
return json.loads(contact.content)
def add_tag(email, tag):
"""
Returns True if successful, otherwise return None and log the error.
From docs:
$ curl https://{domain}.agilecrm.com/dev/api/contacts/email/tags/add -H "Accept: application/xml"
-H "Content-Type :application/x-www-form-urlencoded"
-d 'email=notifications@basecamp.com&tags=["testing"]'
-v -u {email}:{apikey} -X POST
"""
payload = {
'email': email,
'tags': "[%s]" % tag
}
headers = {
'content-type': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
}
contact = requests.post(
CONTACT_ADD_TAG_ENDPOINT,
data=payload,
headers=headers,
auth=(EMAIL, APIKEY)
)
# We get 200 status instead of the expected 201.
if contact.status_code in (200, 201):
return True
else:
print "Failed to add tag.\nError message:\n%s.\nError code: %i" % (contact.content, contact.status_code)
return None
def main():
pass
if __name__ == '__main__':
main()