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 --token YOUR_TOKEN --login YOUR_LOGIN campaigns get

Install with pip install direct-cli, then run commands with direct.

Global Options

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

Usage

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

Plugin-compatible aliases are also available for integrations that expect canonical MCP-facing names: dynamictargets, smarttargets, negativekeywords, list, checkcamp, checkdict, and has-volume.

Campaigns

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

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

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

Ad Groups

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

Ads

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

Keywords

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

Reports

# Get a report (saved to file)
direct 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 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 dictionaries get --names Currencies,GeoRegions

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

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

# Retargeting lists
direct retargeting get --limit 10

# Ad extensions, sitelinks, vCards, images, creatives, feeds, bids, etc.
direct adextensions get
direct sitelinks get --ids 1,2,3
direct 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 campaigns get --format table
direct campaigns get --format csv --output campaigns.csv

Pagination

direct campaigns get --limit 10        # first 10 results
direct 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 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 --token ВАШ_ТОКЕН --login ВАШ_ЛОГИН campaigns get

Установка остаётся через pip install direct-cli, а запуск команд теперь идет через direct.

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

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

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

Для интеграций доступны и alias-имена, совместимые с MCP-контрактом: dynamictargets, smarttargets, negativekeywords, list, checkcamp, checkdict, has-volume.

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

Кампании

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

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

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

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

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

Объявления

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

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

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

Отчёты

# Сформировать отчёт (сохраняется в файл)
direct 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 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 dictionaries get --names Currencies,GeoRegions

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

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

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

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

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

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

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

Пагинация

direct campaigns get --limit 10    # первые 10 результатов
direct 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 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.2.1.tar.gz (37.2 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.2.1-py3-none-any.whl (46.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: direct_cli-0.2.1.tar.gz
  • Upload date:
  • Size: 37.2 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.2.1.tar.gz
Algorithm Hash digest
SHA256 99afdb6e99574b069d2d48bb1168b09a546f04b17b5477017bc87c1b9e1a2de8
MD5 d97a823233255364c37a98cebdcdc83e
BLAKE2b-256 fdd44c785551f3553e8d7340b1373196703a1847e9f699a0c757248052e77814

See more details on using hashes here.

File details

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

File metadata

  • Download URL: direct_cli-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 46.6 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.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f94bfc405b34679bc4fc764c06a6c4dc95fe9665ec31c8dd500fbcf21dc280ad
MD5 c7e058f5abb87ba90aeb39acbda71a63
BLAKE2b-256 424e563ceece763cd031c1ac539318d1e577edaa83929b454f1c484d76eb78ae

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