### API Signup Handler Setup Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Sets up asynchronous handlers for API signups and starts the consumer. This code configures the API to use the defined asynchronous functions for processing signups. ```python # Запуск обоих обработчиков (можно комбинировать sync и async) api.set_signup_handler(handle_all_signups_async) api.set_company_signup_handler(handle_our_signups_async) api.start_signup_consumer() api.start_company_signup_consumer() ``` -------------------------------- ### Start Company Subscriber Registration Consumer Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Set a handler for company-specific signup events and start the Kafka consumer for the company's signup topic. This processes registrations in real-time. ```python # Установить обработчик и запустить потребление (топик компании) api.set_company_signup_handler(handle_signup) api.start_company_signup_consumer() ``` -------------------------------- ### Start General Subscriber Registration Consumer Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Set a handler for general signup events and start the Kafka consumer for the global SIGN_UPS_ALL topic. This processes all registrations across companies. ```python # Для общего топика SIGN_UPS_ALL # api.set_signup_handler(handle_signup) # api.start_signup_consumer() ``` -------------------------------- ### Start Kafka Consumer and Set Handler Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Sets the message handler for the Kafka consumer and then starts the consumer to begin receiving and processing messages. ```python # Установка обработчика и запуск api.set_kafka_message_handler(handle_kafka_message) api.start_kafka_consumer() ``` -------------------------------- ### Simultaneous Handling of General and Company Sign-up Events Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Configures and starts both synchronous handlers for general (SIGN_UPS_ALL) and company-specific (SIGN_UPS_) sign-up events. This allows for parallel processing, such as sending data to analytics and welcoming new clients. ```python # Обработка всех регистраций для аналитики def handle_all_signups(signup: SignUpEvent): print(f"[Аналитика] Регистрация: {signup.abonent.phone}") # Отправить данные в систему аналитики analytics.track_signup(signup) # Обработка только регистраций компании для приветствия def handle_our_signups(signup: SignUpEvent): print(f"[Приветствие] Наш новый клиент: {signup.abonent.phone}") api.send_message_to_abonent( signup.abonent.id, 'support', 'Добро пожаловать! Мы рады видеть вас в нашей компании!' ) # Запуск обоих обработчиков api.set_signup_handler(handle_all_signups) api.set_company_signup_handler(handle_our_signups) api.start_signup_consumer() api.start_company_signup_consumer() ``` -------------------------------- ### Get All Company Services Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Fetches a list of all services offered by the company. It iterates through the services and prints their names and types. ```python # Получить все услуги компании all_services = api.get_all_services() for service in all_services: print(f"{service.name} ({service.type})") ``` -------------------------------- ### Fetch Latest Signups from Kafka Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves the latest N registrations from Kafka without starting a background consumer. ```APIDOC ## Fetch Latest Signups from Kafka ### Description Fetches the most recent subscriber registrations directly from Kafka without the need to run a continuous consumer. Allows specifying the number of records to fetch and whether to query the company-specific topic or the general topic. ### Method GET (assumed) ### Endpoint /api/kafka/signups/latest ### Parameters #### Query Parameters - **limit** (integer) - Required - The maximum number of signup records to fetch. - **company** (boolean) - Required - If true, fetches from the company-specific topic; if false, fetches from the general SIGN_UPS_ALL topic. - **timeout_seconds** (float) - Optional - The timeout in seconds for fetching data. ### Request Example ```python # Fetch the latest 10 registrations from the company topic signups = api.kafka_client.fetch_latest_signups(limit=10, company=True) for signup in signups: print(f"ID: {signup.id}, Phone: {signup.abonent.phone}") print(f"Address: {signup.address.city}, {signup.address.street.name}") print(f"Status: {signup.status}") print("---") # Fetch the latest 5 registrations from the general topic with a timeout signups = api.kafka_client.fetch_latest_signups(limit=5, company=False, timeout_seconds=10.0) ``` ### Response #### Success Response (200) - **signups** (array) - An array of signup objects. - **id** (integer) - Registration ID. - **abonent** (object) - Subscriber information. - **phone** (string) - Subscriber phone number. - **address** (object) - Subscriber address details. - **city** (string) - City. - **street** (object) - Street details. - **name** (string) - Street name. - **status** (string) - Current status of the registration. ``` -------------------------------- ### Get Entrance Services Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves a list of services available for a specific entrance, identified by its ID. It prints the ID, name, and type of each service. ```python # Получить услуги подъезда services = api.get_entrance_services("30130") for service in services: print(f"ID: {service.id}") print(f"Название: {service.name}") print(f"Тип: {service.type}") # HouseChat, VideoSurveillance, Intercom и т.д. ``` -------------------------------- ### Get All Entrances with Pagination Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Fetches all entrances, utilizing automatic pagination, and prints the total number of entrances found along with their address strings and associated services. ```python all_entrances = api.get_entrances(all=True) print(f"Получено {len(all_entrances.content)} подъездов из {all_entrances.total_elements}") for entrance in all_entrances.content: print(f"Подъезд: {entrance.address_string}") for service in entrance.services: print(f" - {service.name} ({service.type})") ``` -------------------------------- ### Get Service Connections Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves all apartment connections for a specific service ID. It prints the total number of connected apartments. ```python # Получить подключения конкретной услуги service_connections = api.get_service_connections(12345) print(f"К услуге подключено {len(service_connections)} квартир") ``` -------------------------------- ### Get Entrances with Services Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Fetches all entrances managed by the company, optionally filtering by address and using pagination. It details services available in each entrance, including camera and RDA device counts. ```python # Получить все подъезды компании entrances = api.get_entrances() print(f"Всего подъездов: {entrances.total_elements}") # Поиск подъездов по адресу с пагинацией entrances = api.get_entrances(address="Москва, Ленина", page=0, size=10) for entrance in entrances.content: print(f"Подъезд {entrance.id}: {entrance.address_string}") for service in entrance.services: print(f" - Услуга: {service.name} ({service.type})") print(f" Камеры: {len(service.cameras)}") print(f" RDA устройства: {len(service.rdas)}") print(f" Тариф: {service.tariff}") ``` -------------------------------- ### Get All Entrances (Automatic Pagination) Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves all entrances for a company by automatically handling pagination. This is useful when you need to process all entrances without manually managing page numbers. ```python # Получить ВСЕ подъезды (автоматическая пагинация) all_entrances = api.get_entrances(all=True) print(f"Загружено {len(all_entrances.content)} подъездов") ``` -------------------------------- ### Handle Incoming Kafka Messages Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Set up a handler for incoming Kafka messages and start the consumer. This function processes messages, printing the sender's phone number and the message content. ```python def handle_message(message: KafkaIncomingMessage): print(f"Сообщение от {message.from_abonent.phone}: {message.message}") api.set_kafka_message_handler(handle_message) api.start_kafka_consumer() ``` -------------------------------- ### Get Entrances with Pagination Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves a paginated list of all entrances for a company. Displays total elements and pages, along with details for each entrance including its address and associated services. ```python # Получить все подъезды компании с пагинацией entrances = api.get_entrances(page=0, size=20) print(f"Всего подъездов: {entrances.total_elements}") print(f"Страниц: {entrances.total_pages}") for entrance in entrances.content: print(f"ID: {entrance.id}") print(f"Адрес: {entrance.address_string}") for service in entrance.services: print(f" Услуга: {service.name} ({service.type})") print(f" Камеры: {len(service.cameras)}") print(f" RDA устройства: {len(service.rdas)}") print(f" Тариф: {service.tariff}") ``` -------------------------------- ### Fetch Latest Registrations from Kafka (Company Topic) Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieve the latest N subscriber registrations directly from the company's Kafka topic without starting a background consumer. Useful for on-demand data retrieval. ```python # Получить последние 10 регистраций из топика компании signups = api.kafka_client.fetch_latest_signups(limit=10, company=True) for signup in signups: print(f"ID: {signup.id}, Телефон: {signup.abonent.phone}") print(f"Адрес: {signup.address.city}, {signup.address.street.name}") print(f"Статус: {signup.status}") print("---") ``` -------------------------------- ### Get Flats in an Entrance by ID Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Fetches all flats within a specific entrance identified by its ID and prints details for each flat, including its address, owner's phone number, virtual status, and camera ID if present. ```python flats = api.get_entrance_flats("27222") print(f"Найдено {len(flats)} квартир в подъезде") for flat in flats: print(f"Квартира ID: {flat.id}") print(f" Адрес: {flat.address.city}, ул.{flat.address.street.name}, д.{flat.address.house.number}, кв.{flat.address.flat}") print(f" Владелец: {flat.owner.phone}") print(f" Виртуальная: {flat.virtual}") if flat.camera_id: print(f" Камера ID: {flat.camera_id}") ``` -------------------------------- ### Initialize RosDomofonAPI and Set Up General Sign-up Handler Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Initializes the RosDomofonAPI with Kafka connection details and sets a synchronous handler for general sign-up events from the SIGN_UPS_ALL topic. Ensure Kafka credentials and certificate paths are correctly configured. ```python from rosdomofon import RosDomofonAPI from models import SignUpEvent # Инициализация с Kafka api = RosDomofonAPI( username="user", password="pass", kafka_bootstrap_servers="kafka.rosdomofon.com:443", company_short_name="asd_asd", kafka_group_id="rosdomofon_group", kafka_username="kafka_user", kafka_password="kafka_pass", kafka_ssl_ca_cert_path="kafka-ca.crt" ) # Синхронный обработчик регистраций (общий топик) def handle_signup(signup: SignUpEvent): print(f"[SIGN_UPS_ALL] Новая регистрация: {signup.abonent.phone}") print(f"Страна: {signup.address.country.name}") print(f"Адрес: {signup.address.city}, ул.{signup.address.street.name}, д.{signup.address.house.number}") print(f"Приложение: {signup.application.name}") print(f"Статус: {signup.status}") # Установка и запуск api.set_signup_handler(handle_signup) api.start_signup_consumer() ``` -------------------------------- ### Set Up Asynchronous General Sign-up Handler Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Configures an asynchronous handler for general sign-up events, suitable for operations like database saves or tracking events via external analytics services. This handler uses `await` for non-blocking I/O operations. ```python import asyncio from rosdomofon import RosDomofonAPI from models import SignUpEvent # Асинхронный обработчик с операциями БД async def handle_signup_async(signup: SignUpEvent): print(f"[SIGN_UPS_ALL] Новая регистрация: {signup.abonent.phone}") # Асинхронное сохранение в БД await db.save_signup(signup) # Асинхронная отправка в аналитику await analytics.track_event("new_signup", { "phone": signup.abonent.phone, "city": signup.address.city }) # Установка и запуск api.set_signup_handler(handle_signup_async) api.start_signup_consumer() ``` -------------------------------- ### Initialization and Authentication Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Demonstrates how to initialize the RosDomofonAPI class with or without Kafka support and authenticate with the API. ```APIDOC ## Initialization and Authentication ### Description Initialize the `RosDomofonAPI` class, which is the main entry point for interacting with the API. It supports optional Kafka integration for real-time messages and events. ### Method N/A (Class Initialization) ### Endpoint N/A ### Parameters #### Initialization Parameters - **username** (string) - Required - Your Rosdomofon username. - **password** (string) - Required - Your Rosdomofon password. - **kafka_bootstrap_servers** (string) - Optional - Kafka bootstrap server addresses (e.g., "kafka.rosdomofon.com:9092"). - **company_short_name** (string) - Optional - Short name of the company for Kafka integration. - **kafka_group_id** (string) - Optional - Kafka consumer group ID. - **kafka_username** (string) - Optional - Kafka username for authentication. - **kafka_password** (string) - Optional - Kafka password for authentication. - **kafka_ssl_ca_cert_path** (string) - Optional - Path to the CA certificate file for Kafka SSL. - **cache_file** (string) - Optional - Path to a JSON file for caching entrance data. ### Request Example ```python from rosdomofon import RosDomofonAPI # Basic initialization (REST API only) api = RosDomofonAPI( username="your_username", password="your_password" ) # Initialization with Kafka support api_with_kafka = RosDomofonAPI( username="your_username", password="your_password", kafka_bootstrap_servers="kafka.rosdomofon.com:9092", company_short_name="Video_SB", kafka_group_id="my_consumer_group", kafka_username="kafka_user", kafka_password="kafka_pass", kafka_ssl_ca_cert_path="/path/to/ca-cert.pem", cache_file="entrances_cache.json" ) # Using as a context manager with RosDomofonAPI(username="user", password="pass") as api_context: pass ``` ### Authentication ### Method `authenticate()` ### Endpoint N/A ### Description Authenticates with the Rosdomofon API using the provided credentials and retrieves an access token. ### Request Example ```python auth = api.authenticate() print(f"Token received: {auth.access_token[:20]}...") print(f"Valid for {auth.expires_in} seconds") ``` ### Response #### Success Response (200) - **access_token** (string) - The authentication token. - **expires_in** (integer) - The token's validity period in seconds. #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expires_in": 3600 } ``` ``` -------------------------------- ### Get Accounts Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieve a list of subscriber accounts and search for accounts by phone number. ```APIDOC ## Get Accounts ### Description Methods to retrieve a list of subscriber accounts for a company and to search for an account by phone number. ### Method `get_accounts()` ### Endpoint N/A ### Description Retrieves a list of all subscriber accounts associated with the authenticated company. ### Request Example ```python accounts = api.get_accounts() for account in accounts: print(f"ID: {account.id}") print(f"Account Number: {account.number or 'Not specified'}") print(f"Owner Phone: {account.owner.phone}") print(f"Owner ID: {account.owner.id}") print(f"Blocked: {account.blocked}") print(f"Company: {account.company.short_name}") print("---") ``` ### Response #### Success Response (200) - **accounts** (list) - A list of account objects. - **id** (integer) - The unique identifier for the account. - **number** (string) - The account number. - **owner** (object) - Information about the account owner. - **phone** (string) - The owner's phone number. - **id** (integer) - The unique identifier for the owner. - **blocked** (boolean) - Indicates if the account is blocked. - **company** (object) - Information about the company. - **short_name** (string) - The short name of the company. #### Response Example ```json [ { "id": 123456, "number": "ACC789012", "owner": { "phone": "+79123456789", "id": 987654 }, "blocked": false, "company": { "short_name": "Video_SB" } } ] ``` --- ### Method `get_account_by_phone(phone_number)` ### Endpoint N/A ### Description Searches for a subscriber account using the provided phone number. ### Parameters #### Path Parameters - **phone_number** (string) - Required - The phone number to search for (e.g., 79308312222). ### Request Example ```python account = api.get_account_by_phone(79308312222) if account: print(f"Found account ID: {account.id}") abonent_id = account.owner.id account_id = account.id else: print("Account not found") ``` ### Response #### Success Response (200) - **account** (object) - The account object if found. - **id** (integer) - The unique identifier for the account. - **owner** (object) - Information about the account owner. - **id** (integer) - The unique identifier for the owner. #### Response Example ```json { "id": 123456, "owner": { "id": 987654 } } ``` ``` -------------------------------- ### Initialize and Authenticate RosDomofon API Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Demonstrates how to initialize the RosDomofonAPI client with credentials and perform authentication. ```python from rosdomofon import RosDomofonAPI # Инициализация клиента api = RosDomofonAPI(username="user", password="pass") # Авторизация auth = api.authenticate() ``` -------------------------------- ### Get Account Details Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieve comprehensive information about a specific account, including balance, services, and apartments. ```APIDOC ## Get Account Details ### Description The `get_account_info` method returns complete information about an account, including its balance, connected services, apartments, and delegations. ### Method `get_account_info(account_id)` ### Endpoint N/A ### Parameters #### Path Parameters - **account_id** (integer) - Required - The ID of the account to retrieve information for. ### Request Example ```python account_info = api.get_account_info(904154) # Balance information if account_info.balance: print(f"Balance: {account_info.balance.balance} {account_info.balance.currency}") print(f"Balance Date: {account_info.balance.balance_date}") print(f"Payment Available: {account_info.balance.is_payment_available}") # Owner information print(f"Owner Phone: {account_info.owner.phone}") print(f"Delegations: {len(account_info.owner.delegations)}") # Company information print(f"Company: {account_info.company.name}") print(f"Support Phone: {account_info.company.support_phone}") # Connected services for conn in account_info.connections: print(f"Service: {conn.service.name} ({conn.service.type})") print(f" Tariff: {conn.tariff} {conn.currency}") print(f" Blocked: {conn.blocked}") print(f" Apartment: {conn.flat.address.flat if conn.flat.address else 'N/A'}") ``` ### Response #### Success Response (200) - **account_info** (object) - Detailed information about the account. - **balance** (object) - Balance details. - **balance** (float) - The current balance amount. - **currency** (string) - The currency of the balance. - **balance_date** (string) - The date the balance was recorded. - **is_payment_available** (boolean) - Indicates if payment is available. - **owner** (object) - Owner details. - **phone** (string) - Owner's phone number. - **delegations** (list) - List of delegations. - **company** (object) - Company details. - **name** (string) - Company name. - **support_phone** (string) - Company support phone number. - **connections** (list) - List of connected services. - **service** (object) - Service details. - **name** (string) - Service name. - **type** (string) - Service type. - **tariff** (string) - The tariff plan. - **currency** (string) - The currency of the tariff. - **blocked** (boolean) - Indicates if the service connection is blocked. - **flat** (object) - Apartment details. - **address** (object) - Apartment address details. - **flat** (string) - Apartment number. #### Response Example ```json { "balance": { "balance": 1500.50, "currency": "RUB", "balance_date": "2023-10-27T10:00:00Z", "is_payment_available": true }, "owner": { "phone": "+79123456789", "delegations": [] }, "company": { "name": "RosDomofon Company", "support_phone": "+78005553535" }, "connections": [ { "service": { "name": "Video Surveillance", "type": "video" }, "tariff": "Basic Plan", "currency": "RUB", "blocked": false, "flat": { "address": { "flat": "101" } } } ] } ``` ``` -------------------------------- ### Async Company Signup Handler with Entrance Search Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Handles company signups asynchronously, including searching for the correct entrance based on address. If the apartment number is missing or multiple entrances are found, it saves the signup for further processing. ```python async def handle_company_signup_with_flat_async(signup: SignUpEvent): print(f"[Регистрация] Новый абонент: {signup.abonent.phone}") # Проверяем наличие номера квартиры if not signup.address.flat: print("⚠️ Номер квартиры не указан при регистрации") # Сохраняем в БД для последующей обработки await db.save_pending_signup(signup) return # Ищем подъезды по адресу entrances = api.find_entrance_by_address( city=signup.address.city, street=signup.address.street.name, house=signup.address.house.number ) if not entrances or len(entrances) > 1: # Сохраняем для ручной обработки await db.save_for_manual_processing(signup, entrances) return entrance_id = str(entrances[0].id) try: # Параллельное выполнение операций flat, _ = await asyncio.gather( # Создание квартиры (выполняется в executor для синхронного API) asyncio.get_event_loop().run_in_executor( None, lambda: api.create_flat( flat_number=str(signup.address.flat), entrance_id=entrance_id, abonent_id=signup.abonent.id, virtual=signup.virtual ) ), # Параллельное сохранение в БД db.save_signup_success(signup) ) print(f"✅ Квартира создана: ID {flat.id}") # Отправляем приветствие await asyncio.get_event_loop().run_in_executor( None, lambda: api.send_message_to_abonent( signup.abonent.id, 'support', f'Добро пожаловать! Ваша квартира {signup.address.flat} успешно добавлена.' ) ) except Exception as e: print(f"❌ Ошибка: {e}") await db.save_error(signup, str(e)) ``` ```python api.set_company_signup_handler(handle_company_signup_with_flat_async) api.start_company_signup_consumer() ``` -------------------------------- ### Initialize RosDomofonAPI with Kafka Support Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Initializes the RosDomofonAPI client with Kafka integration enabled. Requires Kafka bootstrap servers and a company short name for configuration. ```python from rosdomofon.rosdomofon import RosDomofonAPI api = RosDomofonAPI( username="user", password="pass", kafka_bootstrap_servers="kafka.example.com:9092", company_short_name="SK_SB" ) ``` -------------------------------- ### Get Abonnement Messages Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Retrieves messages for a specific subscriber, with options for channel, pagination, and message size. Requires the abonent_id. ```python messages = api.get_abonent_messages(abonent_id, channel='support', page=0, size=10) print(messages) ``` -------------------------------- ### Set Up Asynchronous Company Sign-up Handler Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Implements an asynchronous handler for company-specific sign-up events. This handler performs non-blocking operations such as sending messages via Kafka and registering new contacts in a CRM system. ```python # Асинхронный обработчик с внешними API вызовами async def handle_company_signup_async(signup: SignUpEvent): print(f"[SIGN_UPS_] Новая регистрация: {signup.abonent.phone}") # Асинхронная отправка приветствия через Kafka await api_async.send_message_async( signup.abonent.id, 'support', 'Добро пожаловать в нашу компанию!' ) # Асинхронная регистрация в CRM await crm.create_contact({ "phone": signup.abonent.phone, "address": f"{signup.address.city}, {signup.address.street.name}, {signup.address.house.number}" }) # Установка и запуск api.set_company_signup_handler(handle_company_signup_async) api.start_company_signup_consumer() ``` -------------------------------- ### Get Subscriber Apartments by ID Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves all apartments associated with a specific subscriber ID. Iterates through the results to print detailed apartment information. ```python flats = api.get_abonent_flats(1574870) for flat in flats: print(f"ID квартиры: {flat.id}") print(f"Адрес: {flat.address.city}, {flat.address.street.name}, д.{flat.address.house.number}") print(f"Квартира: {flat.address.flat}") print(f"Подъезд №{flat.address.entrance.number}") print(f"Диапазон квартир подъезда: {flat.address.entrance.flat_start}-{flat.address.entrance.flat_end}") print(f"Виртуальная трубка: {flat.virtual}") print(f"Владелец ID: {flat.owner.id}") print("---") ``` -------------------------------- ### Initialize RosDomofonAPI with Kafka Support Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Initialize RosDomofonAPI with Kafka integration for real-time events. Requires Kafka connection details, company short name, and optional SSL certificate path. A cache file can be specified for entrances. ```python # Инициализация с поддержкой Kafka api = RosDomofonAPI( username="your_username", password="your_password", kafka_bootstrap_servers="kafka.rosdomofon.com:9092", company_short_name="Video_SB", kafka_group_id="my_consumer_group", kafka_username="kafka_user", kafka_password="kafka_pass", kafka_ssl_ca_cert_path="/path/to/ca-cert.pem", cache_file="entrances_cache.json" # Кэш подъездов для ускорения поиска ) api.authenticate() ``` -------------------------------- ### Set Up Synchronous Company Sign-up Handler Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Defines a synchronous handler for company-specific sign-up events from the SIGN_UPS_ topic. This handler processes new registrations within the company and sends a welcome message to the new subscriber. ```python # Синхронный обработчик регистраций компании def handle_company_signup(signup: SignUpEvent): print(f"[SIGN_UPS_] Новая регистрация в нашей компании: {signup.abonent.phone}") print(f"Адрес: {signup.address.city}, ул.{signup.address.street.name}, д.{signup.address.house.number}") # Отправить приветственное сообщение api.send_message_to_abonent( signup.abonent.id, 'support', 'Добро пожаловать в нашу компанию!' ) # Установка и запуск api.set_company_signup_handler(handle_company_signup) api.start_company_signup_consumer() ``` -------------------------------- ### Get Subscriber Conversation History Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieve the message history for a specific subscriber on a given channel. Supports pagination with 'page' and 'size' parameters. ```python # Получить переписку с абонентом messages = api.get_abonent_messages( abonent_id=1480844, channel='support', page=0, size=20 ) print(f"Всего сообщений: {messages.total_elements}") for msg in messages.content: direction = "Входящее" if msg.incoming else "Исходящее" print(f"[{direction}] {msg.message_date}: {msg.message}") print(f" От абонента: {msg.abonent.phone}") ``` -------------------------------- ### Async Signup Handling for Analytics Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Handles new signups asynchronously for analytics tracking and data enrichment. Requires `analytics` and `geo_service` modules. ```python async def handle_all_signups_async(signup: SignUpEvent): print(f"[Аналитика] Регистрация: {signup.abonent.phone}") # Асинхронная отправка в аналитику await analytics.track_signup_async(signup) # Асинхронное обогащение данных geo_data = await geo_service.get_location_info(signup.address.city) await analytics.track_geo(geo_data) ``` -------------------------------- ### Send Message to Abonnement Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Sends a push notification message to a specific subscriber. The message content can be dynamically generated, for example, by referencing previous messages. ```python api.send_message_to_abonent(abonent_id, 'support', f'вы написали {messages.content[0].message}') ``` -------------------------------- ### Create New Apartment Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Creates a new apartment with specified details like flat number, entrance ID, subscriber ID, and virtual status. Prints the ID and address of the newly created apartment. ```python flat = api.create_flat( flat_number="42", entrance_id="26959", # ID подъезда abonent_id=1574870, # ID абонента virtual=False # True если физическая трубка не установлена ) print(f"Создана квартира ID: {flat.id}") print(f"Адрес: {flat.address.city}, {flat.address.street.name}, д.{flat.address.house.number}") print(f"Владелец: {flat.owner.id}") ``` -------------------------------- ### Reply to Last Message in Conversation Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Reply to the most recent message in a subscriber's conversation. This example demonstrates replying to the first message in the fetched history. ```python # Ответить на последнее сообщение if messages.content: last_msg = messages.content[0] api.send_message_to_abonent( last_msg.abonent.id, 'support', f'Получено ваше сообщение: "{last_msg.message[:50]}"' ) ``` -------------------------------- ### Synchronous Signup Handler with Entrance Search Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Handles company signups synchronously, creating a flat and searching for the correct entrance based on address and flat number. Requires `RosDomofonAPI` and `SignUpEvent` models. Ensure `kafka-ca.crt` is accessible. ```python from rosdomofon import RosDomofonAPI from models import SignUpEvent api = RosDomofonAPI( username="user", password="pass", kafka_bootstrap_servers="kafka.rosdomofon.com:443", company_short_name="asd_asd", kafka_group_id="rosdomofon_group", kafka_username="kafka_user", kafka_password="kafka_pass", kafka_ssl_ca_cert_path="kafka-ca.crt" ) def handle_company_signup_with_flat(signup: SignUpEvent): print(f"[Регистрация] Новый абонент: {signup.abonent.phone}") print(f"Адрес: {signup.address.city}, ул.{signup.address.street.name}, д.{signup.address.house.number}") # Проверяем наличие номера квартиры if not signup.address.flat: print("⚠️ Номер квартиры не указан при регистрации") return # Ищем подъезд по адресу и квартире (с проверкой диапазонов) entrance = api.find_entrance_by_address_and_flat( city=signup.address.city, street=signup.address.street.name, house=signup.address.house.number, flat_number=signup.address.flat ) if not entrance: print("❌ Подъезд по этому адресу и квартире не найден") return entrance_id = str(entrance.id) try: # Создаем квартиру с найденным подъездом flat = api.create_flat( flat_number=str(signup.address.flat), entrance_id=entrance_id, abonent_id=signup.abonent.id, virtual=signup.virtual ) print(f"✅ Квартира создана: ID {flat.id}") # Отправляем приветственное сообщение api.send_message_to_abonent( signup.abonent.id, 'support', f'Добро пожаловать! Ваша квартира {signup.address.flat} успешно добавлена.' ) except Exception as e: print(f"❌ Ошибка создания квартиры: {e}") ``` -------------------------------- ### Use RosDomofonAPI with Context Manager Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Demonstrates using the RosDomofonAPI within a 'with' statement, ensuring the API client is properly closed after use. It also shows how to authenticate and fetch accounts. ```python # Контекстный менеджер для автоматического закрытия with RosDomofonAPI(username="user", password="pass") as api: auth = api.authenticate() accounts = api.get_accounts() ``` -------------------------------- ### Get Account Company Short Name Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Retrieve all accounts and iterate through them to print the short name of the associated company. Requires fetching account data first. ```python accounts = api.get_accounts() for account in accounts: print(account.company.short_name) ``` -------------------------------- ### Create Account with Validation Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Illustrates creating a new account with provided details, leveraging Pydantic for data validation. ```python # Создание аккаунта с валидацией response = api.create_account("ACC123456", "79061234567") account_id = response.id ``` -------------------------------- ### Get Entrance Information by ID Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Retrieves detailed information about a specific entrance using its ID, including its address, number of cameras, and RDA device UID if available. ```python entrance = api.get_entrance("30130") print(f"Подъезд ID: {entrance.id}") if entrance.address_string: print(f"Адрес: {entrance.address_string}") if entrance.cameras: print(f"Камеры: {len(entrance.cameras)}") for camera in entrance.cameras: if camera.uid and camera.uri: print(f" - Камера UID: {camera.uid}, URI: {camera.uri}") if entrance.rda: print(f"RDA устройство: {entrance.rda.uid}") ``` -------------------------------- ### Initialize RosDomofonAPI with Kafka Support Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Initializes the RosDomofonAPI client with authentication credentials and Kafka connection details, including bootstrap servers, group ID, and SSL certificate path. ```python from rosdomofon import RosDomofonAPI from models import KafkaIncomingMessage # Инициализация с Kafka поддержкой (с аутентификацией) api = RosDomofonAPI( username="user", password="pass", kafka_bootstrap_servers="kafka.rosdomofon.com:443", company_short_name="asd_asd", kafka_group_id="rosdomofon_group", kafka_username="kafka_user", kafka_password="kafka_pass", kafka_ssl_ca_cert_path="kafka-ca.crt" ) ``` -------------------------------- ### Initialize RosDomofonAPI as Context Manager Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Using RosDomofonAPI as a context manager ensures that connections are automatically closed upon exiting the 'with' block. Authentication is still required. ```python # Использование как контекстный менеджер with RosDomofonAPI(username="user", password="pass") as api: api.authenticate() accounts = api.get_accounts() # Соединения автоматически закроются при выходе ``` -------------------------------- ### Async Company Signup with Complex Logic Source: https://github.com/darkclaw921/rosdomofon/blob/master/rosdomofon/architecture.md Processes company signups asynchronously with complex logic, including sending welcome messages, creating CRM contacts, and sending emails in parallel. Requires `api_async`, `crm`, and `email_service` modules. ```python async def handle_our_signups_async(signup: SignUpEvent): print(f"[Приветствие] Наш новый клиент: {signup.abonent.phone}") # Параллельное выполнение нескольких задач await asyncio.gather( # Отправить приветствие api_async.send_message( signup.abonent.id, 'support', 'Добро пожаловать! Мы рады видеть вас в нашей компании!' ), # Создать контакт в CRM crm.create_contact(signup), # Отправить email email_service.send_welcome_email(signup.abonent.phone) ) ``` -------------------------------- ### Get Apartments for a Specific Entrance Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieves all apartments belonging to a particular entrance, identified by its ID. It then prints the flat number and owner's phone number for each apartment. ```python # Получить квартиры конкретного подъезда flats = api.get_entrance_flats("27222") print(f"В подъезде {len(flats)} квартир") for flat in flats: print(f" Кв. {flat.address.flat if flat.address else 'N/A'}: владелец {flat.owner.phone if flat.owner else 'N/A'}") ``` -------------------------------- ### Get Abonnement Flats Source: https://github.com/darkclaw921/rosdomofon/blob/master/README.md Retrieves all flats associated with a given subscriber ID. It iterates through the flats to print details like flat ID, address, and owner information. ```python # Получить все квартиры абонента flats = api.get_abonent_flats(1574870) print(f"Всего квартир: {len(flats)}") for flat in flats: print(f"ID квартиры: {flat.id}") print(f"Квартира {flat.address.flat}, подъезд {flat.address.entrance.number}") print(f"Адрес: {flat.address.city}, {flat.address.street.name} {flat.address.house.number}") print(f"Виртуальная: {flat.virtual}") print(f"Владелец: {flat.owner.id}") print("---") ``` -------------------------------- ### Initialize RosDomofon API and Kafka Consumer Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Initialize the RosDomofon API client with authentication credentials, Kafka server details, company information, and a Kafka consumer group ID. Ensure to call api.authenticate() after initialization. ```python from rosdomofon import RosDomofonAPI, SignUpEvent api = RosDomofonAPI( username="user", password="pass", kafka_bootstrap_servers="kafka.rosdomofon.com:9092", company_short_name="Video_SB", kafka_group_id="signup_processor" ) api.authenticate() ``` -------------------------------- ### Get Detailed Account Information Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Retrieve comprehensive details for a specific account, including balance, connected services, apartments, and delegations. Useful for displaying a full account profile. ```python # Получить детальную информацию об аккаунте account_info = api.get_account_info(904154) # Информация о балансе if account_info.balance: print(f"Баланс: {account_info.balance.balance} {account_info.balance.currency}") print(f"Дата баланса: {account_info.balance.balance_date}") print(f"Оплата доступна: {account_info.balance.is_payment_available}") # Информация о владельце print(f"Телефон владельца: {account_info.owner.phone}") print(f"Делегирования: {len(account_info.owner.delegations)}") # Информация о компании print(f"Компания: {account_info.company.name}") print(f"Телефон поддержки: {account_info.company.support_phone}") # Подключенные услуги for conn in account_info.connections: print(f"Услуга: {conn.service.name} ({conn.service.type})") print(f" Тариф: {conn.tariff} {conn.currency}") print(f" Заблокирована: {conn.blocked}") print(f" Квартира: {conn.flat.address.flat if conn.flat.address else 'N/A'}") ``` -------------------------------- ### Connect Service to Apartment Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Connects a specific service to an apartment for a given account. Requires service ID, flat ID, and account ID. Prints the ID of the newly created connection. ```python # Подключить услугу к квартире connection = api.connect_service( service_id=12345, flat_id=842554, account_id=904154 ) print(f"Создано подключение ID: {connection.id}") ``` -------------------------------- ### Initialize RosDomofonAPI (REST API Only) Source: https://context7.com/darkclaw921/rosdomofon/llms.txt Basic initialization of the RosDomofonAPI class for REST API interactions. Requires username and password for authentication. ```python from rosdomofon import RosDomofonAPI # Базовая инициализация (только REST API) api = RosDomofonAPI( username="your_username", password="your_password" ) # Авторизация в системе auth = api.authenticate() print(f"Токен получен: {auth.access_token[:20]}...") print(f"Действителен {auth.expires_in} секунд") ```