/** * Post to social media from Google Sheets with the Ampost API. * * Each row of the "Posts" sheet is one post. The script sends every row whose * Status is empty to Ampost and writes the result back into the row. * * Columns (row 1 is the header, this order): * A Text the post text (required) * B Platforms comma-separated, e.g. bluesky,threads,discord (required) * C Link optional link (linkUrl) * D Media URL optional public https URL of an image or video * E Media type image or video (default image) * F Schedule (UTC) optional ISO 8601 time, e.g. 2027-01-14T15:00:00Z; empty posts now * G Status written by the script: the post's status, or the error * H Post ID written by the script * * Setup (guide: https://ampost.io/how-to/post-to-social-media-from-google-sheets): * 1. Extensions > Apps Script, paste this file, save. * 2. Project Settings > Script properties: add AMPOST_API_KEY with an API key from * https://ampost.io/app/settings/api-keys * 3. Reload the sheet and use the Ampost menu: "Set up the Posts sheet", then * "Post pending rows". "Check every 15 minutes" posts new rows automatically. */ var AMPOST_API_URL = "https://api.ampost.io"; var SHEET_NAME = "Posts"; var HEADERS = ["Text", "Platforms", "Link", "Media URL", "Media type", "Schedule (UTC)", "Status", "Post ID"]; var COL = { text: 0, platforms: 1, link: 2, mediaUrl: 3, mediaType: 4, schedule: 5, status: 6, postId: 7 }; function onOpen() { SpreadsheetApp.getUi() .createMenu("Ampost") .addItem("Set up the Posts sheet", "setUpSheet") .addItem("Post pending rows", "postPendingRows") .addItem("Check every 15 minutes", "installTrigger") .addToUi(); } /** Creates the Posts sheet with its header row. */ function setUpSheet() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getSheetByName(SHEET_NAME) || spreadsheet.insertSheet(SHEET_NAME); sheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]).setFontWeight("bold"); sheet.setFrozenRows(1); } /** Sends every row with an empty Status to Ampost; returns how many rows it sent. */ function postPendingRows() { var apiKey = PropertiesService.getScriptProperties().getProperty("AMPOST_API_KEY"); if (!apiKey) throw new Error("Add the AMPOST_API_KEY script property (Project Settings > Script properties)."); var lock = LockService.getScriptLock(); if (!lock.tryLock(30000)) return 0; // another run is still posting try { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getSheetByName(SHEET_NAME); if (!sheet) throw new Error('No "' + SHEET_NAME + '" sheet. Use Ampost > Set up the Posts sheet.'); var lastRow = sheet.getLastRow(); if (lastRow < 2) return 0; var rows = sheet.getRange(2, 1, lastRow - 1, HEADERS.length).getValues(); var sent = 0; for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (String(row[COL.text]).trim() === "" || String(row[COL.status]).trim() !== "") continue; var rowNumber = i + 2; var result = createPost(apiKey, buildBody(row), idempotencyKey(spreadsheet.getId(), rowNumber, row)); if (result.retry) break; // rate limited or Ampost unavailable: the row stays pending for the next run sheet.getRange(rowNumber, COL.status + 1, 1, 2).setValues([[result.status, result.postId]]); SpreadsheetApp.flush(); sent++; } return sent; } finally { lock.releaseLock(); } } /** The POST /api/posts body for one row. */ function buildBody(row) { var platforms = String(row[COL.platforms]) .split(",") .map(function (platform) { return platform.trim().toLowerCase(); }) .filter(function (platform) { return platform !== ""; }); var body = { targets: [{ platforms: platforms }], text: String(row[COL.text]) }; var link = String(row[COL.link]).trim(); if (link) body.linkUrl = link; var mediaUrl = String(row[COL.mediaUrl]).trim(); if (mediaUrl) body.media = [{ url: mediaUrl, type: String(row[COL.mediaType]).trim().toLowerCase() || "image" }]; var schedule = row[COL.schedule]; // A date cell is a Date; a typed time stays text. if (Object.prototype.toString.call(schedule) === "[object Date]") body.scheduledFor = schedule.toISOString(); else if (String(schedule).trim()) body.scheduledFor = String(schedule).trim(); else body.publishNow = true; return body; } /** Same row, same content: the same key, so Ampost never posts a row twice. */ function idempotencyKey(spreadsheetId, rowNumber, row) { var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, JSON.stringify([spreadsheetId, rowNumber, row.slice(0, COL.status)])); return "sheets-" + Utilities.base64EncodeWebSafe(digest).replace(/=+$/, ""); } /** * Calls Ampost and returns { status, postId } for the Status and Post ID columns, * or { retry: true } when the request should be sent again later. */ function createPost(apiKey, body, key) { var response = UrlFetchApp.fetch(AMPOST_API_URL + "/api/posts", { method: "post", contentType: "application/json", headers: { Authorization: "Bearer " + apiKey, "Idempotency-Key": key }, payload: JSON.stringify(body), muteHttpExceptions: true, }); var code = response.getResponseCode(); var json = {}; try { json = JSON.parse(response.getContentText()); } catch (error) { /* not JSON */ } if (code === 200 || code === 201) return { status: json.status, postId: json.id }; if (code === 429 || code >= 500) return { retry: true }; var error = json.error || {}; return { status: "Error " + code + ": " + (error.code || "") + " " + (error.message || response.getContentText()).slice(0, 300), postId: "" }; } /** Runs postPendingRows every 15 minutes. */ function installTrigger() { var triggers = ScriptApp.getProjectTriggers(); for (var i = 0; i < triggers.length; i++) { if (triggers[i].getHandlerFunction() === "postPendingRows") return; } ScriptApp.newTrigger("postPendingRows").timeBased().everyMinutes(15).create(); }