-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.gs
More file actions
555 lines (497 loc) · 22 KB
/
Copy pathcode.gs
File metadata and controls
555 lines (497 loc) · 22 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
// -----------------------------------------------------------------------------
// --- MAIN ROUTER - Processes emails and dispatches tasks to modules ---
// -----------------------------------------------------------------------------
/**
* Main function with added verbose logging for debugging.
*/
function processGoogleVoiceEmails() {
const properties = PropertiesService.getScriptProperties();
const emailAlerts = [];
const groupMeActions = []; // Queue for batching GroupMe adds
// --- 1. Load Configuration from Script Properties ---
const config = {
token: properties.getProperty('GROUPME_TOKEN'),
sheetId: properties.getProperty('LOG_SHEET_ID'),
userPrefix: properties.getProperty('USER_PREFIX') || 'User',
userCount: parseInt(properties.getProperty('USER_COUNT')) || 1,
routingRules: JSON.parse(properties.getProperty('MODULE_ROUTING_RULES') || '{}'),
groupMeConfig: JSON.parse(properties.getProperty('GROUPME_ADDER_CONFIG') || '[]'),
sampleConfig: JSON.parse(properties.getProperty('SAMPLE_MODULE_CONFIG') || '{}')
};
debugLog('Script starting. Debug mode is ON.');
if (!config.token || !config.sheetId) {
Logger.log('FATAL ERROR: GROUPME_TOKEN or LOG_SHEET_ID is not set. Run setup().');
return;
}
const spreadsheet = SpreadsheetApp.openById(config.sheetId);
const logSheet = getSheetByName(spreadsheet, 'Logs');
const idSheet = getSheetByName(spreadsheet, 'ProcessedIDs');
const processedIds = getProcessedIds(idSheet);
const allKeywords = Object.keys(config.routingRules);
debugLog(`Loaded ${processedIds.size} processed IDs. Watching for keywords: [${allKeywords.join(', ')}]`);
// --- 2. Fetch and Process Emails ---
const query = 'from:txt.voice.google.com is:unread';
const threads = GmailApp.search(query, 0, 50);
Logger.log(`Found ${threads.length} unread threads.`);
debugLog(`------------- Start Email Processing Loop -------------`);
threads.forEach(thread => {
thread.getMessages().forEach(message => {
const subject = message.getSubject();
debugLog(`Inspecting message: "${subject}" (ID: ${message.getId()})`);
if (message.isUnread() && !processedIds.has(message.getId())) {
debugLog('-> Condition MET. Message is unread and not processed. Proceeding...');
const body = message.getPlainBody();
const phoneE164 = extractPhoneNumber(subject);
if (!phoneE164) {
logEntry(logSheet, 'N/A', 'N/A', `Error: Could not extract phone number from subject - "${subject}"`);
markMessageProcessed(message, idSheet, processedIds);
return;
}
debugLog(`--> Extracted Phone Number: ${phoneE164}`);
const messageText = body.split('Google Voice')[0].trim().toLowerCase();
const detectedKeyword = detectKeyword(messageText, allKeywords);
if (!detectedKeyword) {
debugLog(`--> No keyword found in message body. Marking as processed.`);
logEntry(logSheet, phoneE164, 'None', 'No keyword found in message.');
markMessageProcessed(message, idSheet, processedIds);
return;
}
debugLog(`--> Detected Keyword: "${detectedKeyword}"`);
// --- 3. Dispatch or Queue Module ---
const moduleName = config.routingRules[detectedKeyword];
const data = { phone: phoneE164, keyword: detectedKeyword, message: messageText };
if (moduleName === 'groupMeAdder') {
debugLog(`--> Queuing for GroupMe batch add. Keyword: "${detectedKeyword}"`);
groupMeActions.push(data);
} else {
try {
dispatchModule(moduleName, data, config, logSheet);
} catch (e) {
const errorMessage = `Error dispatching module '${moduleName}': ${e.message}`;
logEntry(logSheet, phoneE164, detectedKeyword, errorMessage);
emailAlerts.push(errorMessage);
}
}
markMessageProcessed(message, idSheet, processedIds);
} else {
if (!message.isUnread()) {
debugLog('-> SKIPPING: Message was already marked as read.');
}
if (processedIds.has(message.getId())) {
debugLog('-> SKIPPING: Message ID was already in the processed list.');
}
}
});
});
debugLog(`------------- Finished Email Processing Loop -------------`);
// --- 4. Process Batch GroupMe Adds ---
if (groupMeActions.length > 0) {
debugLog(`Processing ${groupMeActions.length} queued GroupMe actions.`);
processGroupMeAdds(groupMeActions, config, logSheet);
}
// --- 5. Send Error Summary Email ---
if (emailAlerts.length > 0) {
const alertBody = 'Errors encountered in Google Voice Script:\n' + emailAlerts.join('\n');
// MailApp.sendEmail('your-email@example.com', 'Google Voice Script Errors', alertBody);
}
}
/**
* Acts as a switchboard, calling the correct module function based on the module name.
* @param {string} moduleName - The name of the module to run.
* @param {object} data - The data object containing phone, keyword, and message.
* @param {object} config - The master configuration object.
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet - The logging sheet object.
*/
function dispatchModule(moduleName, data, config, sheet) {
Logger.log(`Dispatching to module: ${moduleName} for keyword: ${data.keyword}`);
switch (moduleName) {
case 'sampleModule':
runSampleModule(data, config, sheet);
break;
default:
// Note: 'groupMeAdder' is handled separately now and won't be dispatched here.
throw new Error(`Module '${moduleName}' not found or is not a real-time module.`);
}
}
// ---------------------------------------------------------------------------
// --- MODULES - Each function handles a specific type of task ---
// ---------------------------------------------------------------------------
/**
* =================================================================================
* === BATCH PROCESSING LOGIC =====================================================
* =================================================================================
*/
/**
* Updates and saves the user count, either globally or for a specific group.
* This centralizes the counter logic to be used by different adding strategies.
* @param {boolean} useGroupSpecificCounter - Flag to determine which counter to use.
* @param {string} groupId - The group ID (used if group-specific).
* @param {number} newCount - The new count to save.
* @param {object} config - The master configuration object (will be updated in-memory).
*/
function updateGroupMeAdderCount(useGroupSpecificCounter, groupId, newCount, config) {
const properties = PropertiesService.getScriptProperties();
if (useGroupSpecificCounter) {
const groupConfigs = JSON.parse(properties.getProperty('GROUPME_ADDER_CONFIG') || '[]');
const groupIndex = groupConfigs.findIndex(g => g.groupId === groupId);
if (groupIndex !== -1) {
groupConfigs[groupIndex].count = newCount;
properties.setProperty('GROUPME_ADDER_CONFIG', JSON.stringify(groupConfigs, null, 2));
// Also update the in-memory config to prevent stale data during the script run
const inMemoryGroupIndex = config.groupMeConfig.findIndex(g => g.groupId === groupId);
if (inMemoryGroupIndex !== -1) {
config.groupMeConfig[inMemoryGroupIndex].count = newCount;
}
Logger.log(`Group-specific count for group ${groupId} updated to ${newCount}`);
}
} else {
properties.setProperty('USER_COUNT', newCount.toString());
config.userCount = newCount; // Update in-memory config
Logger.log(`Global USER_COUNT updated to ${newCount}`);
}
}
/**
* This function orchestrates the adding process, supporting both batch and one-by-one methods.
* @param {Array<object>} actions - Array of queued actions from the email loop.
* @param {object} config - The master configuration object.
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet - The logging sheet.
*/
function processGroupMeAdds(actions, config, sheet) {
const membersByGroup = {};
// --- 1. Pre-check for duplicates and group members ---
actions.forEach(data => {
const groupConfig = config.groupMeConfig.find(g => g.keywords && g.keywords.includes(data.keyword));
if (!groupConfig) {
logEntry(sheet, data.phone, data.keyword, `Error: No Group config found for this keyword.`);
return;
}
const isDuplicate = checkGroupMeDuplicate(config.token, groupConfig.groupId, data.phone);
if (isDuplicate) {
logEntry(sheet, data.phone, data.keyword, 'Duplicate - User already in group.');
return;
}
if (isDuplicate === null) {
logEntry(sheet, data.phone, data.keyword, 'Error: GroupMe duplicate check failed.');
return;
}
if (!membersByGroup[groupConfig.groupId]) {
membersByGroup[groupConfig.groupId] = {
members: [],
config: groupConfig,
keyword: data.keyword // Store keyword for logging
};
}
membersByGroup[groupConfig.groupId].members.push({ phone_number: data.phone });
});
// --- 2. Process each group's batch ---
for (const groupId in membersByGroup) {
const groupData = membersByGroup[groupId];
const groupConfig = groupData.config;
const membersToAdd = groupData.members;
const prefix = groupConfig.prefix || config.userPrefix;
const useGroupSpecificCounter = groupConfig.count !== undefined;
let currentCount = useGroupSpecificCounter ? groupConfig.count : config.userCount;
// Assign nicknames to members
const membersWithNicknames = membersToAdd.map(member => {
const nickname = prefix + currentCount;
currentCount++;
return { ...member, nickname: nickname };
});
// --- 3. Add members: Batch (default) or One-by-One ---
// The `useBatchAdd` property in the group's config controls this.
// If undefined or true, it will use the batch API. If false, it adds one-by-one.
if (groupConfig.useBatchAdd === false) {
// --- One-by-one processing ---
debugLog(`-> Processing ${membersWithNicknames.length} members one-by-one for group ${groupId}.`);
let allSucceeded = true;
membersWithNicknames.forEach(member => {
const addResult = addToGroupMe(config.token, groupId, [member]); // `addToGroupMe` expects an array
if (addResult.success) {
logEntry(sheet, member.phone_number, groupData.keyword, `Success - Added as: ${member.nickname}`);
} else {
allSucceeded = false;
logEntry(sheet, member.phone_number, groupData.keyword, `Error - Add failed: ${addResult.status}`);
}
Utilities.sleep(500); // Small delay between individual API calls to avoid rate limiting
});
if (allSucceeded) {
updateGroupMeAdderCount(useGroupSpecificCounter, groupId, currentCount, config);
}
} else {
// --- Batch processing (default behavior) ---
debugLog(`-> Processing ${membersWithNicknames.length} members as a batch for group ${groupId}.`);
const addResult = addToGroupMe(config.token, groupId, membersWithNicknames);
const finalNicknames = membersWithNicknames.map(m => m.nickname).join(', ');
const statusMessage = addResult.success
? `Success - Batch added ${membersWithNicknames.length} members as: ${finalNicknames}`
: `Error - Batch add failed: ${addResult.status}`;
membersToAdd.forEach(member => {
logEntry(sheet, member.phone_number, groupData.keyword, statusMessage);
});
if (addResult.success) {
updateGroupMeAdderCount(useGroupSpecificCounter, groupId, currentCount, config);
}
}
}
}
/**
* MODULE: A sample module to demonstrate extensibility.
* @param {object} data - The data object from the dispatcher.
* @param {object} config - The master configuration object.
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet - The logging sheet.
*/
function runSampleModule(data, config, sheet) {
const reply = config.sampleConfig.replyMessage || "No reply message configured.";
const logMessage = `Sample module triggered. Would have replied: "${reply}"`;
logEntry(sheet, data.phone, data.keyword, logMessage);
}
// ---------------------------------------------------------------------------
// --- HELPER FUNCTIONS - Reusable utility functions ---
// ---------------------------------------------------------------------------
/**
* Creates a new GroupMe group.
* @param {string} token - The GroupMe API token.
* @param {string} name - The name for the new group.
* @return {object|null} The new group object on success, or null on failure.
*/
function createGroupMeGroup(token, name) {
try {
const payload = { name: name, share: false };
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const url = `https://api.groupme.com/v3/groups?token=${token}`;
const response = UrlFetchApp.fetch(url, options);
const code = response.getResponseCode();
if (code >= 200 && code < 300) {
return JSON.parse(response.getContentText()).response;
} else {
Logger.log(`GroupMe create group failed: ${code} - ${response.getContentText()}`);
return null;
}
} catch (e) {
Logger.log(`GroupMe create group exception: ${e.message}`);
return null;
}
}
/**
* Posts a message to a GroupMe group.
* @param {string} token - The GroupMe API token.
* @param {string} groupId - The ID of the group to post to.
* @param {string} text - The message text to post.
* @return {boolean} True on success, false on failure.
*/
function postGroupMeMessage(token, groupId, text) {
try {
const guid = Utilities.getUuid();
const payload = { message: { source_guid: guid, text: text } };
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const url = `https://api.groupme.com/v3/groups/${groupId}/messages?token=${token}`;
const response = UrlFetchApp.fetch(url, options);
const code = response.getResponseCode();
if (code >= 200 && code < 300) {
return true;
} else {
Logger.log(`GroupMe post message failed: ${code} - ${response.getContentText()}`);
return false;
}
} catch (e) {
Logger.log(`GroupMe post message exception: ${e.message}`);
return false;
}
}
/**
* Adds one or more members to a specific GroupMe group.
* @param {string} token - The GroupMe API token.
* @param {string} groupId - The ID of the group to add members to.
* @param {Array<object>} members - An array of member objects to add, e.g., [{nickname: 'User1', phone_number: '+1...'}].
* @return {object} An object with the status and success of the add operation.
*/
function addToGroupMe(token, groupId, members) {
try {
// Add a unique guid to each member for idempotency
const membersWithGuid = members.map(m => ({
...m,
guid: `guid-${new Date().getTime()}-${Math.random()}`
}));
const payload = { members: membersWithGuid };
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const url = `https://api.groupme.com/v3/groups/${groupId}/members/add?token=${token}`;
const response = UrlFetchApp.fetch(url, options);
const code = response.getResponseCode();
if (code === 202) { // 202 Accepted is the success code for this endpoint
return { success: true, status: 'Success - Add request accepted.' };
} else {
const responseText = response.getContentText();
Logger.log(`GroupMe add failed: ${code} - ${responseText}`);
return { success: false, status: `Error: GroupMe API returned code ${code}` };
}
} catch (e) {
Logger.log(`GroupMe add exception: ${e.message}`);
return { success: false, status: `Exception during add: ${e.message}` };
}
}
/**
* Checks if a phone number is already a member of a GroupMe group.
* @param {string} token - The GroupMe API token.
* @param {string} groupId - The ID of the group to check.
* @param {string} phoneE164 - The phone number to check.
* @return {boolean|null} True if a duplicate, false if not, null on error.
*/
function checkGroupMeDuplicate(token, groupId, phoneE164) {
try {
const url = `https://api.groupme.com/v3/groups/${groupId}?token=${token}`;
const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
if (response.getResponseCode() !== 200) {
Logger.log(`GroupMe check error: ${response.getContentText()}`);
return null;
}
const groupData = JSON.parse(response.getContentText()).response;
return groupData.members.some(member => member.phone_number === phoneE164);
} catch (e) {
Logger.log(`GroupMe check exception: ${e.message}`);
return null;
}
}
/**
* Finds the first keyword from a list that exists in the message text.
* @param {string} messageText - The body of the email/SMS.
* @param {string[]} keywords - An array of keywords to search for.
* @return {string|null} The first keyword found, or null if none are found.
*/
function detectKeyword(messageText, keywords) {
for (const keyword of keywords) {
const regex = new RegExp(`\\b${keyword}\\b`, 'i');
if (regex.test(messageText)) {
return keyword;
}
}
return null;
}
/**
* Extracts a phone number from a Google Voice email subject.
* @param {string} subject - The email subject line.
* @return {string|null} The phone number in E.164 format or null.
*/
function extractPhoneNumber(subject) {
if (!subject.startsWith('New text message from')) return null;
const phoneMatch = subject.match(/\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}/);
if (!phoneMatch) return null;
return `+1${phoneMatch[0].replace(/\D/g, '')}`;
}
/**
* Marks a message as read and logs its ID to prevent reprocessing.
* @param {GoogleAppsScript.Gmail.GmailMessage} message The message to process.
* @param {GoogleAppsScript.Spreadsheet.Sheet} idSheet The sheet where processed IDs are stored.
* @param {Set<string>} processedIdsSet The in-memory Set of processed IDs.
*/
function markMessageProcessed(message, idSheet, processedIdsSet) {
const messageId = message.getId();
message.markRead();
idSheet.appendRow([messageId]);
processedIdsSet.add(messageId);
Logger.log(`Marked message as processed: ID ${messageId}`);
}
/**
* Logs a message to both the Logger and a Google Sheet.
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet - The logging sheet object.
* @param {string} phone - The phone number involved.
* @param {string} keyword - The keyword detected.
* @param {string} status - The result or status message.
*/
function logEntry(sheet, phone, keyword, status) {
const timestamp = new Date().toISOString();
Logger.log(`LOG | ${phone} | ${keyword} | ${status}`);
if (sheet) {
sheet.appendRow([timestamp, phone, keyword, status]);
}
}
/**
* Gets a sheet by name from a spreadsheet, creating it if it doesn't exist.
* @param {GoogleAppsScript.Spreadsheet.Spreadsheet} spreadsheet The spreadsheet object.
* @param {string} sheetName The name of the sheet to get or create.
* @param {string[]} [headers] Optional array of headers to set if the sheet is created.
* @return {GoogleAppsScript.Spreadsheet.Sheet} The sheet object.
*/
function getSheetByName(spreadsheet, sheetName, headers = []) {
let sheet = spreadsheet.getSheetByName(sheetName);
if (!sheet) {
sheet = spreadsheet.insertSheet(sheetName);
if (headers.length > 0) {
sheet.appendRow(headers);
sheet.setFrozenRows(1);
}
}
return sheet;
}
/**
* Reads all message IDs from the ProcessedIDs sheet into a Set for fast lookup.
* @param {GoogleAppsScript.Spreadsheet.Sheet} idSheet The sheet containing processed IDs.
* @return {Set<string>} A Set containing all previously processed message IDs.
*/
function getProcessedIds(idSheet) {
if (idSheet.getLastRow() < 2) {
return new Set();
}
const ids = idSheet.getRange(2, 1, idSheet.getLastRow() - 1, 1).getValues();
return new Set(ids.flat().filter(id => id));
}
// ---------------------------------------------------------------------------
// --- ONE-TIME SETUP FUNCTION ---
// ---------------------------------------------------------------------------
/**
* Run this function MANUALLY to set up the script properties with new data structures.
*/
function setup() {
const properties = PropertiesService.getScriptProperties();
if (!properties.getProperty('LOG_SHEET_ID')) {
const spreadsheet = SpreadsheetApp.create('GroupMe Bot Logs');
const sheetId = spreadsheet.getId();
properties.setProperty('LOG_SHEET_ID', sheetId);
getSheetByName(spreadsheet, 'Logs', ['Timestamp', 'Phone Number', 'Keyword', 'Status']);
getSheetByName(spreadsheet, 'ProcessedIDs', ['MessageID']);
const defaultSheet = spreadsheet.getSheetByName('Sheet1');
if (defaultSheet) {
spreadsheet.deleteSheet(defaultSheet);
}
Logger.log(`✅ Logging Sheet created. URL: ${spreadsheet.getUrl()}`);
Logger.log(`-> Set LOG_SHEET_ID property to: ${sheetId}`);
} else {
Logger.log('ℹ️ LOG_SHEET_ID already exists. Skipping sheet creation.');
}
const defaultProperties = {
// IMPORTANT: Set the GROUPME_TOKEN in Project Settings > Script Properties
'USER_PREFIX': 'User',
'USER_COUNT': '1',
'DEBUG_MODE': 'false', // New property for verbose logging
'MODULE_ROUTING_RULES': JSON.stringify({
'info': 'sampleModule'
}, null, 2),
'GROUPME_ADDER_CONFIG': JSON.stringify([], null, 2), // Now defaults to an empty array
'SAMPLE_MODULE_CONFIG': JSON.stringify({
'replyMessage': 'Thanks for your interest! We will be in touch.'
}, null, 2)
};
for (const key in defaultProperties) {
if (!properties.getProperty(key)) {
properties.setProperty(key, defaultProperties[key]);
Logger.log(`✅ Created property: ${key}. PLEASE EDIT ITS VALUE.`);
} else {
Logger.log(`ℹ️ Property '${key}' already exists. Skipping.`);
}
}
Logger.log('\nSetup complete. Please go to Project Settings > Script Properties to edit the values, then deploy the web app to manage group mappings.');
}