Managing Facebook ads manually is one of the most time-consuming jobs in digital marketing. You're checking dashboards, pausing underperformers, tweaking budgets, rotating creatives, and doing it all over again tomorrow. It's repetitive work that pulls your attention away from strategy, and every hour you spend on it is an hour you're not spending on the things that actually move the needle.
There's a better way. Claude Code, Anthropic's agentic coding tool, lets you build custom automation scripts that connect directly to the Meta Marketing API. With the right prompts, you can have Claude Code write Python scripts that automatically pause underperforming ads, scale budgets based on ROAS thresholds, rotate creatives, and send you alerts when something changes. It's powerful, flexible, and gives you complete control over your automation logic.
This guide is written for marketers and developers who are comfortable with basic coding concepts and want to build their own automation layer on top of Meta Ads. You don't need to be a senior engineer, but you should be familiar with running scripts in a terminal, working with Python, and navigating API documentation.
That said, there's an important caveat: this approach takes real setup effort. You'll need to configure API access, write and test scripts, handle errors, and maintain your code as Meta updates its API. It's a meaningful investment of time and technical energy.
If that sounds like more than you want to take on, there's a no-code path that delivers the same automation outcomes without writing a single line of code. We'll cover AdStellar at the end of this guide as the purpose-built alternative for marketers who want results without the engineering overhead.
By the time you finish reading, you'll either have a working Claude Code automation system for your Meta campaigns, or you'll have a clear picture of which approach is right for your team. Let's get into it.
Step 1: Set Up Your Prerequisites and API Access
Before Claude Code can write a single line of automation logic, you need two things working: Claude Code itself, and a properly configured connection to the Meta Marketing API. Getting this foundation right saves you hours of debugging later.
Install Claude Code: Claude Code runs in your terminal as a CLI tool. Install it via npm with npm install -g @anthropic-ai/claude-code, then authenticate using your API key from console.anthropic.com. Once installed, you launch it by typing claude in your terminal from within your project directory. It can read your project files, write new ones, and execute code directly in your environment.
Set up your Meta Developer account: Head to developers.facebook.com and create a Business App if you don't have one already. Under your app settings, add the Marketing API product. This gives your app the permissions it needs to interact with ad accounts programmatically.
Generate your access token: Use Meta's Graph API Explorer (developers.facebook.com/tools/explorer) to generate a User Access Token with ads_management and ads_read permissions. Standard short-lived tokens expire quickly, so you'll want to exchange yours for a long-lived token, which is valid for approximately 60 days. Meta's documentation covers the token exchange process in detail.
Store credentials securely: Never hardcode your access token or ad account ID directly in a script. Instead, create a .env file in your project root and store them there. Install the python-dotenv library and load your variables at the top of every script. This keeps sensitive credentials out of your codebase and makes it easy to update tokens without editing your scripts.
Install your Python dependencies: Run pip install facebook-business python-dotenv requests to get the Facebook Business SDK and supporting libraries. The Facebook Business SDK is Meta's officially supported Python library and handles a lot of the API call complexity for you.
Common pitfall: Make sure your Meta app is set to Live mode, not Development mode. In Development mode, your app can only access data for app admins and testers. Also double-check that your ad account ID is formatted correctly as act_XXXXXXXXXX, including the act_ prefix. Forgetting this prefix is one of the most common causes of API errors for people just starting out.
Success indicator: Write a five-line Python script that initializes the Facebook Business SDK with your credentials and fetches your ad account name. If it prints your account name without errors, your API connection is working and you're ready to build. If you're new to the platform overall, it helps to first understand how to use Facebook Ads Manager before diving into API-level automation.
Step 2: Define Your Automation Goals and Prompt Claude Code
Here's where Claude Code earns its keep. Once you're inside your project directory and have launched Claude Code with the claude command, you're working with an AI that can read your existing files, understand your project context, and write production-ready Python scripts based on your instructions.
The quality of what Claude Code produces is directly tied to the quality of your prompts. Vague instructions produce vague code. Specific, structured prompts produce scripts you can actually use.
Start by defining what you want to automate. The most common Meta Ads automation use cases include: pausing ads that fall below a CTR or CPA threshold, scaling budgets for ad sets hitting ROAS targets, rotating creatives to prevent audience fatigue, and generating scheduled performance reports. Pick one to start with rather than trying to build everything at once. Understanding how to automate Facebook ad campaigns at a strategic level will help you prioritize which tasks to tackle first.
Write a specific prompt. Here's an example of the kind of prompt that produces useful output: "Write a Python script using the Facebook Business SDK that connects to ad account act_XXXXX using credentials from a .env file, fetches all active ads over the last 7 days using the insights endpoint, calculates the ROAS for each ad, and prints a table showing ad name, spend, revenue, and ROAS. Include error handling for API rate limits and missing data fields."
Notice what's in that prompt: the specific SDK, the credential method, the exact data source, the output format, and the error handling requirement. The more detail you provide, the less back-and-forth you'll need.
Review the explanation, not just the code. One of Claude Code's strengths is that it explains its logic alongside the code it generates. Read those explanations. They help you understand what each function does so you can modify the script later without breaking it.
Always request a dry-run mode. Before any script touches your live campaigns, ask Claude Code to add a --dry-run flag that runs all the logic and prints what it would do without actually making any changes. This is non-negotiable. A script that accidentally pauses your best-performing ads or doubles every budget is a bad day you don't need.
Follow-up prompts are where you refine the output: "Add a logging function that writes every action to a timestamped CSV file," or "Add a check that skips any ad set that has been live for fewer than 3 days." Claude Code handles these additions cleanly and can integrate them into the existing script structure.
Success indicator: Claude Code produces a readable script with clear function names, inline comments, error handling blocks, and a dry-run flag. If you can read through the script and understand what each section does, you're in good shape.
Step 3: Build a Budget Automation Script
Budget automation is one of the highest-value things you can do with the Meta Marketing API. The idea is straightforward: ad sets that are generating strong returns should get more budget, and ad sets that are burning money without results should be held back. Doing this manually every day is tedious. Doing it automatically means your best performers always have fuel. If you want to understand why scaling Facebook ads manually is difficult, the budget management problem is a perfect illustration.
The API endpoints you'll use: To fetch ad set data, you'll hit /act_{ad-account-id}/adsets with fields for name, daily_budget, and status. For performance data, you'll use /act_{ad-account-id}/insights with a date range, filtering by ad set. To update a budget, you'll send a PATCH request to /{adset-id} with the new daily_budget value. The Facebook Business SDK wraps all of these into cleaner Python calls.
Ask Claude Code to structure the script with three functions. Give it this prompt: "Structure the budget automation script with three separate functions: fetch_adset_performance() that returns a list of ad sets with their ROAS and spend for the last 7 days, calculate_budget_adjustment() that applies scaling rules and returns a list of proposed changes, and apply_budget_changes() that sends the PATCH requests and logs the results. Add a dry-run parameter to apply_budget_changes() that prints changes instead of sending them."
This separation of concerns makes the script much easier to test and modify. You can run fetch_adset_performance() and calculate_budget_adjustment() independently to verify the logic before you ever call apply_budget_changes().
Define your scaling rules in plain language. Tell Claude Code: "In calculate_budget_adjustment(), apply these rules: if ROAS is above 3.0 and spend is above $50, increase daily budget by 20% up to a maximum of $500. If ROAS is between 1.5 and 3.0, keep the budget unchanged. If ROAS is below 1.5 and spend is above $30, decrease daily budget by 15% down to a minimum of $20." Claude Code will translate these conditions into the appropriate if/elif/else logic.
Add logging from the start. Ask Claude Code to include a logging function that writes every proposed or applied change to a CSV with columns for timestamp, ad set name, ad set ID, old budget, new budget, current ROAS, and the rule that triggered the change. This audit trail is invaluable when you need to explain why a budget changed or when you're debugging unexpected behavior.
Common pitfall: Meta enforces minimum budget requirements per ad set, and these vary by optimization goal and billing type. Ask Claude Code to include a validation check before sending any PATCH request: "Before applying a budget decrease, check that the new budget meets Meta's minimum requirements for this ad set's optimization goal. If it doesn't, skip the change and log a warning instead."
Success indicator: Run the script with the dry-run flag against your real ad account. The output should print a clean table of proposed changes that match your expected rules. Check a few ad sets manually in Ads Manager to confirm the ROAS figures and budget math are correct.
Step 4: Automate Creative Rotation and Ad Pausing
Budget automation handles the money side of your campaigns. Creative automation handles the performance side. Ads with declining engagement drag down your overall campaign results and increase your costs. Catching them early and rotating in fresh creatives keeps your campaigns performing at their best. This is one of the core reasons automating Facebook ad creation has become such a priority for performance marketers.
Fetching per-ad performance data: Use the /insights endpoint with breakdowns=['ad_id'] to get performance metrics at the individual ad level. Request fields including impressions, clicks, spend, actions (for conversions), and ctr. Set your date range to the last 7 days to get a meaningful sample without including stale data from older periods.
Building the pausing function: Prompt Claude Code with: "Add a function called identify_underperforming_ads() that takes the per-ad insights data and returns a list of ads that have more than 1,000 impressions and a CTR below 0.8%. For each identified ad, include the ad name, ad set name, impressions, CTR, and the reason for flagging. Then add a pause_ads() function that sends a status update to PAUSED for each flagged ad, with a dry-run parameter."
Build in a learning phase check. This is critical. Meta's algorithm needs time to optimize delivery before you can make meaningful judgments about an ad's performance. Pausing ads too early disrupts the learning phase and can hurt your ad set's overall performance. Ask Claude Code to add a check: "Before flagging any ad for pausing, verify that the ad has been live for at least 3 days. If the ad was created within the last 3 days, skip it and log that it was excluded due to the learning phase."
Add notification alerts: Ask Claude Code to write a notification function that sends an alert when ads are paused automatically. You have two straightforward options: use Python's built-in smtplib to send an email summary, or use a Slack webhook to post a message to a channel. Prompt Claude Code with your preferred method and it will generate the integration code. Getting a Slack message that says "3 ads paused in Campaign X" gives you visibility without requiring you to check logs manually.
Creative rotation: Rather than letting underperforming ads sit or rebuilding campaigns from scratch, you can use the API to duplicate top-performing ads with new creative asset IDs. Ask Claude Code to add a function that identifies your top two ads by CTR in each ad set and duplicates them with a naming convention that includes the date. This keeps your campaigns fresh and gives you a systematic way to launch multiple Facebook ads quickly as you test new creatives against proven performers.
Success indicator: Run the script in dry-run mode against a real campaign. The output should correctly identify ads that meet your pause criteria, exclude ads that have been live fewer than 3 days, and show the proposed pausing actions. Cross-reference a few flagged ads manually in Ads Manager to confirm the logic is working correctly.
Step 5: Schedule and Monitor Your Automation
A script that only runs when you remember to run it isn't really automation. The final step is getting your scripts running on a schedule and making sure you'll know immediately if something goes wrong.
Setting up scheduled runs: On Linux or Mac, use cron jobs to schedule your scripts. Open your crontab with crontab -e and add your schedule. A common setup runs the budget automation script once daily at 6am and the creative monitoring script every 12 hours. The cron syntax for a daily 6am run looks like this: 0 6 * * * /usr/bin/python3 /path/to/budget_automation.py. On Windows, use Task Scheduler to achieve the same result. Ask Claude Code to help you write the exact cron syntax for your specific schedule.
Organize your logs: Store all script logs in a dedicated folder with date-stamped filenames, such as logs/budget_changes_2026-05-23.csv. This makes it easy to audit every automated decision and trace back any unexpected campaign changes. Ask Claude Code to add a log rotation function that archives logs older than 30 days so your logs folder doesn't grow indefinitely.
Monitor for script failures: Ask Claude Code to wrap your main script logic in a try/except block that catches any unhandled exception and sends an alert before exiting. If your budget automation script crashes silently at 6am, you won't know until you check your campaigns manually. A quick Slack message or email saying "budget_automation.py failed with error: [error message]" means you can fix it before it causes problems.
Review your rules regularly: Static thresholds set today may not be the right thresholds three months from now. Meta's algorithm evolves, seasonality affects performance benchmarks, and your business goals may shift. Set a monthly reminder to review your automation rules and adjust thresholds based on recent performance trends. Teams that want to avoid this ongoing maintenance burden entirely often look at an automated Facebook ads platform that handles rule updates and optimizations without requiring code changes.
An honest assessment: This approach is genuinely powerful, but it comes with real ongoing costs. Meta updates its API periodically, which can break existing scripts. Your access tokens expire every 60 days and need to be refreshed. New campaign types or bidding strategies may require script updates. And any time your business rules change, someone needs to update the code. For teams with developer resources, this is manageable. For everyone else, there's a better path.
Skip the Code: How AdStellar Does This Automatically
The Claude Code approach covered in this guide is genuinely useful. If you have Python experience and developer time available, building your own automation layer gives you complete control over your Meta Ads logic. But let's be honest about the trade-offs: you're looking at significant setup time, ongoing maintenance as Meta updates its API, token management, debugging sessions, and the need to update scripts every time your strategy changes.
For most marketing teams, that's not where their time is best spent.
AdStellar is an AI-powered Meta ad platform built specifically to deliver the same automation outcomes without writing a single line of code. Here's how it maps to everything covered in this guide.
AI Campaign Builder: This is the equivalent of your budget and performance automation scripts, but built into the platform. AdStellar's AI analyzes your historical campaign data, ranks every creative, headline, and audience by performance metrics including ROAS, CPA, and CTR, and builds complete Meta Ad campaigns in minutes. Every decision comes with a full explanation so you understand the strategy behind it, not just the output. And unlike a static script, the AI gets smarter with every campaign it processes.
AI Insights and Leaderboards: Instead of writing scripts to identify winners and losers, AdStellar surfaces them automatically. Leaderboards rank your creatives, headlines, copy, audiences, and landing pages by real metrics against your specific goals. Set your targets and the AI scores everything against your benchmarks so you can instantly see what's working and what needs to be cut. This replaces the monitoring scripts, the CSV logs, and the manual review sessions.
Bulk Ad Launch: Creating hundreds of ad variations by mixing creatives, headlines, audiences, and copy is exactly the kind of repetitive work that automation is meant to handle. AdStellar generates every combination and launches them to Meta in clicks. No API calls, no scripts, no debugging. What might take a developer hours to script and test happens in minutes through the platform interface.
Winners Hub: Your best-performing creatives, headlines, and audiences are automatically collected in one place with real performance data attached. When you're ready to build your next campaign, you can pull directly from proven winners instead of starting from scratch. This replaces the creative rotation logic you'd otherwise need to build and maintain in code.
AI Ad Creative: This is where AdStellar goes beyond what a Marketing API script can do. Generate image ads, video ads, and UGC-style avatar content directly from a product URL. Clone competitor ads from the Meta Ad Library. Refine any creative with chat-based editing. No designers, no video editors, no actors needed. Your Claude Code scripts can manage existing ads, but they can't create new ones from scratch.
Pricing starts at $49 per month with a 7-day free trial. Compare that to the developer hours required to build, test, and maintain a custom automation system, plus the ongoing cost of debugging when Meta changes something. For most marketing teams, AdStellar delivers more capability at a fraction of the total cost.
Choosing the Right Path for Your Team
Both approaches covered in this guide can meaningfully reduce the manual work involved in running Meta Ads campaigns. The right choice depends on your team's resources, technical comfort, and how much time you want to invest in building versus running campaigns.
Here's a quick decision checklist to help you decide.
Choose the Claude Code approach if: You or someone on your team has solid Python experience. You want complete, custom control over your automation logic. You have time to build, test, and maintain scripts over the long term. Your automation needs are highly specific and unlikely to be covered by a standard platform.
Choose AdStellar if: You want to launch campaigns faster without a development investment. You want AI to generate creatives as well as manage campaigns. You want automation that improves over time without you updating any code. You want leaderboards and performance insights built in, not bolted on. You want to clone competitor ads and generate UGC-style content without a production team.
The honest summary: Claude Code gives you a blank canvas and powerful tools to build whatever you need. AdStellar gives you a purpose-built system that handles the full cycle from creative generation to campaign launch to performance optimization, starting at $49 per month.
If you're ready to skip the setup and start seeing results faster, Start Free Trial With AdStellar and see how quickly AI can take the manual work out of your Meta advertising.



