/** * FastDAR for Gmail: puts a label on each new email in your inbox, using one of your saved label sets. * Move an email to a different FastDAR label and FastDAR learns from it. * * Set-up (about 3 minutes, full steps with pictures at https://fastdar.com/gmail): * 1. Go to https://script.google.com, click New project, delete what's there and paste all of this. * 2. Put your FastDAR key and the name of your saved label set in the two lines below. * 3. Pick "install" in the function menu at the top and click Run. Google asks you to allow it; that's * this script asking to read and label your own email. Nothing is sent anywhere except fastdar.com. * To stop it, pick "uninstall" and click Run. */ const FASTDAR_KEY = 'PASTE_YOUR_KEY_HERE'; // from your FastDAR account page const LABEL_SET = 'support'; // the name of a label set you saved in FastDAR // You can leave these as they are. const LABEL_FOLDER = 'FastDAR'; // labels show up as FastDAR/Billing, FastDAR/Shipping and so on const NOT_SURE = 'Not sure'; // emails FastDAR isn't sure about get FastDAR/Not sure const MIN_CONFIDENCE = 0.6; // how sure FastDAR must be, from 0 to 1 const SEARCH = 'in:inbox newer_than:2d'; // which emails to look at const EVERY_MINUTES = 5; const FASTDAR_URL = 'https://fastdar.com/mcp'; const MAX_EMAILS = 50; // per run const REMEMBER = 300; // recent emails remembered so moving one can teach FastDAR const MAX_CHARS = 2000; function install() { checkSettings_(); uninstall(); sortNewEmails(); // runs once first, so a wrong key or set name stops here instead of failing every few minutes ScriptApp.newTrigger('sortNewEmails').timeBased().everyMinutes(EVERY_MINUTES).create(); Logger.log('FastDAR is on. New emails get a label every ' + EVERY_MINUTES + ' minutes.'); } function uninstall() { ScriptApp.getProjectTriggers().forEach(function (t) { if (t.getHandlerFunction() === 'sortNewEmails') ScriptApp.deleteTrigger(t); }); } function sortNewEmails() { checkSettings_(); const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) return; // the last run is still going try { const seen = load_(); learnFromMoves_(seen); const todo = GmailApp.search(SEARCH, 0, MAX_EMAILS).filter(function (t) { return !seen[t.getId()]; }); if (todo.length) { const answers = callTool_('classify', {label_set: LABEL_SET, texts: todo.map(textOf_), min_confidence: MIN_CONFIDENCE}).results; answers.forEach(function (a) { const t = todo[a.index]; t.addLabel(label_(a.label === 'not_sure' ? NOT_SURE : a.label)); seen[t.getId()] = {label: a.label === 'not_sure' ? NOT_SURE : a.label, at: Date.now()}; }); } save_(seen); } finally { lock.releaseLock(); } } // If you moved an email from one FastDAR label to another, tell FastDAR the right label so it learns. function learnFromMoves_(seen) { Object.keys(seen).forEach(function (id) { const was = seen[id]; let t; try { t = GmailApp.getThreadById(id); } catch (e) { t = null; } if (!t) { delete seen[id]; return; } const now = t.getLabels().map(function (l) { return l.getName(); }) .filter(function (n) { return n.indexOf(LABEL_FOLDER + '/') === 0; }) .map(function (n) { return n.slice(LABEL_FOLDER.length + 1); }) .filter(function (n) { return n !== NOT_SURE && n !== was.label; }); if (now.length !== 1) return; // not moved, or given more than one new label try { callTool_('correct_label', {label_set: LABEL_SET, text: textOf_(t), label: now[0]}); if (was.label !== NOT_SURE) t.removeLabel(label_(was.label)); t.removeLabel(label_(NOT_SURE)); seen[id] = {label: now[0], at: was.at}; } catch (e) { Logger.log('Could not teach FastDAR from one email: ' + e.message); } }); } function textOf_(thread) { const m = thread.getMessages()[0]; return (thread.getFirstMessageSubject() + '\n\n' + m.getPlainBody()).slice(0, MAX_CHARS); } function label_(name) { const full = LABEL_FOLDER + '/' + name; return GmailApp.getUserLabelByName(full) || GmailApp.createLabel(full); } function callTool_(name, args) { const res = UrlFetchApp.fetch(FASTDAR_URL, { method: 'post', contentType: 'application/json', muteHttpExceptions: true, headers: {Authorization: 'Bearer ' + FASTDAR_KEY}, payload: JSON.stringify({jsonrpc: '2.0', id: 1, method: 'tools/call', params: {name: name, arguments: args}}) }); if (res.getResponseCode() === 401) throw new Error('FastDAR did not accept your key. Check FASTDAR_KEY at the top.'); if (res.getResponseCode() !== 200) throw new Error('FastDAR answered ' + res.getResponseCode() + ': ' + res.getContentText().slice(0, 300)); const body = JSON.parse(res.getContentText()); if (body.error) throw new Error(body.error.message); if (body.result.isError) { const msg = body.result.content[0].text; if (/no saved label set/.test(msg)) throw new Error('You have no saved label set called "' + LABEL_SET + '". On your FastDAR ' + 'account page, open Saved labels and make one with that name, or change LABEL_SET at the top to the name of a set ' + 'you already saved. Then save and run install again.'); throw new Error(msg); } return body.result.structuredContent; } function load_() { try { return JSON.parse(PropertiesService.getUserProperties().getProperty('fastdar_seen') || '{}'); } catch (e) { return {}; } } function save_(seen) { const keep = Object.keys(seen).sort(function (a, b) { return seen[b].at - seen[a].at; }).slice(0, REMEMBER); const out = {}; keep.forEach(function (k) { out[k] = seen[k]; }); PropertiesService.getUserProperties().setProperty('fastdar_seen', JSON.stringify(out)); } function checkSettings_() { if (!FASTDAR_KEY || FASTDAR_KEY === 'PASTE_YOUR_KEY_HERE') throw new Error('Put your FastDAR key in FASTDAR_KEY at the top first.'); if (!LABEL_SET) throw new Error('Put the name of your saved label set in LABEL_SET at the top first.'); }