К основному содержанию
скилл CX Codex

delete-no-email-contacts — скилл для Claude Code

Скилл находит в HubSpot CRM контакты без email, сохраняет аудит и удаляет их через API. Нужен для очистки базы перед работой с контактами.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add TomGranot/hubspot-admin-skills --skill delete-no-email-contacts -a claude-code
Открыть на GitHub

Что делает delete-no-email-contacts

Скилл ищет контакты HubSpot CRM без свойства email через CRM Search API. Перед удалением он считает записи и сохраняет исходное состояние, затем собирает все ID постранично и записывает CSV-аудит в data/audit-logs/deleted-no-email-contacts.csv.

Работа разбита на этапы Plan → Before → Execute → After. Скрипты scripts/before.py, scripts/execute.py и scripts/after.py запускаются через uv run. Удаление выполняется пакетами по 100 записей через Batch Archive API, с подтверждением и защитным порогом 500 контактов.

Нужны Python 3.10+, uv, файл .env с HUBSPOT_ACCESS_TOKEN и права crm.objects.contacts.read и crm.objects.contacts.write. Без токена HubSpot скрипты не запустятся. Удалённые контакты можно восстановить в HubSpot в течение 90 дней.

Какие задачи решает

  • найти контакты HubSpot без email
  • сохранить исходный список перед удалением
  • удалить записи пакетами через API
  • проверить, что такие контакты больше не остались

Примеры запросов агенту

  • Проведи плановую проверку контактов HubSpot без email и покажи результаты перед удалением.
  • Запусти scripts/before.py, затем подготовь аудит и дождись моего подтверждения.
  • Выполни очистку через scripts/execute.py, а после проверь результат с помощью scripts/after.py.

Как установить delete-no-email-contacts

1Через Skills CLI (Vercel)

npx skills add TomGranot/hubspot-admin-skills --skill delete-no-email-contacts -a claude-code

2Вручную: положить файлы

~/.claude/skills/delete-no-email-contacts/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/delete-no-email-contacts/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о delete-no-email-contacts

Как установить delete-no-email-contacts в Claude Code?

Выполните npx skills add TomGranot/hubspot-admin-skills --skill delete-no-email-contacts -a claude-code, затем проверьте файл ~/.claude/skills/delete-no-email-contacts/SKILL.md.

Что делает delete-no-email-contacts?

Скилл находит контакты HubSpot без email, экспортирует CSV-аудит и удаляет записи пакетами через CRM Search и Batch Archive API. После этого он проверяет результат.

Что нужно для работы скилла?

Нужны Python 3.10+, uv, файл .env с HUBSPOT_ACCESS_TOKEN и права crm.objects.contacts.read и crm.objects.contacts.write.

Исходный текст

SKILL.md · MIT
---
name: delete-no-email-contacts
description: "Delete contacts with no email address from a HubSpot CRM instance. These contacts cannot receive any communication and inflate billing. Fully automated via the HubSpot CRM Search and Batch Archive APIs."
license: MIT
metadata:
  author: tomgranot
  version: "1.1"
  category: database-hygiene
---

# Delete Contacts With No Email Address

## Purpose

Contacts without an email address serve no functional purpose in a HubSpot Marketing Hub instance. They cannot receive marketing emails, sales sequences, or transactional messages. They inflate the billed contact count. This skill identifies and deletes them via the API.

## Prerequisites

- A HubSpot service key (`HUBSPOT_ACCESS_TOKEN` in `.env`; an existing legacy private app token also works) with `crm.objects.contacts.read` and `crm.objects.contacts.write` scopes
- Python 3.10+ with `uv` for package management
- A `.env` file containing `HUBSPOT_ACCESS_TOKEN`

## Scripts

Script paths are relative to this skill's directory. Run them from your project directory so `.env`, `data/`, and `reports/` resolve there: prefix each path with wherever this skill is installed (`skills/delete-no-email-contacts/` in a clone of the repo).

| Stage | Script | Run with |
|-------|--------|----------|
| Before | [`scripts/before.py`](./scripts/before.py) | `uv run scripts/before.py` |
| Execute | [`scripts/execute.py`](./scripts/execute.py) | `uv run scripts/execute.py` |
| After | [`scripts/after.py`](./scripts/after.py) | `uv run scripts/after.py` |

`before.py` counts contacts with no email and exports the CSV baseline. `execute.py` collects IDs, exports the audit CSV, and batch-archives (typed confirmation + safety threshold). `after.py` verifies zero remain.

## Execution Pattern

This skill follows a 4-stage execution pattern: **Plan -> Before -> Execute -> After**.

### Stage 1: Plan

Before writing any code, confirm these items with the user:

1. **Root cause**: Ask whether any integrations (CRM sync, form tool, import process) are intentionally creating contacts without email. If so, fix the inflow first.
2. **Threshold**: The default safety abort threshold is 500 contacts. If the user expects more, adjust the threshold in the execute script.
3. **Recovery window**: Confirm the user understands that deleted contacts are recoverable for 90 days via HubSpot Settings > Data Management > Deleted Objects.

### Stage 2: Before

Run a count query to establish the baseline. Save results for comparison.

```python
"""
Before State: Count contacts with no email address.
"""
import os
import json
import requests
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.environ["HUBSPOT_ACCESS_TOKEN"]
BASE = "https://api.hubapi.com"
headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json",
}

search_payload = {
    "filterGroups": [
        {
            "filters": [
                {
                    "propertyName": "email",
                    "operator": "NOT_HAS_PROPERTY",
                }
            ]
        }
    ],
    "properties": ["firstname", "lastname", "createdate", "hs_object_id"],
    "limit": 1,  # Only need the total count
}

url = f"{BASE}/crm/v3/objects/contacts/search"
response = requests.post(url, headers=headers, json=search_payload)
response.raise_for_status()

data = response.json()
total = data.get("total", 0)

print(f"BEFORE STATE: {total} contacts exist with no email address.")

if total > 0 and data.get("results"):
    sample = data["results"][0]
    props = sample.get("properties", {})
    print(f"  Sample: ID {sample['id']}, "
          f"{props.get('firstname', '(empty)')} {props.get('lastname', '(empty)')}, "
          f"created {props.get('createdate', '(unknown)')}")
```

**Expected output**: A count of contacts with no email and a sample record for sanity checking.

**Present findings to the user** before proceeding. Ask for explicit confirmation to continue.

### Stage 3: Execute

Collect all contact IDs via paginated search, export a CSV audit trail, then batch-delete.

```python
"""
Execute: Delete all contacts with no email address.
Steps:
  1. Paginated search to collect all contact IDs
  2. Export CSV audit log before deletion
  3. Batch archive in groups of 100
"""
import os
import csv
import time
import requests
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.environ["HUBSPOT_ACCESS_TOKEN"]
BASE = "https://api.hubapi.com"
headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json",
}

# --- Step 1: Collect all contact IDs ---
all_contacts = []
after = None

search_payload = {
    "filterGroups": [
        {
            "filters": [
                {
                    "propertyName": "email",
                    "operator": "NOT_HAS_PROPERTY",
                }
            ]
        }
    ],
    "properties": ["firstname", "lastname", "createdate", "hs_object_id"],
    "limit": 100,
}

while True:
    payload = search_payload.copy()
    if after:
        payload["after"] = after

    resp = requests.post(
        f"{BASE}/crm/v3/objects/contacts/search",
        headers=headers, json=payload,
    )
    resp.raise_for_status()
    data = resp.json()

    for contact in data.get("results", []):
        props = contact.get("properties", {})
        all_contacts.append({
            "id": contact["id"],
            "firstname": props.get("firstname", ""),
            "lastname": props.get("lastname", ""),
            "createdate": props.get("createdate", ""),
        })

    paging = data.get("paging", {})
    after = paging.get("next", {}).get("after")
    if not after:
        break
    time.sleep(0.2)  # Rate limiting

print(f"Total contacts to delete: {len(all_contacts)}")

# --- Step 2: SAFETY CHECK ---
ABORT_THRESHOLD = 500
if len(all_contacts) > ABORT_THRESHOLD:
    print(f"SAFETY ABORT: Found {len(all_contacts)} contacts, "
          f"exceeds threshold of {ABORT_THRESHOLD}.")
    print("Review the data and adjust the threshold if this is expected.")
    exit(1)

# --- Step 3: Export CSV audit trail ---
os.makedirs("data/audit-logs", exist_ok=True)
csv_path = "data/audit-logs/deleted-no-email-contacts.csv"

with open(csv_path, "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["id", "firstname", "lastname", "createdate"])
    writer.writeheader()
    writer.writerows(all_contacts)

print(f"Audit log saved: {csv_path} ({len(all_contacts)} records)")

# --- Step 4: Batch delete ---
all_ids = [c["id"] for c in all_contacts]
BATCH_SIZE = 100
deleted_count = 0
failed_ids = []

for i in range(0, len(all_ids), BATCH_SIZE):
    batch = all_ids[i : i + BATCH_SIZE]
    delete_payload = {"inputs": [{"id": cid} for cid in batch]}

    resp = requests.post(
        f"{BASE}/crm/v3/objects/contacts/batch/archive",
        headers=headers, json=delete_payload,
    )

    if resp.status_code == 204:
        deleted_count += len(batch)
        print(f"  Batch {i // BATCH_SIZE + 1}: deleted {len(batch)} contacts")
    else:
        failed_ids.extend(batch)
        print(f"  Batch FAILED: {resp.status_code} — {resp.text[:200]}")

    time.sleep(0.5)  # Rate limiting between batches

print(f"\nDeleted: {deleted_count}, Failed: {len(failed_ids)}")
```

**Key API details**:
- `POST /crm/v3/objects/contacts/search` with `NOT_HAS_PROPERTY` filter on `email`
- Paginate with `after` cursor, 100 results per page
- `POST /crm/v3/objects/contacts/batch/archive` accepts up to 100 IDs per call
- Successful archive returns HTTP 204 (no content)

### Stage 4: After

Re-run the before-state query to confirm zero contacts remain.

```python
"""
After State: Verify no contacts with missing email remain.
"""
# (Same search payload as Before State)
response = requests.post(url, headers=headers, json=search_payload)
response.raise_for_status()
total = response.json().get("total", 0)

if total == 0:
    print("SUCCESS: 0 contacts with no email remain.")
else:
    print(f"WARNING: {total} contacts with no email still exist.")
    print("New contacts may have been created since deletion. Investigate.")
```

**Present results to the user.** If new contacts appeared, investigate the source (form submissions, integrations, imports).

## Safety Mechanisms

| Mechanism | Detail |
|-----------|--------|
| **Abort threshold** | Hard-coded at 500 contacts by default. If the search returns more, the script exits without deleting anything. Adjust only with explicit user confirmation. |
| **CSV audit trail** | Every contact ID, name, and create date is exported to CSV before any deletion occurs. |
| **Confirmation prompt** | Always present the Before State count to the user and wait for explicit confirmation before running Execute. |
| **90-day recovery** | Deleted contacts can be restored via HubSpot Settings > Data Management > Deleted Objects for 90 days. |
| **Archived contacts audit** | After deletion, you can retrieve deleted contacts via the standard contacts endpoint with `archived=true` parameter to verify what was removed. |

## Technical Gotchas

1. **`NOT_HAS_PROPERTY` vs `EQ ""`**: Use `NOT_HAS_PROPERTY` operator, not `EQ` with an empty string. HubSpot treats "property not set" differently from "property set to empty string."

2. **Search API pagination limit**: The HubSpot CRM Search API has a hard cap of 10,000 results per query. For this use case (typically a few hundred contacts), this is not an issue. If you encounter it, use segmented queries (e.g., filter by create date ranges).

3. **Rate limiting**: The Search API allows 5 requests per second per token, separate from the general burst limit. The batch archive API is more restrictive. Use `time.sleep(0.5)` between batch archive calls.

4. **Batch archive returns 204**: A successful batch archive returns HTTP 204 with an empty body, not 200. Check for `status_code == 204`.

5. **Contacts may reappear**: If an integration or form is creating contacts without email, new ones will appear after deletion. Always investigate the root cause.

## Rollback

- Deleted contacts are recoverable for 90 days via HubSpot Settings > Data Management > Deleted Objects.
- The execute script's CSV audit trail lists every deleted contact ID for selective restoration.

## Setup

Create a `.env` file in the repo root:

```
HUBSPOT_ACCESS_TOKEN=pat-na1-xxxxxxxx
```

No package install is needed — scripts carry PEP 723 inline metadata and run with [`uv`](https://github.com/astral-sh/uv), which resolves dependencies automatically:

```bash
uv run scripts/before.py
```

© tomgranot · MIT · TomGranot/hubspot-admin-skills

Похожие скиллы

Все скиллы по теме «Данные и базы» →
xlsx официальный anthropics Работает с табличными файлами: создаёт, читает, правит и преобразует книги. Подходит, когда итогом должен стать файл Excel или другой табличный формат. 187 223установок google-agents-cli-observability официальный Google Помогает настроить трассировку и сбор данных о работе ИИ-агентов, включая агентов на ADK. Пригодится, когда нужно разбирать выполнение запросов или наблюдать за агентом после развёртывания. CX Codex +1 511 300установок caveman-evidence-review JuliusBrussee Скилл читает данные Caveman Cloud о расходах LLM, трассах и маршрутизации. Подходит для проверки того, куда уходит бюджет проекта. CX Codex +1 104 500установок migration JuliusBrussee Скилл задаёт правила безопасных миграций схем, данных и API с обязательным откатом. Пригодится при изменениях, где нельзя терять данные или ломать совместимость. CX Codex +1 103 900установок performance-optimization addyosmani Скилл для агентов ИИ-кодинга: сначала замеряет, потом чинит узкое место — от Core Web Vitals до N+1 запросов и индексов в базе. CX Codex +1 65 200установок supabase официальный supabase Скилл помогает настраивать базу данных, аутентификацию и RLS в Supabase без скрытых дыр в безопасности. CX Codex GP ChatGPT 8установок

Из того же набора21

new-contact-hygiene-workflow Создаёт в HubSpot воркфлоу, который при появлении контакта ставит стадию жизненного цикла и подтягивает компанию с отраслью. CX Codex +1 ★ 78звёзд репо lifecycle-progression-workflow Скилл помогает создать в HubSpot четыре workflow для перехода контактов от лида до клиента. Переходы запускаются по событиям в воронке продаж. CX Codex +1 ★ 78звёзд репо enrich-industry Скилл помогает скопировать отрасль из связанной компании в карточки контактов HubSpot. Пригодится для сегментации контактов по отраслям. CX Codex +1 ★ 78звёзд репо enrich-company-name Копирует название компании из связанной записи в пустое поле контакта HubSpot. Пригодится, если сегментация и токены персонализации ломаются из-за пустых значений. CX Codex +1 ★ 78звёзд репо create-segment-lists Собирает в HubSpot библиотеку списков сегментов: клиенты, партнёры, конкуренты, сотрудники, уровни ICP и отрасли. Нужна для таргетинга, подавления рассылок и отчётности. CX Codex +1 ★ 78звёзд репо connect-hubspot-mcp Подключает Claude Code к удалённому MCP-серверу HubSpot для поиска записей, проверки результатов и небольших подтверждённых изменений в CRM. CX Codex +1 ★ 78звёзд репо cleanup-workflows Находит в HubSpot воркфлоу, которые никогда не запускались, отключены больше 90 дней или остались от тестов, и помогает их удалить. CX Codex +1 ★ 78звёзд репо cleanup-lead-owners Убирает из HubSpot уволенных сотрудников и переназначает их контакты, компании и сделки. Нужен, когда человек уходит, а его записи остаются висеть. CX Codex +1 ★ 78звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой