Skip to main content

Command-line interface for Yandex Direct API

Project description

Direct CLI

English | Русский


English

Command-line interface for the Yandex Direct API.

Installation

pip install direct-cli

Configuration

Create a .env file in your working directory:

YANDEX_DIRECT_TOKEN=your_access_token
YANDEX_DIRECT_LOGIN=your_yandex_login

Or pass credentials directly per command:

direct-cli --token YOUR_TOKEN --login YOUR_LOGIN campaigns get

Global Options

Option Description
--token API access token
--login Yandex advertiser login
--sandbox Use sandbox API

Usage

All commands follow the pattern: direct-cli <resource> <action> [options]

Campaigns

# Get campaigns
direct-cli campaigns get
direct-cli campaigns get --status ACTIVE
direct-cli campaigns get --ids 1,2,3 --format table
direct-cli campaigns get --fetch-all --format csv --output campaigns.csv

# Create (use --dry-run to preview the request)
direct-cli campaigns add --name "My Campaign" --start-date 2024-02-01 --type TEXT_CAMPAIGN --budget 1000
direct-cli campaigns add --name "My Campaign" --start-date 2024-02-01 --dry-run

# Update / lifecycle
direct-cli campaigns update --id 12345 --name "New Name"
direct-cli campaigns suspend --id 12345
direct-cli campaigns resume  --id 12345
direct-cli campaigns archive --id 12345
direct-cli campaigns unarchive --id 12345
direct-cli campaigns delete  --id 12345

Ad Groups

direct-cli adgroups get --campaign-ids 1,2,3 --limit 50
direct-cli adgroups add --name "Group 1" --campaign-id 12345 --dry-run
direct-cli adgroups update --id 67890 --name "New Name"
direct-cli adgroups delete --id 67890

Ads

direct-cli ads get --campaign-ids 1,2,3
direct-cli ads get --adgroup-ids 45678 --format table
direct-cli ads add --adgroup-id 12345 --type TEXT_AD --title "Title" --text "Ad text" --href "https://example.com" --dry-run
direct-cli ads update --id 99999 --status PAUSED
direct-cli ads delete --id 99999

Keywords

direct-cli keywords get --campaign-ids 1,2,3
direct-cli keywords add --adgroup-id 12345 --keyword "buy laptop" --bid 10.50 --dry-run
direct-cli keywords update --id 88888 --bid 15.00
direct-cli keywords delete --id 88888

Reports

# Get a report (saved to file)
direct-cli reports get \
  --type CAMPAIGN_PERFORMANCE_REPORT \
  --from 2024-01-01 --to 2024-01-31 \
  --name "January Report" \
  --fields "Date,CampaignId,Clicks,Cost" \
  --format csv --output report.csv

# List available report types
direct-cli reports list-types

Available report types: CAMPAIGN_PERFORMANCE_REPORT, ADGROUP_PERFORMANCE_REPORT, AD_PERFORMANCE_REPORT, CRITERIA_PERFORMANCE_REPORT, CUSTOM_REPORT, REACH_AND_FREQUENCY_CAMPAIGN_REPORT, SEARCH_QUERY_PERFORMANCE_REPORT

Other Resources

# Reference dictionaries
direct-cli dictionaries get --names Currencies,GeoRegions

# Client info
direct-cli clients get --fields ClientId,Login,Currency

# Changes feed
direct-cli changes get --campaign-ids 1,2,3

# Retargeting lists
direct-cli retargeting get --limit 10

# Ad extensions, sitelinks, vCards, images, creatives, feeds, bids, etc.
direct-cli adextensions get
direct-cli sitelinks get --ids 1,2,3
direct-cli bids get --campaign-ids 1,2,3

Output Formats

All get commands support --format:

Format Description
json JSON (default)
table Formatted table
csv CSV
tsv TSV
direct-cli campaigns get --format table
direct-cli campaigns get --format csv --output campaigns.csv

Pagination

direct-cli campaigns get --limit 10        # first 10 results
direct-cli campaigns get --fetch-all       # all pages

⚠️ Destructive Commands

The following commands make irreversible changes — use with caution:

Command Effect
campaigns delete --id Permanently deletes a campaign and all its contents
adgroups delete --id Permanently deletes an ad group
ads delete --id Permanently deletes an ad
keywords delete --id Permanently deletes a keyword
audiencetargets delete --id Permanently deletes an audience target

Commands that affect live ad delivery: suspend, resume, archive, unarchive (available on campaigns, ads, keywords).

Commands that affect bids and spending: bids set, keywordbids set, bidmodifiers set.

Use --dry-run on add / update commands to preview the API request before sending:

direct-cli campaigns add --name "Test" --start-date 2024-01-01 --dry-run

Release Process

Build, validate and upload to PyPI:

pip install -e ".[dev]"
scripts/release_pypi.sh testpypi   # upload to TestPyPI
scripts/release_pypi.sh pypi       # upload to PyPI
scripts/release_pypi.sh all        # both

The script reads credentials from .env:

TWINE_USERNAME=__token__
TEST_PYPI_TOKEN=pypi-...
PYPI_TOKEN=pypi-...

PyPI Token Scoping

PyPI API tokens can be account-wide or project-scoped:

  • Project-scoped tokens only allow uploads to the specific project they were created for. A token scoped to telethon-cli cannot upload direct-cli — you will get 403 Forbidden.
  • Account-wide tokens allow uploads to any project under your account.
  • For the first publication of a new project, you must use an account-wide token (project-scoped tokens cannot be created until the project exists on PyPI).
  • After the first successful upload, create a project-scoped token at https://pypi.org/manage/account/token/ and replace the account-wide token in .env.

Bump version in pyproject.toml before each release — PyPI rejects duplicate versions.

License

MIT


Русский

Интерфейс командной строки для Яндекс.Директ API.

Установка

pip install direct-cli

Настройка

Создайте файл .env в рабочей директории:

YANDEX_DIRECT_TOKEN=ваш_токен
YANDEX_DIRECT_LOGIN=ваш_логин_на_яндексе

Или передавайте credentials напрямую в команду:

direct-cli --token ВАШ_ТОКЕН --login ВАШ_ЛОГИН campaigns get

Глобальные опции

Опция Описание
--token OAuth-токен доступа к API
--login Логин рекламодателя на Яндексе
--sandbox Использовать тестовое API (песочница)

Использование

Все команды следуют шаблону: direct-cli <ресурс> <действие> [опции]

Кампании

# Получить кампании
direct-cli campaigns get
direct-cli campaigns get --status ACTIVE
direct-cli campaigns get --ids 1,2,3 --format table
direct-cli campaigns get --fetch-all --format csv --output campaigns.csv

# Создать (--dry-run покажет запрос без отправки)
direct-cli campaigns add --name "Моя кампания" --start-date 2024-02-01 --type TEXT_CAMPAIGN --budget 1000
direct-cli campaigns add --name "Моя кампания" --start-date 2024-02-01 --dry-run

# Обновление и управление статусом
direct-cli campaigns update   --id 12345 --name "Новое название"
direct-cli campaigns suspend  --id 12345
direct-cli campaigns resume   --id 12345
direct-cli campaigns archive  --id 12345
direct-cli campaigns unarchive --id 12345
direct-cli campaigns delete   --id 12345

Группы объявлений

direct-cli adgroups get --campaign-ids 1,2,3 --limit 50
direct-cli adgroups add --name "Группа 1" --campaign-id 12345 --dry-run
direct-cli adgroups update --id 67890 --name "Новое название"
direct-cli adgroups delete --id 67890

Объявления

direct-cli ads get --campaign-ids 1,2,3
direct-cli ads get --adgroup-ids 45678 --format table
direct-cli ads add --adgroup-id 12345 --type TEXT_AD --title "Заголовок" --text "Текст объявления" --href "https://example.com" --dry-run
direct-cli ads update --id 99999 --status PAUSED
direct-cli ads delete --id 99999

Ключевые слова

direct-cli keywords get --campaign-ids 1,2,3
direct-cli keywords add --adgroup-id 12345 --keyword "купить ноутбук" --bid 10.50 --dry-run
direct-cli keywords update --id 88888 --bid 15.00
direct-cli keywords delete --id 88888

Отчёты

# Сформировать отчёт (сохраняется в файл)
direct-cli reports get \
  --type CAMPAIGN_PERFORMANCE_REPORT \
  --from 2024-01-01 --to 2024-01-31 \
  --name "Отчёт за январь" \
  --fields "Date,CampaignId,Clicks,Cost" \
  --format csv --output report.csv

# Список доступных типов отчётов
direct-cli reports list-types

Доступные типы: CAMPAIGN_PERFORMANCE_REPORT, ADGROUP_PERFORMANCE_REPORT, AD_PERFORMANCE_REPORT, CRITERIA_PERFORMANCE_REPORT, CUSTOM_REPORT, REACH_AND_FREQUENCY_CAMPAIGN_REPORT, SEARCH_QUERY_PERFORMANCE_REPORT

Другие ресурсы

# Справочники
direct-cli dictionaries get --names Currencies,GeoRegions

# Информация о клиенте
direct-cli clients get --fields ClientId,Login,Currency

# Лента изменений
direct-cli changes get --campaign-ids 1,2,3

# Списки ретаргетинга
direct-cli retargeting get --limit 10

# Расширения объявлений, быстрые ссылки, визитки, изображения, ставки и т.д.
direct-cli adextensions get
direct-cli sitelinks get --ids 1,2,3
direct-cli bids get --campaign-ids 1,2,3

Форматы вывода

Все команды get поддерживают --format:

Формат Описание
json JSON (по умолчанию)
table Таблица
csv CSV
tsv TSV
direct-cli campaigns get --format table
direct-cli campaigns get --format csv --output campaigns.csv

Пагинация

direct-cli campaigns get --limit 10    # первые 10 результатов
direct-cli campaigns get --fetch-all   # все страницы

⚠️ Опасные команды

Следующие команды вносят необратимые изменения — используйте осторожно:

Команда Эффект
campaigns delete --id Безвозвратно удаляет кампанию и весь её контент
adgroups delete --id Безвозвратно удаляет группу объявлений
ads delete --id Безвозвратно удаляет объявление
keywords delete --id Безвозвратно удаляет ключевое слово
audiencetargets delete --id Безвозвратно удаляет условие подбора аудитории

Команды, влияющие на показ рекламы: suspend, resume, archive, unarchive (доступны для campaigns, ads, keywords).

Команды, влияющие на ставки и расходы: bids set, keywordbids set, bidmodifiers set.

Используйте --dry-run в командах add / update, чтобы увидеть тело запроса до отправки:

direct-cli campaigns add --name "Тест" --start-date 2024-01-01 --dry-run

Публикация на PyPI

Сборка, проверка и загрузка на PyPI:

pip install -e ".[dev]"
scripts/release_pypi.sh testpypi   # загрузить на TestPyPI
scripts/release_pypi.sh pypi       # загрузить на PyPI
scripts/release_pypi.sh all        # оба

Скрипт читает credentials из .env:

TWINE_USERNAME=__token__
TEST_PYPI_TOKEN=pypi-...
PYPI_TOKEN=pypi-...

Области действия токенов PyPI

API-токены PyPI могут быть account-wide (на весь аккаунт) или project-scoped (на конкретный проект):

  • Project-scoped токены работают только для конкретного проекта. Токен от telethon-cli не может загрузить direct-cli — будет 403 Forbidden.
  • Account-wide токены позволяют загружать в любой проект аккаунта.
  • Для первой публикации нового проекта необходим account-wide токен (project-scoped нельзя создать, пока проект не зарегистрирован на PyPI).
  • После первой успешной загрузки создайте project-scoped токен на https://pypi.org/manage/account/token/ и замените account-wide токен в .env.

Перед каждым релизом обновите version в pyproject.toml — PyPI отклоняет дубли версий.

Лицензия

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

direct_cli-0.1.2.tar.gz (38.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

direct_cli-0.1.2-py3-none-any.whl (43.5 kB view details)

Uploaded Python 3

File details

Details for the file direct_cli-0.1.2.tar.gz.

File metadata

  • Download URL: direct_cli-0.1.2.tar.gz
  • Upload date:
  • Size: 38.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for direct_cli-0.1.2.tar.gz
Algorithm Hash digest
SHA256 3b973fc8c0b4fe60a52761f89ce960cc3cc5ae83bbd8d18c60549d55773e7d3d
MD5 da7266eda8c168f850db434234a7cb81
BLAKE2b-256 66cbdfded14c2ff71d930633b07a12c553f08b81cee8690fcac743a9d071002f

See more details on using hashes here.

File details

Details for the file direct_cli-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: direct_cli-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 43.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for direct_cli-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ea5cebf1485ce307dcf5e6dc53da230284e28ac9a38bce8f47339d6c73d7c275
MD5 1d1649c74e9dc38b5fc15a27f789754b
BLAKE2b-256 460e811567b44c84d1745234702853e5e8f8ea02e30d29b96d90c50d423f236a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page