### Install amocrm_api with CLI support Source: https://context7.com/krukov/amocrm_api/llms.txt Install the amocrm_api library including command-line interface tools for model generation. Set necessary environment variables for authentication. ```bash # Установка с поддержкой CLI pip install amocrm_api[cli] # Установка переменных окружения export AMOCRM_CLIENT_ID=443850d2-f019-4671-aced-ef3c42991c37 export AMOCRM_SECRET=your_client_secret export AMOCRM_SUBDOMAIN=mycompany export AMOCRM_REDIRECT_URL=https://myapp.ru/oauth export AMOCRM_CODE=def50200... # опционально, если токены уже сохранены ``` -------------------------------- ### Example AmoCRM Model Definition Source: https://context7.com/krukov/amocrm_api/llms.txt Illustrates how to define custom models for amoCRM entities like Lead and Contact, inheriting from base classes and specifying custom fields. ```python class Lead(BaseLead): utm_source = custom_field.UrlCustomField("UTM метка") deal_type = custom_field.SelectCustomField("Тип сделки") ... class Contact(BaseContact): phone = custom_field.ContactPhoneField("Телефон") ... ``` -------------------------------- ### Manage Leads with AmoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt Learn how to retrieve, create, and update leads using the Lead model. You can get leads by name or ID, create new ones, and modify their status and tags. ```python from amocrm.v2 import Lead, Pipeline # Получить сделку lead = Lead.objects.get(query="Крупный клиент 2024") print(lead.name) # Крупный клиент 2024 print(lead.price) # 150000 print(lead.status) # print(lead.pipeline) # # Получить сделку по ID lead = Lead.objects.get(object_id=55555) # Создать новую сделку new_lead = Lead(name="Новая сделка", price=50000) new_lead.save() # Изменить статус по имени lead.status = "принимают решение" lead.save() # Изменить статус через объект Status from amocrm.v2.entity.pipeline import Status status = Status.get_for(lead.pipeline).get(query="переговоры") lead.status = status lead.save() # Добавить тег к сделке lead.tags.append("vip") lead.save() # Перебрать все сделки for lead in Lead.objects.all(): print(lead.name, lead.price, lead.status) ``` -------------------------------- ### Lead Management Source: https://context7.com/krukov/amocrm_api/llms.txt Manage leads, including retrieval, creation, and updates. You can get leads by name or ID, create new ones, and modify their status, price, and other attributes. ```APIDOC ## Lead Management ### Description Manage leads, including retrieval, creation, and updates. You can get leads by name or ID, create new ones, and modify their status, price, and other attributes. ### Methods - **Get Lead by Name** Retrieve a lead using its name. ```python lead = Lead.objects.get(query="Крупный клиент 2024") ``` - **Get Lead by ID** Retrieve a lead using its unique ID. ```python lead = Lead.objects.get(object_id=55555) ``` - **Create Lead** Create a new lead with specified name and price. ```python new_lead = Lead(name="Новая сделка", price=50000) new_lead.save() ``` - **Update Lead Status** Update the status of a lead by providing the status name or a `Status` object. ```python # By status name lead.status = "принимают решение" lead.save() # By Status object from amocrm.v2.entity.pipeline import Status status = Status.get_for(lead.pipeline).get(query="переговоры") lead.status = status lead.save() ``` - **Add Tag to Lead** Append a tag to a lead. ```python lead.tags.append("vip") lead.save() ``` - **Iterate All Leads** Loop through all available leads. ```python for lead in Lead.objects.all(): print(lead.name, lead.price, lead.status) ``` ### Fields - `name` (string) - `price` (number) - `status` (Status object or string) - `pipeline` (Pipeline object) - `responsible_user` (User object) - `closed_at` (datetime) - `tags` (list of strings) - `notes` (list of Note objects) - `tasks` (list of Task objects) - `contacts` (list of Contact objects) - `loss_reason_id` (integer) ``` -------------------------------- ### Initialize OAuth Authorization with Token Managers Source: https://context7.com/krukov/amocrm_api/llms.txt Configure the global token manager with integration parameters and choose a storage backend (memory, file, or Redis). The `init` method is used for the initial authorization code exchange. ```python from amocrm.v2 import tokens import redis # --- Вариант 1: хранение в файлах (по умолчанию) --- tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", # поддомен вашего аккаунта amoCRM redirect_url="https://myapp.ru/oauth", storage=tokens.FileTokensStorage(directory_path="/var/tokens/"), ) # Первичная инициализация: получить code из OAuth-редиректа и передать сюда tokens.default_token_manager.init( code="def50200e9a4fe5a...очень_длинный_код...", skip_error=True, # не бросать исключение если код уже использован ) # --- Вариант 2: хранение в памяти (данные теряются при перезапуске) --- tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", redirect_url="https://myapp.ru/oauth", storage=tokens.MemoryTokensStorage(), ) # --- Вариант 3: хранение в Redis (для многоэкземплярных приложений) --- redis_client = redis.Redis(host="localhost", port=6379, db=0) tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", redirect_url="https://myapp.ru/oauth", storage=tokens.RedisTokensStorage(client=redis_client, ttl=86400), ) tokens.default_token_manager.init(code="...", skip_error=True) ``` -------------------------------- ### Retrieve and Use User Information Source: https://context7.com/krukov/amocrm_api/llms.txt Fetch user details like name, email, and admin status using the User model. Users cannot be created via API, only read. ```python from amocrm.v2.entity.user import User # Получить всех пользователей for user in User.objects.all(): print(user.id, user.name, user.email, user.is_admin) # Найти пользователя по email manager = User.objects.get(query="manager@company.ru") print(manager.name) # Иван Менеджеров print(manager.is_admin) # False print(manager.is_active) # True # Назначить ответственного при создании сделки from amocrm.v2 import Lead lead = Lead(name="Новая сделка") lead.responsible_user = manager lead.save() ``` -------------------------------- ### Generate Model File with pyamogen Source: https://context7.com/krukov/amocrm_api/llms.txt Use the pyamogen CLI tool to generate Python model files for amoCRM entities. This tool helps in creating model definitions based on amoCRM's custom fields. ```bash pyamogen > models.py ``` -------------------------------- ### Manage Companies with Company.objects Source: https://context7.com/krukov/amocrm_api/llms.txt Utilize the `Company.objects` manager to find, create, and update company records. Companies can be directly linked to contacts, and associated leads and contacts can be iterated. ```python from amocrm.v2 import Contact, Company # Найти компанию company = Company.objects.get(query="Газпром") print(company.name) # Газпром print(company.id) # 67890 # Создать компанию и сразу привязать к контакту contact = Contact.objects.get(object_id=12345) contact.company = Company(name="Новая компания ООО") # создаст компанию и прилинкует contact.save() print(contact.company.id) # ID созданной компании # Перебрать всех сотрудников компании for c in company.contacts: print(c.name) # Перебрать все сделки компании for lead in company.leads: print(lead.name, lead.price) # Обновить название company.name = "Обновлённое ООО" company.save() ``` -------------------------------- ### pyamogen CLI - Auto-generating Python Models Source: https://context7.com/krukov/amocrm_api/llms.txt The `pyamogen` command-line utility automatically generates Python classes for your custom fields, simplifying integration with the amoCRM API. ```APIDOC ## Генератор моделей (CLI) ### `pyamogen` — автогенерация Python-классов с кастомными полями Утилита командной строки `pyamogen` подключается к amoCRM-аккаунту и генерирует готовый файл `models.py` с маппингом всех кастомных полей. Требует установки `pip install amocrm_api[cli]`. ### Installation ```bash # Установка с поддержкой CLI pip install amocrm_api[cli] ``` ### Environment Variables Setup ```bash # Установка переменных окружения export AMOCRM_CLIENT_ID=443850d2-f019-4671-aced-ef3c42991c37 export AMOCRM_SECRET=your_client_secret export AMOCRM_SUBDOMAIN=mycompany export AMOCRM_REDIRECT_URL=https://myapp.ru/oauth export AMOCRM_CODE=def50200... # опционально, если токены уже сохранены ``` ### Generate Models ```bash pyamogen --output models.py ``` ``` -------------------------------- ### tokens.default_token_manager - Initialization and Token Management Source: https://context7.com/krukov/amocrm_api/llms.txt Initializes the global token manager for OAuth authorization with amoCRM. Supports different token storage mechanisms (memory, file, Redis) and handles token refresh automatically. ```APIDOC ## tokens.default_token_manager ### Description Initializes the global token manager for OAuth authorization with amoCRM. Supports different token storage mechanisms (memory, file, Redis) and handles token refresh automatically. ### Method `tokens.default_token_manager(...)` ### Parameters - **client_id** (string) - Required - Your amoCRM client ID. - **client_secret** (string) - Required - Your amoCRM client secret. - **subdomain** (string) - Required - Your amoCRM account subdomain. - **redirect_url** (string) - Required - The redirect URL configured in amoCRM. - **storage** (object) - Optional - Token storage instance (e.g., `MemoryTokensStorage`, `FileTokensStorage`, `RedisTokensStorage`). Defaults to `FileTokensStorage`. ### Initialization `tokens.default_token_manager.init(code: str, skip_error: bool = False)` Initializes the token manager with an authorization `code` obtained from the OAuth redirect. `skip_error` prevents exceptions if the code has already been used. ### Request Example (File Storage) ```python from amocrm.v2 import tokens tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", redirect_url="https://myapp.ru/oauth", storage=tokens.FileTokensStorage(directory_path="/var/tokens/"), ) tokens.default_token_manager.init(code="def50200e9a4fe5a...", skip_error=True) ``` ### Request Example (Memory Storage) ```python from amocrm.v2 import tokens tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", redirect_url="https://myapp.ru/oauth", storage=tokens.MemoryTokensStorage(), ) ``` ### Request Example (Redis Storage) ```python import redis from amocrm.v2 import tokens redis_client = redis.Redis(host="localhost", port=6379, db=0) tokens.default_token_manager( client_id="443850d2-f019-4671-aced-ef3c42991c37", client_secret="your_client_secret", subdomain="mycompany", redirect_url="https://myapp.ru/oauth", storage=tokens.RedisTokensStorage(client=redis_client, ttl=86400), ) tokens.default_token_manager.init(code="...", skip_error=True) ``` ``` -------------------------------- ### Define and Use Custom Fields for Leads and Contacts Source: https://context7.com/krukov/amocrm_api/llms.txt Extend Lead and Contact models with custom fields using provided types like TextCustomField, SelectCustomField, etc. Read and write custom field values directly as object attributes. ```python from amocrm.v2 import Lead as _Lead, Contact as _Contact from amocrm.v2.entity import custom_field from datetime import datetime # --- Расширение модели Lead кастомными полями --- class Lead(_Lead): utm_source = custom_field.UrlCustomField("UTM метка") deal_type = custom_field.SelectCustomField("Тип сделки") amount = custom_field.NumericCustomField("Сумма контракта") is_repeat = custom_field.CheckboxCustomField("Повторная сделка") deadline = custom_field.DateCustomField("Дедлайн") # Чтение кастомных полей lead = Lead.objects.get(object_id=55555) print(lead.utm_source) # "https://example.com?utm_source=google" print(lead.amount) # 250000.0 print(lead.is_repeat) # True print(lead.deadline) # date(2024, 12, 31) print(lead.deal_type) # SelectValue(id=1, value='Новый') # Запись кастомных полей lead.utm_source = "https://example.com?utm=yandex" lead.amount = 300000 lead.is_repeat = True lead.deadline = datetime(2024, 12, 31) lead.deal_type = "Повторный" # поиск по имени варианта lead.save() # --- Кастомные поля контакта (телефон и email) --- class Contact(_Contact): phone = custom_field.ContactPhoneField("Телефон", enum_code="WORK") mobile = custom_field.ContactPhoneField("Телефон", enum_code="MOB") email = custom_field.ContactEmailField("Email", enum_code="WORK") contact = Contact.objects.get(object_id=12345) print(contact.phone) # "+79001234567" print(contact.email) # "ivan@example.com" contact.phone = "+79009876543" contact.email = "new@example.com" contact.save() ``` -------------------------------- ### Manage Pipelines and Statuses with AmoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt This section explains how to retrieve, update, and manage sales pipelines and their statuses. You can fetch all pipelines, update their names, and find specific statuses within a pipeline. ```python from amocrm.v2 import Pipeline from amocrm.v2.entity.pipeline import Status # Получить все воронки pipelines = list(Pipeline.objects.all()) for p in pipelines: print(p.id, p.name, p.is_main) # Получить первую воронку pipeline = pipelines[0] # Обновить название воронки pipeline.name = "Основная воронка 2024" pipeline.save() # Получить все статусы воронки for status in pipeline.statuses: print(status.id, status.name, status.color) # Найти статус по имени status = Status.get_for(pipeline).get(query="переговоры") print(status.id, status.name) # Найти статус по конкретной воронке через её ID status = Status.get_for(pipeline.id).get(query="принимают решение") ``` -------------------------------- ### Manage Contacts with Contact.objects Source: https://context7.com/krukov/amocrm_api/llms.txt Interact with contacts using the `Contact.objects` manager for retrieval, creation, and updates. Associated objects like companies and leads can be accessed and modified. ```python from amocrm.v2 import Contact, Company # Получить контакт по поисковому запросу contact = Contact.objects.get(query="Иван Петров") print(contact.id) # 12345 print(contact.first_name) # Иван print(contact.last_name) # Петров print(contact.created_at) # datetime(2024, 3, 15, 10, 30, 0) # Получить контакт по ID contact = Contact.objects.get(object_id=12345) # Перебрать все контакты for contact in Contact.objects.all(): print(contact.name, contact.id) # Создать новый контакт new_contact = Contact( first_name="Мария", last_name="Иванова", name="Мария Иванова", ) new_contact.save() # выполняет POST /api/v4/contacts print(new_contact.id) # ID присвоен после сохранения # Обновить существующий контакт contact.last_name = "Сидорова" contact.save() # выполняет PATCH /api/v4/contacts/{id} # Привязать компанию к контакту company = Company.objects.get(query="ООО Рога и Копыта") contact.company = company contact.save() # Получить связанные сделки контакта for lead in contact.leads: print(lead.name, lead.price) ``` -------------------------------- ### Add Notes to Entities with AmoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt Learn to add various types of notes (text, calls, etc.) to contacts, companies, or leads. Notes are managed through the `notes` field of the respective entity. ```python from amocrm.v2 import Contact, Lead # Добавить текстовое примечание к контакту contact = Contact.objects.get(object_id=12345) contact.notes.objects.create( text="Клиент заинтересован в расширенном тарифе" ) # Добавить примечание к сделке lead = Lead.objects.get(object_id=55555) lead.notes.objects.create( text="Договор подписан, ожидаем оплату" ) # Перебрать все примечания for note in contact.notes.objects.all(): print(note.note_type, note.created_at) if note.note_type == "common": print("Текст:", note.text) ``` -------------------------------- ### Company - Managing Companies Source: https://context7.com/krukov/amocrm_api/llms.txt Provides methods for retrieving, creating, and updating companies in amoCRM. Companies can be associated with contacts, leads, and other entities. ```APIDOC ## Company ### Description Manages companies in amoCRM. Supports retrieval by query, iteration through all companies, creation, and updating. Companies can be linked to contacts, leads, and other entities. ### Methods - `Company.objects.get(query: str)`: Retrieves a company by a search query. - `Company.objects.all()`: Returns an iterable of all companies. - `Company.objects.filter(...)`: (Implied) Filters companies based on criteria. - `Company(name: str, ...)`: Constructor for creating a new company instance. - `company_instance.save()`: Creates a new company (if not saved) or updates an existing one. - `company_instance.create()`: (Implied) Method for creating a company. - `company_instance.update()`: (Implied) Method for updating a company. ### Fields - `id` (int): Unique identifier for the company. - `name` (str): Name of the company. - `responsible_user` (object): The user responsible for the company. - `created_at` (datetime): Timestamp when the company was created. - `updated_at` (datetime): Timestamp when the company was last updated. - `leads` (list of Lead objects): Associated leads. - `customers` (list of Customer objects): Associated customers. - `contacts` (list of Contact objects): Associated contacts. - `tags` (list of Tag objects): Associated tags. - `notes` (list of Note objects): Associated notes. - `tasks` (list of Task objects): Associated tasks. ### Request Example (Get Company) ```python from amocrm.v2 import Company company = Company.objects.get(query="Газпром") print(company.name) print(company.id) ``` ### Request Example (Create Company and Link to Contact) ```python from amocrm.v2 import Contact, Company contact = Contact.objects.get(object_id=12345) contact.company = Company(name="Новая компания ООО") # Creates company and links it contact.save() print(contact.company.id) ``` ### Request Example (Update Company Name) ```python from amocrm.v2 import Company company = Company.objects.get(object_id=67890) company.name = "Обновлённое ООО" company.save() # PATCH /api/v4/companies/{id} ``` ``` -------------------------------- ### Manage Tasks with AmoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt This section covers task management, including retrieving tasks associated with contacts, creating new tasks, and marking them as completed. Ensure you have the necessary task type IDs and entity information. ```python from amocrm.v2 import Contact from amocrm.v2.entity.task import Task from datetime import datetime, timedelta # Получить задачи контакта contact = Contact.objects.get(object_id=12345) for task in contact.tasks: print(task.text, task.is_completed, task.complete_till) # Создать задачу и прикрепить к контакту new_task = Task( text="Позвонить клиенту для уточнения деталей", task_type_id=1, complete_till=datetime.now() + timedelta(days=2), ) contact.tasks.add(new_task) # автоматически сохраняет с entity_id и entity_type # Прямое создание через менеджер task = Task.objects.create( text="Отправить КП", task_type_id=1, entity_id=12345, entity_type="contacts", complete_till=datetime(2024, 12, 31, 18, 0, 0), ) # Отметить задачу выполненной task.is_completed = True task.result = "КП отправлено по email" task.save() ``` -------------------------------- ### Register Calls with amoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt Use the Call class to log inbound and outbound calls. Specify direction, source, duration, status, and optionally link to recordings or assign to a user. ```python from datetime import timedelta from amocrm.v2 import Call, CallDirection, CallStatus from amocrm.v2.entity.user import User # Зарегистрировать исходящий звонок call_result = Call().create( direction=CallDirection.OUTBOUNT, phone="+79001234567", source="Менеджер Сидоров", duration=timedelta(minutes=5, seconds=30), status=CallStatus.SUCCESS, result="Договорились о встрече", link="https://pbx.example.com/recordings/12345.mp3", ) print(call_result) # {'id': ..., 'phone': '+79001234567', ...} # Зарегистрировать входящий звонок с привязкой к менеджеру manager = User.objects.get(query="manager@company.ru") Call().create( direction=CallDirection.INBOUND, phone="+74951234567", source="Офисная АТС", duration=120, # секунды, можно передавать int status=CallStatus.CALL_LATER, created_by=manager, # объект User или int (ID) uniq="unique-call-id-abc", ) # Доступные статусы: # CallStatus.LEAVE_MESSAGE = 1 — оставил сообщение # CallStatus.CALL_LATER = 2 — перезвонить позже # CallStatus.OUT_OFF = 3 — нет на месте # CallStatus.SUCCESS = 4 — разговор состоялся # CallStatus.WRONG_NUMBER = 5 — неверный номер # CallStatus.UNAVAILABLE = 6 — не дозвонился # CallStatus.BUSY = 7 — номер занят ``` -------------------------------- ### Pipeline and Status Management Source: https://context7.com/krukov/amocrm_api/llms.txt Manage sales pipelines and their associated statuses. You can retrieve pipelines and statuses, update pipeline details, and find specific statuses within a pipeline. ```APIDOC ## Pipeline and Status Management ### Description Manage sales pipelines and their associated statuses. You can retrieve pipelines and statuses, update pipeline details, and find specific statuses within a pipeline. ### Methods - **Get All Pipelines** Retrieve a list of all available sales pipelines. ```python pipelines = list(Pipeline.objects.all()) for p in pipelines: print(p.id, p.name, p.is_main) ``` - **Update Pipeline Name** Modify the name of an existing pipeline. ```python pipeline = pipelines[0] # Assuming pipelines is already fetched pipeline.name = "Основная воронка 2024" pipeline.save() ``` - **Get All Statuses for a Pipeline** Retrieve all statuses belonging to a specific pipeline. ```python pipeline = pipelines[0] # Assuming pipelines is already fetched for status in pipeline.statuses: print(status.id, status.name, status.color) ``` - **Find Status by Name within a Pipeline** Search for a status by its name within a given pipeline. ```python # Using Status object associated with a pipeline status = Status.get_for(pipeline).get(query="переговоры") print(status.id, status.name) # Using pipeline ID status = Status.get_for(pipeline.id).get(query="принимают решение") ``` ### Fields **Pipeline Fields:** - `name` (string) - `sort` (integer) - `is_main` (boolean) - `is_archive` (boolean) - `statuses` (list of Status objects) **Status Fields:** - `name` (string) - `sort` (integer) - `color` (string) - `type` (string) ``` -------------------------------- ### Note Management Source: https://context7.com/krukov/amocrm_api/llms.txt Add and manage notes for entities like contacts, companies, and leads. Notes can be of various types, including text, calls, and geolocation. ```APIDOC ## Note Management ### Description Add and manage notes for entities like contacts, companies, and leads. Notes can be of various types, including text, calls, and geolocation. ### Methods - **Add Text Note to Entity** Create a new text note and associate it with an entity. ```python # For a contact contact = Contact.objects.get(object_id=12345) contact.notes.objects.create( text="Клиент заинтересован в расширенном тарифе" ) # For a lead lead = Lead.objects.get(object_id=55555) lead.notes.objects.create( text="Договор подписан, ожидаем оплату" ) ``` - **Iterate Notes for an Entity** Loop through all notes associated with an entity. ```python for note in contact.notes.objects.all(): print(note.note_type, note.created_at) if note.note_type == "common": print("Текст:", note.text) ``` ### Fields - `note_type` (string) - `created_at` (datetime) - `text` (string, for 'common' note type) ``` -------------------------------- ### Contact - Managing Contacts Source: https://context7.com/krukov/amocrm_api/llms.txt Provides methods for retrieving, creating, and updating contacts in amoCRM. Contacts can be associated with companies, leads, tags, notes, and tasks. ```APIDOC ## Contact ### Description Manages contacts in amoCRM. Supports retrieval by query or ID, iteration through all contacts, creation of new contacts, and updating existing ones. Contacts can be linked to companies and other entities. ### Methods - `Contact.objects.get(query: str)`: Retrieves a contact by a search query. - `Contact.objects.get(object_id: int)`: Retrieves a contact by its unique ID. - `Contact.objects.all()`: Returns an iterable of all contacts. - `Contact.objects.filter(...)`: (Implied) Filters contacts based on criteria. - `Contact(field1=value1, ...)`: Constructor for creating a new contact instance. - `contact_instance.save()`: Creates a new contact (if not saved) or updates an existing one. - `contact_instance.create()`: (Implied) Method for creating a contact. - `contact_instance.update()`: (Implied) Method for updating a contact. ### Fields - `id` (int): Unique identifier for the contact. - `name` (str): Full name of the contact. - `first_name` (str): First name of the contact. - `last_name` (str): Last name of the contact. - `responsible_user` (object): The user responsible for the contact. - `created_at` (datetime): Timestamp when the contact was created. - `updated_at` (datetime): Timestamp when the contact was last updated. - `company` (Company object): Associated company. - `leads` (list of Lead objects): Associated leads. - `tags` (list of Tag objects): Associated tags. - `notes` (list of Note objects): Associated notes. - `tasks` (list of Task objects): Associated tasks. ### Request Example (Get Contact) ```python from amocrm.v2 import Contact contact = Contact.objects.get(query="Иван Петров") print(contact.id) print(contact.first_name) ``` ### Request Example (Create Contact) ```python from amocrm.v2 import Contact new_contact = Contact( first_name="Мария", last_name="Иванова", name="Мария Иванова", ) new_contact.save() # POST /api/v4/contacts print(new_contact.id) ``` ### Request Example (Update Contact) ```python from amocrm.v2 import Contact contact = Contact.objects.get(object_id=12345) contact.last_name = "Сидорова" contact.save() # PATCH /api/v4/contacts/{id} ``` ### Request Example (Link Company) ```python from amocrm.v2 import Contact, Company contact = Contact.objects.get(object_id=12345) company = Company.objects.get(query="ООО Рога и Копыта") contact.company = company contact.save() ``` ``` -------------------------------- ### Call - Registering Calls Source: https://context7.com/krukov/amocrm_api/llms.txt The `Call` class allows you to log incoming and outgoing calls in amoCRM. You can specify the direction, phone number, source, duration, status, and result of the call. ```APIDOC ## `Call` — регистрация звонков Класс `Call` позволяет фиксировать входящие и исходящие звонки в amoCRM. Направление задаётся через `CallDirection.INBOUND` / `CallDirection.OUTBOUNT`, статус — через константы `CallStatus`. ### Register Outbound Call ```python from datetime import timedelta from amocrm.v2 import Call, CallDirection, CallStatus call_result = Call().create( direction=CallDirection.OUTBOUNT, phone="+79001234567", source="Менеджер Сидоров", duration=timedelta(minutes=5, seconds=30), status=CallStatus.SUCCESS, result="Договорились о встрече", link="https://pbx.example.com/recordings/12345.mp3", ) print(call_result) # {'id': ..., 'phone': '+79001234567', ...} ``` ### Register Inbound Call with Manager Assignment ```python from amocrm.v2 import Call, CallDirection, CallStatus from amocrm.v2.entity.user import User manager = User.objects.get(query="manager@company.ru") Call().create( direction=CallDirection.INBOUND, phone="+74951234567", source="Офисная АТС", duration=120, # секунды, можно передавать int status=CallStatus.CALL_LATER, created_by=manager, # объект User или int (ID) uniq="unique-call-id-abc", ) ``` ### Available Call Statuses - `CallStatus.LEAVE_MESSAGE` = 1 — оставил сообщение - `CallStatus.CALL_LATER` = 2 — перезвонить позже - `CallStatus.OUT_OFF` = 3 — нет на месте - `CallStatus.SUCCESS` = 4 — разговор состоялся - `CallStatus.WRONG_NUMBER` = 5 — неверный номер - `CallStatus.UNAVAILABLE` = 6 — не дозвонился - `CallStatus.BUSY` = 7 — номер занят ``` -------------------------------- ### Manage Entity Tags with AmoCRM API v2 Source: https://context7.com/krukov/amocrm_api/llms.txt This snippet demonstrates how to add and remove tags from contacts, companies, and leads using the `tags` field. Remember to call `.save()` on the entity to apply changes. ```python from amocrm.v2 import Contact, Lead # Добавить теги к контакту contact = Contact.objects.get(object_id=12345) contact.tags.append("vip") contact.tags.add("крупный клиент") # add — псевдоним append contact.save() # Удалить тег contact.tags.remove("vip") contact.save() # Перебрать теги for tag in contact.tags: print(tag.name) # Добавить тег к сделке lead = Lead.objects.get(object_id=55555) lead.tags.append("горячий") lead.save() # Перебрать глобальные теги сделок (через Tag.leads) from amocrm.v2.entity.tag import Tag for tag in Tag.leads.all(): print(tag.name, tag.id) ``` -------------------------------- ### Task Management Source: https://context7.com/krukov/amocrm_api/llms.txt Manage tasks associated with entities. Tasks can be retrieved through the Task manager or via the tasks field of an entity. You can create, update, and mark tasks as completed. ```APIDOC ## Task Management ### Description Manage tasks associated with entities. Tasks can be retrieved through the Task manager or via the tasks field of an entity. You can create, update, and mark tasks as completed. ### Methods - **Get Tasks for an Entity** Retrieve all tasks associated with a specific entity (e.g., Contact). ```python contact = Contact.objects.get(object_id=12345) for task in contact.tasks: print(task.text, task.is_completed, task.complete_till) ``` - **Create and Add Task to Entity** Create a new task and associate it with an entity. ```python new_task = Task( text="Позвонить клиенту для уточнения деталей", task_type_id=1, complete_till=datetime.now() + timedelta(days=2), ) contact.tasks.add(new_task) # Automatically saves with entity_id and entity_type ``` - **Create Task Directly** Create a task directly using the Task manager, specifying entity details. ```python task = Task.objects.create( text="Отправить КП", task_type_id=1, entity_id=12345, entity_type="contacts", complete_till=datetime(2024, 12, 31, 18, 0, 0), ) ``` - **Mark Task as Completed** Update a task to mark it as completed and provide a result. ```python task.is_completed = True task.result = "КП отправлено по email" task.save() ``` ### Fields - `name` (string) - `text` (string) - `entity_id` (integer) - `entity_type` (string) - `responsible_user` (User object) - `is_completed` (boolean) - `task_type_id` (integer) - `complete_till` (datetime) - `duration_sec` (integer) - `result` (string) ``` -------------------------------- ### Tag Management Source: https://context7.com/krukov/amocrm_api/llms.txt Manage tags for entities such as contacts, companies, and leads. Tags can be added, removed, and iterated. ```APIDOC ## Tag Management ### Description Manage tags for entities such as contacts, companies, and leads. Tags can be added, removed, and iterated. ### Methods - **Add Tag to Entity** Append one or more tags to an entity. ```python # For a contact contact = Contact.objects.get(object_id=12345) contact.tags.append("vip") contact.tags.add("крупный клиент") # add is an alias for append contact.save() # For a lead lead = Lead.objects.get(object_id=55555) lead.tags.append("горячий") lead.save() ``` - **Remove Tag from Entity** Remove a specific tag from an entity. ```python contact.tags.remove("vip") contact.save() ``` - **Iterate Tags for an Entity** Loop through all tags associated with an entity. ```python for tag in contact.tags: print(tag.name) ``` - **Iterate All Lead Tags** Retrieve all global tags available for leads. ```python from amocrm.v2.entity.tag import Tag for tag in Tag.leads.all(): print(tag.name, tag.id) ``` ### Fields - `name` (string) - `id` (integer, for global tags) ``` -------------------------------- ### User - Retrieving Account Users Source: https://context7.com/krukov/amocrm_api/llms.txt The `User` model provides access to user information within your amoCRM account. Users cannot be created via the API but can be read and used for assignments. ```APIDOC ## Пользователи ### `User` — получение пользователей аккаунта Модель `User` содержит поля `name`, `email`, `language`, `is_admin`, `is_active`, `is_free`. Пользователей нельзя создавать через API, только читать. ### Get All Users ```python from amocrm.v2.entity.user import User for user in User.objects.all(): print(user.id, user.name, user.email, user.is_admin) ``` ### Get User by Email ```python from amocrm.v2.entity.user import User manager = User.objects.get(query="manager@company.ru") print(manager.name) # Иван Менеджеров print(manager.is_admin) # False print(manager.is_active) # True ``` ### Assign Responsible User to Lead ```python from amocrm.v2 import Lead from amocrm.v2.entity.user import User manager = User.objects.get(query="manager@company.ru") lead = Lead(name="Новая сделка") lead.responsible_user = manager lead.save() ``` ``` -------------------------------- ### Custom Fields - Working with Entity Custom Fields Source: https://context7.com/krukov/amocrm_api/llms.txt Custom fields allow you to extend amoCRM entities with additional attributes. The API supports various custom field types for entities like Leads and Contacts. ```APIDOC ## Кастомные поля ### `custom_field` — работа с пользовательскими полями сущностей Кастомные поля декларируются как атрибуты класса-наследника модели. Поддерживаются типы: `TextCustomField`, `UrlCustomField`, `SelectCustomField`, `MultiSelectCustomField`, `NumericCustomField`, `CheckboxCustomField`, `DateCustomField`, `DateTimeCustomField`, `ContactPhoneField`, `ContactEmailField`, `TextAreaCustomField`, `StreetAddressCustomField`, `RadioButtonCustomField`. ### Lead Custom Fields ```python from amocrm.v2 import Lead as _Lead from amocrm.v2.entity import custom_field from datetime import datetime class Lead(_Lead): utm_source = custom_field.UrlCustomField("UTM метка") deal_type = custom_field.SelectCustomField("Тип сделки") amount = custom_field.NumericCustomField("Сумма контракта") is_repeat = custom_field.CheckboxCustomField("Повторная сделка") deadline = custom_field.DateCustomField("Дедлайн") # Reading custom fields lead = Lead.objects.get(object_id=55555) print(lead.utm_source) # "https://example.com?utm_source=google" print(lead.amount) # 250000.0 print(lead.is_repeat) # True print(lead.deadline) # date(2024, 12, 31) print(lead.deal_type) # SelectValue(id=1, value='Новый') # Writing custom fields lead.utm_source = "https://example.com?utm=yandex" lead.amount = 300000 lead.is_repeat = True lead.deadline = datetime(2024, 12, 31) lead.deal_type = "Повторный" # поиск по имени варианта lead.save() ``` ### Contact Custom Fields (Phone and Email) ```python from amocrm.v2 import Contact as _Contact from amocrm.v2.entity import custom_field class Contact(_Contact): phone = custom_field.ContactPhoneField("Телефон", enum_code="WORK") mobile = custom_field.ContactPhoneField("Телефон", enum_code="MOB") email = custom_field.ContactEmailField("Email", enum_code="WORK") contact = Contact.objects.get(object_id=12345) print(contact.phone) # "+79001234567" print(contact.email) # "ivan@example.com" contact.phone = "+79009876543" contact.email = "new@example.com" contact.save() ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.