### Completion API Usage Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Example configuration for invoking the completion action. ```yaml action: completion params: prompt: "Explain the concept of quantum entanglement." model: "gpt-4" temperature: 0.7 ``` -------------------------------- ### Detailed YAML Configuration Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md A comprehensive example of a YAML configuration file detailing various settings, limits, features, and pricing tiers. ```yaml # Basic settings settings: max_users: 100 # Integer max_storage: 500 # Integer default_language: "en" # String allowed_languages: ["ru", "en", "de"] # String array enable_notifications: true # Boolean maintenance_mode: false # Boolean # Limits and restrictions limits: daily_requests: 1000 # Integer max_file_size: 10485760 # Integer (10 MB in bytes) rate_limit_per_minute: 30 # Integer discount_percentage: 10.5 # Float price_tiers: [9.99, 19.99, 29.99] # Float array # Features and capabilities features: enable_premium: true # Boolean enable_api: false # Boolean enable_webhooks: false # Boolean supported_regions: ["eu", "us", "asia"] # String array # Tariffs and prices pricing: base_price: 9.99 # Float premium_price: 29.99 # Float trial_days: 14 # Integer ``` -------------------------------- ### Practical Example: AI Processing Workflow Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md A comprehensive example demonstrating the use of asynchronous actions, readiness checks, and `wait_for_action` within a practical AI processing scenario. ```APIDOC ## Practical Example: AI Processing Workflow ### Description This example illustrates a common pattern for handling asynchronous AI requests, including displaying a loading indicator, polling for completion, and finally retrieving and displaying the AI's response. ### Method N/A (Scenario definition) ### Endpoint N/A ### Parameters N/A (This is a scenario definition, not an API endpoint) ### Request Example ```yaml ai_processing: description: "Processing AI request with loading indicator" trigger: - event_type: "message" event_text: "/ai" step: # Step 1: Launch AI request asynchronously - action: "completion" async: true action_id: "ai_req_1" params: prompt: "{event_text|regex:/ai\s+(.+)}" # Step 2: Send loading message - action: "send_message" params: text: "⏳ Processing request..." # Step 3: Delay before check - action: "sleep" params: seconds: 1.0 # 1 second delay between checks # Step 4: Check readiness via validation # Use placeholder {_async_action.ai_req_1|ready} to check action state - action: "validate" params: condition: "{_async_action.ai_req_1|ready} == True" transition: - action_result: "failed" transition_action: "move_steps" transition_value: -1 # Go back to delay step (step 3) if not ready yet # Step 5: Delete loading message (executes only when action ready) - action: "delete_message" params: delete_message_id: "{last_message_id}" # Step 6: Wait for AI result (get data into context) - action: "wait_for_action" params: action_id: "ai_req_1" timeout: 60 # 60 second timeout # response_data goes to flat _cache = {response_completion: "AI answer", prompt_tokens: 50, completion_tokens: 100} # Step 7: Send AI result - action: "send_message" params: text: "{_cache.response_completion|fallback:Processing error}" ``` ### Response #### Success Response (200) This example does not define a direct API response. The outcome is determined by the scenario's execution flow and the final `send_message` action. #### Response Example N/A ``` -------------------------------- ### View Initialization Order Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/PLUGINS_GUIDE.md Example of the topological order in which plugins are initialized based on their dependency graph. ```text 1. logger (foundation, no dependencies) 2. plugins_manager (foundation, depends on logger) 3. settings_manager (foundation, depends on logger) 4. tg_bot_api (telegram layer, depends on logger, settings_manager) 5. tg_permission_manager (telegram layer, depends on logger, tg_bot_api) 6. event_processor (core, depends on logger, settings_manager, database_service) 7. chat_service (depends on logger, database_service, event_processor) ``` -------------------------------- ### Practical Example: Async AI Request Processing Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md This example demonstrates a complete workflow for processing an asynchronous AI request. It includes launching the request, sending a loading indicator, polling for readiness using validation and a delay loop, deleting the loading message, waiting for the final AI result, and sending the response. ```yaml ai_processing: description: "Processing AI request with loading indicator" trigger: - event_type: "message" event_text: "/ai" step: # Step 1: Launch AI request asynchronously - action: "completion" async: true action_id: "ai_req_1" params: prompt: "{event_text|regex:/ai\s+(.+)}" # Step 2: Send loading message - action: "send_message" params: text: "⏳ Processing request..." # Step 3: Delay before check - action: "sleep" params: seconds: 1.0 # 1 second delay between checks # Step 4: Check readiness via validation # Use placeholder {_async_action.ai_req_1|ready} to check action state - action: "validate" params: condition: "{_async_action.ai_req_1|ready} == True" transition: - action_result: "failed" transition_action: "move_steps" transition_value: -1 # Go back to delay step (step 3) if not ready yet # Step 5: Delete loading message (executes only when action ready) - action: "delete_message" params: delete_message_id: "{last_message_id}" # Step 6: Wait for AI result (get data into context) - action: "wait_for_action" params: action_id: "ai_req_1" timeout: 60 # 60 second timeout # response_data goes to flat _cache = {response_completion: "AI answer", prompt_tokens: 50, completion_tokens: 100} # Step 7: Send AI result - action: "send_message" params: text: "{_cache.response_completion|fallback:Processing error}" ``` -------------------------------- ### Unit Test Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/TESTING_GUIDE.md An example of a unit test for ConditionParser. It uses a pytest fixture for setup and asserts the result of a matching operation. ```python # plugins/utilities/core/condition_parser/tests/test_baseline.py import pytest from plugins.utilities.core.condition_parser.condition_parser import ConditionParser @pytest.fixture def parser(logger): return ConditionParser(logger=logger) @pytest.mark.asyncio async def test_condition_parser(parser): result = await parser.check_match("$x == 1", {"x": 1}) assert result is True ``` -------------------------------- ### Install Python Test Dependencies Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/TESTING_GUIDE.md Installs test dependencies, including main project modules and pytest, from the tests/requirements.txt file. ```bash pip install -r tests/requirements.txt ``` -------------------------------- ### Foundation Logger Implementation Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/PLUGINS_GUIDE.md Example of a foundation utility using only standard Python libraries. ```python # ✅ Correct: logger uses only system libraries import logging import sys from datetime import datetime class Logger: def __init__(self): # Only Python system libraries pass ``` -------------------------------- ### YAML Configuration Structure Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md Illustrates the hierarchical structure of a typical configuration file, including settings, limits, and features. ```yaml storage/ ├── config.yaml # Arbitrary file name │ settings: │ max_users: 100 │ default_language: "en" │ limits: │ daily_requests: 1000 │ max_file_size: 10485760 │ └── additional.yaml # Another file for additional settings features: enable_premium: true enable_api: false ``` -------------------------------- ### Configure Plugin Dependencies Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/PLUGINS_GUIDE.md YAML configuration examples for defining required and optional dependencies for utilities and services. ```yaml # Foundation utility (logger) # dependencies: absent (uses only system libraries) # Custom layer utility (tg_bot_api) dependencies: - "logger" # Foundation utility - "settings_manager" # Foundation utility # Service (chat_service) dependencies: - "logger" # Foundation utility - "database_service" # Core utility - "event_processor" # Core utility # Plugin with optional dependencies (any type) dependencies: - "logger" # Required dependency - "hash_manager" # Required dependency optional_dependencies: - "cache_service" # Optional dependency - "analytics_service" # Optional dependency ``` -------------------------------- ### Define Start Scenario Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/getting-started/EXAMPLES_GUIDE.md Create a trigger for the /start command and define the bot's response, including placeholders, inline buttons, and file attachments. ```yaml start: trigger: - event_type: "message" event_text: "/start" step: - action: "send_message" params: text: | 👋 Hello, {first_name|fallback:friend}! Welcome to the bot! inline: - [{"📋 Menu": "menu"}, {"📚 Help": "help"}] # Attach file (optional) # Can use file_id from event: {event_attachment[0].file_id} attachment: - file_id: "AgACAgIAAxkBAAIUJWjyLorr_d8Jwof3V_gVjVNdGHyXAAJ--zEb4vGQS-a9UiGzpkTNAQADAgADeQADNgW" type: "photo" ``` -------------------------------- ### Universal Transition 'any' Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Demonstrates the 'any' transition which executes regardless of the action result and has the highest priority, preventing other transitions from executing. ```yaml step: - action: "send_message" params: text: "Message sent" transition: - action_result: "any" # Executes regardless of result transition_action: "abort" # Always interrupt execution - action_result: "success" transition_action: "continue" # ❌ This transition won't execute due to "any" - action_result: "error" transition_action: "continue" # ❌ This transition won't execute due to "any" ``` -------------------------------- ### Integration Test Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/TESTING_GUIDE.md An example of an integration test that verifies dependency resolution within the DI container. It checks if a specific utility can be retrieved. ```python # tests/integration/test_di_container.py import pytest @pytest.mark.asyncio async def test_di_resolves_dependencies(initialized_di_container): db_manager = initialized_di_container.get_utility("database_manager") assert db_manager is not None ``` -------------------------------- ### User Storage Flat Structure Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md Demonstrates the flat key-value structure of User Storage, suitable for storing individual user settings and preferences. ```yaml language: "en" theme: "dark" messages_sent: 150 favorite_colors: ["red", "blue", "green"] user_preferences: language: "en" theme: "dark" notifications: true ``` -------------------------------- ### Implement complete payment flow Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/getting-started/EXAMPLES_GUIDE.md A comprehensive example covering invoice creation, pre-checkout query handling, and final payment success processing. ```yaml # 1. Invoice creation create_payment: description: "Creating invoice for payment" trigger: - event_type: "message" event_text: "/buy" step: - action: "create_invoice" params: title: "Premium Subscription" description: "Access to premium features for 1 month" amount: 100 currency: "XTR" # 2. Handling pre_checkout_query (payment confirmation) handle_pre_checkout: description: "Handling payment confirmation request" trigger: - event_type: "pre_checkout_query" step: # Confirm payment (with automatic status check) - action: "confirm_payment" params: pre_checkout_query_id: "{pre_checkout_query_id}" invoice_payload: "{invoice_payload}" # Automatic status check # 3. Handling payment_successful (final processing) handle_payment_successful: description: "Handling successful payment" trigger: - event_type: "payment_successful" step: # Mark invoice as paid - action: "mark_invoice_as_paid" params: invoice_payload: "{invoice_payload}" telegram_payment_charge_id: "{telegram_payment_charge_id}" # Send confirmation - action: "send_message" params: text: | ✅ Payment successfully processed! Thank you for your purchase! # Activate subscription (example) - action: "set_user_storage" params: key: "premium_active" value: true ``` -------------------------------- ### Logging Statuses and Group Counts Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/LOGGING_GUIDE.md Provides examples of using parentheses for logging statuses and additional information like group counts. ```python self.logger.info(f"[Tenant-137] Synchronization (3 groups)") self.logger.warning(f"[Bot-1] Missing token (polling not started)") ``` -------------------------------- ### Simple Trigger Conditions Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/EVENT_GUIDE.md YAML configuration examples for filtering events based on type, text, callback data, or user state. ```yaml # Check event type trigger: - event_type: "message" # Check message text trigger: - event_type: "message" event_text: "/start" # Check callback data trigger: - event_type: "callback" callback_data: "menu_main" # Check user state trigger: - event_type: "message" user_state: "feedback" ``` -------------------------------- ### Define a User Registration Scenario Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md A complete example of a registration scenario featuring triggers, sequential steps, conditional transitions, and file attachments. ```yaml user_registration: description: "User registration process with validation and notifications" # TRIGGERS: Each works independently - any of them will launch scenario trigger: - event_type: "message" # Command /register event_text: "/register" - event_type: "callback" # Button "Start Registration" callback_data: "start_registration" # STEPS: Executed sequentially one after another step: # Step 1: Send greeting - action: "send_message" params: text: | 👋 Welcome, {username|fallback:Guest}! Let's register you in the system. inline: - [{"✅ Continue": "continue_registration"}] # Step 2: Check user permissions with transitions - action: "validate" params: condition: "$user_role == 'admin'" transition: - action_result: "success" transition_action: "jump_to_scenario" transition_value: "admin_welcome" # Transition to admin welcome - action_result: "error" transition_action: "continue" # Normal flow for users # Step 3: Request name - action: "send_message" params: text: | 📝 Step 2 of 3 Please enter your name: inline: - [{"❌ Cancel": "cancel_registration"}] # Step 4: Send confirmation with attachments - action: "send_message" params: text: | ✅ Registration started! We sent you instructions via email. 📎 Also attaching useful materials: attachment: - file_id: "AgACAgIAAxkBAAIUJWjyLorr_d8Jwof3V_gVjVNdGHyXAAJ--zEb4vGQS-a9UiGzpkTNAQADAgADeQADNgW" type: "photo" - file_id: "AgACAgIAAxkBAAIUQWjyOH65wQYR4onkrrqM4J65yUD7AAM8-zEb4vGQS1mwvckFcZHlAQADAgADdwADNgQ" type: "photo" inline: - [{"🏠 Main Menu": "main_menu"}] # Step 5: Delete previous message - action: "delete_message" params: delete_message_id: "{last_message_id}" # Use previous message ID admin_welcome: description: "Admin welcome (transition scenario)" # NO TRIGGERS - called only programmatically step: - action: "send_message" params: text: | 🔧 Welcome, administrator! You have additional permissions. inline: - [{"⚙️ Control Panel": "admin_panel"}] ``` -------------------------------- ### Dynamic Keyboard with Expand Modifier Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/PLACEHOLDERS.md This example shows how to build an inline keyboard dynamically from a list of public tenants and then combine it with a static 'Back' button using the 'expand' modifier. ```yaml step: # Get tenant list - action: "get_tenants_list" params: {} # Build dynamic keyboard from public tenants - action: "build_keyboard" params: items: "{public_tenant_ids}" keyboard_type: "inline" text_template: "Tenant $value$" callback_template: "select_tenant_$value$" buttons_per_row: 2 # Send message with dynamic keyboard + static buttons - action: "send_message" params: text: "Select tenant:" inline: - "{keyboard|expand}" # Expand dynamic keyboard - [{"🔙 Back": "main_menu"}] # Static button ``` -------------------------------- ### Example Scenario File Structure Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Organize your scenario YAML files in folders and subfolders within the 'scenarios/' directory. All YAML files are automatically loaded recursively. ```yaml tenant_101/ scenarios/ commands.yaml # Scenarios: start, menu, help settings.yaml # Scenarios: settings, profile admin/ # Subfolder for organization panel.yaml # Scenarios: admin_panel, logs moderation.yaml # Scenarios: ban, kick users/ # Another subfolder profile.yaml # Scenarios: user_profile, edit_profile ``` -------------------------------- ### Get available actions Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Retrieves all available actions with metadata. Parameters are not required for this action. ```yaml # In scenario - action: "get_available_actions" params: # Parameters not required ``` -------------------------------- ### Retrieving File Information in Scenarios Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/PLACEHOLDERS.md Example of a scenario step that extracts file_id and type from event or reply attachments with fallback logic. ```yaml file_info: description: "Getting file_id and type of attachments for subsequent forwarding" trigger: - event_type: "message" event_text: "/file" step: - action: "send_message" params: text: | 📎 File information: file_id: {event_attachment[0].file_id|fallback:{reply_attachment[0].file_id|fallback:File not found}} type: {event_attachment[0].type|fallback:{reply_attachment[0].type|fallback:Type not found}} ``` -------------------------------- ### Flat Caching Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Demonstrates how data is merged directly into `_cache` with flat caching. Access data using `{_cache.field}`. This is the default behavior. ```yaml step: - action: "generate_int" params: min: 1 max: 100 # response_data: {"random_value": 42, "random_seed": 123} # Goes to: _cache.random_value = 42, _cache.random_seed = 123 - action: "send_message" params: text: "Number: {_cache.random_value}" # ✅ CORRECT ``` -------------------------------- ### Getting User Storage Values via Scenario Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md Demonstrates how to retrieve all user storage values using the 'get_user_storage' action and display them in a message. ```yaml show_user_preferences: description: "Show user preferences" trigger: - event_type: "callback" callback_data: "show_preferences" step: # Get all values in one request - action: "get_user_storage" - action: "send_message" params: text: | 👤 Your settings Language: {_cache.user_storage_values.language|fallback:not set} Theme: {_cache.user_storage_values.theme|fallback:not set} ``` -------------------------------- ### Run Core Manager Utility Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/getting-started/DEPLOYMENT.md Execute the Core Manager utility from the tools directory. This script is essential for initial setup and ongoing management of the Coreness platform. ```bash python tools/core_manager/core_manager.py ``` -------------------------------- ### Using Response Key for Replacement (YAML) Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/PLUGIN_CONFIG_GUIDE.md Example of using 'response_key' in an action to specify where a replaceable field's value should be stored in the cache. ```yaml # In config.yaml output: response_data: properties: user_storage_values: type: any replaceable: true description: "User data" # In scenario - action: "get_user_storage" params: key: "active_tenant_id" response_key: "active_tenant_id" # Value will be in _cache.active_tenant_id ``` -------------------------------- ### Tenant Storage File Structure Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md Illustrates how to structure tenant storage configuration files using YAML. Data is grouped by keys within files, and multiple files can be used for logical organization. ```yaml # storage/config.yaml - file name doesn't matter settings: max_users: 100 max_storage: 500 default_language: "en" limits: daily_requests: 1000 max_file_size: 10485760 ``` -------------------------------- ### Get Invoice API Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Retrieves information about a specific invoice. ```APIDOC ## POST /get_invoice ### Description Get invoice info ### Method POST ### Endpoint /get_invoice ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **invoice_id** (integer) - Required - Invoice ID (required) - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. ### Request Example ```yaml { "invoice_id": 123 } ``` ### Response #### Success Response (200) - **result** (string) - Result: success, error - **response_data** (object) - Response data - **invoice** (object) - Invoice data #### Error Response - **result** (string) - Result: success, error - **error** (object) - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) - Optional - Error details #### Response Example ```json { "result": "success", "response_data": { "invoice": { "invoice_id": 123, "title": "Example Product", "amount": 100, "currency": "XTR", "status": "pending" } } } ``` ``` -------------------------------- ### Attachment Object Structure Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/EVENT_GUIDE.md Example of the JSON structure for an attachment object. ```json { "type": "photo", "file_id": "AgACAgIAAxkBAAIB..." } ``` -------------------------------- ### GET /openai/models Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/AI_MODELS_GUIDE.md Retrieves the list of available OpenAI models and their technical specifications. ```APIDOC ## GET /openai/models ### Description Returns a list of supported OpenAI models, including details on context window, modalities, and pricing. ### Method GET ### Endpoint /openai/models ### Response #### Success Response (200) - **models** (array) - A list of model objects containing: - **name** (string) - The model identifier (e.g., openai/gpt-4o) - **context** (string) - The context window size - **modalities** (string) - Supported input/output types - **price** (string) - Pricing information - **parameters** (string) - Supported features/capabilities ``` -------------------------------- ### start_telegram_bot Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Starts a Telegram bot using either polling or webhook methods. ```APIDOC ## start_telegram_bot ### Description Start Telegram bot (polling or webhook) ### Parameters #### Request Body - **bot_id** (integer) - Required - Bot ID ### Response #### Success Response (200) - **result** (string) - Result: success, error - **error** (object) - Optional - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) - Optional - Error details ``` -------------------------------- ### Access Tenant Configuration Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Demonstrates automatic parameter injection from tenant configuration and manual access via placeholders. ```yaml step: - action: "completion" params: prompt: "Hello, how are you?" # ai_token automatically taken from _config.ai_token # No need to specify ai_token explicitly! ``` ```yaml step: - action: "send_message" params: text: | Tenant configuration: Token: {_config.ai_token|fallback:Not set} ``` -------------------------------- ### Get Tenant Users API Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Retrieves a list of all user IDs for a given tenant. ```APIDOC ## GET /vensus137/coreness-docs/get_tenant_users ### Description Get list of all user_id for tenant ### Method GET ### Endpoint /vensus137/coreness-docs/get_tenant_users ### Parameters #### Query Parameters - **tenant_id** (integer) - Required - Tenant ID - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. - **_response_key** (string) - Optional - Custom name for main result field (marked 🔀). ### Response #### Success Response (200) - **result** (string) - Result: success, error - **error** (object) (optional) - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) (optional) - Error details - **response_data** (object) - - 🔀 **user_ids** (array (of integer)) - Array of Telegram user IDs - **user_count** (integer) - Number of users ### Response Example ```json { "result": "success", "response_data": { "user_ids": [123, 456], "user_count": 2 } } ``` ``` -------------------------------- ### Get User Invoices API Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Retrieves a list of all invoices associated with a specific user. ```APIDOC ## POST /get_user_invoices ### Description Get all user invoices ### Method POST ### Endpoint /get_user_invoices ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **target_user_id** (integer) - Optional - User ID for invoices (optional; default from event user_id) - **include_cancelled** (boolean) - Optional - Include cancelled invoices (default false) - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. ### Request Example ```yaml { "target_user_id": 456 } ``` ### Response #### Success Response (200) - **result** (string) - Result: success, error - **response_data** (object) - Response data - **invoices** (array (of object)) - Array of user invoices #### Error Response - **result** (string) - Result: success, error - **error** (object) - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) - Optional - Error details #### Response Example ```json { "result": "success", "response_data": { "invoices": [ { "invoice_id": 1, "title": "Product A", "amount": 50, "status": "paid" }, { "invoice_id": 2, "title": "Service B", "amount": 75, "status": "pending" } ] } } ``` ``` -------------------------------- ### Plugin Management Logic Cases Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SETTINGS_CONFIG_GUIDE.md Demonstrates how the system interprets different plugin management configurations. ```yaml plugin_management: services: default_enabled: true # All services enabled by default disabled_services: [] # Exceptions (disabled) enabled_services: [] # Explicitly enabled (if default_enabled: false) utilities: default_enabled: true # All utilities enabled by default disabled_utilities: [] # Exceptions (disabled) enabled_utilities: [] # Explicitly enabled (if default_enabled: false) ``` ```yaml # No plugin_management section at all ``` ```yaml plugin_management: services: default_enabled: false # All disabled by default enabled_services: # Explicitly enable only needed - "logger" - "database_service" ``` -------------------------------- ### Define a Scheduled Scenario Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Example of a scenario configured to run on a schedule using a cron expression. ```yaml daily_report: description: "Daily report at 9:00" # Cron expression for launch every day at 9:00 schedule: "0 9 * * *" # Triggers optional - scenario will work on schedule # Can add triggers for hybrid mode (on events AND on schedule) step: - action: "send_message" params: target_chat_id: 123456789 text: | 📊 Daily Report Launch time: {scheduled_at|format:datetime} Scenario: {scheduled_scenario_name} ``` -------------------------------- ### Build Keyboard Action Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Configures a keyboard layout using templates for button text and callbacks. ```yaml # In scenario - action: "build_keyboard" params: items: [] keyboard_type: "example" text_template: "example" # callback_template: string (optional) # buttons_per_row: integer (optional) ``` -------------------------------- ### Define Scenario Triggers Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/SCENARIO_CONFIG_GUIDE.md Examples of simple and complex trigger configurations and their underlying condition logic. ```yaml trigger: - event_type: "message" event_text: "/start" ``` ```python $event_type == "message" and $event_text == "/start" ``` ```yaml trigger: - event_type: "message" condition: | $event_text == "test" and $user_id > 100 or $username in ('@admin', '@moderator') ``` ```python $event_type == "message" and ($event_text == "test" and $user_id > 100 or $username in ('@admin', '@moderator')) ``` -------------------------------- ### Correct Tenant and Bot Logging Hierarchy Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/LOGGING_GUIDE.md Demonstrates the correct hierarchical order for logging context, ensuring Tenant is logged before Bot. ```python # ✅ Correct self.logger.info(f"[Tenant-{tenant_id}] [Bot-{bot_id}] Bot updated") # ❌ Incorrect self.logger.info(f"[Bot-{bot_id}] [Tenant-{tenant_id}] Bot updated") ``` -------------------------------- ### Tenant Storage Synchronization Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/STORAGE_CONFIG_GUIDE.md Explains the database synchronization process for Tenant Storage. Groups present in the configuration are fully synchronized (deleted and reloaded), while groups absent in the configuration remain untouched in the database. ```text If DB has groups: settings, limits, features, old_group And config has only: settings, limits, features Then during synchronization: - ✅ settings, limits, features — will be deleted and reloaded from config - ✅ old_group — will remain untouched in DB (won't be deleted) ``` -------------------------------- ### Disable Heavy Services for Testing Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SETTINGS_CONFIG_GUIDE.md Example of disabling specific resource-intensive services during test runs. ```yaml # config/settings.yaml plugin_management: services: disabled_services: - "gigachat_service" - "salute_speech" - "promo_manager" ``` -------------------------------- ### Start Telegram Bot Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Initiates the Telegram bot using either polling or webhook methods. ```yaml # In scenario - action: "start_telegram_bot" params: bot_id: 123 ``` -------------------------------- ### Personalized Greeting Example Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/PLACEHOLDERS.md Uses fallback modifiers to provide default values for user profile fields. ```yaml step: - action: "send_message" params: text: | 👋 Hello, {username|fallback:Guest}! 📊 Your statistics: • ID: {user_id} • Chats: {chat_count|fallback:0} • Last login: {last_login|format:datetime|fallback:Unknown} ``` -------------------------------- ### Correct Keyboard Expansion with Expand Modifier Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/PLACEHOLDERS.md This example shows the correct way to use the 'expand' modifier to flatten the dynamically generated keyboard rows, allowing for proper integration with static buttons. ```yaml inline: - "{keyboard|expand}" # ✅ Gets [[...], [...]] - 2 nesting levels - [{"🔙 Back": "main_menu"}] ``` -------------------------------- ### POST build_keyboard Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Builds a keyboard from an array of IDs using specified templates for text and callbacks. ```APIDOC ## POST build_keyboard ### Description Build keyboard from ID array using templates. ### Parameters #### Request Body - **items** (array) - Required - Array of IDs for button generation - **keyboard_type** (string) - Required - Keyboard type (inline or reply) - **text_template** (string) - Required - Text template with $value$ placeholder - **callback_template** (string) - Optional - Callback data template for inline - **buttons_per_row** (integer) - Optional - Buttons per row - **_namespace** (string) - Optional - Custom key for creating nesting in _cache ### Response #### Success Response (200) - **result** (string) - Build result - **response_data** (object) - Keyboard data - **keyboard** (array) - Array of button rows - **keyboard_type** (string) - Keyboard type - **rows_count** (integer) - Number of rows - **buttons_count** (integer) - Number of buttons ``` -------------------------------- ### Bad Logging Practices Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/LOGGING_GUIDE.md Highlights an example of poor logging by including excessive internal process details. ```python # ❌ Bad: too many internal process details self.logger.info(f"[Tenant-{tenant_id}] Starting scenario parsing, checking files, reading configuration...") ``` -------------------------------- ### Accessing Data with Placeholders Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/PLACEHOLDERS.md Demonstrates various ways to access object fields, array elements, and tenant configuration values within parameters. ```yaml params: # Objects text: "Message: {message.text}" text: "User: {user.profile.name|fallback:Unknown}" # Arrays text: "First file: {attachment[0].file_id}" text: "Last user: {users[-1].name|upper}" text: "File: {attachment[0].file_id}, size: {attachment[0].size}" # Combined access text: "Event: {event.attachment[0].type}" text: "Data: {response.data.items[0].value}" # Tenant configuration text: "Token: {_config.ai_token|fallback:Not set}" # Safe access text: "{attachment[10].file_id|fallback:File not found}" ``` -------------------------------- ### Get Storage Groups Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Retrieves a list of unique group keys for a tenant. The list is limited by the `storage_groups_max_limit`. ```APIDOC ## GET /storage/groups ### Description Get list of unique group keys for tenant. Returns group_key list only (limited by storage_groups_max_limit) ### Method GET ### Endpoint /storage/groups ### Parameters #### Query Parameters - **tenant_id** (integer) - Required - Tenant ID (min: 1) - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. If specified, data is saved in `_cache[_namespace]` instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via `{_cache._namespace.field}`. By default, data is merged directly into `_cache` (flat caching). - **_response_key** (string) - Optional - Custom name for main result field (marked 🔀). If specified, main field will be saved in `_cache` under specified name instead of standard. Access via `{_cache.{_response_key}}`. Works only for actions that support renaming main field. ### Response #### Success Response (200) - **result** (string) - Result: success, error - **error** (object) - Optional - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) - Optional - Error details - **response_data** (object) - - 🔀 **group_keys** (array (of string)) - List of unique group keys (limited by storage_groups_max_limit) - **is_truncated** (boolean) - Optional - Flag that list was truncated (true if more groups than limit) ### Response Example ```json { "result": "success", "response_data": { "group_keys": ["group1", "group2"], "is_truncated": false } } ``` ``` -------------------------------- ### Get Bot ID by Tenant ID Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Retrieves the database identifier for a bot associated with a specific tenant. ```yaml # In scenario - action: "get_bot_id_by_tenant_id" params: tenant_id: 123 # bot_type: string (optional) ``` -------------------------------- ### Get User State API Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Retrieves the state of a user within a specific tenant, including an expiry check. ```APIDOC ## GET /vensus137/coreness-docs/get_user_state ### Description Get user state with expiry check ### Method GET ### Endpoint /vensus137/coreness-docs/get_user_state ### Parameters #### Query Parameters - **user_id** (integer) - Required - Telegram user ID - **tenant_id** (integer) - Required - Tenant ID - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. - **_response_key** (string) - Optional - Custom name for main result field (marked 🔀). ### Response #### Success Response (200) - **result** (string) - Result: success, error - **error** (object) (optional) - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) (optional) - Error details - **response_data** (object) - Response data - 🔀 **user_state** (string) (optional) - User state or None if expired/not set - **user_state_expired_at** (string) (optional) - State expiry time (ISO) or None if not set ### Response Example ```json { "result": "success", "response_data": { "user_state": "active", "user_state_expired_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Project Folder Structure Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/PLUGINS_GUIDE.md The standard directory layout for organizing plugins and services within the project. ```text plugins/ ├── utilities/ # Supporting utilities │ ├── foundation/ # Fundamental utilities (logger, plugins_manager) │ ├── custom_layers/ # Thematic layers (telegram, api, database) │ ├── core/ # Core utilities (event_processor, database_service) │ └── extensions/ # Utility extensions (not included in base platform version) └── services/ # Business services ├── core/ # Core services ├── hub/ # Hub services ├── additional/ # Additional services └── extensions/ # Service extensions (not included in base platform version) ``` -------------------------------- ### Get Telegram Bot Info by ID API Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Retrieves Telegram bot information from the database, with caching support. ```APIDOC ## get_telegram_bot_info_by_id ### Description Get Telegram bot info from database by bot_id (with caching) ### Method GET ### Endpoint /get_telegram_bot_info_by_id ### Parameters #### Path Parameters None #### Query Parameters - **bot_id** (integer) - Required - Bot ID - **force_refresh** (boolean) - Optional - Force refresh cache - **_namespace** (string) - Optional - Custom key for creating nesting in `_cache`. #### Request Body None ### Request Example { "bot_id": 123, "force_refresh": false } ### Response #### Success Response (200) - **result** (string) - Request result - **error** (object) (optional) - Error structure - **code** (string) - Error code - **message** (string) - Error message - **details** (array) (optional) - Error details - **response_data** (object) - Bot data from database - **bot_id** (integer) - Bot ID - **telegram_bot_id** (integer) - Bot ID in Telegram - **tenant_id** (integer) - Tenant ID - **bot_token** (string) - Bot token - **username** (string) - Bot username - **first_name** (string) - Bot first name - **is_active** (boolean) - Whether bot is active - **bot_command** (array) - Bot commands #### Response Example { "result": "success", "response_data": { "bot_id": 123, "telegram_bot_id": 456, "tenant_id": 789, "bot_token": "...", "username": "my_bot", "first_name": "My Bot", "is_active": true, "bot_command": ["start", "help"] } } ``` -------------------------------- ### Create Invoice Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/reference/ACTION_GUIDE.md Use this action to create an invoice in the database and optionally send it or create a payment link. Ensure all required parameters like tenant_id, bot_id, title, and amount are provided. ```yaml # In scenario - action: "create_invoice" params: tenant_id: 123 bot_id: 123 # target_user_id: integer (optional) # chat_id: integer (optional) title: "example" description: "example" amount: 123 # currency: string (optional) # as_link: boolean (optional) ``` -------------------------------- ### Good Logging Practices Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/LOGGING_GUIDE.md Illustrates effective logging practices including brevity, focus on the current function, and clear error reporting. ```python # ✅ Good: brief, about current function self.logger.info(f"[Tenant-{tenant_id}] Parsing scenarios...") # ✅ Good: process start and end self.logger.info(f"[Tenant-{tenant_id}] Updating data from GitHub...") # ... process ... self.logger.info(f"[Tenant-{tenant_id}] GitHub data updated") # ✅ Good: with count specified self.logger.info(f"[Tenant-{tenant_id}] Synchronizing {groups_count} scenario groups...") # ✅ Good: error with description self.logger.error(f"[Tenant-{tenant_id}] Scenario synchronization error: {error}") ``` -------------------------------- ### Get Telegram Bot Status Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Checks the current operational status of a Telegram bot, including polling and webhook activity. ```yaml # In scenario - action: "get_telegram_bot_status" params: bot_id: 123 ``` -------------------------------- ### Get Telegram Bot Info Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/SYSTEM_ACTION_GUIDE.md Retrieves bot information from the database using a bot ID, with optional cache refreshing. ```yaml # In scenario - action: "get_telegram_bot_info_by_id" params: bot_id: 123 # force_refresh: boolean (optional) ``` -------------------------------- ### Logging Multiple Contexts Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/advanced/LOGGING_GUIDE.md Illustrates how to log multiple contexts by separating them with spaces. ```plaintext [Tenant-1] [Bot-2] Command synchronization [Queue-system] Processing task ``` -------------------------------- ### Configure Tenant Settings Source: https://github.com/vensus137/coreness-docs/blob/main/docs/en/guides/TENANT_CONFIG_GUIDE.md General tenant configuration file for storing attributes like API keys. ```yaml # Tenant configuration ai_token: "sk-or-v1-..." # AI API key for tenant (optional) ```