# `valstorm-plugin-meta` — Meta Ads, Business Suite & Organic Publishing Plugin (`NF-487`) Unified multi-tenant **Meta Ads**, **Meta Business Suite (Assets & Pixels)**, and **Meta Organic Publishing (Facebook Pages & Instagram Reels/Carousels)** plugin for **Open Valstorm**, mounted at `platform.meta` (`VALSTORM_PLUGINS=meta` or `*`). Replaces local configuration files (`meta_ads_config.json`) and standalone scripts (`provision_meta_ads.py`, `provision_us_micro_demo_video_ads.py`) with tenant-isolated encrypted credentials (`platform.credentials.get("meta")`), direct **Valstorm VFS** creative uploads (`platform.files`), $O(1)$ webhook routing, FastAPI routes, and 11 AI Agent tools: - **Meta Ads (`platform.meta.ads`)**: Campaign, AdSet, Ad Creative, and Ad CRUD, SHA-256 normalized Value-Based Custom Audience & Lookalike uploads, VFS image (`/adimages`) & video (`/advideos`) uploads, audience interest sizing, Ad Library competitor search, and daily ROAS/spend insights. - **Meta Business Suite (`platform.meta.business`)**: Discover assigned Ad Accounts (`act_...`), Facebook Pages, Instagram Business Accounts, and Datasets/Pixels. - **Meta Organic Publishing (`platform.meta.publishing`)**: Publish organic Facebook Page feed/photo posts (`fbpo_...`) and Instagram single images, Reels, or Carousels (`ins_...`) directly from Valstorm VFS `file_id`s, and query post engagement metrics. --- ## 🤖 Agent-Assisted Quick Setup (Let the Valstorm Agent Set It Up) Because Meta does not offer a CLI to create a System User token, the fastest way to set up `valstorm-plugin-meta` is to generate one permanent System User token in Meta Business Settings and let your **Valstorm AI Agent** automatically discover your Ad Account ID (`act_...`), Facebook Page ID, Instagram Business Account ID, and Pixel/Dataset ID via the Meta Graph API, encrypt and store the full configuration, register $O(1)$ webhook routing, and run live connection verification. ### 1. Quick Human Prerequisite (2 Minutes in Meta Business Settings) 1. Go to [Meta Business Settings -> System Users](https://business.facebook.com/settings/system-users). 2. Create an **Admin System User** named `valstorm-marketing-agent` and click **Assign Assets** to grant Full Control over your **Ad Account**, **Facebook Page**, **Instagram Account**, and **Dataset/Pixel**. 3. Click **Generate New Token**, select your Meta Developer App, set Token Expiration to **Never**, check `ads_read`, `ads_management`, `read_insights`, `business_management`, `pages_read_engagement`, `pages_manage_ads`, `pages_manage_posts`, and `instagram_content_publish`, and copy the token. ### 2. Copy-Paste Prompt for Your Valstorm Agent Drop this prompt into Valstorm Chat: > *"Set up `valstorm-plugin-meta` using my permanent Meta System User token `` (optional App ID: ``, App Secret: ``). Follow `plugins/valstorm-plugin-meta/README.md` to query the Meta Graph API and auto-discover my Ad Account ID (`act_...`), Facebook Page ID, Instagram Business Account ID, and Pixel ID, save the encrypted credentials via `platform.credentials.save('meta', ...)`, and run `meta_verify_connection`."* ### 3. Agent Execution Runbook (Instructions for the AI Agent) When a user asks you to set up `valstorm-plugin-meta` with a System User token, execute this sequence autonomously: 1. **Save Initial Token & Auto-Discover Assigned Business Assets**: - Temporarily initialize `MetaContext` (or call `await platform.credentials.save("meta", {"access_token": token, ...})`). - Call `await platform.meta.business.get_assigned_assets()` (`meta_list_business_assets`), which queries: - `/me/adaccounts?fields=id,name,account_status,currency` -> selects primary active `act_...` Ad Account ID. - `/me/accounts?fields=id,name,instagram_business_account{id,username}` -> selects primary `page_id` and linked `instagram_account_id`. - `/{ad_account_id}/adspixels?fields=id,name` -> selects primary `pixel_id`. 2. **Persist Complete Encrypted Credential & $O(1)$ Webhook Routing**: - Call `await platform.credentials.save("meta", { "access_token": ..., "ad_account_id": ..., "page_id": ..., "instagram_account_id": ..., "pixel_id": ... })`. - Call `await platform.meta.register_routing()` to register `page_id`, `instagram_account_id`, and `ad_account_id` in `external_account_routing` (`provider="meta"`). 3. **Run Live Verification Smoke Test**: - Call `meta_verify_connection` (or `await platform.meta.verify_connection()`) and report the connected System User, Ad Account status, Page, Instagram handle, and Pixel back to the user. --- ## 🛠️ End-to-End DIY Setup Guide (Manual) ### Step 1: Add the Marketing API to Your Meta Developer App 1. Go to [developers.facebook.com/apps](https://developers.facebook.com/apps). 2. Open your app (or click **Create App -> Other -> Business**). 3. In the App Dashboard sidebar, click **Add Product** and click **Set Up** on **Marketing API** (and **Webhooks** if using Lead Ads / Instagram webhooks). 4. Under **App Settings -> Basic**, copy your **App ID** and **App Secret**. ### Step 2: Create a Permanent Admin System User *Standard Meta user tokens expire after 60 days. A System User token never expires.* 1. Open [business.facebook.com/settings](https://business.facebook.com/settings) -> **Users -> System Users**. 2. Click **Add**: - **System User Name**: `valstorm-marketing-agent` - **System User Role**: **Admin System User** 3. Click **Create System User**. ### Step 3: Assign Assets to the System User 1. Select `valstorm-marketing-agent` and click **Assign Assets**. 2. Grant **Full Control** on: - **Ad Accounts**: Select your target Ad Account -> Toggle ON **Manage Ad Account**. - **Pages**: Select your Facebook Page -> Toggle ON **Full Control**. - **Instagram Accounts**: Select your connected Instagram Business profile -> Toggle ON **Content & Insights**. - **Datasets / Pixels**: Select your tracking Pixel -> Toggle ON **Full Control**. 3. Click **Save Changes**. ### Step 4: Generate the Permanent Access Token 1. Click **Generate New Token** on the System User page. 2. Select your Developer App and set **Token Expiration** to **Never**. 3. Grant the required scopes: - `ads_read`, `ads_management`, `read_insights`, `business_management` - `pages_read_engagement`, `pages_manage_ads`, `pages_manage_posts` - `instagram_basic`, `instagram_content_publish`, `instagram_manage_insights` 4. Copy the generated token string. ### Step 5: Save Encrypted Credentials in Open Valstorm ```python await platform.credentials.save( "meta", { "app_id": "YOUR_META_APP_ID", "app_secret": "YOUR_META_APP_SECRET", "access_token": "YOUR_PERMANENT_SYSTEM_USER_TOKEN", "ad_account_id": "act_1234567890", "page_id": "107438288683733", "instagram_account_id": "17841405620088372", "pixel_id": "1365568045373394", "webhook_verify_token": "your-webhook-verify-token", }, ) ``` --- ## Registered Object Prefixes & Marketplace App Bundle - **Object ID Prefixes (`NF-490`)**: - `ins` -> `instagram_post` - `insw` -> `instagram_webhook` - `fbpo` -> `facebook_post` - **Marketplace App Bundle (`NF-499`)**: - `app_meta_business` (**"Meta Business & Ads"**) --- ## Python Usage Examples (`platform.meta`) ```python # 1. Inspect all assigned Business Suite assets (Ad Accounts, Pages, IG, Pixels) assets = await platform.meta.business.get_assigned_assets() # 2. Upload a Value-Weighted Custom Audience (SHA-256 hashed automatically) + 1% US Lookalike audience = await platform.meta.ads.upload_custom_audience( name="VS - Enterprise Prospects", contacts=[ {"email": "founder@acme.com", "phone": "+15552345678", "first_name": "Alex", "last_name": "Rivera", "state": "CT"} ], create_lookalike_us_1pct=True, ) # 3. Create a PAUSED Meta Ad Campaign & pull insights campaign = await platform.meta.ads.create_campaign( name="[BOFU] US Phone System Conversion Engine", objective="OUTCOME_LEADS", status="PAUSED", daily_budget_cents=4000, ) insights = await platform.meta.ads.get_insights(level="campaign", date_preset="last_30d") # 4. Publish an organic Facebook Page post & Instagram Reel from Valstorm VFS fb_post = await platform.meta.publishing.publish_facebook_post( message="See how Open Valstorm unifies CRM, telephony, and AI in one platform.", link="https://www.valstorm.com", ) ig_reel = await platform.meta.publishing.publish_instagram_media( caption="0.78s mobile load speed vs 26.1s industry bounce wall ⚡", media_type="REELS", video_url="https://cdn.valstorm.com/demos/speed-race.mp4", ) ``` --- ## REST API Endpoints (`/v1/meta/*`) | Method | Endpoint | Description | | :--- | :--- | :--- | | `GET` | `/v1/meta/setup-guide` | Interactive System User & Business Suite setup guide | | `POST` | `/v1/meta/verify` | Verifies System User token, scopes, and Ad Account status | | `GET` | `/v1/meta/business/assets` | Lists assigned Ad Accounts, Pages, Instagram Accounts & Pixels | | `GET` | `/v1/meta/ads/campaigns` | Lists Meta Ad campaigns | | `POST` | `/v1/meta/ads/campaigns` | Creates a Meta Ad campaign (defaults to `PAUSED` safety guardrail) | | `POST` | `/v1/meta/ads/audiences/custom` | Uploads SHA-256 normalized Custom Audience (+ optional 1% Lookalike) | | `GET` | `/v1/meta/ads/insights` | Queries campaign/adset/ad performance insights | | `GET` | `/v1/meta/ads/interests` | Searches Meta ad interest targeting & audience sizes | | `POST` | `/v1/meta/publishing/facebook` | Publishes an organic Facebook Page post & logs `fbpo_` record | | `POST` | `/v1/meta/publishing/instagram` | Publishes an Instagram Image/Reel/Carousel & logs `ins_` record | | `GET/POST` | `/v1/meta/webhooks` | Meta Graph API challenge verification & $O(1)$ LeadGen/IG webhook receiver | --- ## Running Tests ```bash cd apps/open-api .venv/bin/pytest tests/test_plugin_meta.py -v ```