-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathintercom-segment-tagger.gs
More file actions
320 lines (277 loc) · 10.6 KB
/
intercom-segment-tagger.gs
File metadata and controls
320 lines (277 loc) · 10.6 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
function intercomTagger() {
// Make it your own
var target = "contacts"; // set to either "contacts" or "companies"
var desiredTag = "Test failure tag"; // e.g., "New Tag 1". Tag name must match exactly.
// If target is companies and the tag name doesn't exist, a new tag will be created
// If target is contacts and the tag name doesn't exist, the task will fail with an explanation
var segmentId = ""; // e.g., "5c1d18fddf74c998cb0a9dcd" get this from the URL while viewing a segment
var ownerEmail = ""; // email address to notify of errors and optional script results
var sendResultEmails = true; // true or false -- do you want to be notified every time the script runs?
// ************************************
// No need to touch anything below this
// ************************************
// ************************************
// Utilities
// ************************************
// Get the Intercom auth token from the script properties (see setup function below)
var scriptProperties = PropertiesService.getScriptProperties();
var authToken = scriptProperties.getProperty('AUTH_TOKEN');
// Prompt you for your auth token, then store in the script properties
// Note that the prompt happens in the containing spreadsheet, not in the script editor!
function setup() {
Logger.log("Running setup.");
var ui = SpreadsheetApp.getUi();
var result = ui.prompt(
'Apply a tag to segment members',
'Enter your Intercom auth token:',
ui.ButtonSet.OK_CANCEL);
// Process the user's response.
var button = result.getSelectedButton();
var text = result.getResponseText();
if (button == ui.Button.OK) {
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('AUTH_TOKEN', text);
}
}
// Verify everything is ready to go
function ready() {
Logger.log("Initiating script.");
if (target && desiredTag && segmentId && authToken && ownerEmail) {
if (target != "contacts" && target != "companies") {
throw new Error("Must set target to either companies or contacts.");
} else {
return;
}
} else if (!authToken) {
setup(); // prompt for auth token in the spreadsheet
} else if (!ownerEmail) {
throw new Error("Add your email address so you can be notified of errors.");
} else {
MailApp.sendEmail(ownerEmail, "Error: Intercom script cannot run yet", "You are missing some key details. Please add them.");
throw new Error("The script can't run without the required details.");
}
}
// Retrieve an array of Intercom contacts from a specific segment
function getContactsSegment() {
Logger.log("Getting the contacts segment " + segmentId + ".");
try {
var url = "https://api.intercom.io/contacts/search";
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + authToken
};
var payload = {
"query": {
"field": "segment_id",
"operator": "=",
"value": segmentId
}
};
var options = {
"method": "post",
"headers": headers,
"payload": JSON.stringify(payload),
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var segment = JSON.parse(response)["data"];
return segment;
} catch (e) {
MailApp.sendEmail(ownerEmail, "Error: could not retrieve " + target, e.message);
}
}
// Retrieve an array of Intercom companies from a specific segment
function getCompaniesSegment() {
Logger.log("Getting the companies segment " + segmentId + ".");
try {
var url = "https://api.intercom.io/" + target + "?segment_id=" + segmentId;
var headers = {
"Accept": "application/json",
"Authorization": "Bearer " + authToken
};
var options = {
"method": "get",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var segment = JSON.parse(response)[target];
return segment;
} catch (e) {
MailApp.sendEmail(ownerEmail, "Error: could not retrieve " + target, e.message);
}
}
function updateTags() {
Logger.log("Updating the list of tags.");
try {
var url = "https://api.intercom.io/tags";
var headers = {
"Accept": "application/json",
"Authorization": "Bearer " + authToken
};
var options = {
"method": "get",
"headers": headers,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var allTags = JSON.parse(response)["data"];
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('TAGS', JSON.stringify(allTags));
} catch (e) {
MailApp.sendEmail(ownerEmail, "Error: unable to retrieve the list of all tags from Intercom.", e.message);
}
}
function getTagId(tagName) {
Logger.log("Getting the tag ID by tag name.");
var scriptProperties = PropertiesService.getScriptProperties();
var storedTags = JSON.parse(scriptProperties.getProperty('TAGS'));
var tagId = null;
if (storedTags) {
for (var i = 0; i < storedTags.length; i++) {
if (storedTags[i]["name"] == desiredTag) {
var tagId = storedTags[i]["id"];
}
}
}
return tagId;
}
// Apply a tag to an array of contact IDs
function applyContactsTag(blob,tagId) {
Logger.log("Applying the tag " + desiredTag + " to the contacts.");
for (var j = 0; j < blob.length; j++) {
var currentContactId = blob[j];
try {
var entities = {"id": tagId};
var url = "https://api.intercom.io/contacts/" + currentContactId + "/tags";
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + authToken
};
var options = {
"method": "post",
"headers": headers,
"payload": JSON.stringify(entities),
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
} catch (e) {
MailApp.sendEmail(ownerEmail, "Error: could not apply " + desiredTag, e.message);
}
}
}
// Apply a tag to an array of company IDs
function applyCompaniesTag(blob) {
Logger.log("Applying the tag " + desiredTag + " to the companies.");
try {
var entities = blob;
var url = "https://api.intercom.io/tags";
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + authToken
};
var options = {
"method": "post",
"headers": headers,
"payload": JSON.stringify(entities),
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
} catch (e) {
MailApp.sendEmail(ownerEmail, "Error: could not apply " + desiredTag, e.message);
}
}
function createCompaniesPayload() {
Logger.log("Creating the companies payload for the Intercom POST.");
// verify the retrieval worked
if (!intercomData) {
throw new Error("Something went wrong when retrieving the " + target + " segment from Intercom.");
} else if (intercomData.length > 0) { // proceed only if there are members of the segment
Logger.log("Building the companies items array.");
// turn the segment into an array of user/company IDs
var items = [];
for (var i = 0; i < intercomData.length; i++) {
items[i] = {};
items[i]["id"] = intercomData[i]["id"];
}
Logger.log("Companies items: " + items);
// prepare the Intercom API object
var applyList = {};
applyList["name"] = desiredTag;
applyList[target] = items;
return applyList;
} else {
var jobResult = "did not apply any tags.";
var msg = "";
return;
}
}
function createContactsPayload() {
Logger.log("Creating the contacts payload for the Intercom POST.");
// verify the retrieval worked
if (!intercomData) {
throw new Error("Something went wrong when retrieving the " + target + " segment from Intercom.");
} else if (intercomData.length > 0) { // proceed only if there are members of the segment
// turn the segment into an array of user/company IDs
Logger.log("Building the contacts items array.");
var items = [];
for (var i = 0; i < intercomData.length; i++) {
items[i] = intercomData[i]["id"];
}
Logger.log("Contacts items: " + items);
// prepare the Intercom API object
var applyList = items;
return applyList;
} else {
var jobResult = "did not apply any tags.";
var msg = "";
return;
}
}
// ************************************
// The action
// ************************************
// Run the show or fail gracefully if any of the required variables are missing
ready();
// get the list of entities as a JSON object
if (target === "companies") {
Logger.log("The target is companies.");
var intercomData = getCompaniesSegment();
var applyList = createCompaniesPayload();
if (!applyList) {
Logger.log("There is no list of companies to update.");
return;
}
applyCompaniesTag(applyList);
} else if (target === "contacts") {
Logger.log("The target is contacts.");
var intercomData = getContactsSegment();
var applyList = createContactsPayload();
if (!applyList) {
Logger.log("There is no list of contacts to update.");
return;
}
// Attempt to get the tag ID. If it doesn't exist, update the list of tags and try once more.
var getTagIdSuccess = false;
for (var t = 0; t < 2; t++) {
var desiredTagId = getTagId(desiredTag);
if (desiredTagId) {
Logger.log("Found the tag ID.");
getTagIdSuccess = true;
applyContactsTag(applyList,desiredTagId);
t = 2;
} else if (t < 1) {
Logger.log("Did not find the tag ID. Updating the tags list.");
updateTags();
}
}
if (!getTagIdSuccess) {
throw new Error("Could not find any ID for that tag name. Verify the tag name exists and retry.");
}
}
var jobResult = "updated the " + target + ".";
var msg = "Applied the " + desiredTag + " tag to the " + target + ".";
sendResultEmails === true ? MailApp.sendEmail(ownerEmail, "Intercom script run: " + jobResult, msg) : null;
}