-
Notifications
You must be signed in to change notification settings - Fork 2
/
intercom.py
68 lines (59 loc) · 2.08 KB
/
intercom.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
import os
import requests
import pandas as pd
from datetime import datetime
consortia_admin_emails = []
zzz = os.getenv("INTERCOM_CONSORTIA_ADMIN_EMAILS")
if zzz:
consortia_admin_emails = zzz.split(",")
def intercom(emails, domain):
if not emails and not domain:
return ['', '']
emails_array = [{"field": "email", "operator": "=", "value": w} for w in emails]
if domain:
if '@' not in domain:
domain = '@' + domain
domain_dict = {"field": "email", "operator": "$", "value": domain}
emails_array.append(domain_dict)
body = {
"query": {
"operator": "AND",
"value": [
{
"field": "segment_id",
"operator": "=",
"value": "622995922effdb52e71bb464" # segment: "All users-Not-Portland"
},
{
"operator": "OR",
"value": emails_array
}
]
}
}
intercom_base = "https://api.intercom.io"
key = os.getenv("INTERCOM_API_KEY")
auth = {"Authorization": "Bearer " + key}
res = requests.post(intercom_base + "/contacts/search", json=body, headers=auth)
last_seen_at = ''
email_last_seen_at = ''
if res.ok:
data = res.json()
# remove consortia admins
data = list(filter(lambda x: x['email'] not in consortia_admin_emails, data['data']))
# filter to emails searched or domain for organization
data = list(filter(lambda x: x['email'] in emails or domain in x['email'], data))
# times = [datetime.fromtimestamp(w['last_seen_at']) for w in data if w['last_seen_at'] is not None]
times = [w['last_seen_at'] for w in data if w['last_seen_at'] is not None]
if len(times) > 1:
last_seen_at = max(times)
elif len(times) == 0:
last_seen_at = ''
else:
last_seen_at = times[0]
if last_seen_at:
email_last_seen_at = list(filter(lambda z: z['last_seen_at'] == last_seen_at, data))[0].get('email')
last_seen_at = datetime.fromtimestamp(last_seen_at)
if isinstance(last_seen_at, pd.Timestamp) or isinstance(last_seen_at, datetime):
last_seen_at = last_seen_at.strftime("%Y-%m-%d")
return [str(last_seen_at), email_last_seen_at]