OpenClaw: A Practical Guide to Running a Local Autonomous AI Agent — Part 3: Skills
I’m not arguing, I’m just explaining why I’m right.
I speak three languages: English, profanity, and sarcasm.
Facebook automation
The goal is: let a Python script drive a real Chrome window to publish a photo post on Facebook, instead of clicking manually. Two ideas make that possible:
- A dedicated browser profile — a separate, clean Chrome “identity” folder just for the bot. Your personal bookmarks, passwords and Facebook session stay untouched, and the bot’s login (cookies) gets saved in that folder so you don’t sign in every run.
- Automation control — Playwright starts (or attaches to) Chrome and controls it: types text, picks files, clicks buttons.
Normally, Python scripts work invisibly in the background. However, some websites—like Facebook—make it very difficult or expensive to post automatically from the background.
To solve this, this script uses a famous tool called Playwright. Think of Playwright as an invisible robot sitting at your keyboard and mouse. It literally opens up Google Chrome on your screen, goes to facebook.com, types your message into the box, and attaches your picture!
Why does this script ask YOU to press “Enter” twice? (“Human-in-the-Loop”)
Facebook has strict security guards that look for robots. If a robot tries to log in, click buttons too fast, and hit “Post” all by itself, Facebook might lock your account thinking you were hacked! So, this script uses a clever strategy called Human-in-the-Loop Automation (you and the robot work as a team):
- The Robot opens Chrome and goes to Facebook.
- You click the “Create post” button on the screen, then press Enter in the terminal to tag the robot back in.
- The Robot instantly types your text and uploads the photo from your hard drive.
- You look at the finished post on your screen to make sure it looks great, click the blue “Post” button yourself, and press Enter in the terminal to close Chrome.
Step 1 — Launch Chrome yourself, with debugging on
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
--remote-debugging-port=9222 \
--user-data-dir="$HOME/chrome-fb-profile"
What each part means:
Google\ Chrome— the backslash escapes the space in the folder name (macOS shell syntax).--remote-debugging-port=9222— opens a local “remote control” door (the Chrome DevTools Protocol, the same thing DevTools uses). A script can connect tohttp://localhost:9222and drive this exact window.--user-data-dir=...— use a brand-new profile folder instead of your normal one. First launch it’s empty, so you sign in to Facebook once; afterwards the cookies live there and you’re already logged in.
Windows equivalent (PowerShell):
"C:\Program Files\Google\Chrome\Application\chrome.exe" `
--remote-debugging-port=9222 `
--user-data-dir="$HOME\chrome-fb-profile"
Step 2 — The Python script
context = p.chromium.launch_persistent_context(
user_data_dir=str(user_data_dir),
channel="chrome",
headless=False,
args=["--disable-blink-features=AutomationControlled"],
ignore_default_args=["--enable-automation"],
)
launch_persistent_context(...)— “start the browser AND remember my login”. The profile folder is reused between runs, so cookies/localStorage survive. This is why you sign in only once.channel="chrome"— use the Chrome you actually installed, rather than the stripped-down Chromium build Playwright normally downloads. Real Chrome looks and behaves more like a normal user’s browser.headless=False— show the window. Essential here, because you have to log in and watch.args=["--disable-blink-features=AutomationControlled"]andignore_default_args=["--enable-automation"]— these remove the tell-tale signs that a browser is being automated (sites can read a flag callednavigator.webdriverand know a bot is driving). “Stealth” just means less obvious, not invisible.page = context.pages[0] if context.pages else context.new_page()— a fresh Chrome opens with a tab; reuse it instead of opening a second one.
input("Sign in if needed, open Create post -> Photo/video, then press Enter here...")
A pause button. The script literally stops and waits for you to press Enter in the terminal, giving you time to do manually the two fiddly things it doesn’t do: log in, and click “Create post → Photo/video” so the post dialog is open. This is a pragmatic shortcut — Facebook’s UI is very hard to script reliably, so the human handles the opening.
text_box = page.locator(
'[role="dialog"] [contenteditable="true"][role="textbox"]'
).first
text_box.fill(post_text)
- A locator is a CSS-selector-like recipe for “find this element on the page”.
role="dialog"= the popup window (the create-post box).contenteditable ... textbox= the text area where you’d type the status..first= if several match, take the first one (defensive, because Facebook’s DOM is full of duplicates).fill(...)= type the post text, as if you typed it.
file_input = page.locator('[role="dialog"] input[type="file"]').first
file_input.set_input_files(str(image_path))
Hidden <input type="file"> elements are what a “Browse” button really is. set_input_files hands the file straight to that input — much more reliable than trying to click the button and drive the native Windows file-picker dialog (which Playwright cannot control, since it’s an OS window, not a web page).
Bugs and sharp edges worth knowing
- Fragile selectors. Facebook changes its markup constantly, and its class names are meaningless gibberish, so the code leans on
roleattributes — which still break from A/B test to A/B test. Expect to re-fix this. - The real risk. Facebook actively detects automated posting and can flag, rate-limit or disable accounts, regardless of “stealth” flags. Keep the volume human-like and keep a second login method. For anything serious, the official Meta Graph API (a Page + access token, no browser at all) is the sanctioned way to post.
- Install once:
pip install playwrightthenplaywright install chromium(you can skip the last one if you only usechannel="chrome").
The Python Code
# =====================================================================
# 1. IMPORTS (Bringing in our toolkits)
# =====================================================================
# 'Path' helps Python find files and folders on your Mac without getting confused by slashes (/).
from pathlib import Path
# From the 'playwright' library, we import two things:
# 1. 'sync_playwright': The "Synchronous" version of our browser robot (remember "Synchronous"
# means it does one step at a time, waiting for each step to finish before moving on).
# 2. 'TimeoutError as PlaywrightTimeoutError': An error that happens if a webpage takes
# too long to load. We use the keyword `as` to give it a nickname ('PlaywrightTimeoutError')
# so we don't confuse it with Python's built-in TimeoutError!
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
# =====================================================================
# 2. SETTING UP YOUR VARIABLES (File Paths & Text)
# =====================================================================
# Point to the exact picture file on your Mac that you want to upload to Facebook.
image_path = Path("/Users/nmaximo7/macOS/claude/skills/daily-gospel/assets/twoWitnesses.jpg")
# Normally, when a robot opens Chrome, it opens in "Amnesia Mode" (Incognito)—meaning
# it forgets your Facebook password every single time it closes!
# Here, we create a path to a special folder in your Mac's Home directory (`Path.home()`)
# called "playwright-fb-profile".
# (Cool trick: With `Path` objects, using the `/` division symbol automatically glues
# folder names together!) Chrome will save your login cookies inside this folder so you
# only have to log into Facebook the very first time!
user_data_dir = Path.home() / "playwright-fb-profile"
# The message you want the robot to type into your Facebook post.
post_text = "Your post text goes here"
# =====================================================================
# 3. SAFETY CHECK: Does the picture actually exist?
# =====================================================================
# Before wasting time opening Google Chrome, let's check if `image_path` is a real file.
# If `not image_path.is_file()` is True (meaning the file is missing), stop immediately
# and show a clear error message.
if not image_path.is_file():
raise FileNotFoundError(f"Image not found: {image_path}")
# =====================================================================
# 4. LAUNCHING THE ROBOT BROWSER
# =====================================================================
# `with sync_playwright() as p:` starts up the Playwright robot engine and nicknames it `p`.
# Using the word `with` is a neat Python safety feature: it guarantees that when the
# indented code block finishes (or even if it crashes!), Python will cleanly shut down
# the robot engine so it doesn't stay stuck running in the background.
with sync_playwright() as p:
# Now we launch Google Chrome with a "Persistent Context" (meaning: "Remember my login cookies!").
context = p.chromium.launch_persistent_context(
# Tell Chrome to save our login memory inside the folder we picked earlier:
user_data_dir=str(user_data_dir),
# Tell Playwright to use your real installed Google Chrome browser:
channel="chrome",
# 'headless=True' means "run invisibly in the background with no window" (it has no "head").
# 'headless=False' means "Show the actual Chrome window on my monitor so I can see and click it!"
headless=False,
# --- DISGUISE SETTINGS (So Facebook doesn't think we are a bad bot) ---
# Normally, when Playwright opens Chrome, Chrome waves a giant digital flag that says
# "HEY WEBSITE, A ROBOT IS DRIVING ME!" and shows a banner saying "Chrome is being controlled
# by automated test software." These two lines turn off that robot flag and hide that banner:
args=["--disable-blink-features=AutomationControlled"],
ignore_default_args=["--enable-automation"],
)
# =====================================================================
# 5. OPENING A TAB & GOING TO FACEBOOK
# =====================================================================
# When Chrome opens, it might already have a blank tab open (`context.pages[0]`),
# or it might have zero tabs open.
# This 1-line shortcut says: "Grab the first open tab (`pages[0]`) if any tabs exist (`if context.pages`);
# otherwise (`else`), open a brand-new tab (`context.new_page()`)."
page = context.pages[0] if context.pages else context.new_page()
# Tell the tab to go to Facebook!
# `wait_until="domcontentloaded"` tells Python: "Wait until the main structure of the
# webpage (buttons, boxes, text) has arrived, then move on—don't wait around for every
# single slow video ad in the feed to finish loading."
page.goto("https://www.facebook.com", wait_until="domcontentloaded")
# =====================================================================
# 6. HUMAN STEP #1: You open the "Create Post" window!
# =====================================================================
# `input(...)` is a built-in Python command that prints a message in your Terminal
# and completely PAUSES the Python script until you press the `Enter` key on your keyboard.
#
# While paused, you look at the Chrome window, log into Facebook (if it's your first time),
# click "What's on your mind?" (Create post) -> click "Photo/video", and then come back
# to the Terminal and hit Enter!
input("Sign in if needed, open Create post -> Photo/video, then press Enter here...")
# =====================================================================
# 7. FINDING THE FACEBOOK POST BOX ON THE SCREEN
# =====================================================================
# Once you hit Enter, the robot wakes up! Now it needs to find where to type on the webpage.
# Webpages are built out of invisible HTML tags with labels like `role="dialog"`.
#
# First, `page.locator('[role="dialog"]')` tells the robot: "Find the popup box
# ('dialog' window) that is currently floating in the middle of Facebook."
dialog = page.locator('[role="dialog"]')
# Next, look INSIDE that popup box (`dialog.locator(...)`) and find the area where
# humans can type text (`[contenteditable="true"][role="textbox"]`).
# `.first` means: "If there happens to be more than one text box inside the popup,
# pick the very first one."
text_box = dialog.locator(
'[contenteditable="true"][role="textbox"]'
).first
# =====================================================================
# 8. MAKING SURE THE TEXT BOX IS ACTUALLY READY
# =====================================================================
# What if you accidentally pressed Enter in the Terminal BEFORE clicking "Create post"
# on Facebook? We use a `try...except` block to check safely!
try:
# Tell the robot to wait up to 10 seconds for the text box to be visible on screen.
# Why does it say `10_000`?
# 1. Computers count time in milliseconds (1,000 milliseconds = 1 second, so 10,000 = 10 seconds).
# 2. In Python, you aren't allowed to put commas in big numbers (like `10,000`),
# so Python lets you use underscores (`10_000`) to make big numbers easy for human eyes to read!
text_box.wait_for(state="visible", timeout=10_000)
except PlaywrightTimeoutError:
# If 10 seconds pass and the robot still can't find the "Create post" text box,
# stop and give the human a friendly reminder of what went wrong.
raise RuntimeError(
"Couldn't find the post editor. Make sure the Create post "
"dialog is open, then try again."
)
# =====================================================================
# 9. ROBOT ACTION: Type the Text & Attach the Image!
# =====================================================================
# `.fill()` tells the robot to click inside the Facebook text box and instantly
# type your `post_text` message!
text_box.fill(post_text)
# Now, how does the robot attach a photo?
# Whenever a website has an "Upload Photo" button, hidden underneath that pretty button
# in the website's code is a secret tag called `input[type="file"]`.
# Here, the robot finds that secret file-upload receiver inside the popup box:
file_input = dialog.locator('input[type="file"]').first
# And `.set_input_files()` injects your photo (`image_path`) directly into Facebook's
# file receiver! You don't even have to watch a Mac Finder window pop up—the photo
# just magically appears inside your Facebook post!
file_input.set_input_files(str(image_path))
# =====================================================================
# 10. HUMAN STEP #2: Review, Click "Post", and Close!
# =====================================================================
# Once again, `input(...)` pauses the script so Chrome stays open!
# Now you can look at your Facebook window, see your text and photo sitting there ready to go,
# click Facebook's blue "Post" button yourself, wait a few seconds for it to upload,
# and then press `Enter` in the Terminal.
input("Review the post in Facebook, then press Enter to close...")
# Once you press Enter, gently close the Google Chrome window and save your login cookies.
context.close()
YouTube automation
This is a neat summary of YOUR YouTube Studio dashboard: views, subscribers and the latest comments. We will use Playwright. Playwright is a library for controlling a real web browser from code. It can click, type, navigate, read page content — like a robot sitting at your keyboard.
When you run it, the script launches a visible Chrome window using a dedicated profile, navigates to YouTube Studio, waits for you to sign in manually, then scrapes the rendered dashboard text. It extracts three numbers:
- Views over the last 28 days
- Current subscriber count
- The most recent visible comment
It prints a compact summary to the terminal so you can glance at your channel health without opening the Studio website yourself.
Setup
# It changes into your project directory.
cd ~/macOS/mylauncher
# It installs Playwright into the project's virtual environment so it does not interfere with your system Python.
.venv/bin/pip install playwright # or: .venv/bin/pip install -r tools/requirements-youtube.txt
After installing, you need Google Chrome installed on your computer because the script uses channel="chrome".
Why Real Chrome and Nothing Else
- Google refuses to let you sign in with a browser it recognises as automated or embedded. You see “This browser or app may not be secure”. Playwright’s own Chromium, Firefox and WebKit builds are recognised (different build, automation flags, no Google components).
- Real Chrome is the browser Google expects. In the code:
channel="chrome"means use the Chrome that is installed, not a downloaded one. - A persistent profile (
launch_persistent_context(user_data_dir=...)) is simply a folder where Chrome keeps its cookies, like your normal profile. You sign in by hand once; later runs are already signed in. Nobody types your password: this script never sees it. --disable-blink-features=AutomationControlledremoves the flagnavigator.webdriver = true. This is a Chrome command-line flag. Websites detect automation by checking navigator.webdriver — a JavaScript property that is true when a program is driving the browser. This flag removes that telltale flag, making the browser look human-driven.headless=False: a visible window. Invisible browsers are exactly what Google’s bot detection looks for. A visible window looks normal.
The Python code
import re
from pathlib import Path
from playwright.sync_api import sync_playwright
# Use a dedicated, persistent Chrome profile
profile_dir = Path.home() / "chrome-youtube-profile"
profile_dir.mkdir(exist_ok=True)
def get_youtube_stats(page: object) -> dict:
"""
Extract a small, useful summary from the YouTube Studio dashboard:
- views (last 28 days)
- current subscribers
- latest visible comment
"""
# Give Studio time to finish loading its dashboard cards.
page.wait_for_load_state("networkidle", timeout=30_000)
text = page.locator("body").inner_text(timeout=15_000)
stats = {
"views_last_28_days": None,
"current_subscribers": None,
"latest_comment": None,
}
# Views: "Views 602"
views_match = re.search(
r"Views\s+(\d[\d.,]*)\s*(?:—)?",
text,
re.IGNORECASE,
)
if views_match:
stats["views_last_28_days"] = views_match.group(1)
# Current subscribers: "Current subscribers\n12"
subscribers_match = re.search(
r"Current subscribers\s*\n\s*(\d[\d.,]*)",
text,
re.IGNORECASE,
)
if subscribers_match:
stats["current_subscribers"] = subscribers_match.group(1)
# Latest comment:
# "@username\n•\n2 weeks ago\nComment text"
comment_match = re.search(
r"@\S+\s*•\s*[^\n]+\n([^\n]+)",
text,
)
if comment_match:
stats["latest_comment"] = comment_match.group(1).strip()
return stats
def print_youtube_stats(stats: dict) -> None:
print("YouTube Studio summary")
print("----------------------")
print(f"Views, last 28 days: {stats['views_last_28_days']}")
print(f"Current subscribers: {stats['current_subscribers']}")
print(f"Latest comment: {stats['latest_comment']}")
with sync_playwright() as p:
context = p.chromium.launch_persistent_context(
user_data_dir=str(profile_dir),
channel="chrome", # requires Google Chrome installed
headless=False,
args=[
"--disable-blink-features=AutomationControlled",
],
)
try:
page = context.pages[0] if context.pages else context.new_page()
page.goto(
"https://studio.youtube.com/",
wait_until="domcontentloaded",
)
input("Sign in manually if prompted.\nAfter YouTube Studio has fully loaded, press Enter here...")
stats = get_youtube_stats(page)
print_youtube_stats(stats)
input("\nPress Enter to close...")
finally:
context.close()