### Install @mobilon-dev/amotop Source: https://github.com/mobilon-dev/amotop/blob/main/docs/index.html Installs the @mobilon-dev/amotop package using npm. This is the primary step to begin using the library in a Node.js project. ```bash npm i @mobilon-dev/amotop ``` -------------------------------- ### Install @mobilon-dev/amotop Package Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Installs the @mobilon-dev/amotop library using npm. This is the first step to integrate the amoCRM API client into your project. ```bash npm install @mobilon-dev/amotop ``` -------------------------------- ### Add a Lead to amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Shows how to add a new lead to amoCRM using the AmoApiClient. It includes creating the lead object with necessary details like name and price, and utilizing helper methods to get pipeline payload. ```javascript // Добавление сделки const lead = { name: 'Продать слона', price: 1000, ...amoApiClient.getPipelineLeadPayload(7183562, 60002878) }; const newLead = await amoApiClient.addLead(lead); ``` -------------------------------- ### Get Leads with Filtering Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Demonstrates how to retrieve leads from amoCRM with specific filters applied, such as filtering by responsible user ID. This allows for targeted data retrieval. ```javascript // Получение сделок с фильтрацией const leads = await amoApiClient.getLeads({ limit: 50, filter: { responsible_user_id: [12345] } }); ``` -------------------------------- ### Get All Contacts from amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Shows how to retrieve all contacts stored in amoCRM using the AmoApiClient. This is useful for fetching a complete list of contacts. ```javascript // Получение всех контактов const contacts = await amoApiClient.getAllContacts(); ``` -------------------------------- ### Get amoCRM OAuth 2.0 Authorization URL Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Illustrates how to generate the authorization URL for amoCRM OAuth 2.0 using the AmoService. This URL is used to redirect users for authentication. ```javascript const { AmoService } = require('@mobilon-dev/amotop'); const amoService = new AmoService('your-domain.amocrm.ru'); // Получение URL для авторизации const authUrl = amoService.getAuthUrl({ clientId: 'your-client-id', redirectUri: 'your-redirect-uri', state: 'random-state' }); ``` -------------------------------- ### Initialize and Use AmoCRM API Clients Source: https://github.com/mobilon-dev/amotop/blob/main/docs/index.html Demonstrates how to initialize AmoJoScopeClient and AmoApiClient from the @mobilon-dev/amotop library. It shows fetching leads and sending messages to a chat. Requires configuration details like scopeId, channelSecret, domain, and accessToken. ```javascript const {AmoJoScopeClient, AmoApiClient} = require('@mobilon-dev/amotop'); const {debug, scopeId, channelSecret, domain, accessToken} = require('../_config'); const amoJoScopeClient = new AmoJoScopeClient({scopeId, channelSecret, debug}); const amoApiClient = new AmoApiClient(domain, accessToken, {debug}); // получаем сделки const leads = await amoApiClient.getLeads({limit: 20}); // отправляем сообщение в чат const response = await amoJoScopeClient.sendMessage(message); /*логи [AmoApiClient][Request] GET https://mobilonchatitest6.amocrm.ru/api/v4/leads?page=1&limit=20 [AmoApiClient][Response] GET https://mobilonchatitest6.amocrm.ru/api/v4/leads?page=1&limit=20 200:OK {"_page":1,"_links":{"self":{"href":"https://mobilonchatitest6.amocrm.ru/api/v4/leads?page=1&limit=20"}},"_embedded":{"leads":[{"id":4214965,"name":"Продать стул","price":10000,"responsible_user_id":886363,"group_id":0,"status_id":64831342,"pipeline_id":7883550,"loss_reason_id":null,"created_by":886363,"updated_by":886363,"created_at":1709609319,"updated_at":1709692894,"closed_at":null,"closest_task_at":null,"is_deleted":false,"custom_fields_values":null,"score":null,"account_id":31612010,"labor_cost":null,"_links":{"self":{"href":"https://mobilonchatitest6.amocrm.ru/api/v4/leads/4214965?page=1&limit=20"}},"_embedded":{"tags":[],"companies":[]}}]}} */ ``` -------------------------------- ### Initialize Theme Setting Source: https://github.com/mobilon-dev/amotop/blob/main/docs/index.html Sets the document's theme based on the 'tsd-theme' value from local storage, defaulting to 'os' if not found. It also hides the body and then shows the app page or removes the display style after a short delay. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize and Use amoCRM API Clients Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Demonstrates the initialization of AmoApiClient and AmoJoScopeClient from the amotop library. It shows how to fetch leads using the AmoApiClient and send messages via the Chat API using AmoJoScopeClient. ```javascript const { AmoApiClient, AmoJoScopeClient } = require('@mobilon-dev/amotop'); const config = require('./config'); // Инициализация клиентов const amoApiClient = new AmoApiClient(config.domain, config.accessToken, { debug: config.debug }); const amoJoScopeClient = new AmoJoScopeClient({ scopeId: config.scopeId, channelSecret: config.channelSecret, debug: config.debug }); // Получение сделок const leads = await amoApiClient.getLeads({ limit: 20 }); // Отправка сообщения в чат const message = { text: 'Привет! Это тестовое сообщение.', source: 'bot' }; const response = await amoJoScopeClient.sendMessage(message); ``` -------------------------------- ### Configure amotop Client Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Sets up the configuration for the amotop client, including domain, access token, and optional debug mode. This configuration file is required for initializing the API clients. ```javascript module.exports = { domain: 'your-domain.amocrm.ru', accessToken: 'your-access-token', scopeId: 'your-scope-id', channelSecret: 'your-channel-secret', debug: true }; ``` -------------------------------- ### Добавление компании в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример создания новой компании в amoCRM. Необходимо указать название компании и связанную информацию. ```javascript import { addCompany } from '@mobilon-dev/amotop'; async function main() { const company = { name: 'Новая Компания', // ... другие параметры компании }; await addCompany(company); } ``` -------------------------------- ### Получение списка причин отказа с описанием из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения списка причин отказа сделок вместе с их описаниями из amoCRM. Полезно для аналитики. ```javascript import { getLossReasons } from '@mobilon-dev/amotop'; async function main() { const lossReasons = await getLossReasons(); console.log(lossReasons); } ``` -------------------------------- ### Получение сделок из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения списка сделок из amoCRM. Можно фильтровать сделки по различным параметрам. ```javascript import { getLeads } from '@mobilon-dev/amotop'; async function main() { const leads = await getLeads({ status: 'active' }); console.log(leads); } ``` -------------------------------- ### Добавление контакта в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример создания нового контакта в amoCRM. Необходимо указать имя контакта и другую релевантную информацию. ```javascript import { addContact } from '@mobilon-dev/amotop'; async function main() { const contact = { name: 'Новый Контакт', // ... другие параметры контакта }; await addContact(contact); } ``` -------------------------------- ### Простая загрузка файла в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример простой загрузки файла в amoCRM. Файл будет доступен в общем хранилище amoCRM. ```javascript import { uploadFile } from '@mobilon-dev/amotop'; import fs from 'fs'; async function main() { const fileStream = fs.createReadStream('path/to/your/file.txt'); const uploadedFile = await uploadFile(fileStream); console.log(uploadedFile); } ``` -------------------------------- ### Получение воронок и этапов воронок из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения структуры воронок продаж и их этапов из amoCRM. Важно для понимания процесса продаж. ```javascript import { getPipelines } from '@mobilon-dev/amotop'; async function main() { const pipelines = await getPipelines(); console.log(pipelines); } ``` -------------------------------- ### Получение всех контактов из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения списка всех контактов из amoCRM. Может потребовать пагинацию при большом количестве контактов. ```javascript import { getAllContacts } from '@mobilon-dev/amotop'; async function main() { const allContacts = await getAllContacts(); console.log(allContacts); } ``` -------------------------------- ### Получение всех полей с вариантами из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения списка всех пользовательских полей с их возможными вариантами значений из amoCRM. ```javascript import { getCustomFields } from '@mobilon-dev/amotop'; async function main() { const customFields = await getCustomFields(); console.log(customFields); } ``` -------------------------------- ### Добавление сделки к существующему контакту в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример создания сделки и привязки ее к конкретному контакту в amoCRM. Требуется ID контакта. ```javascript import { complexLead } from '@mobilon-dev/amotop'; async function main() { const leadData = { name: 'Сделка для контакта', contact_id: 12345, // ... другие параметры сделки }; await complexLead(leadData); } ``` -------------------------------- ### Добавление пользовательского поля контакту в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример добавления пользовательского поля к существующему контакту в amoCRM. Требуется ID контакта и ID поля. ```javascript import { addField } from '@mobilon-dev/amotop'; async function main() { const fieldData = { contact_id: 12345, field_id: 6789, value: 'Новое значение', }; await addField(fieldData); } ``` -------------------------------- ### Добавление сделки в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример добавления новой сделки в amoCRM. Необходимо указать название сделки и связанные параметры. ```javascript import { addLead } from '@mobilon-dev/amotop'; async function main() { const lead = { name: 'Новая сделка', // ... другие параметры сделки }; await addLead(lead); } ``` -------------------------------- ### Отправка сообщения в чат amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример отправки текстового сообщения в существующий чат amoCRM. Необходимо указать ID чата и текст сообщения. ```javascript import { generateTextConversation } from '@mobilon-dev/amotop'; async function main() { const message = { chat_id: 54321, text: 'Привет, как дела?', // ... другие параметры сообщения }; await generateTextConversation(message); } ``` -------------------------------- ### Добавление тысячи сделок в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример пакетного добавления большого количества сделок в amoCRM. Оптимизировано для высокой производительности. ```javascript import { addThousandLeads } from '@mobilon-dev/amotop'; async function main() { const leads = []; for (let i = 0; i < 1000; i++) { leads.push({ name: `Сделка ${i}`, // ... другие параметры сделки }); } await addThousandLeads(leads); } ``` -------------------------------- ### Добавление задачи в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример создания новой задачи в amoCRM. Необходимо указать описание задачи, срок и ответственного. ```javascript import { addTask } from '@mobilon-dev/amotop'; async function main() { const task = { text: 'Новая задача', complete_till: Math.floor(Date.now() / 1000) + 86400, // Через 1 день // ... другие параметры задачи }; await addTask(task); } ``` -------------------------------- ### Подключение канала чата к аккаунту amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример подключения нового канала чата к вашему аккаунту amoCRM. Требуется информация о типе и настройках канала. ```javascript import { connectAccount } from '@mobilon-dev/amotop'; async function main() { const chatAccount = { type: 'telegram', // ... настройки подключения к Telegram }; await connectAccount(chatAccount); } ``` -------------------------------- ### Добавление неразобранного типа 'форма' в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример добавления неразобранного элемента типа 'форма' в amoCRM. Требуется указать необходимые параметры для формы. ```javascript import { addUnsortedForm } from '@mobilon-dev/amotop'; async function main() { const form = { name: 'Новая форма', // ... другие параметры формы }; await addUnsortedForm(form); } ``` -------------------------------- ### Добавление неразобранного типа 'звонок' в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример добавления неразобранного элемента типа 'звонок' в amoCRM. Необходимо предоставить информацию о звонке. ```javascript import { addUnsortedSip } from '@mobilon-dev/amotop'; async function main() { const sip = { from: '+1234567890', to: '+0987654321', // ... другие параметры звонка }; await addUnsortedSip(sip); } ``` -------------------------------- ### Получение всех сделок из amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения всех сделок, доступных в amoCRM. Может потребовать пагинацию для больших объемов данных. ```javascript import { getAllLeads } from '@mobilon-dev/amotop'; async function main() { const allLeads = await getAllLeads(); console.log(allLeads); } ``` -------------------------------- ### Upload File using File API Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Shows how to upload a file to amoCRM using the AmoFileClient. This involves specifying the file path and name, and then using the uploadFile method. ```javascript const { AmoFileClient } = require('@mobilon-dev/amotop'); const fileClient = new AmoFileClient(accessToken, { debug: true }); // Загрузка файла const uploadResult = await fileClient.uploadFile({ file: './document.pdf', name: 'document.pdf' }); ``` -------------------------------- ### Получение всех типов задач в amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения списка всех доступных типов задач в amoCRM. Полезно для стандартизации постановки задач. ```javascript import { getAccountTaskTypes } from '@mobilon-dev/amotop'; async function main() { const taskTypes = await getAccountTaskTypes(); console.log(taskTypes); } ``` -------------------------------- ### Загрузка файла к сделке amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример загрузки файла и привязки его к конкретной сделке в amoCRM. Требуется ID сделки и сам файл. ```javascript import { uploadFileToLead } from '@mobilon-dev/amotop'; import fs from 'fs'; async function main() { const leadId = 12345; const fileStream = fs.createReadStream('path/to/your/document.pdf'); const uploadedFile = await uploadFileToLead(leadId, fileStream); console.log(uploadedFile); } ``` -------------------------------- ### Exchange OAuth 2.0 Code for Tokens Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Shows how to exchange an authorization code for access and refresh tokens using the AmoService. This is a crucial step in the OAuth 2.0 authentication flow. ```javascript // Обмен кода на токен const tokens = await amoService.exchangeCode({ clientId: 'your-client-id', clientSecret: 'your-client-secret', code: 'authorization-code', redirectUri: 'your-redirect-uri' }); ``` -------------------------------- ### Attach Uploaded File to a Lead Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Demonstrates how to link a previously uploaded file to a specific lead in amoCRM using the AmoApiClient. It requires the lead ID and the uploaded file ID. ```javascript // Привязка файла к сделке await amoApiClient.attachFileToLead(leadId, uploadResult.id); ``` -------------------------------- ### Получение неразобранного amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/docs/media/index.md Пример получения неразобранных элементов из amoCRM. Необходима предварительная настройка подключения к API amoCRM. ```javascript import { getUnsorted } from '@mobilon-dev/amotop'; async function main() { const unsorted = await getUnsorted(); console.log(unsorted); } ``` -------------------------------- ### Add a Contact to amoCRM Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Illustrates how to add a new contact to amoCRM using the AmoApiClient, including providing contact details like name, phone, and email. ```javascript // Добавление контакта const contact = { name: 'Иван Иванов', phone: '+79001234567', email: 'ivan@example.com' }; const newContact = await amoApiClient.addContact(contact); ``` -------------------------------- ### AmoApiClient Request and Response Logging Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Logs API requests and responses when debug mode is enabled. Shows the HTTP method, URL, and response status code. No specific dependencies are mentioned for this logging functionality itself. ```text [AmoApiClient][Request] GET https://domain.amocrm.ru/api/v4/leads?page=1&limit=20 [AmoApiClient][Response] GET https://domain.amocrm.ru/api/v4/leads?page=1&limit=20 200:OK ``` -------------------------------- ### Send Image Message via Chat API Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Illustrates sending an image message to a chat using the AmoJoScopeClient. This includes providing the image URL, an optional caption, and the message source. ```javascript // Отправка изображения await amoJoScopeClient.sendImageMessage({ image: 'https://example.com/image.jpg', caption: 'Описание изображения', source: 'bot' }); ``` -------------------------------- ### Send Text Message via Chat API Source: https://github.com/mobilon-dev/amotop/blob/main/README.md Demonstrates sending a text message to a chat using the AmoJoScopeClient. It specifies the message content and the source of the message (e.g., 'bot'). ```javascript // Отправка текстового сообщения await amoJoScopeClient.sendTextMessage({ text: 'Привет! Чем могу помочь?', source: 'bot' }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.