Ora / tools /make-n8n-workflow.py
umer-wasim's picture
Developer handover: tools/, .gitignore, README-DEVELOPERS for a new computer
c523d5c verified
Raw History Blame Contribute Delete
18.3 kB
# Writes app/n8n/ora-automation.json: the n8n workflow learners import into their n8n Cloud account.
# Ora sends it JSON { action: "test" | "posts" | "remind" | "linkedin" | "unlog", ... }; it answers JSON, so Ora can show which
# accounts work. Account steps ship switched off (n8n will not run a workflow with an unfinished step): the learner
# connects an account, then switches its steps on. A switched-off step passes its input through unchanged, so each
# check below looks for what only a real answer has.
import json, os
# the first box is named after what the automation does (other boxes refer to it as $('Ora'), renamed at the end)
WEBHOOK = 'Ora: Google Sheets log + Gmail reminders + LinkedIn posts'
status = r"""// The answer to Ora's Test: which accounts this workflow can use.
// A box that is switched off passes the request through (it still has "body"); a box that failed carries "error".
const settings = $('Ora').first().json.body || {}; // Ora sends the sheet link with every request
const check = (name, needs) => {
let items = [];
try { items = $(name).all(); } catch { return { ok: false, why: 'off' }; }
const j = (items[0] || {}).json || {};
if ('body' in j) return { ok: false, why: 'off' }; // passed through unchanged
if (needs && !/^https:\/\//.test(String(settings[needs] || '').trim())) return { ok: false, why: 'nolink' };
if (j.error) return { ok: false, why: 'error', error: String(j.error.message || j.error).slice(0, 200) };
return { ok: true };
};
const mailCheck = (name, needs) => { const r = check(name, null); if (r.ok && !/@/.test(String(settings[needs] || ''))) return { ok: false, why: 'noemail' }; return r; };
return [{ json: { ora: 1, accounts: { sheets: check('Google Sheets: check', 'sheetLink'), gmail: mailCheck('Gmail: check', 'email'), linkedin: check('LinkedIn: check', null) } } }];"""
rows = r"""// One row per post and platform, for the Google Sheet (first row: Date | Time | Platform | Title | Caption | Picture | ID)
// ID (the day's id from Ora, then the platform) lets Ora delete these rows later (Plan › Campaigns)
const posts = ($('Ora').first().json.body || {}).posts || [];
return posts.flatMap(p => (p.platforms && p.platforms.length ? p.platforms : ['-']).map(platform => ({ json: {
Date: p.date || '', Time: p.time || '', Platform: platform, Title: p.title || '', Caption: (p.captions || {})[platform] || '', Picture: p.picture || '',
ID: p.id ? `${p.id}:${platform}` : '',
} })));"""
# Unlog: which rows of the sheet have the IDs Ora asks to delete; bottom row first, so the row numbers stay right
unlog = r"""const ids = new Set((($('Ora').first().json.body || {}).ids) || []);
let rows = [];
try { rows = $('Google Sheets: find the rows').all().map(i => i.json); } catch { return [{ json: { off: true, count: 0 } }]; }
if (rows.length === 1 && 'body' in rows[0]) return [{ json: { off: true, count: 0 } }]; // the box is switched off
const hit = rows.filter(r => ids.has(String(r.ID || ''))).map(r => r.row_number).filter(Boolean).sort((a, b) => b - a);
if (!hit.length) return [{ json: { count: 0 } }];
return hit.map(row => ({ json: { row, count: hit.length } }));"""
only_rows = r"""return $input.all().filter(i => i.json.row);"""
# after a wait that Ora can end early: Ora calls the cancel link with { cancel: true }; at the planned time the wait
# ends by itself and passes Ora's request on (no 'cancel'). A cancelled one stops here.
wanted = r"""const j = $input.first().json || {};
return j.body && j.body.cancel === true ? [] : $input.all();"""
# a wait until a time, which Ora can also end early by calling $execution.resumeUrl (its cancel link)
def wait(name, at, pos, hook):
return {"parameters": {"resume": "webhook", "httpMethod": "POST", "responseMode": "onReceived", "limitWaitTime": True,
"limitType": "atSpecifiedTime", "maxDateAndTime": at, "options": {}},
"name": name, "type": "n8n-nodes-base.wait", "typeVersion": 1.1, "position": pos, "webhookId": hook}
received = r"""// The answer to Ora's Send: how many posts came in, and what the sheet box did with them
const posts = ($('Ora').first().json.body || {}).posts || [];
let sheets = { added: 0 };
try {
const out = $('Google Sheets: add the rows').all().map(i => i.json);
const bad = out.find(j => j.error);
sheets = bad ? { error: String(bad.error.message || bad.error).slice(0, 200) } : { added: out.length };
} catch { sheets = { error: 'The Google Sheets box did not run.' }; }
return [{ json: { ora: 1, received: posts.length, sheets } }];"""
sheet = lambda op, extra: {**{"resource": "sheet", "operation": op,
"documentId": {"__rl": True, "value": "={{ $('Ora').first().json.body.sheetLink }}", "mode": "url"},
"sheetName": {"__rl": True, "value": "gid=0", "mode": "list", "cachedResultName": "Sheet1"}}, **extra}
nodes = [
{"parameters": {"httpMethod": "POST", "path": "ora", "responseMode": "responseNode", "options": {}},
"name": "Ora", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [0, 300], "webhookId": "0e5c7a1e-5a6e-4d1f-9b1a-0a0000000001"},
{"parameters": {"rules": {"values": [
{"conditions": {"options": {"caseSensitive": True, "typeValidation": "loose", "version": 2}, "combinator": "and",
"conditions": [{"leftValue": "={{ $('Ora').first().json.body.action }}", "rightValue": "test", "operator": {"type": "string", "operation": "equals"}}]},
"renameOutput": True, "outputKey": "Test"},
{"conditions": {"options": {"caseSensitive": True, "typeValidation": "loose", "version": 2}, "combinator": "and",
"conditions": [{"leftValue": "={{ $('Ora').first().json.body.action }}", "rightValue": "posts", "operator": {"type": "string", "operation": "equals"}}]},
"renameOutput": True, "outputKey": "Posts"},
{"conditions": {"options": {"caseSensitive": True, "typeValidation": "loose", "version": 2}, "combinator": "and",
"conditions": [{"leftValue": "={{ $('Ora').first().json.body.action }}", "rightValue": "remind", "operator": {"type": "string", "operation": "equals"}}]},
"renameOutput": True, "outputKey": "Remind"},
{"conditions": {"options": {"caseSensitive": True, "typeValidation": "loose", "version": 2}, "combinator": "and",
"conditions": [{"leftValue": "={{ $('Ora').first().json.body.action }}", "rightValue": "linkedin", "operator": {"type": "string", "operation": "equals"}}]},
"renameOutput": True, "outputKey": "LinkedIn"},
{"conditions": {"options": {"caseSensitive": True, "typeValidation": "loose", "version": 2}, "combinator": "and",
"conditions": [{"leftValue": "={{ $('Ora').first().json.body.action }}", "rightValue": "unlog", "operator": {"type": "string", "operation": "equals"}}]},
"renameOutput": True, "outputKey": "Delete rows"}]}, "options": {}},
"name": "What does Ora want?", "type": "n8n-nodes-base.switch", "typeVersion": 3.2, "position": [240, 300]},
# Test: try each account, then answer
{"parameters": sheet("read", {"filtersUI": {}, "options": {}}),
"name": "Google Sheets: check", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [520, 140],
"disabled": True, "alwaysOutputData": True, "onError": "continueRegularOutput", "executeOnce": True},
{"parameters": {"resource": "label", "operation": "getAll", "returnAll": False, "limit": 1},
"name": "Gmail: check", "type": "n8n-nodes-base.gmail", "typeVersion": 2.1, "position": [520, -40],
"disabled": True, "alwaysOutputData": True, "onError": "continueRegularOutput", "executeOnce": True},
# LinkedIn: a switch (n8n does not let a LinkedIn sign-in be used in an HTTP Request box, and the LinkedIn box can
# only post). Switched on it answers {linkedin: 'on'}; switched off it passes Ora's request through ('body').
{"parameters": {"mode": "manual", "assignments": {"assignments": [{"id": "0e5c7a1e-5a6e-4d1f-9b1a-0b0000000001", "name": "linkedin", "value": "on", "type": "string"}]}, "includeOtherFields": False, "options": {}},
"name": "LinkedIn: check", "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [520, -220],
"disabled": True, "alwaysOutputData": True, "onError": "continueRegularOutput", "executeOnce": True},
# the checks run side by side, so one switched off cannot look like another's answer
{"parameters": {"numberInputs": 3}, "name": "Both checks done", "type": "n8n-nodes-base.merge", "typeVersion": 3.1, "position": [700, 60]},
{"parameters": {"jsCode": status}, "name": "Which accounts work", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [880, 60], "executeOnce": True},
{"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify($json) }}", "options": {}},
"name": "Answer the test", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [1100, 60]},
# Remind: answer Ora at once, wait until the reminder time, then email it (one request per post)
{"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify({ ora: 1, remind: true, at: $('Ora').first().json.body.remindAt, cancel: $execution.resumeUrl }) }}", "options": {}},
"name": "Answer: reminder set", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [520, 700]},
wait("Wait until the reminder time", "={{ $('Ora').first().json.body.remindAt }}", [760, 700], "0e5c7a1e-5a6e-4d1f-9b1a-0a0000000002"),
{"parameters": {"jsCode": wanted}, "name": "Reminder still wanted?", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [940, 700]},
# LinkedIn: answer Ora at once, wait until the post time, turn the poster back into a file, post it (one request per post)
{"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify({ ora: 1, linkedin: true, at: $('Ora').first().json.body.postAt, cancel: $execution.resumeUrl }) }}", "options": {}},
"name": "Answer: LinkedIn post set", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [520, 900]},
wait("Wait until the post time", "={{ $('Ora').first().json.body.postAt }}", [760, 900], "0e5c7a1e-5a6e-4d1f-9b1a-0a0000000003"),
{"parameters": {"jsCode": wanted}, "name": "Post still wanted?", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [940, 900]},
{"parameters": {"operation": "toBinary", "sourceProperty": "body.image", "options": {"fileName": "={{ $('Ora').first().json.body.fileName }}", "mimeType": "={{ $('Ora').first().json.body.mimeType }}"}},
"name": "The poster as a file", "type": "n8n-nodes-base.convertToFile", "typeVersion": 1.1, "position": [1120, 900]},
{"parameters": {"postAs": "person", "person": "", "text": "={{ $('Ora').first().json.body.caption }}", "shareMediaCategory": "IMAGE", "binaryPropertyName": "data", "additionalFields": {"visibility": "PUBLIC"}},
"name": "LinkedIn: post", "type": "n8n-nodes-base.linkedIn", "typeVersion": 1, "position": [1340, 900], "disabled": True},
{"parameters": {"sendTo": "={{ $('Ora').first().json.body.email }}", "subject": "={{ $('Ora').first().json.body.subject }}", "emailType": "text",
"message": "={{ $('Ora').first().json.body.text }}", "options": {"appendAttribution": False}},
"name": "Gmail: send the reminder", "type": "n8n-nodes-base.gmail", "typeVersion": 2.1, "position": [1120, 700], "disabled": True},
# Posts: log them
{"parameters": {"jsCode": rows}, "name": "One row per post", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [520, 460]},
{"parameters": sheet("append", {"columns": {"mappingMode": "autoMapInputData", "value": {}, "matchingColumns": [], "schema": []}, "options": {"handlingExtraData": "insertInNewColumn"}}),
"name": "Google Sheets: add the rows", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [780, 460],
"disabled": True, "onError": "continueRegularOutput"},
{"parameters": {"jsCode": received}, "name": "Count the posts", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [1020, 460], "executeOnce": True},
{"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify($json) }}", "options": {}},
"name": "Answer: received", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [1260, 460]},
# Delete rows (Plan › Campaigns): find the rows with Ora's IDs, answer how many, delete them (bottom first)
{"parameters": sheet("read", {"filtersUI": {}, "options": {}}),
"name": "Google Sheets: find the rows", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [520, 1100],
"disabled": True, "alwaysOutputData": True, "onError": "continueRegularOutput", "executeOnce": True},
{"parameters": {"jsCode": unlog}, "name": "Which rows to delete", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [760, 1100]},
{"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify({ ora: 1, deleted: $json.count, off: !!$json.off }) }}", "options": {}},
"name": "Answer: rows deleted", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [980, 1100]},
{"parameters": {"jsCode": only_rows}, "name": "Any rows?", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [1180, 1100]},
{"parameters": sheet("delete", {"toDelete": "rows", "startIndex": "={{ $json.row }}", "numberToDelete": 1}),
"name": "Google Sheets: delete the rows", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [1380, 1100],
"disabled": True, "onError": "continueRegularOutput"},
{"parameters": {"content": "## Ora automation\n1. Press **Publish** at the top right.\n2. Double-click the box **Ora**, open **Production URL** and copy it.\n3. In Ora: **Connections › n8n**, paste it and press **Connect**.\n\n**After every change here: Save, then Publish.** n8n only runs the published version.\n\n### Google Sheets: log every post\nOra shows every step (Connections › n8n › Google Sheets). Here in n8n:\n1. Double-click **Google Sheets: check** › *Credential* › **Create new** › **Sign in with Google**.\n2. Double-click the other three Google Sheets boxes (**add the rows**, **find the rows**, **delete the rows**) › pick the same *Credential*. In **add the rows**, *Mapping Column Mode*: **Map Automatically**.\n3. Select the four Google Sheets boxes and press **D** (they stop looking faded).\n4. **Save**, then **Publish**.\n\nYou do not paste the sheet link here: Ora sends it.\n\n### Gmail: a reminder on the morning of each post\n1. Double-click **Gmail: check** › *Credential* › **Create new** › **Sign in with Google**.\n2. Double-click **Gmail: send the reminder** › pick the same *Credential*.\n3. Switch both Gmail boxes on (select them, press **D**). **Save**, then **Publish**.\n\nOra sends your email address and each reminder's time.\n\n### LinkedIn: post at the planned time\n1. Double-click **LinkedIn: post** › *Credential* › **Create new** › **Connect my account**, sign in to LinkedIn and press **Allow**. Pick your name under *Person*.\n2. Switch both LinkedIn boxes on (**LinkedIn: check** is only an on/off switch) (select them, press **D**). **Save**, then **Publish**.", "height": 980, "width": 440},
"name": "Read me", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [-520, 40]},
]
connections = {
"Ora": {"main": [[{"node": "What does Ora want?", "type": "main", "index": 0}]]},
"What does Ora want?": {"main": [[{"node": "Google Sheets: check", "type": "main", "index": 0}, {"node": "Gmail: check", "type": "main", "index": 0}, {"node": "LinkedIn: check", "type": "main", "index": 0}],
[{"node": "One row per post", "type": "main", "index": 0}], [{"node": "Answer: reminder set", "type": "main", "index": 0}], [{"node": "Answer: LinkedIn post set", "type": "main", "index": 0}], [{"node": "Google Sheets: find the rows", "type": "main", "index": 0}]]},
"Google Sheets: check": {"main": [[{"node": "Both checks done", "type": "main", "index": 0}]]},
"Gmail: check": {"main": [[{"node": "Both checks done", "type": "main", "index": 1}]]},
"LinkedIn: check": {"main": [[{"node": "Both checks done", "type": "main", "index": 2}]]},
"Answer: LinkedIn post set": {"main": [[{"node": "Wait until the post time", "type": "main", "index": 0}]]},
"Wait until the post time": {"main": [[{"node": "Post still wanted?", "type": "main", "index": 0}]]},
"Post still wanted?": {"main": [[{"node": "The poster as a file", "type": "main", "index": 0}]]},
"The poster as a file": {"main": [[{"node": "LinkedIn: post", "type": "main", "index": 0}]]},
"Both checks done": {"main": [[{"node": "Which accounts work", "type": "main", "index": 0}]]},
"Answer: reminder set": {"main": [[{"node": "Wait until the reminder time", "type": "main", "index": 0}]]},
"Wait until the reminder time": {"main": [[{"node": "Reminder still wanted?", "type": "main", "index": 0}]]},
"Reminder still wanted?": {"main": [[{"node": "Gmail: send the reminder", "type": "main", "index": 0}]]},
"Google Sheets: find the rows": {"main": [[{"node": "Which rows to delete", "type": "main", "index": 0}]]},
"Which rows to delete": {"main": [[{"node": "Answer: rows deleted", "type": "main", "index": 0}]]},
"Answer: rows deleted": {"main": [[{"node": "Any rows?", "type": "main", "index": 0}]]},
"Any rows?": {"main": [[{"node": "Google Sheets: delete the rows", "type": "main", "index": 0}]]},
"Which accounts work": {"main": [[{"node": "Answer the test", "type": "main", "index": 0}]]},
"One row per post": {"main": [[{"node": "Google Sheets: add the rows", "type": "main", "index": 0}]]},
"Google Sheets: add the rows": {"main": [[{"node": "Count the posts", "type": "main", "index": 0}]]},
"Count the posts": {"main": [[{"node": "Answer: received", "type": "main", "index": 0}]]},
}
wf = {"name": "Ora automation", "nodes": nodes, "connections": connections, "settings": {"executionOrder": "v1"}, "pinData": {}}
for n in wf["nodes"]:
if n["name"] == "Ora": n["name"] = WEBHOOK
wf["connections"][WEBHOOK] = wf["connections"].pop("Ora")
text = json.dumps(wf, indent=2, ensure_ascii=False).replace("$('Ora')", "$('" + WEBHOOK + "')").replace("the box **Ora**", "the first box, **" + WEBHOOK + "**")
assert "$('Ora')" not in text
out = os.path.join(os.path.dirname(__file__), '..', 'app', 'n8n', 'ora-automation.json')
with open(out, 'w') as f: f.write(text + '\n')
print('wrote', os.path.normpath(out))