Skip to content
How I use AI

Lead Ads without copy-paste

Two scripts that replace a daily copy-and-paste job: one downloads Meta form leads every morning and files them in folders, the other turns them into an Excel file ready to import into the CRM. They freed up two hours a day for three people.

2 hours a day freed up for 3 people

10 min read · Meta Lead Ads · Excel

01

The problem

At one of the companies I work with, leads come in through Meta Lead Ads forms spread across several ad accounts and dozens of ads. Every morning someone had to open each ad, download the previous day's leads, save them in their campaign's folder and then rebuild the file by hand so the CRM would accept it: columns in a different order, phone numbers without the prefix, provinces spelled properly, every lead assigned to its sales team.

That was two hours a day of manual work split across three people. With the usual copy-and-paste mistakes: a forgotten ad, a shifted column, a phone number the CRM rejects.

We solved it with two Python scripts and a custom app in Meta for Developers. Here's how they're built, with the code adapted so it works for any business. The code and comments are in Spanish, as in the original.

02

How it's put together

There are two separate pieces, on purpose:

  1. The downloader. Runs on its own every morning. Checks which ads had leads the day before, downloads each one's leads and saves one CSV per ad in the folder it belongs to, according to an Excel file of rules.
  2. The processor. Merges a campaign's CSVs, cleans every field, decides which team each lead goes to and produces an Excel file in the exact format the CRM imports.

Keeping them apart has a non-obvious upside. The downloader writes CSVs the same way Meta exports them when you do it by hand from Ads Manager: semicolon-separated, with p: in front of the phone number. So the processor works the same with an automatic file as with one downloaded by hand on a day something breaks.

03

What you'll need

  • Meta for DevelopersTo create the app the script uses to talk to Meta.
  • Graph APIMeta's API. You use it to check which ads had leads and to download them.
  • Meta Lead AdsThe forms. You need access to the ad accounts and to the page that publishes them.
  • PythonBoth scripts. They use requests for the API and openpyxl to read and write Excel.
  • pandasIn the processor, to merge the CSVs and transform the columns.
  • ExcelThe rules file that says where each ad goes, and the final Excel file imported into the CRM.

Plus a computer or server that's on in the morning to launch the downloader. Here it's a Windows machine with a scheduled task.

04

The Meta app

Reading leads through the API takes your own app. Go to developers.facebook.com, create a Business type app and link it to the business portfolio that holds the ad accounts and the page.

The permissions this flow needs:

  • leads_retrieval to download leads.
  • ads_read to query stats and find out which ads had leads.
  • pages_show_list and pages_read_engagement to read the page's forms.

For internal use you don't need to publish the app. In development mode it works with the accounts and pages you manage.

05

The access token

The token is the key the script uses to get into Meta. A regular user token expires, and the day it does the script stops downloading without a word. A system user is the way to go:

  1. In the business portfolio settings, create a system user.
  2. Assign it the ad accounts, the page and the app.
  3. Generate a token for the app with the permissions above.

06

Settings and rules

At the top of the downloader sits the only part anyone edits by hand: the accounts, the rules file and a test mode that does everything except create files.

descargar_leads.py
import os

# Las cuentas publicitarias de las que se descargan leads.
# Los IDs y el token van en variables de entorno, nunca en el código.
CUENTAS = [
    {"nombre": "Cuenta principal", "ad_account_id": os.environ["META_CUENTA_1"]},
    {"nombre": "Cuenta secundaria", "ad_account_id": os.environ["META_CUENTA_2"]},
]
TOKEN = os.environ["META_TOKEN"]

EXCEL_REGLAS = "reglas_formularios_meta.xlsx"
CARPETA_LOGS = "logs"
MODO_PRUEBA = False   # True: hace todo menos crear archivos

API_VERSION = "v22.0"  # usa la versión actual de la Graph API
BASE_URL = f"https://graph.facebook.com/{API_VERSION}"

The rules spreadsheet is what lets the team change the behavior without touching code. Each row says: if the ad name contains these words, save its leads in this folder.

reglas_formularios_meta.xlsx
Hoja «Reglas» de reglas_formularios_meta.xlsx

palabras_clave        carpeta_base                         activa
──────────────────    ─────────────────────────────────    ──────
CURSO, VERANO         D:\Leads\Campaña verano              SI
WEBINAR               D:\Leads\Webinars                    SI
OFERTA, ENERO         D:\Leads\Oferta enero                NO
Reading and applying the rules
import openpyxl

def cargar_reglas(ruta):
    reglas = []
    ws = openpyxl.load_workbook(ruta)["Reglas"]
    for palabras, carpeta, activa in ws.iter_rows(min_row=2, max_col=3, values_only=True):
        if not palabras or not carpeta or str(activa).strip().upper() != "SI":
            continue
        reglas.append({
            "palabras_clave": [p.strip().upper() for p in str(palabras).split(",") if p.strip()],
            "carpeta_base": str(carpeta).strip(),
        })
    return reglas

def buscar_regla(nombre_anuncio, reglas):
    """La regla gana si TODAS sus palabras están en el nombre del anuncio.
    Si encajan varias, gana la que tiene más palabras (la más específica)."""
    nombre = nombre_anuncio.upper()
    mejor, puntos = None, 0
    for r in reglas:
        aciertos = sum(1 for p in r["palabras_clave"] if p in nombre)
        if aciertos == len(r["palabras_clave"]) and aciertos > puntos:
            mejor, puntos = r, aciertos
    return mejor

Two design decisions. A rule only matches if all its words are present, and if several match, the one with the most words wins, since it's the most specific. And ads with no rule are ignored. That way a test campaign or another department's ads don't fill anyone's folders. It's noted in the log in case someone forgot to add a rule.

For the rules to work, ads need consistent names. If each one is named however its creator felt like, no script will fix it.

07

Which ads had leads yesterday

Instead of going through every form, the script first asks each account's stats which ads had leads the day before. It's one call per account and avoids asking hundreds of paused ads for leads.

Ads with leads
import json, requests

def anuncios_con_leads_ayer(ad_account_id, token, fecha):
    dia = fecha.strftime("%Y-%m-%d")
    url = f"{BASE_URL}/{ad_account_id}/insights"
    params = {
        "access_token": token,
        "level": "ad",
        "fields": "ad_id,ad_name,actions",
        "time_range": json.dumps({"since": dia, "until": dia}),
        "filtering": json.dumps([{"field": "action_type", "operator": "IN", "value": ["lead"]}]),
        "limit": 200,
    }
    anuncios = []
    while url:
        r = requests.get(url, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        for item in data.get("data", []):
            leads = sum(int(a.get("value", 0)) for a in item.get("actions", [])
                        if a.get("action_type") == "lead")
            if leads:
                anuncios.append({"ad_id": item["ad_id"], "ad_name": item["ad_name"], "leads": leads})
        url = data.get("paging", {}).get("next")
        params = {}  # la URL de "next" ya lleva los parámetros
    return anuncios

The lead count it returns doubles as a check: the log shows how many it expected and how many it downloaded for each ad. If they don't match, something's up.

08

Downloading each ad's leads

For each ad with a rule, it requests the leads with every useful field: the form, the campaign, the ad set, the platform and the answers.

Leads for one ad
from datetime import datetime

CAMPOS = ("id,created_time,field_data,ad_id,ad_name,adset_id,adset_name,"
          "campaign_id,campaign_name,form_id,is_organic,platform")

def leads_del_anuncio(ad_id, token, fecha):
    inicio = datetime(fecha.year, fecha.month, fecha.day, 0, 0, 0)
    fin = datetime(fecha.year, fecha.month, fecha.day, 23, 59, 59)
    url = f"{BASE_URL}/{ad_id}/leads"
    params = {"access_token": token, "fields": CAMPOS, "limit": 100}
    leads, seguir = [], True

    while url and seguir:
        r = requests.get(url, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        for lead in data.get("data", []):
            creado = datetime.strptime(lead["created_time"][:19], "%Y-%m-%dT%H:%M:%S")
            if creado < inicio:      # vienen del más nuevo al más antiguo:
                seguir = False       # en cuanto aparece uno de antes de ayer, paro
                break
            if creado <= fin:
                leads.append(lead)
        url = data.get("paging", {}).get("next") if seguir else None
        params = {}
    return leads

Meta returns leads newest first. As soon as one from before yesterday shows up, the script stops requesting pages: everything after it is older still. On ads that have run for months, that saves a lot of calls.

09

One CSV per ad

Each ad produces a file in its rule's folder, inside a subfolder per month and another per day. It's the same structure people used by hand, so nobody had to change how they look for files.

Paths and columns
import csv
from pathlib import Path

MESES = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio",
         "agosto", "septiembre", "octubre", "noviembre", "diciembre"]

def ruta_destino(carpeta_base, fecha):
    # D:\Leads\Webinars\10 - Octubre\28 octubre\
    mes = MESES[fecha.month - 1]
    return Path(carpeta_base) / f"{fecha.month} - {mes.capitalize()}" / f"{fecha.day} {mes}"

def nombre_csv(ad_name, fecha):
    return f"{ad_name.replace(' ', '_')[:60]}_{fecha.day:02d}{MESES[fecha.month - 1][:3]}.csv"

def preguntas_del_formulario(form_id, token):
    """Nombre del formulario y sus preguntas, en el orden en que aparecen."""
    r = requests.get(f"{BASE_URL}/{form_id}",
                     params={"access_token": token, "fields": "name,questions"}, timeout=10)
    data = r.json()
    return data.get("name", ""), [q["key"] for q in data.get("questions", []) if q.get("key")]

def fila(lead, form_name):
    f = {k: lead.get(k, "") for k in ("id", "created_time", "ad_id", "ad_name", "adset_id",
                                      "adset_name", "campaign_id", "campaign_name",
                                      "form_id", "is_organic", "platform")}
    f["form_name"] = form_name
    for campo in lead.get("field_data", []):
        valores = campo.get("values", [])
        if "phone" in campo["name"].lower() or "tel" in campo["name"].lower():
            valores = [v if v.startswith("p:") else f"p:{v}" for v in valores]  # como lo exporta Meta
        f[campo["name"]] = ", ".join(valores)
    return f

# Punto y coma y utf-8-sig: así Excel en español lo abre bien con doble clic.
# with open(ruta, "w", newline="", encoding="utf-8-sig") as archivo:
#     w = csv.DictWriter(archivo, fieldnames=columnas, delimiter=";", extrasaction="ignore")

The answer columns come out in the same order as the form's questions. For that, the script asks Meta for the form and its questions. Without that step, the order shifts from day to day depending on which fields each person filled in first.

The file is written with semicolons and utf-8-sig encoding, which is what Excel set up for Spanish needs to open it with a double click without breaking accents or columns.

10

Running every morning

On Windows, a .bat next to the script and a scheduled task that launches it daily. On Linux or Mac, one cron line:

Scheduling it
:: ejecutar.bat, junto al script
@echo off
cd /d "%~dp0"
python descargar_leads.py

:: Crear la tarea en Windows (una vez, desde una consola):
schtasks /create /tn "Descargar leads de Meta" /tr "C:\leads\ejecutar.bat" /sc daily /st 08:00

# En Linux o Mac, lo mismo con cron:
0 8 * * *  cd /ruta/leads && python3 descargar_leads.py

Every run leaves a log with the date in its name: which rules it loaded, which ads it downloaded, which it skipped for having no rule, and the totals. When someone says they're missing leads from an ad, that's the first place to look.

11

The processor: merging the CSVs

The second script is dropped into a campaign's folder and run with a double click. It finds the CSVs starting with a prefix (the campaign name), reads them and merges them into one table.

It reads each file with semicolons first and, if that yields a single column, reads it again with commas. That way it takes both the downloader's CSVs and ones someone exported by hand with different settings.

Then it drops the technical columns the CRM doesn't need (ad set, campaign and form IDs) and keeps what matters.

12

When Meta renames the fields

This was the hardest bug to spot. When a form is edited, Meta can change a field's internal name: “¿cuál_es_tu_provincia?” becomes “province”. On the same day you get leads from the old form and the new one, each with its own column.

If the script only takes the first matching column, half the rows come out with an empty province and nobody notices until a sales rep opens the record. The fix is to merge every variant row by row:

Merging columns
def combinar_columnas(df, candidatos):
    """Junta fila a fila todas las columnas que se llamen como alguno de los
    candidatos. Para cada fila se queda con el primer valor que no esté vacío."""
    cols = {c.lower().strip(): c for c in df.columns}
    encontradas = [cols[c.lower().strip()] for c in candidatos if c.lower().strip() in cols]
    if not encontradas:
        return None
    resultado = df[encontradas[0]].copy()
    for col in encontradas[1:]:
        vacio = resultado.isna() | (resultado.astype(str).str.strip().isin(["", "nan"]))
        resultado = resultado.where(~vacio, df[col])
    return resultado

# El mismo dato, con el nombre que tuvo en cada versión del formulario
provincia = combinar_columnas(df, ["province", "provincia", "¿cuál_es_tu_provincia?"])
telefono  = combinar_columnas(df, ["phone_number", "teléfono", "telefono"])
email     = combinar_columnas(df, ["email", "correo electrónico", "correo_electronico"])

Whenever a new name shows up, it goes on the list of candidates and that's it.

13

Cleaning each field

With the columns found, they need to look the way the CRM wants:

Cleanup
import re
import pandas as pd

def limpiar_telefono(v):
    if pd.isna(v):
        return v
    v = re.sub(r"^p:\+34", "", str(v).strip())   # p:+34600111222 → 600111222
    return re.sub(r"^p:", "", v).strip()

PLATAFORMA = {"fb": "Facebook", "ig": "Instagram"}

# Respuestas de opción múltiple que llegan como código
TIPO_CLIENTE = {"1": "Particular", "2": "Autónomo", "3": "Empresa"}

def corregir_provincia(v):
    """La gente escribe su ciudad, su comunidad o su código postal.
    El CRM solo acepta el nombre de la provincia."""
    if pd.isna(v) or not str(v).strip():
        return ""
    texto = str(v).strip()
    bajo = texto.lower()
    municipios = {"sabadell": "Barcelona", "reus": "Tarragona", "gerona": "Girona",
                  "vizcaya": "Bizkaia", "la coruña": "A Coruña", "orense": "Ourense"}
    if bajo in municipios:
        return municipios[bajo]
    if re.fullmatch(r"\d{5}", texto):                # código postal
        prefijos = {"08": "Barcelona", "28": "Madrid", "30": "Murcia", "46": "Valencia"}
        return prefijos.get(texto[:2], texto)
    if any(c in bajo for c in ("comunidad autónoma", "andalucía", "castilla", "galicia")):
        return ""                                    # una comunidad con varias provincias no vale
    return texto.title() if texto.islower() else texto
  • The phone number loses the p: and the Spanish prefix, because the CRM wants nine digits.
  • The platform goes from fb and ig to Facebook and Instagram, which is how it reads in reports.
  • Multiple-choice answers can arrive as codes. A dictionary translates them.
  • The province is the most work. People type their city, their region, their postcode or the province's old name. A map of common towns, the first two digits of the postcode and a list of regions that can't be reduced to one province cover almost every case.

The town map grows with use. Every time the final file has an odd province, it goes into the dictionary and never happens again.

14

From the form to the CRM format

The CRM imports an Excel file with specific columns in a specific order. The processor builds that table from scratch. Some columns are fixed for the whole campaign and others come from each lead:

CRM template
final = pd.DataFrame(index=range(len(df)))

# Columnas fijas: iguales para todos los leads de esta campaña
final["Fuente de lead"]  = "Facebook Ads"
final["Estado"]          = "Nuevo"
final["UTM Medium"]      = "cpc"

# Columnas que salen del lead
final["UTM Campaign"]    = df["ad_name"].values          # el nombre del anuncio
final["UTM Source"]      = plataforma.values              # Facebook o Instagram
final["Formulario"]      = df["form_name"].values
final["Nombre"]          = nombre.values
final["Apellidos"]       = apellidos.values
final["Móvil"]           = telefono.values
final["Email"]           = email.values
final["Provincia"]       = provincia.values
final["Tipo de cliente"] = tipo.map(lambda x: TIPO_CLIENTE.get(str(x).strip(), x)).values
final["ID de producto"]  = df["form_name"].str.extract(r"(\d{6})$")[0].fillna("").values
final["Equipo asignado"] = ""                             # lo rellenan las reglas

Two tricks that save a lot of work. The ad name is stored as UTM Campaign, so the CRM shows which ad each sale came from. And the product ID goes at the end of the form name (six digits), so the script pulls it out with a regular expression without anyone having to look it up.

Assignment rules

Each lead has to go to a sales team based on its answers. Your business's rules will be different, but the way to write them is the same: from most specific to most general, and anything that doesn't fit stays unassigned to review by hand.

Assignment (example)
ZONA_CENTRO = {"Madrid", "Toledo", "Guadalajara", "Segovia"}

def asignar(fila):
    """Decide a qué equipo del CRM va cada lead. Las reglas son de ejemplo:
    pon aquí las de tu negocio, de la más específica a la más general."""
    if fila["Tipo de cliente"] == "Empresa":
        return "Equipo empresas"
    if fila["Provincia"] in ZONA_CENTRO:
        return "Equipo centro"
    if fila["Provincia"]:
        return "Equipo resto de España"
    return ""   # sin provincia: se revisa a mano

final["Equipo asignado"] = final.apply(asignar, axis=1)

The final Excel file

Export
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill

ruta = f"LEADS_PROCESADOS_{datetime.now():%d%m%Y}.xlsx"
final.to_excel(ruta, index=False)

wb = load_workbook(ruta)
ws = wb.active
for celda in ws[1]:                              # cabecera oscura y en negrita
    celda.font = Font(bold=True, color="FFFFFF")
    celda.fill = PatternFill("solid", fgColor="1F4E79")
ws.freeze_panes = "A2"                           # la cabecera siempre visible
wb.save(ruta)

sin_asignar = (final["Equipo asignado"] == "").sum()
print(f"{len(final)} leads procesados → {ruta}")
if sin_asignar:
    print(f"⚠ {sin_asignar} sin equipo asignado: revísalos a mano")

The file carries the date in its name, a frozen header and a summary at the end. If any leads are left unassigned, it says so: that's the sign a case has come up the rules don't cover.

15

Testing without breaking anything

  • Turn on MODO_PRUEBA in the downloader: it makes every request and logs what it would save and where, but creates no files.
  • Use Meta's Lead Ads Testing Tool to create test leads on a form without running a campaign.
  • Run a CSV downloaded by hand from Meta and one from the downloader through the processor, and check the final Excel file comes out the same.
  • Before the first real import, import a file with two or three leads into the CRM and check the records one by one.

16

What to keep an eye on

  • The token. If someone removes the system user's permissions or changes the app, the downloader stops working. Check the log now and then even when everything seems fine.
  • Skipped ads. A new ad with no rule downloads nothing. The log lists them; check it whenever campaigns launch.
  • Renamed fields. If a column in the final file suddenly comes out empty, Meta has most likely renamed that form field.
  • The API version. Meta retires old Graph API versions from time to time. When it announces yours is expiring, bump it and test.
  • Personal data. The CSV folders hold names, phone numbers and emails. Only people who need access should have it, and delete the files once they're in the CRM.

Want something like this in your business?

Email me and let's talk.

Email me