Установка
SKILL.md
Meta Ads (Marketing API)
Pull ad performance data from Meta (Facebook, Instagram, Messenger, Click-to-WhatsApp, Threads), run analyses, and — with explicit confirmation — write changes back (pause, budget change, duplicate, full campaign creation with images and copy).
When to consult this skill
Any question about Meta ad performance, creative health, audience/placement mix, or campaign management. If the user asks "how are my ads doing" without specifying a platform, ask whether they mean Meta or Google before defaulting.
Three things to internalize before touching any script
1. Where the scripts run matters. The scripts call graph.facebook.com over the open internet. Some execution environments (including Claude's Linux sandbox in certain configurations) block this endpoint via proxy. If you hit a ProxyError / Tunnel connection failed: 403 on the first call, run the scripts from the user's host machine — macOS, Windows, or Linux — using that machine's Python. Per-OS commands:
- macOS:
python3 scripts/auth_check.py, deps viapython3 -m pip install --user requests - Windows:
python scripts/auth_check.py(orpy scripts/auth_check.pyifpythonisn't on PATH), deps viapython -m pip install --user requests - Linux:
python3 scripts/auth_check.py, deps viapython3 -m pip install --user requests(add--break-system-packageson Debian/Ubuntu 22+)
The scripts themselves are pure Python with one dependency (requests) and no shell/OS assumptions, so they run identically everywhere once dependencies are installed.
2. WhatsApp is not a separate ad surface. Click-to-WhatsApp ads run on Facebook and Instagram placements. They show up in the Marketing API as regular ads with destination_type=WHATSAPP and conversion events under actions (look for onsite_conversion.messaging_conversation_started_7d and similar). Don't promise the user a "WhatsApp ads dashboard" — there isn't one.
3. Read is safe, write is not. Insights endpoints (GET) are idempotent and harmless. Pause / budget / duplicate (POST) actions touch real money. The write rules in references/write-actions.md are non-negotiable — read that file before any write call.
The 37-month data wall
Meta's insights API only serves data from the last 37 months. Any campaign older than that returns error 3018 and is effectively invisible. If the user asks "what was my best campaign ever" and their activity predates the window, the answer is "the API can't tell you — check Ads Manager's archived reports UI." Surface this before starting a query that's going to fail.
Before anything else: check setup + discover accounts
The first three calls are always the same:
python scripts/auth_check.py— is the token alive, what identity does it resolve to, how many ad accounts does it see?python scripts/list_accounts.py --with-recent-spend— which accounts are actually running ads right now? (Sorted by last-30-day spend, then lifetime spend.) This tells you which account to pin asMETA_AD_ACCOUNT_ID.python scripts/list_campaigns.py— once you have the right account, what campaigns are on it?
If any of these fail, stop and walk the user through references/setup.md. Don't try to be clever and guess credentials.
How to guide a user through setup (first-timers)
references/setup.md is written as a click-by-click walkthrough. When a user has no credentials yet:
- One step at a time. Don't dump the whole document. Ask them which OS they're on, then give them the prerequisites block for that OS. Wait for them to report "done" before moving on.
- Confirm the path choice. Walk through the Step 0 decision questions with them in chat. Don't assume — especially "do you boost from Instagram?" is easy to misjudge.
- Read back what they paste. When they share a token, App ID, or ad account ID, echo it back (redact tokens to the first 8 chars) and confirm you have it right before you move on. This catches the #1 setup bug: pasting the System User's ID where the Ad Account ID should go.
- Verify before moving on. After they fill in
.env, runauth_check.pyimmediately. Don't let them run analysis commands until the verification returnsok: true— every "the report is empty" issue traces back to a half-broken.env. - Match their OS in every command. If they said "I'm on Windows," don't tell them to run
python3— tell thempythonorpy. If they said "Mac", usepython3. The setup.md has per-OS blocks; copy the matching one into chat.
Required env vars (user provides these once during setup):
META_ACCESS_TOKEN— either a long-lived user token (Path B, 60 days) or System User token (Path A, never expires). See the decision tree below.META_AD_ACCOUNT_ID— default ad account, formatact_1234567890(scripts accept--account-idto override per call).META_API_VERSION— defaults tov25.0(current as of early 2026; v26.0 expected ~Sep 2026).
The user puts these in a .env file at the working directory or exports them in the shell. Scripts auto-load .env if present. See assets/env.template.
Path A vs Path B: which token type?
This is the single most common failure mode. Get it right up front.
Use Path A (System User token) when:
- Ads run inside a Meta Business Manager you control.
- The ad accounts you want to analyze are owned by that BM.
- You want a token that never expires.
Use Path B (long-lived user token) when:
- You boost posts from the Instagram app (these often create a personal ad account outside any BM — invisible to System User tokens no matter what permissions you grant).
- Your ad account is attached to your personal Facebook profile, not a BM.
- You want to see every ad account your personal FB login can access (typically the broadest view).
Can't tell which? Start with Path B. It sees a strict superset of what Path A sees. Once you've identified the important accounts, you can optionally move them into a BM and switch to Path A for permanence.
Full setup steps for both paths: references/setup.md.
Workflow: read operations
For any read request, follow this loop:
-
Pick the right script. Don't reinvent. The bundled scripts cover the common cases:
auth_check.py— verify token, list visible accounts brieflylist_accounts.py— discover all ad accounts, decode status, show lifetime + optional recent spendlist_campaigns.py— campaigns under an account, with status filtersfetch_insights.py— the workhorse. Date ranges, breakdowns (publisher_platform, age, gender, country, placement, device_platform), level (account/campaign/adset/ad), custom field lists. Read its--helpbefore calling.creative_fatigue.py— frequency + CTR decay analysis at the ad levelanomaly_detect.py— compares a date range against the prior equivalent range, flags significant changesexchange_token.py— Path B only: swap short-lived user token for 60-day long-lived token
Write scripts (pause/budget/duplicate/create — read
write-actions.mdfirst):pause_ad.py— pause/resume a single campaign, ad set, or adupdate_budget.py— modify daily or lifetime budget with 2×-per-call safety capduplicate_ad.py— clone an ad, ad set, or entire campaign into a new copycreate_campaign.py— build a whole campaign (campaign + ad sets + creatives + ads) from a spec JSON. Handles image upload and interest resolution. Seereferences/campaign-creation.md.rollback_creation.py— pause or delete every object from acreate_campaign.pyrun using its state file
-
Run it, capture JSON output. Every script outputs structured JSON to stdout. Don't try to parse human-readable text — there isn't any. Pipe to a file if the user wants to keep the raw data:
python scripts/fetch_insights.py ... > insights.json. -
Analyze with the playbooks. Once you have the data, consult
references/analysis-playbooks.mdfor the relevant pattern (fatigue, funnel, audience mix, anomalies). The playbook tells you what thresholds matter and what to recommend. -
Present in the user's preferred language. If the user writes in Hebrew, respond in Hebrew. Keep metric names in English (
CTR,CPA,ROAS) so they cross-reference cleanly with Ads Manager. If asked for a doc/dashboard, follow whatever design system skill they've set up.
Workflow: write operations (pause, budget, duplicate)
These are the dangerous ones. Follow this protocol every time, no shortcuts:
- Surface the action and the impact in plain language before calling. Example: "Pause ad
Campaign_v3(ID 120214...). This ad spent ₪47 in the last 7 days with 0.8% CTR. Confirm?" - Wait for explicit
yes/confirm/ the user's language equivalent in chat. A previous "go ahead" in the conversation does not carry over. Each write needs its own confirmation. - One action at a time by default. If the user wants to bulk-pause 12 ads, present a numbered list and confirm the whole batch in one explicit message ("pause all 12") — but log each call separately.
- Always do a dry-run first when the script supports it (
--dry-runflag prints what would change without calling the API). - Never auto-shift budgets above +50% in one call. If the user wants a 3x increase, do it in steps with confirmation each time. Meta's learning phase resets on big budget changes anyway.
Full rules and edge cases in references/write-actions.md. Read it before calling any of: pause_ad.py, update_budget.py, duplicate_ad.py, create_campaign.py.
Workflow: creating a campaign from scratch
Use create_campaign.py to build a full campaign tree (campaign → ad sets → creatives → ads) in one shot from a spec JSON. Good for A/B flights where you want the exact same structure with disciplined naming and auditable creation history.
Before you touch the script:
- Check if the user has a pixel. No pixel → force
objective: OUTCOME_TRAFFICandoptimization_goal: LINK_CLICKS. Don't build a conversions campaign against an account that can't measure conversions; you'd be paying Meta to optimize toward an event it never sees. Surface this to the user and let them decide whether to wait for pixel install or launch blind on traffic. - Check the account balance. Status code 3 (
UNSETTLED) on the ad account means objects can be created but nothing will deliver until balance clears. Don't block creation, but tell the user before they expect spend. - Discover the right page + Instagram identity. Users often own multiple pages. Query
/me/accountsand/act_.../promote_pagesand match against which page ran their historical winning ads (fetch a handful of recent ads, pullcreative.effective_object_story_idto see the page ID in the prefix). - Default everything to PAUSED. The campaign, ad sets, and ads should all be
PAUSEDat creation. The user flips ACTIVE themselves in Ads Manager once they've eyeballed the creative. This is the last safety net. - Dry-run first, always.
create_campaign.py --spec foo.json --dry-runprints the full plan with resolved interest IDs, currency-corrected budgets, and targeting summary. Walk the dry-run back to the user in plain language before asking for--confirm.
Per write-actions.md, a fresh explicit confirmation is required for --confirm even if the user approved the plan earlier in the same session. That confirmation must name the action (e.g. "confirm create", "בצע יצירה") — not a generic "ok".
Full spec format, field reference, currency handling, interest resolution, state file and rollback details: references/campaign-creation.md.
When NOT to use create_campaign.py
- Single ad addition to existing ad set — just call the ads endpoint directly or use the UI. Overkill to spec-and-run for one ad.
- Duplicating a winner —
duplicate_ad.pyis faster and preserves learning signals. - Dynamic creative, catalog ads, collection ads — not supported in v1. The script only handles single-image link ads via
link_data. Extend it or build a sibling script if needed.
Gotchas the scripts already handle for you
- Currency minor units.
amount_spent,balance,spend_cap,daily_budget,lifetime_budgetare returned by Meta as strings of minor units (agorot/cents/pence).list_accounts.pyandlist_campaigns.pyconvert these to major units in a_majoror plain decimal field. Zero-decimal currencies (JPY, KRW, VND, ISK, TWD, etc.) are not divided. - Account status codes. Scripts decode 1→ACTIVE, 2→DISABLED, 3→UNSETTLED, 7→PENDING_RISK_REVIEW, etc.
- Pagination. All scripts auto-paginate via
meta_client.paginate(). - Rate limits.
meta_client._request()backs off on subcodes 1487742 / 2446079 / 1487390 and retries. - Async insights.
fetch_insights.pyauto-falls-back to async jobs when sync queries would time out (or you can force with--async). - DELETED campaigns. Meta's campaigns endpoint returns error 1815001 when you request DELETED. The script's
--statuschoices намеренно исключают DELETED. Чтобы увидеть удалённые кампании, используйте интерфейс Ads Manager.
Что не обрабатывают встроенные скрипты
- Первичная аутентификация / генерация токена (вручную, см.
references/setup.md). - Приём событий Pixel / Conversions API (отдельный API).
- Форматы динамических креативов / каталога / коллекций (только одиночные ссылочные объявления с изображением).
- Создание Custom Audience (можно ссылаться на существующие аудитории, но нельзя создавать новые отсюда).
- Редактирование уже запущенного креатива на месте (вы создаёте новые креативы через
create_campaign.py; редактирование существующего — это другая структура API).
Если пользователю нужно что-то, что скрипты не покрывают, расширьте навык в записываемой копии и перепакуйте — см. references/campaign-creation.md для шаблона create_campaign.py задаёт для скриптов записи. Не создавайте отдельные разовые скрипты в рабочей директории пользователя; консолидируйте в навык, чтобы следующий запуск получил преимущество.
Справочные файлы
Читайте их по требованию, а не все сразу.
references/setup.md— Разовая настройка: дерево решений Path A vs Path B, как создать приложение, получить токены, найти ID аккаунтов. Читайте это, когда у пользователя нет учётных данных или когдаauth_check.pyне срабатывает.references/insights-fields.md— Глоссарий полей, варианты разбивки, распространённые определения метрик, подводные камни (окна атрибуции, action_attribution, дедупликация). Читайте это при построении пользовательского запроса insights.references/analysis-playbooks.md— Шаблоны для усталости креативов, анализа аудитории, диагностики воронки, реагирования на аномалии. Читайте это, когда пользователь просит анализ, а не просто данные.references/write-actions.md— Обязательно перед любым вызовом записи. Поток подтверждения, пороги безопасности, шаблоны отката — включая раздел создания кампании перед использованиемcreate_campaign.py.references/campaign-creation.md— Формат спецификации, справочник полей, обработка валют, разрешение интересов, файл состояния и детали отката дляcreate_campaign.py. Читайте это, когда пользователь просит запустить кампанию, A/B-тест или новый рекламный флайт с нуля.references/troubleshooting.md— Распространённые режимы отказа (песочница-прокси, IG boost невидим для SU-токенов, отсутствующий модуль requests, проблемы с кодировкой, 37-месячный лимит и т. д.). Читайте это, когда любой скрипт возвращаетok: falseили что-то неожиданное.
Масштабирование за пределы личного использования
Этот навык создан для одного пользователя, одного набора учётных данных, нескольких рекламных аккаунтов. Мультитенантное / клиентско-агентское использование (один оператор управляет десятками клиентских BM) — это другая сборка:
- Хранение учётных данных для каждого клиента (не токены всех в одном .env).
- Каждый клиент выпускает свой собственный System User токен из своего BM.
- Журнал аудита каждого действия записи, кто его инициировал, против какого аккаунта.
Не пытайтесь приспособить личный навык для мультитенантного использования. Скажите пользователю, что это другая сборка.
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: meta-ads](https://darkplay.ru/ai/skills/hoodini-ai-agents-skills-meta-ads)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
Seo Specialistaffaan-m · SEO-специалист: технический аудит, оптимизация страниц, структурированные данные, Core…
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
ruflo-metaharnessruvnet · Интеграция MetaHarness: доступ к score/genome/mint/mcp-scan/threat-model через навыки…
Requirement Parsershanraisshan · Анализирует описания запросов функций и извлекает требования, цели, ограничения и…
datahub-skillsanthropics · Инструментарий разработки и работы с DataHub: планирование коннекторов, ревью PR, поиск…
windsor-aianthropics · Подключение Claude Code к более чем 325 источникам бизнес-данных через Windsor.ai…
seo-technical-optimizationwshobson · Техническая SEO-оптимизация: метатеги, ключевые слова, структура и расширенные сниппеты
adspirer-ads-agentanthropics · Кроссплатформенное управление рекламой в Google Ads, Meta Ads, TikTok Ads и LinkedIn Ads…
Meta Agentic Project Scaffoldgithub · Мета-агент для создания проектов, помогающий пользователям эффективно создавать рабочие…
c-level-agentsalirezarezvani · Плагин управленческой команды: 13 C-suite агентов и 21 слэш-команда.Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton