В этой статье я дал вам один инструмент (отвертку), а в телеграм канале лежит много пользы, инструментов и видео.
Если вы планируете хранить код в Git, обязательно создайте файл .gitignore, чтобы случайно не закоммитить ключи, конфиг и сгенерированные отчеты:
D:\Projects\google_ads_ai\
├── .env
├── .gitignore
├── service-account.json
├── ads_client.py
├── test_connection.py
├── create_test_search.py
├── add_negatives.py
├── export_report.py
└── test_assets.py.env
service-account.json
*.xlsx
*.png
__pycache__/Если вы работаете строго локально на своем ПК без Git, .gitignore не обязателен.
Создайте файл .env в корне рабочей папки (подставьте свои 10-значные ID без дефисов):
GOOGLE_ADS_JSON_KEY_FILE_PATH=service-account.json GOOGLE_ADS_LOGIN_CUSTOMER_ID=1234567890 GOOGLE_ADS_CUSTOMER_ID=0987654321 GOOGLE_ADS_USE_PROTO_PLUS=TrueОткройте терминал в папке D:\Projects\google_ads_ai и установите актуальные версии всех необходимых библиотек:
pip install -U google-ads python-dotenv openpyxl PillowНа момент написания гайда используются google-ads 35.1.0 (API v26), python-dotenv 1.2.4, openpyxl 3.1.5 и Pillow 13.0.0.
Чтобы не дублировать загрузку переменных из .env и разбор ошибок GoogleAdsException в каждом скрипте, вынесем их в общий модуль ads_client.py:
"""Shared Google Ads client initialization and error reporting helpers."""
import os
from dotenv import load_dotenv
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def build_client() -> tuple[GoogleAdsClient, str]:
"""Load credentials from .env and return an initialized GoogleAdsClient and customer_id."""
load_dotenv()
json_key_file_path = os.getenv("GOOGLE_ADS_JSON_KEY_FILE_PATH")
login_customer_id = os.getenv("GOOGLE_ADS_LOGIN_CUSTOMER_ID")
customer_id = os.getenv("GOOGLE_ADS_CUSTOMER_ID")
use_proto_plus = os.getenv("GOOGLE_ADS_USE_PROTO_PLUS", "True").strip().lower() == "true"
if not json_key_file_path or not customer_id:
raise ValueError(
"Missing required environment variables: "
"GOOGLE_ADS_JSON_KEY_FILE_PATH and GOOGLE_ADS_CUSTOMER_ID."
)
config = {
"json_key_file_path": json_key_file_path,
"use_proto_plus": use_proto_plus,
}
if login_customer_id:
config["login_customer_id"] = login_customer_id
client = GoogleAdsClient.load_from_dict(config)
return client, customer_id
def print_google_ads_exception(ex: GoogleAdsException) -> None:
"""Print detailed Google Ads API error information to stdout."""
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
print(f"\t\tError code: {error.error_code}")
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")Создайте test_connection.py с простым GAQL-запросом к ресурсу customer:
import os
from dotenv import load_dotenv
from google.ads.googleads.client import GoogleAdsClient
load_dotenv()
config = {
"json_key_file_path": os.getenv("GOOGLE_ADS_JSON_KEY_FILE_PATH"),
"login_customer_id": os.getenv("GOOGLE_ADS_LOGIN_CUSTOMER_ID"),
"use_proto_plus": True,
}
client = GoogleAdsClient.load_from_dict(config)
ga_service = client.get_service("GoogleAdsService")
customer_id = os.getenv("GOOGLE_ADS_CUSTOMER_ID")
query = """
SELECT
customer.id,
customer.descriptive_name,
customer.currency_code,
customer.status
FROM customer
"""
response = ga_service.search(customer_id=customer_id, query=query)
for row in response:
c = row.customer
print(f"OK! ID: {c.id} | Name: {c.descriptive_name} | Currency: {c.currency_code} | Status: {c.status.name}")python test_connection.pyOK! ID: 0987654321 | Name: Test Sandbox | Currency: USD | Status: CLOSEDЕсли вы видите OK! и ID вашего дочернего аккаунта — авторизация через Service Account работает, можно переходить к автоматизации.
from datetime import datetime
import sys
from google.ads.googleads.errors import GoogleAdsException
from ads_client import build_client, print_google_ads_exception
def create_ad_text_asset(client, text: str):
asset = client.get_type("AdTextAsset")
asset.text = text
return asset
def create_campaign_budget(client, customer_id: str, suffix: str) -> str:
service = client.get_service("CampaignBudgetService")
operation = client.get_type("CampaignBudgetOperation")
budget = operation.create
budget.name = f"Test Search Budget {suffix}"
budget.delivery_method = client.enums.BudgetDeliveryMethodEnum.STANDARD
budget.amount_micros = 10_000_000 # 10 USD/день
budget.explicitly_shared = False
response = service.mutate_campaign_budgets(customer_id=customer_id, operations=[operation])
resource_name = response.results[0].resource_name
print(f"1. Created CampaignBudget: {resource_name}")
return resource_name
def create_search_campaign(client, customer_id: str, budget_rn: str, suffix: str) -> str:
service = client.get_service("CampaignService")
operation = client.get_type("CampaignOperation")
campaign = operation.create
campaign.name = f"Test Search Campaign {suffix}"
campaign.advertising_channel_type = client.enums.AdvertisingChannelTypeEnum.SEARCH
campaign.status = client.enums.CampaignStatusEnum.PAUSED
campaign.contains_eu_political_advertising = (
client.enums.EuPoliticalAdvertisingStatusEnum.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING
)
campaign.manual_cpc.enhanced_cpc_enabled = False
campaign.campaign_budget = budget_rn
campaign.network_settings.target_google_search = True
campaign.network_settings.target_search_network = True
campaign.network_settings.target_content_network = False
campaign.network_settings.target_partner_search_network = False
response = service.mutate_campaigns(customer_id=customer_id, operations=[operation])
resource_name = response.results[0].resource_name
print(f"2. Created Campaign (PAUSED): {resource_name}")
return resource_name
def create_ad_group(client, customer_id: str, campaign_rn: str, suffix: str) -> str:
service = client.get_service("AdGroupService")
operation = client.get_type("AdGroupOperation")
ad_group = operation.create
ad_group.name = f"Test Search AdGroup {suffix}"
ad_group.campaign = campaign_rn
ad_group.status = client.enums.AdGroupStatusEnum.PAUSED
ad_group.type_ = client.enums.AdGroupTypeEnum.SEARCH_STANDARD
ad_group.cpc_bid_micros = 1_000_000
response = service.mutate_ad_groups(customer_id=customer_id, operations=[operation])
resource_name = response.results[0].resource_name
print(f"3. Created AdGroup (PAUSED): {resource_name}")
return resource_name
def create_keywords(client, customer_id: str, ad_group_rn: str) -> None:
service = client.get_service("AdGroupCriterionService")
keywords = [
("test search keyword", client.enums.KeywordMatchTypeEnum.EXACT),
("test marketing service", client.enums.KeywordMatchTypeEnum.PHRASE),
]
operations = []
for text, match_type in keywords:
operation = client.get_type("AdGroupCriterionOperation")
criterion = operation.create
criterion.ad_group = ad_group_rn
criterion.status = client.enums.AdGroupCriterionStatusEnum.ENABLED
criterion.keyword.text = text
criterion.keyword.match_type = match_type
operations.append(operation)
response = service.mutate_ad_group_criteria(customer_id=customer_id, operations=operations)
for result in response.results:
print(f"4. Created Keyword: {result.resource_name}")
def create_responsive_search_ad(client, customer_id: str, ad_group_rn: str) -> None:
service = client.get_service("AdGroupAdService")
operation = client.get_type("AdGroupAdOperation")
ad_group_ad = operation.create
ad_group_ad.ad_group = ad_group_rn
ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED
ad = ad_group_ad.ad
ad.final_urls.append("https://example.com")
headlines = ["Test Product Online", "Quality Service Today", "Order Online Easily"]
descriptions = [
"Discover reliable test solutions with fast delivery and clear pricing.",
"Visit our website to learn more about our test services and offers.",
]
ad.responsive_search_ad.headlines.extend(create_ad_text_asset(client, t) for t in headlines)
ad.responsive_search_ad.descriptions.extend(create_ad_text_asset(client, t) for t in descriptions)
response = service.mutate_ad_group_ads(customer_id=customer_id, operations=[operation])
print(f"5. Created ResponsiveSearchAd: {response.results[0].resource_name}")
def main() -> int:
suffix = datetime.now().strftime("%Y%m%d_%H%M%S")
try:
client, customer_id = build_client()
budget_rn = create_campaign_budget(client, customer_id, suffix)
campaign_rn = create_search_campaign(client, customer_id, budget_rn, suffix)
ad_group_rn = create_ad_group(client, customer_id, campaign_rn, suffix)
create_keywords(client, customer_id, ad_group_rn)
create_responsive_search_ad(client, customer_id, ad_group_rn)
print("SUCCESS: Test Search campaign structure created in PAUSED status.")
return 0
except GoogleAdsException as ex:
print_google_ads_exception(ex)
return 1
if __name__ == "__main__":
sys.exit(main())1. Created CampaignBudget: customers/0987654321/campaignBudgets/10000000001
2. Created Campaign (PAUSED): customers/0987654321/campaigns/11223344556
3. Created AdGroup (PAUSED): customers/0987654321/adGroups/20000000001
4. Created Keyword: customers/0987654321/adGroupCriteria/20000000001~30000000001
4. Created Keyword: customers/0987654321/adGroupCriteria/20000000001~30000000002
5. Created ResponsiveSearchAd: customers/0987654321/adGroupAds/20000000001~40000000001
SUCCESS: Test Search campaign structure created in PAUSED status.Запишите созданный ID кампании из второй строки (в нашем примере — 11223344556): он понадобится для добавления минус-слов, отчета и привязки активов.
Минус-слова уровня кампании добавляются через CampaignCriterionService с обязательным флагом criterion.negative = True:
import sys
from google.ads.googleads.errors import GoogleAdsException
from ads_client import build_client, print_google_ads_exception
CAMPAIGN_ID = "11223344556"
def add_campaign_negatives(campaign_id: str) -> list[str]:
client, customer_id = build_client()
campaign_service = client.get_service("CampaignService")
criterion_service = client.get_service("CampaignCriterionService")
campaign_rn = campaign_service.campaign_path(customer_id, campaign_id)
negatives = [
("бесплатно", client.enums.KeywordMatchTypeEnum.PHRASE),
("скачать", client.enums.KeywordMatchTypeEnum.EXACT),
]
operations = []
for text, match_type in negatives:
operation = client.get_type("CampaignCriterionOperation")
criterion = operation.create
criterion.campaign = campaign_rn
criterion.negative = True
criterion.keyword.text = text
criterion.keyword.match_type = match_type
operations.append(operation)
response = criterion_service.mutate_campaign_criteria(
customer_id=customer_id,
operations=operations,
)
created = []
for (text, match_type), result in zip(negatives, response.results):
print(
f"Added campaign negative keyword: '{text}' [{match_type.name}] -> "
f"{result.resource_name}"
)
created.append(result.resource_name)
return created
if __name__ == "__main__":
try:
add_campaign_negatives(CAMPAIGN_ID)
print("SUCCESS: Campaign negative keywords added.")
except GoogleAdsException as ex:
print_google_ads_exception(ex)
sys.exit(1)Added campaign negative keyword: 'бесплатно' [PHRASE] -> customers/0987654321/campaignCriteria/11223344556~30000000003
Added campaign negative keyword: 'скачать' [EXACT] -> customers/0987654321/campaignCriteria/11223344556~30000000004
SUCCESS: Campaign negative keywords added.import sys
from google.ads.googleads.errors import GoogleAdsException
import openpyxl
from openpyxl.styles import Font
from ads_client import build_client, print_google_ads_exception
TARGET_CAMPAIGN_ID = "11223344556"
REPORT_FILE = "google_ads_report.xlsx"
def fetch_campaigns(ga_service, customer_id: str) -> list[dict]:
base_query = """
SELECT
campaign.id,
campaign.name,
campaign.advertising_channel_type,
campaign.status,
campaign_budget.amount_micros
FROM campaign
ORDER BY campaign.id
"""
metrics_query = """
SELECT
campaign.id,
metrics.clicks,
metrics.impressions,
metrics.cost_micros
FROM campaign
WHERE segments.date DURING LAST_30_DAYS
"""
metrics_by_id = {}
for row in ga_service.search(customer_id=customer_id, query=metrics_query):
metrics_by_id[row.campaign.id] = {
"clicks": row.metrics.clicks,
"impressions": row.metrics.impressions,
"cost_micros": row.metrics.cost_micros,
}
campaigns = []
for row in ga_service.search(customer_id=customer_id, query=base_query):
cid = row.campaign.id
m = metrics_by_id.get(cid, {"clicks": 0, "impressions": 0, "cost_micros": 0})
campaigns.append(
{
"id": cid,
"name": row.campaign.name,
"type": row.campaign.advertising_channel_type.name,
"status": row.campaign.status.name,
"budget_usd": round(row.campaign_budget.amount_micros / 1_000_000, 2)
if row.campaign_budget.amount_micros
else 0.0,
"clicks": m["clicks"],
"impressions": m["impressions"],
"cost_usd": round(m["cost_micros"] / 1_000_000, 2),
}
)
return campaigns
def fetch_keywords_and_negatives(ga_service, customer_id: str, campaign_id: str) -> list[dict]:
rows = []
ad_group_query = f"""
SELECT
campaign.id, ad_group.id, ad_group.name,
ad_group_criterion.criterion_id, ad_group_criterion.keyword.text,
ad_group_criterion.keyword.match_type, ad_group_criterion.negative,
ad_group_criterion.status
FROM ad_group_criterion
WHERE campaign.id = {campaign_id} AND ad_group_criterion.type = 'KEYWORD'
ORDER BY ad_group_criterion.criterion_id
"""
for row in ga_service.search(customer_id=customer_id, query=ad_group_query):
c = row.ad_group_criterion
rows.append(
{
"level": "AD_GROUP",
"campaign_id": row.campaign.id,
"ad_group_id": row.ad_group.id,
"ad_group_name": row.ad_group.name,
"criterion_id": c.criterion_id,
"text": c.keyword.text,
"match_type": c.keyword.match_type.name,
"negative": c.negative,
"status": c.status.name,
}
)
campaign_query = f"""
SELECT
campaign.id, campaign_criterion.criterion_id,
campaign_criterion.keyword.text, campaign_criterion.keyword.match_type,
campaign_criterion.negative, campaign_criterion.status
FROM campaign_criterion
WHERE campaign.id = {campaign_id} AND campaign_criterion.type = 'KEYWORD'
ORDER BY campaign_criterion.criterion_id
"""
for row in ga_service.search(customer_id=customer_id, query=campaign_query):
c = row.campaign_criterion
rows.append(
{
"level": "CAMPAIGN",
"campaign_id": row.campaign.id,
"ad_group_id": "",
"ad_group_name": "",
"criterion_id": c.criterion_id,
"text": c.keyword.text,
"match_type": c.keyword.match_type.name,
"negative": c.negative,
"status": c.status.name,
}
)
return rows
def fetch_rsa_ads(ga_service, customer_id: str) -> list[dict]:
query = """
SELECT
campaign.id, campaign.name, ad_group.id, ad_group.name,
ad_group_ad.ad.id, ad_group_ad.status,
ad_group_ad.ad.responsive_search_ad.headlines,
ad_group_ad.ad.responsive_search_ad.descriptions
FROM ad_group_ad
WHERE ad_group_ad.ad.type = 'RESPONSIVE_SEARCH_AD'
ORDER BY ad_group_ad.ad.id
"""
ads = []
for row in ga_service.search(customer_id=customer_id, query=query):
ad = row.ad_group_ad.ad
rsa = ad.responsive_search_ad
ads.append(
{
"ad_id": ad.id,
"status": row.ad_group_ad.status.name,
"campaign_id": row.campaign.id,
"campaign_name": row.campaign.name,
"ad_group_id": row.ad_group.id,
"ad_group_name": row.ad_group.name,
"headlines": " | ".join(asset.text for asset in rsa.headlines),
"descriptions": " | ".join(asset.text for asset in rsa.descriptions),
}
)
return ads
# Далее в main() вызываются эти три функции, выводится сводка в консоль
# и выполняется сохранение трех листов в REPORT_FILE через openpyxl.Workbook().=== Campaigns (1) ===
- ID: 11223344556 | Test Search Campaign 20261201_164513 | SEARCH | PAUSED | Budget: $10.00 | Clicks(30d): 0 | Impr(30d): 0 | Cost(30d): $0.00
=== Keywords & Negatives for Campaign 11223344556 (4) ===
- [AD_GROUP] POSITIVE | ID: 30000000001 | 'test search keyword' (EXACT) | Status: ENABLED
- [AD_GROUP] POSITIVE | ID: 30000000002 | 'test marketing service' (PHRASE) | Status: ENABLED
- [CAMPAIGN] NEGATIVE | ID: 30000000003 | 'бесплатно' (PHRASE) | Status: ENABLED
- [CAMPAIGN] NEGATIVE | ID: 30000000004 | 'скачать' (EXACT) | Status: ENABLED
=== RSA Ads (1) ===
- Ad ID: 40000000001 | Status: PAUSED | Headlines: Test Product Online | Quality Service Today | Order Online Easily | Descriptions: Discover reliable test solutions with fast delivery and clear pricing. | Visit our website to learn more about our test services and offers.
Saved Excel report to: google_ads_report.xlsxСохранение в google_ads_report.xlsx формирует три листа с жирными заголовками и автоподбором ширины колонок: Campaigns (сводка по всем кампаниям аккаунта), Keywords_and_Negatives (ключевые слова и минус-слова целевой кампании) и RSA_Ads (все адаптивные объявления с заголовками и описаниями).
from datetime import datetime
from pathlib import Path
import sys
from google.ads.googleads.errors import GoogleAdsException
from PIL import Image, ImageDraw
from ads_client import build_client, print_google_ads_exception
CAMPAIGN_ID = "11223344556"
IMAGE_PATH = Path("test_image_1200x628.png")
def generate_test_png(output_path: Path) -> bytes:
image = Image.new("RGB", (1200, 628), color=(30, 90, 160))
draw = ImageDraw.Draw(image)
draw.rectangle([(40, 40), (1160, 588)], outline=(255, 255, 255), width=6)
draw.text((80, 290), "Test Ad Image 1200x628", fill=(255, 255, 255))
image.save(output_path, format="PNG")
data = output_path.read_bytes()
print(f"1a. Generated PNG: {output_path} ({len(data)} bytes, 1200x628)")
return data
def create_image_asset(client, customer_id: str, image_bytes: bytes, suffix: str) -> str | None:
asset_service = client.get_service("AssetService")
operation = client.get_type("AssetOperation")
asset = operation.create
asset.name = f"Test Image Asset {suffix}"
asset.type_ = client.enums.AssetTypeEnum.IMAGE
asset.image_asset.data = image_bytes
try:
response = asset_service.mutate_assets(customer_id=customer_id, operations=[operation])
resource_name = response.results[0].resource_name
print(f"1b. Created ImageAsset: {resource_name}")
return resource_name
except GoogleAdsException as ex:
print("1b. ERROR creating ImageAsset:")
print_google_ads_exception(ex)
return None
def create_lead_form_asset(client, customer_id: str, suffix: str) -> str | None:
asset_service = client.get_service("AssetService")
operation = client.get_type("AssetOperation")
asset = operation.create
asset.name = f"Test Lead Form Asset {suffix}"
lead_form = asset.lead_form_asset
lead_form.business_name = "Test Brand"
lead_form.headline = "Получите консультацию"
lead_form.description = "Оставьте заявку для теста"
lead_form.call_to_action_type = client.enums.LeadFormCallToActionTypeEnum.LEARN_MORE
lead_form.call_to_action_description = "Узнать больше"
lead_form.privacy_policy_url = "https://example.com/privacy"
for input_type in (
client.enums.LeadFormFieldUserInputTypeEnum.FULL_NAME,
client.enums.LeadFormFieldUserInputTypeEnum.PHONE_NUMBER,
client.enums.LeadFormFieldUserInputTypeEnum.EMAIL,
):
field = client.get_type("LeadFormField")
field.input_type = input_type
lead_form.fields.append(field)
try:
response = asset_service.mutate_assets(customer_id=customer_id, operations=[operation])
resource_name = response.results[0].resource_name
print(f"2. Created LeadFormAsset: {resource_name}")
return resource_name
except GoogleAdsException as ex:
print("2. ERROR creating LeadFormAsset:")
print_google_ads_exception(ex)
return None
def link_campaign_asset(client, customer_id: str, campaign_rn: str, asset_rn: str | None, field_type) -> None:
if not asset_rn:
print(f"3. Skipped linking {field_type.name}: asset was not created.")
return
service = client.get_service("CampaignAssetService")
operation = client.get_type("CampaignAssetOperation")
campaign_asset = operation.create
campaign_asset.campaign = campaign_rn
campaign_asset.asset = asset_rn
campaign_asset.field_type = field_type
try:
response = service.mutate_campaign_assets(customer_id=customer_id, operations=[operation])
print(f"3. Linked {field_type.name}: {response.results[0].resource_name}")
except GoogleAdsException as ex:
print(f"3. ERROR linking {field_type.name}:")
print_google_ads_exception(ex)1a. Generated PNG: test_image_1200x628.png (5548 bytes, 1200x628)
1b. Created ImageAsset: customers/0987654321/assets/50000000001
2. ERROR creating LeadFormAsset:
Request with ID "aBcDeFgHiJkLmNoPqRsTuV" failed with status "INVALID_ARGUMENT" and includes the following errors:
Error with message "Lead forms require that the Terms of Service have been agreed to before mutates can be executed.".
Error code: asset_error: LEAD_FORM_MISSING_AGREEMENT
On field: operations
3. Linked AD_IMAGE: customers/0987654321/campaignAssets/11223344556~50000000001~AD_IMAGE
3. Skipped linking LEAD_FORM: asset was not created.При первом запуске python test_assets.py картинка загружается и привязывается без проблем, а на лид-форме API возвращает ожидаемую ошибку LEAD_FORM_MISSING_AGREEMENT.
После принятия условий повторный запуск создания и привязки лид-формы проходит без ошибок:
2. Created LeadFormAsset: customers/0987654321/assets/50000000002
3. Linked LEAD_FORM: customers/0987654321/campaignAssets/11223344556~50000000002~LEAD_FORM| Проблема / Подводный камень | Причина | Решение |
|---|---|---|
| Холд средств при создании обычного аккаунта | Google подтягивает платежный профиль в мастере | Создавайте MCC по ссылке ?sf=mt, а внутри него — дочерний аккаунт, закрывая мастер с картой на ✕ |
| Возврат на список аккаунтов при создании саб-аккаунта | Сработал этап SMS-верификации | После ввода SMS-кода нажмите + → Create new account (Создать новый аккаунт) повторно |
Дочерний аккаунт получил статус CLOSED | Не привязана банковская карта | Для тестов API это не мешает — читайте отчеты и создавайте PAUSED-структуры без ограничений |
Ошибка создания кампании в v26 | Отсутствует декларация политической рекламы ЕС | Обязательно задавайте contains_eu_political_advertising = DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING |
| Пустой список кампаний при GAQL-запросе за 30 дней | Кампании со статусом PAUSED и 0 показов отсекаются фильтром segments.date | Делайте базовый запрос FROM campaign без фильтра по дате и мерджите метрики за LAST_30_DAYS по campaign.id |
asset_error: LEAD_FORM_MISSING_AGREEMENT | Не приняты условия использования лид-форм в кабинете | Внутри дочернего аккаунта откройте Campaigns → Assets → Assets → + → Lead form и нажмите Accept |
| Не видно кампаний и картинок в веб-интерфейсе | Активен фильтр Enabled или вы находитесь на уровне MCC | Включите фильтр All для кампаний и перейдите внутрь дочернего аккаунта для просмотра Assets |