Something went wrong. Try again.
Google Apps Script that turns Regal Cinemas ticket emails into Google Calendar events
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308/** * Regal ticket emails -> Google Calendar events. * * --------------------------------------------------------------------------- * EMAIL TEMPLATE (checked 2026-10-28 against samples from Dec 2025 and Oct 2026) * --------------------------------------------------------------------------- * From: tickets@regaltickets.com * Subject: "Regal Tickets for <Movie Title> #<BookingNumber>" * Title quirks seen in the wild: * - Leading article moved to the end: "Sheep Detectives, The" * - Format prefixes: "IMAX: Dune: Part Three", "MOM2: Nausicaa ..." * - Suffixes: " 3D", " (Dub)", " (Japanese)", " 4K" * Body: Text/HTML contains ONLY the order table (qty, ticket type, price, * fees, total) plus refund/pickup boilerplate. * Ticket type cells look like: <td style="max-width:70%;">Adult Ticket</td> * There is NO showtime, theater, address, auditorium, or runtime in * the text. * Image: One inline JPEG (cid: image at the top of the body). This is the * ticket graphic and is the only place showtime/theater appear. * We OCR it with Drive's built-in image->Google Doc conversion (no AI). * Other: No .ics attachment, no schema.org event markup. * * Image text layout (verified 2026-10-30) is documented on parseTicketText(). * The image has no address or runtime: the address is geocoded from the * theater name, and the runtime comes from Wikidata (CONFIG.defaultMinutes * if it isn't found). * --------------------------------------------------------------------------- * * Setup: * 1. Paste this file and appsscript.json into a new Apps Script project. * 2. Run debugLatestOcr() and check the log (grants permissions too). * 3. Run install() to poll every 15 minutes. */
const CONFIG = { calendarId: 'primary', doneLabel: 'regal-calendar', failedLabel: 'regal-calendar-failed', searchWindow: '14d', // Only look at recent emails. defaultMinutes: 120, // Used when runtime isn't found. reminderMinutes: 10, // Popup reminder before the showtime.};
const SENDER = 'tickets@regaltickets.com';const SUBJECT_RE = /^Regal Tickets for (.+?) #([A-Z0-9]+)\s*$/;
/** Main entry point. Run by the time-based trigger. */function processRegalEmails() { const done = getOrCreateLabel(CONFIG.doneLabel); const failed = getOrCreateLabel(CONFIG.failedLabel); const cal = CalendarApp.getCalendarById(CONFIG.calendarId);
const query = [ `from:${SENDER}`, 'subject:"Regal Tickets for"', `-label:${CONFIG.doneLabel}`, `-label:${CONFIG.failedLabel}`, `newer_than:${CONFIG.searchWindow}`, ].join(' ');
for (const thread of GmailApp.search(query, 0, 50)) { let ok = true; for (const msg of thread.getMessages()) { const m = msg.getSubject().match(SUBJECT_RE); if (!m) continue; try { createEventFromMessage(cal, msg, m[1], m[2]); } catch (e) { ok = false; console.error(`Failed on "${msg.getSubject()}": ${e.message}`); } } thread.addLabel(ok ? done : failed); }}
function createEventFromMessage(cal, msg, rawTitle, booking) { const text = ocrImage(getTicketImage(msg).copyBlob()); const info = parseTicketText(text, msg.getDate()); if (!info.start) throw new Error('No showtime found. OCR text:\n' + text);
// Skip if an event for this booking already exists (e.g. manual re-run). const dayMs = 24 * 3600 * 1000; const existing = cal.getEvents( new Date(info.start.getTime() - dayMs), new Date(info.start.getTime() + dayMs), { search: booking }); if (existing.length) return;
const title = cleanTitle(rawTitle); info.runtimeMin = info.runtimeMin || lookupRuntime(title, info.start); const minutes = info.runtimeMin || CONFIG.defaultMinutes; const end = new Date(info.start.getTime() + minutes * 60000); const tickets = getTicketTypes(msg);
const description = [ `Booking #: ${booking}`, info.theater && `Theater: ${info.theater}`, info.auditorium && `Auditorium: ${info.auditorium}`, info.seats && `Seats: ${info.seats}`, tickets.length && `Tickets: ${tickets.join(', ')}`, info.runtimeMin ? `Runtime: ${info.runtimeMin} min` : `Runtime: unknown (defaulted to ${CONFIG.defaultMinutes} min)`, '', `Email: https://mail.google.com/mail/u/0/#all/${msg.getId()}`, ].filter(l => typeof l === 'string').join('\n');
cal.createEvent(title, info.start, end, { location: [info.theater, lookupAddress(info.theater)].filter(Boolean).join(', '), description, }).addPopupReminder(CONFIG.reminderMinutes);}
/** Returns the inline ticket JPEG. */function getTicketImage(msg) { const img = msg .getAttachments({ includeInlineImages: true, includeAttachments: true }) .find(a => a.getContentType().indexOf('image/') === 0); if (!img) throw new Error('No ticket image in email'); return img;}
/** OCR via Drive image->Docs conversion. Temp doc is deleted afterward. */function ocrImage(blob) { const file = Drive.Files.create( { name: 'regal-ocr-tmp.jpg', mimeType: MimeType.GOOGLE_DOCS }, blob, { ocrLanguage: 'en', fields: 'id' }); try { return DocumentApp.openById(file.id).getBody().getText(); } finally { Drive.Files.remove(file.id); }}
/** Ticket types from the order table, e.g. ["1x Adult Ticket"]. */function getTicketTypes(msg) { const html = msg.getBody(); const re = /<td style="max-width:15%;">\s*(\d+)\s*<\/td>\s*<td style="max-width:70%;">([^<]+)<\/td>/g; const out = []; let m; while ((m = re.exec(html))) out.push(`${m[1]}x ${m[2].trim()}`); return out;}
/** * Pulls showtime, theater, auditorium, seats, runtime from OCR text. * Verified 2026-10-30 against real OCR output, which looks like: * CROWN CLUB / UNLIMITED / REGAL. ... (logo noise) * City North Stm 14 IMAX & RPX (theater, no "Regal", no address) * Wildwood (title) * Wednesday, 28 October 2026 7:55 PM (day-first date + time) * Seats: N14 * Auditorium: 13 * Order#: WXR77G7 * No runtime or address is printed; address comes from lookupAddress(). */function parseTicketText(text, emailDate) { const lines = text.split(/\r?\n/).map(s => s.trim()).filter(Boolean); const flat = lines.join(' '); const out = {};
const MONTHS = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']; const MON = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\\.?'; let y, mo, d, m; if ((m = flat.match(new RegExp('\\b(\\d{1,2})\\s+' + MON + ',?\\s+(\\d{4})\\b', 'i')))) { d = +m[1]; mo = MONTHS.indexOf(m[2].slice(0, 3).toLowerCase()); y = +m[3]; // 28 October 2026 } else if ((m = flat.match(new RegExp('\\b' + MON + '\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(\\d{4}))?\\b', 'i')))) { mo = MONTHS.indexOf(m[1].slice(0, 3).toLowerCase()); d = +m[2]; y = m[3] ? +m[3] : null; // Oct 28, 2026 } else if ((m = flat.match(/\b(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\b/))) { mo = +m[1] - 1; d = +m[2]; y = m[3] ? (m[3].length === 2 ? 2000 + +m[3] : +m[3]) : null; }
// Time: "7:55 PM", "7:55PM", "7:55 p.m." const t = flat.match(/\b(\d{1,2}):(\d{2})\s*([AaPp])\.?\s*[Mm]\.?/);
if (mo >= 0 && d && t) { let h = +t[1] % 12; if (t[3].toLowerCase() === 'p') h += 12; if (!y) { y = emailDate.getFullYear(); if (new Date(y, mo, d) < new Date(emailDate.getTime() - 86400000)) y++; } out.start = new Date(y, mo, d, h, +t[2]); // Script time zone. }
// Theater: two lines above the date line (theater, title, date). const dateIdx = lines.findIndex(l => /\d{1,2}:\d{2}\s*[AaPp]/.test(l)); const cand = dateIdx >= 2 ? lines[dateIdx - 2] : null; if (cand && !/crown|unlimited|^regal\.?$|^[A-Z]$/i.test(cand)) { out.theater = ('Regal ' + cand.replace(/^Regal\s+/i, '')) .replace(/\bStm\b/i, 'Stadium'); }
m = flat.match(/\bAuditorium\s*#?:?\s*(\d{1,2})\b/i); if (m) out.auditorium = m[1];
m = flat.match(/\bSeats?\s*:?\s*([A-Z]{1,2}\s?\d{1,2}(?:\s*,\s*[A-Z]{1,2}\s?\d{1,2})*)/); if (m) out.seats = m[1];
// Runtime (not printed today; kept in case Regal adds it). m = flat.match(/\b(\d)\s*(?:h|hr|hrs|hours?)\.?\s*(\d{1,2})\s*(?:m|min|mins|minutes?)\b/i); if (m) out.runtimeMin = +m[1] * 60 + +m[2];
return out;}
/** * Theater name -> street address via Apps Script's built-in Maps geocoder. * Cached in Script Properties. To override a wrong result, set a property * named "addr:<theater name>" in Project Settings > Script Properties. */function lookupAddress(theater) { if (!theater) return ''; const props = PropertiesService.getScriptProperties(); const key = 'addr:' + theater; const cached = props.getProperty(key); if (cached !== null) return cached; const query = theater.replace(/\s+(IMAX|RPX|4DX|ScreenX|&|\s)+$/i, ''); const r = Maps.newGeocoder().geocode(query); const addr = r.status === 'OK' && r.results.length ? r.results[0].formatted_address : ''; if (addr) props.setProperty(key, addr); return addr;}
/** * Title -> runtime in minutes from Wikidata (free, no API key). Picks the * film whose release date is closest to the showtime, so remakes and * same-name films resolve correctly. Cached in Script Properties as * "runtime:<title>"; misses aren't cached so new releases get retried. */function lookupRuntime(title, showtime) { const props = PropertiesService.getScriptProperties(); const key = 'runtime:' + title; const cached = props.getProperty(key); if (cached) return +cached; // "IMAX: Dune: Part Three" -> "Dune: Part Three", "Wildwood 3D" -> "Wildwood". const name = title .replace(/^[A-Z0-9]{2,}:\s+/, '') .replace(/\s+(3D|4K|\([^)]*\))$/i, ''); // The SPARQL endpoint hangs for Apps Script, so use the regular API: // search films that have a duration, then compare exact English labels. const api = params => JSON.parse(UrlFetchApp.fetch('https://www.wikidata.org/w/api.php?format=json&' + Object.keys(params).map(k => k + '=' + encodeURIComponent(params[k])).join('&')).getContentText()); try { const ids = api({ action: 'query', list: 'search', srlimit: 20, srsearch: `"${name.replace(/"/g, '')}" haswbstatement:P2047 ` + 'haswbstatement:P31=Q11424|P31=Q202866|P31=Q29168811|P31=Q93204', }).query.search.map(r => r.title); if (!ids.length) return 0; const ents = api({ action: 'wbgetentities', ids: ids.join('|'), props: 'labels|claims', languages: 'en' }).entities; const values = (claims, p) => (claims[p] || []).map(c => c.mainsnak.datavalue).filter(Boolean).map(d => d.value); let best = null; for (const e of Object.values(ents)) { const label = e.labels && e.labels.en && e.labels.en.value; if (!label || label.toLowerCase() !== name.toLowerCase()) continue; const mins = values(e.claims, 'P2047').filter(v => /\/Q7727$/.test(v.unit)).map(v => +v.amount); if (!mins.length) continue; // Dates look like "+2025-04-18T00:00:00Z". const dist = Math.min(Infinity, ...values(e.claims, 'P577') .map(v => Math.abs(new Date(v.time.slice(1, 11)) - showtime)).filter(n => !isNaN(n))); if (!best || dist < best.dist) best = { dist, mins: Math.round(mins[0]) }; } const mins = best ? best.mins : 0; if (mins) props.setProperty(key, String(mins)); return mins; } catch (e) { console.warn(`Runtime lookup failed for "${title}": ${e.message}`); return 0; }}
/** "Sheep Detectives, The" -> "The Sheep Detectives". */function cleanTitle(raw) { return raw.replace(/^(.+),\s+(The|A|An)$/, '$2 $1').trim();}
function getOrCreateLabel(name) { return GmailApp.getUserLabelByName(name) || GmailApp.createLabel(name);}
/** Logs OCR text and parsed fields for the most recent Regal email. */function debugLatestOcr() { const thread = GmailApp.search(`from:${SENDER} subject:"Regal Tickets for"`, 0, 1)[0]; if (!thread) throw new Error('No Regal ticket emails found'); const msg = thread.getMessages()[0]; const text = ocrImage(getTicketImage(msg).copyBlob()); console.log('--- OCR TEXT ---\n' + text); const info = parseTicketText(text, msg.getDate()); console.log('--- PARSED ---\n' + JSON.stringify(info, null, 2)); console.log('--- ADDRESS ---\n' + lookupAddress(info.theater)); console.log('--- TICKETS ---\n' + getTicketTypes(msg).join(', ')); const title = cleanTitle(msg.getSubject().match(SUBJECT_RE)[1]); console.log('--- TITLE ---\n' + title); console.log('--- RUNTIME ---\n' + (lookupRuntime(title, info.start || msg.getDate()) || 'not found'));}
/** Creates a 15-minute polling trigger (replaces any existing one). */function install() { ScriptApp.getProjectTriggers() .filter(t => t.getHandlerFunction() === 'processRegalEmails') .forEach(t => ScriptApp.deleteTrigger(t)); ScriptApp.newTrigger('processRegalEmails').timeBased().everyMinutes(15).create();}