### SaluteBot Entity Extraction Examples Source: https://context7.com/baslie/salutebot-docs/llms.txt Demonstrates how to extract and validate various data types from user input using system and custom entities in SaluteBot. Includes examples for phone numbers, cities, quantities, custom dictionaries, and free text. ```javascript state: GetPhoneNumber q!: * $PHONE::userPhone * script: // Phone automatically extracted and validated $session.phone = $parseTree.userPhone; a: Спасибо! Ваш номер: {{$session.phone}} // Multiple entity extraction state: TravelRoute q!: * из $CITY::from * в $CITY::to * script: $session.departure = $parseTree.from; $session.destination = $parseTree.to; a: Маршрут: {{$session.departure}} → {{$session.destination}} // Number extraction state: CollectQuantity q!: * $NUMBER::quantity * (штук|единиц) * script: if ($parseTree.quantity > 0 && $parseTree.quantity <= 100) { $session.orderQuantity = $parseTree.quantity; $reactions.transition('/ConfirmOrder'); } else { $reactions.answer('Количество должно быть от 1 до 100'); } // Custom entity from CSV dictionary // File: entities/pizzaTypes.csv // Content: // "Маргарита,Margherita" // "Пепперони,Pepperoni" // "Четыре сыра,Four Cheese" state: SelectPizzaType q!: * $pizzaTypes::pizzaName * script: $session.selectedPizza = $parseTree.pizzaName; a: Отличный выбор - {{$session.selectedPizza}}! // Text extraction (greedy match) state: FreeTextComment q!: комментарий $TEXT::comment script: $session.orderComment = $parseTree.comment; a: Комментарий сохранен: {{$session.orderComment}} // Available system entities: // $TEXT, $NUMBER, $FLOATNUMBER, $PHONE, $CITY, $EMAIL // Date/time entities for temporal expressions ``` -------------------------------- ### HTTP GET Request (JavaScript) Source: https://context7.com/baslie/salutebot-docs/llms.txt Performs an HTTP GET request to retrieve product information. It includes setting custom headers and handling the response, including checking if the request was successful and displaying the product name or an error message. Dependencies include the `$http` and `$injector` services. ```javascript // Code/DSL: HTTP Request in script state: CreateOrder script: // GET request $http.get("https://api.example.com/products/123", { headers: { "API-Key": $injector.apiKey } }).then(function(response) { if (response.isOk) { $session.product = response.data; $reactions.answer("Товар: " + response.data.name); } else { $reactions.answer("Ошибка: " + response.statusCode); } }); ``` -------------------------------- ### Simplified Message Send (GET) Source: https://context7.com/baslie/salutebot-docs/llms.txt Simplified method for sending client requests using URL parameters, useful for quick testing or simple integrations. ```APIDOC ## GET /chatapi/bot/{token} ### Description Simplified method for sending client requests using URL parameters, useful for quick testing or simple integrations. ### Method GET ### Endpoint /chatapi/bot/{token} ### Parameters #### Path Parameters - **token** (string) - Required - Bot token for authentication. #### Query Parameters - **query** (string) - Required (if event is not provided) - The user's text query. - **event** (string) - Required (if query is not provided) - An event triggered by the user. - **userId** (string) - Required - Unique identifier for the user. ### Request Example ```bash # Send text query curl "https://api.salutebot.com/chatapi/bot/{token}?query=привет&userId=user123" # Send event curl "https://api.salutebot.com/chatapi/bot/{token}?event=startOrder&userId=user123" ``` ### Response #### Success Response (200) - **response** (string) - The bot's reply to the user. - **sessionId** (string) - The unique session identifier. #### Response Example ```json { "response": "Привет! Чем могу помочь?", "sessionId": "sess_123456" } ``` #### Error Responses - **400**: Required to pass either 'query' or 'event' in request. ``` -------------------------------- ### Simplified Message Send (GET) Source: https://context7.com/baslie/salutebot-docs/llms.txt A simplified method for sending client requests via URL parameters, suitable for quick testing or basic integrations. It supports sending text queries or events directly in the URL. ```bash # Send text query curl "https://api.salutebot.com/chatapi/bot/{token}?query=привет&userId=user123" # Send event curl "https://api.salutebot.com/chatapi/bot/{token}?event=startOrder&userId=user123" # Response (200 OK) { "response": "Привет! Чем могу помочь?", "sessionId": "sess_123456" } # Error: Missing required parameter # 400: Required to pass either 'query' or 'event' in request ``` -------------------------------- ### Get Pizza Price Helper Function Source: https://context7.com/baslie/salutebot-docs/llms.txt A JavaScript helper function to retrieve the price of a pizza based on its name. It uses a hardcoded object for pizza prices and defaults to 500 if the pizza is not found. ```javascript function getPizzaPrice(pizzaName) { var prices = { "Маргарита": 500, "Пепперони": 600, "Четыре сыра": 650, "Гавайская": 550 }; return prices[pizzaName] || 500; } ``` -------------------------------- ### Independent GigaChat Query (JavaScript) Source: https://context7.com/baslie/salutebot-docs/llms.txt This JavaScript example demonstrates how to perform an independent query with GigaChat, where conversation history is explicitly ignored by setting `noHistory: true`. This is suitable for single-turn, self-contained questions. It also shows the usage of the 'GigaChat-Lite' model, which is part of the free tier, and how to configure parameters like `temperature` for more deterministic output. ```javascript // No-history mode for independent queries state: IndependentQuery script: $llm.fetchRequest({ systemContent: "Ответь на вопрос пользователя кратко.", userContent: $request.query, noHistory: true, // Don't use conversation history llmModelSettings: { model: "GigaChat-Lite", // Free tier model temperature: 0.3, // More deterministic maxTokens: 256 } }).then(function(response) { if (response.isOk) { $reactions.answer(response.message); } }); ``` -------------------------------- ### Load Chat State (GET) Source: https://context7.com/baslie/salutebot-docs/llms.txt Retrieves the previously saved state of a chat application for a given user ID. This allows for resuming conversations or accessing stored session data, such as current screen and variables. ```bash curl "https://api.salutebot.com/chatapi/client/{token}/state?userId=user123" # Response (200 OK) { "userId": "user123", "state": { "currentScreen": "/orderConfirmation", "variables": { "cart": [ {"item": "Пицца Маргарита", "quantity": 2, "price": 500}, {"item": "Напиток Кола", "quantity": 1, "price": 100} ], "totalAmount": 1100, "deliveryAddress": "ул. Ленина, д. 10, кв. 5" }, "sessionStart": "2025-11-17T09:15:00Z", "lastInteraction": "2025-11-17T10:20:00Z" } } # 404: ChannelChat config not found or no saved state # 408: Request timeout ``` -------------------------------- ### GET /chatapi/client/{token}/history Source: https://context7.com/baslie/salutebot-docs/llms.txt Retrieves conversation history between the bot and a specific client. Supports pagination and date filtering. ```APIDOC ## GET /chatapi/client/{token}/history ### Description Retrieve conversation history between the bot and a specific client with pagination and date filtering support. ### Method GET ### Endpoint `https://api.salutebot.com/chatapi/client/{token}/history` ### Parameters #### Path Parameters - **token** (string) - Required - The authentication token for the client. #### Query Parameters - **userId** (string) - Required - The ID of the user whose chat history is being requested. - **limit** (integer) - Optional - The maximum number of messages to return. Defaults to 50. - **offset** (integer) - Optional - The number of messages to skip. Defaults to 0. - **from** (string, YYYY-MM-DD) - Optional - Start date for filtering history. - **to** (string, YYYY-MM-DD) - Optional - End date for filtering history. ### Request Example ```bash # Get recent history (last 50 messages) curl "https://api.salutebot.com/chatapi/client/{token}/history?userId=user123&limit=50" # Get history for specific date range curl "https://api.salutebot.com/chatapi/client/{token}/history?userId=user123&from=2025-11-01&to=2025-11-17&limit=100&offset=0" ``` ### Response #### Success Response (200 OK) - **userId** (string) - The ID of the user. - **total** (integer) - The total number of messages available. - **messages** (array) - An array of message objects. - **timestamp** (string) - The time the message was sent. - **direction** (string) - Direction of the message ('incoming' or 'outgoing'). - **text** (string) - The content of the message. - **type** (string) - The type of message (e.g., 'text'). - **buttons** (array, optional) - Array of buttons associated with the message. - **hasMore** (boolean) - Indicates if there are more messages available. #### Response Example ```json { "userId": "user123", "total": 45, "messages": [ { "timestamp": "2025-11-17T09:15:00Z", "direction": "incoming", "text": "Здравствуйте", "type": "text" }, { "timestamp": "2025-11-17T09:15:05Z", "direction": "outgoing", "text": "Здравствуйте! Чем могу помочь?", "type": "text", "buttons": ["Заказать", "Статус заказа"] }, { "timestamp": "2025-11-17T09:16:00Z", "direction": "incoming", "text": "Заказать пиццу", "type": "text" } ], "hasMore": false } ``` #### Error Responses - **400**: Invalid date range or pagination parameters. ``` -------------------------------- ### Check Order Status Helper Function Source: https://context7.com/baslie/salutebot-docs/llms.txt A JavaScript helper function that performs an HTTP GET request to check an order's status. It utilizes the `$http.get` method and processes the response to display the order status or handle potential issues. ```javascript function checkOrderStatus(orderId) { $http.get($injector.apiUrl + "/orders/" + orderId) .then(function(response) { if (response.isOk) { var status = response.data.status; $reactions.answer("Статус заказа: " + status); } }); } ``` -------------------------------- ### Check Order Status in SaluteBot Source: https://context7.com/baslie/salutebot-docs/llms.txt This snippet demonstrates how to check the status of an order using a bot. It defines states for checking the order and retrieving the order ID. The `checkOrderStatus` function makes an HTTP GET request to an API to fetch the status, dependent on the `orderId` input. ```javascript state: CheckOrder q: * (статус|где) * заказ * intent: /checkOrderStatus a: Введите номер заказа state: GetOrderId q: * $NUMBER::orderId * script: var orderId = $parseTree.orderId; checkOrderStatus(orderId); ``` -------------------------------- ### Get Chat History API Request Source: https://context7.com/baslie/salutebot-docs/llms.txt Retrieve conversation history between the bot and a specific client. Supports pagination and date filtering. Requires a client token and userId. Responses include message history and pagination details. ```bash # Get recent history (last 50 messages) curl "https://api.salutebot.com/chatapi/client/{token}/history?userId=user123&limit=50" # Get history for specific date range curl "https://api.salutebot.com/chatapi/client/{token}/history?userId=user123&from=2025-11-01&to=2025-11-17&limit=100&offset=0" ``` -------------------------------- ### Get Asynchronous Events API Request Source: https://context7.com/baslie/salutebot-docs/llms.txt Poll for asynchronous events from the server, useful for handling bot-initiated messages or system events. Requires a client token and userId, and a 'since' timestamp to filter events. Responses contain a list of events with their type, timestamp, and data. ```bash curl "https://api.salutebot.com/chatapi/events/{token}?userId=user123&since=1700220000" ``` -------------------------------- ### SmartApp DSL: Core Scenario Structure and Patterns Source: https://context7.com/baslie/salutebot-docs/llms.txt Defines the fundamental structure of a SmartApp DSL scenario, including module requirements, pattern definitions for user input matching, and the root theme for the conversational bot. It sets up the basic conversational flow and user interaction elements. ```javascript // main.sc - Main scenario file // Import required modules require: slotfilling/slotFilling.sc module = sys.zb-common require: patterns/commonPatterns.sc // Define patterns patterns: $hello = (привет|здравствуй|добрый день|hi|hello) $bye = (пока|до свидания|bye|goodbye) $yes = (да|конечно|ага|yes|yep) $no = (нет|не надо|no|nope) // Main theme (root) theme: / // Entry point state: Start q!: $hello [*] event: start script: // Initialize session $session.userId = $request.channelUserId; $session.startTime = new Date().toISOString(); $session.messageCount = 0; a: Здравствуйте! Я бот ресторана "Вкусная Пицца". Чем могу помочь? buttons: "Меню" -> /Menu "Заказать" -> /Order "Забронировать стол" -> /BookTable "Статус заказа" -> /CheckOrder // Menu branch state: Menu intent: /showMenu q: * меню * a: Наше меню: script: var menu = [ "🍕 Маргарита - 500₽", "🍕 Пепперони - 600₽", "🍕 Четыре сыра - 650₽", "🍕 Гавайская - 550₽", "🥤 Напитки - от 100₽" ]; $reactions.answer(menu.join("\n")); buttons: "Заказать" -> /Order "Назад" -> /Start // Order flow state: Order q: * (заказ|заказать) * intent: /startOrder a: Что хотите заказать? go!: /SelectPizza state: SelectPizza q: * $pizzaTypes::pizzaName * script: $session.selectedPizza = $parseTree.pizzaName; $session.pizzaPrice = getPizzaPrice($parseTree.pizzaName); a: {{$session.selectedPizza}} - {{$session.pizzaPrice}}₽ go!: /SelectQuantity state: SelectQuantity a: Сколько пицц? state: GetQuantity q: * $NUMBER::quantity * script: if ($parseTree.quantity > 0 && $parseTree.quantity <= 10) { $session.quantity = $parseTree.quantity; $session.totalAmount = $session.pizzaPrice * $session.quantity; $reactions.transition('/ConfirmOrder'); } else { $reactions.answer('Укажите от 1 до 10 пицц'); } // Order confirmation state: ConfirmOrder script: var summary = "Ваш заказ:\n" + $session.selectedPizza + " x " + $session.quantity + "\n" + "Сумма: " + $session.totalAmount + "₽\n\n" + "Подтверждаете?"; $reactions.answer(summary); buttons: "Да" -> /GetDeliveryInfo "Отменить" -> /CancelOrder // Collect delivery information state: GetDeliveryInfo q: $yes a: Укажите адрес доставки state: SaveAddress q: $TEXT::address script: $session.deliveryAddress = $parseTree.address; a: Ваш номер телефона? state: SavePhone q: * $PHONE::phone * script: $session.phone = $parseTree.phone; go!: /ProcessOrder // Process order (call external API) state: ProcessOrder script: $http.post($injector.apiUrl + "/orders", { headers: { "Authorization": "Bearer " + $injector.apiKey }, body: { pizza: $session.selectedPizza, quantity: $session.quantity, amount: $session.totalAmount, address: $session.deliveryAddress, phone: $session.phone } }).then(function(response) { if (response.isOk) { $session.orderId = response.data.orderId; $reactions.transition('/OrderSuccess'); } else { $reactions.transition('/OrderError'); } }); state: OrderSuccess a: Заказ №{{$session.orderId}} принят! Доставим через 45 минут. go!: /End state: CancelOrder q: $no a: Заказ отменен. Чем еще могу помочь? go!: /Start state: OrderError a: Ошибка создания заказа. Попробуйте позже или обратитесь к оператору. buttons: "Повторить" -> /Order "Оператор" -> /TransferToOperator // Table booking state: BookTable q: * (забронировать|бронь) * стол * intent: /bookTable a: На сколько человек и на какое время? go!: /CollectBookingSlots ``` -------------------------------- ### Configure SaluteBot Project Settings in YAML Source: https://context7.com/baslie/salutebot-docs/llms.txt This YAML configuration file defines the structure, dependencies, and settings for a SaluteBot project. It includes settings for the bot's name, entry point, language, testing, error messages, external Git dependencies, injector variables, NLU parameters, webhook configurations, and session timeouts. This file is crucial for defining the chatbot's environment and behavior. ```yaml # chatbot.yaml - Main configuration file name: MyRestaurantBot entryPoint: main.sc language: ru # Test configuration tests: include: - '**/*.xml' exclude: - 'draft/*.xml' - 'broken-tests.xml' # Error messages (localized) messages: onError: defaultMessage: Что-то пошло не так. Попробуйте еще раз. locales: ru: Извините, произошла ошибка. Попробуйте позже. en: Sorry, something went wrong. Please try again. # External dependencies (Git repositories) dependencies: - name: common type: git url: https://github.com/myorg/bot-common-library.git version: heads/master - name: payment-module type: git url: https://github.com/myorg/payment-integration.git version: tags/v2.1.0 # Injector variables (accessible via $injector) injector: apiKey: sk_live_abc123xyz789 webhookUrl: https://myapp.com/webhook webhookSecret: secret_xyz123 databaseUrl: https://api.mydb.com paymentGateway: https://payment.example.com emailServiceUrl: https://email.api.com supportEmail: support@myrestaurant.com maxOrderAmount: 10000 deliveryRadius: 15 # NLU settings nlu: classifierThreshold: 0.2 enableSynonyms: true enableSpellcheck: true maxIntents: 1000 # Webhook configuration webhooks: public: https://myapp.com/bot-webhook test: https://test.myapp.com/bot-webhook # Timeout and session settings session: timeoutMinutes: 1440 # 24 hours maxInactivityMonths: 12 ``` -------------------------------- ### GET /chatapi/events/{token} Source: https://context7.com/baslie/salutebot-docs/llms.txt Poll for asynchronous events from the server. Useful for handling bot-initiated messages or system events. ```APIDOC ## GET /chatapi/events/{token} ### Description Poll for asynchronous events from the server, useful for handling bot-initiated messages or system events. ### Method GET ### Endpoint `https://api.salutebot.com/chatapi/events/{token}` ### Parameters #### Path Parameters - **token** (string) - Required - The authentication token for the client. #### Query Parameters - **userId** (string) - Required - The ID of the user for whom to fetch events. - **since** (integer) - Required - Unix timestamp in seconds. Events after this time will be returned. ### Request Example ```bash curl "https://api.salutebot.com/chatapi/events/{token}?userId=user123&since=1700220000" ``` ### Response #### Success Response (200 OK) - **events** (array) - An array of event objects. - **eventId** (string) - Unique identifier for the event. - **type** (string) - The type of event (e.g., 'reminder', 'status_update'). - **timestamp** (string) - The time the event occurred. - **data** (object) - Event-specific data. - **message** (string) - A human-readable message related to the event. - **orderId** (string, optional) - The ID of the associated order. - **estimatedArrival** (string, optional) - Estimated arrival time for status updates. - **lastEventTime** (integer) - Unix timestamp of the last event processed. #### Response Example ```json { "events": [ { "eventId": "evt_123", "type": "reminder", "timestamp": "2025-11-17T10:30:00Z", "data": { "message": "Напоминание: ваш заказ будет доставлен через 30 минут", "orderId": "12345" } }, { "eventId": "evt_124", "type": "status_update", "timestamp": "2025-11-17T10:35:00Z", "data": { "message": "Курьер в пути", "estimatedArrival": "2025-11-17T11:00:00Z" } } ], "lastEventTime": 1700220900 } ``` #### Error Responses - **404**: ChannelChat config not found. ``` -------------------------------- ### Telegram Bot Testing and Deployment Source: https://context7.com/baslie/salutebot-docs/llms.txt Provides instructions for testing and deploying a SaluteBot integrated with Telegram. It covers finding the bot, sending initial commands, interacting with it, and emphasizes thorough testing before production deployment and monitoring. ```markdown # Test your bot: # 1. Find your bot in Telegram by username # 2. Send /start command # 3. Interact with bot # Production deployment: # 1. Test thoroughly in Studio widget # 2. Deploy scenario # 3. Test in actual Telegram # 4. Monitor logs in Studio ``` -------------------------------- ### SaluteBot Pattern Matching Syntax Source: https://context7.com/baslie/salutebot-docs/llms.txt Illustrates advanced pattern matching techniques in SaluteBot for precise phrase recognition and conversation routing. Covers basic elements, wildcards, word stems, alternatives, optional elements, permutations, and named patterns. ```javascript // Basic pattern elements patterns: $greetings = (привет|здравствуй|добрый день|hi|hello) $thanks = (спасибо|благодарю|thank you|thanks) $yes = (да|конечно|разумеется|yes|sure) $no = (нет|не надо|no|nope) theme: / state: Start q!: $greetings [*] a: Здравствуйте! Чем могу помочь? // Wildcards state: AnyOrder q!: * заказ * a: Что хотите заказать? // Word stems (morphology-aware) state: Delivery q!: * (*доставк*|*доставл*) * a: Стоимость доставки - 200 рублей // Alternatives state: Confirm q!: ($yes|$no) script: if ($request.query.toLowerCase().includes('да') || $request.query.toLowerCase().includes('yes')) { $reactions.transition('/ProcessOrder'); } else { $reactions.transition('/CancelOrder'); } // Optional elements state: OrderPizza q!: [я] [хочу] заказать пиццу a: Какую пиццу вы хотите? // Permutations (any word order) state: TableBooking q!: {забронировать стол на} * (человек|персон) a: Бронирование стола... // Named patterns with entity capture state: ComplexOrder q!: * заказать * $NUMBER::quantity * $pizzaTypes::type * script: $session.pizzaQuantity = $parseTree.quantity; $session.pizzaType = $parseTree.type; a: Заказать {{$session.pizzaQuantity}} пицц {{$session.pizzaType}}. Верно? // Pattern priority demonstration state: SpecificPattern q!: * специальная пицца * a: Обработано специальным паттерном (приоритет высокий) state: GeneralIntent intent!: /orderPizza a: Обработано интентом (приоритет низкий) // Pattern operators: // * - any characters (zero or more) // word - exact word match // *stem* - word stem/root matching // (a|b) - alternatives // [optional] - optional elements // {a b c} - permutations (any order) // $ENTITY - entity reference // $ENTITY::var - named capture ``` -------------------------------- ### Implement RAG for Knowledge Base Search in Javascript Source: https://context7.com/baslie/salutebot-docs/llms.txt This Javascript code demonstrates how to implement Retrieval-Augmented Generation (RAG) for searching a knowledge base in SaluteBot. It shows how to configure the RAG block, search the knowledge base with a user query, and provide answers with sources or fallback messages. Dependencies include the $rag and $reactions modules. ```javascript // Upload documents in SaluteBot Studio: // 1. Navigate to Knowledge Base section // 2. Upload PDF files (max 50MB per file) // 3. Total limit: 300,000 words across all documents // 4. Documents automatically parsed and indexed // Graph Block: AI Answer (RAG) // Configuration: { "priority": "high", // high | low | block-only "resultVariable": "ragResponse", "outputToUser": true, "fallbackMessage": "Информация не найдена в базе знаний" } // Code/DSL: RAG implementation state: SearchKnowledgeBase script: var userQuery = $request.query; // Search knowledge base $rag.search({ query: userQuery, maxResults: 3, minConfidence: 0.7 }).then(function(response) { if (response.isOk && response.results.length > 0) { // Found relevant documents var answer = response.results[0].content; var sources = response.results.map(function(r) { return r.documentName + " (стр. " + r.page + ")"; }).join(", "); $reactions.answer( answer + "\n\nИсточники: " + sources ); $session.lastRAGSources = sources; } else { // No relevant documents found $reactions.answer("К сожалению, информация не найдена."); $reactions.transition('/AskOperator'); } }); // Combine RAG with GigaChat for enhanced responses state: RAGWithGigaChat script: var userQuery = $request.query; // First, search knowledge base $rag.search({ query: userQuery, maxResults: 5 }).then(function(ragResponse) { if (ragResponse.isOk && ragResponse.results.length > 0) { // Build context from RAG results var context = ragResponse.results.map(function(r) { return r.content; }).join("\n\n"); // Use GigaChat to synthesize answer $llm.fetchRequest({ systemContent: "На основе предоставленного контекста " + "ответь на вопрос пользователя. " + "Контекст:\n" + context, userContent: userQuery, noHistory: true, llmModelSettings: { model: "GigaChat-2-Max", temperature: 0.3, maxTokens: 512 } }).then(function(aiResponse) { if (aiResponse.isOk) { $reactions.answer(aiResponse.message); } }); } else { // Fallback to pure GigaChat $reactions.transition('/AskGigaChatDirect'); } }); // Priority modes: // - "high": RAG checked first, then intents/patterns // - "low": Intents/patterns first, RAG as fallback // - "block-only": RAG only when explicitly called // Limitations: // - Max 300,000 words total // - PDF files only // - 3+ second response time // - Requires Embeddings model for custom GigaChat keys ``` -------------------------------- ### Help and Goodbye States in SaluteBot Source: https://context7.com/baslie/salutebot-docs/llms.txt Defines standard conversational states for 'Help' and 'Goodbye'. The 'Help' state responds to queries about assistance and lists available bot functions. The 'Goodbye' state handles exit commands and gracefully ends the session. ```javascript state: Help intent: /help q: * (помощь|help) * a: Я могу помочь вам:\n- Показать меню\n- Оформить заказ\n- Забронировать стол\n- Проверить статус заказа state: Goodbye q: $bye [*] a: До свидания! Будем рады видеть вас снова! go!: /End ``` -------------------------------- ### Telegram Channel Integration Configuration Source: https://context7.com/baslie/salutebot-docs/llms.txt This YAML configuration outlines the steps to integrate SaluteBot with the Telegram messenger. It includes instructions for registering a bot with @BotFather, configuring the bot token in SaluteBot Studio, and enabling privacy mode for group chats. ```yaml # Step 1: Register bot with @BotFather # Send to @BotFather: /newbot # Follow prompts to get bot token: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz # Step 2: Configure in SaluteBot Studio # Navigate to: Settings > Channels > Add Channel > Telegram # Enter bot token: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz # Save configuration # Step 3: Enable Privacy Mode (for group chats) # Send to @BotFather: /setprivacy # Select your bot # Choose: Disable (bot sees all messages) ``` -------------------------------- ### Telegram-Specific Features in SaluteBot Scenarios Source: https://context7.com/baslie/salutebot-docs/llms.txt This snippet demonstrates how to leverage Telegram-specific features within SaluteBot scenarios. It shows how to detect the channel type, access user information, send images and documents, and implement inline keyboard buttons. ```javascript state: TelegramFeatures script: // Detect channel if ($request.channelType === "telegram") { // Telegram-specific logic $reactions.answer("Вы пишете из Telegram!"); // Access Telegram user info var telegramUserId = $request.rawRequest.message.from.id; var username = $request.rawRequest.message.from.username; // Send photo $reactions.sendImage({ url: "https://example.com/image.jpg", caption: "Наше меню" }); // Send document $reactions.sendFile({ url: "https://example.com/menu.pdf", filename: "menu.pdf" }); // Inline keyboard buttons $reactions.buttons([ {text: "Заказать", callback_data: "order"}, {text: "Меню", callback_data: "menu"}, {text: "Сайт", url: "https://example.com"} ]); } ``` -------------------------------- ### Configure and Send GigaChat Request (JavaScript) Source: https://context7.com/baslie/salutebot-docs/llms.txt This snippet demonstrates how to configure and send a request to the GigaChat AI using JavaScript. It includes settings for system prompts, user queries, response variables, model parameters like temperature and max tokens, and options for including conversation history. It handles successful responses and provides a function for managing GigaChat-specific error codes. ```javascript // Graph Block: GigaChat Request // Configuration: { "systemPrompt": "Ты - помощник в ресторане. Отвечай вежливо и кратко.", "userQuery": "$queryText", "resultVariable": "gigaChatResponse", "outputToUser": true, "includeHistory": true, "modelSettings": { "model": "GigaChat-2-Max", "temperature": 0.7, "maxTokens": 512, "topP": 0.9 } } // Code/DSL: GigaChat integration state: AskGigaChat script: var systemContent = "Ты - эксперт по пицце. " + "Помогай пользователям выбрать пиццу по их предпочтениям."; var userContent = $request.query; var modelSettings = { model: "GigaChat-2-Max", temperature: 0.7, // Creativity: 0.0-1.0 maxTokens: 512, // Max response length topP: 0.9, // Nucleus sampling repetitionPenalty: 1.0 // Prevent repetition }; $llm.fetchRequest({ systemContent: systemContent, userContent: userContent, noHistory: false, // Include conversation history llmModelSettings: modelSettings }).then(function(response) { if (response.isOk) { $reactions.answer(response.message); $session.lastAIResponse = response.message; } else { // Handle errors handleGigaChatError(response.errorCode); } }); function handleGigaChatError(errorCode) { switch(errorCode) { case 408: $reactions.answer("Время ожидания истекло. Попробуйте снова."); break; case 413: $reactions.answer("Слишком длинное сообщение."); break; case 500: $reactions.answer("Ошибка сервиса. Попробуйте позже."); break; case "503.1": $reactions.answer("Превышен дневной лимит запросов."); break; case "503.2": $reactions.answer("Лимит тестового виджета исчерпан."); break; default: $reactions.answer("Произошла ошибка: " + errorCode); } } ``` -------------------------------- ### Slot-Filling Implementation in Bot Script Source: https://context7.com/baslie/salutebot-docs/llms.txt This script defines a state machine for collecting user information (slots) for booking a restaurant. It includes definitions for required slots, input validation, type-specific parsing, and confirmation. ```botscript // Import slot-filling module require: slotfilling/slotFilling.sc module = sys.zb-common theme: / // Define slot-filling scenario state: BookRestaurant intent!: /bookTable script: $session.slots = { guestCount: null, date: null, time: null, name: null, phone: null }; go!: /CollectSlots state: CollectSlots script: // Define required fields var slots = [ { name: "guestCount", question: "На сколько человек бронировать?", type: "number", validation: function(value) { return value >= 1 && value <= 20; }, errorMessage: "Укажите от 1 до 20 человек" }, { name: "date", question: "На какую дату?", type: "date" }, { name: "time", question: "На какое время?", type: "time" }, { name: "name", question: "Ваше имя?", type: "text" }, { name: "phone", question: "Ваш номер телефона?", type: "phone", validation: function(value) { return /^\+7\d{10}$/.test(value); }, errorMessage: "Введите номер в формате +79991234567" } ]; // Start slot-filling process $context.temp.slotConfig = slots; $context.temp.slotIndex = 0; go!: /AskSlot state: AskSlot script: var currentSlot = $context.temp.slotConfig[$context.temp.slotIndex]; if (!currentSlot) { // All slots filled $reactions.transition('/ConfirmBooking'); return; } $reactions.answer(currentSlot.question); state: CollectSlotValue q: * script: var currentSlot = $context.temp.slotConfig[$context.temp.slotIndex]; var userInput = $request.query; var value; // Type-specific extraction switch(currentSlot.type) { case "number": value = parseInt(userInput.match(/\d+/)?.[0]); break; case "phone": value = userInput.replace(/\s/g, ''); break; case "date": // Date entity extraction value = $parseTree.$DATE || userInput; break; default: value = userInput; } // Validation if (currentSlot.validation && !currentSlot.validation(value)) { $reactions.answer(currentSlot.errorMessage); return; } // Save and proceed $session.slots[currentSlot.name] = value; $context.temp.slotIndex++; go!: /AskSlot // Break slot-filling on user request state: BreakSlotFilling q!: * (стоп|отмена|отменить) * a: Бронирование отменено. Чем еще могу помочь? script: delete $context.temp.slotConfig; delete $context.temp.slotIndex; state: ConfirmBooking script: var s = $session.slots; $reactions.answer( "Подтвердите бронирование:\n" + "Гостей: " + s.guestCount + "\n" + "Дата: " + s.date + "\n" + "Время: " + s.time + "\n" + "Имя: " + s.name + "\n" + "Телефон: " + s.phone ); state: FinalConfirm q!: * (да|подтверждаю) * script: // Save to database or send to external service $reactions.answer("Стол забронирован! Ждем вас " + $session.slots.date); ``` -------------------------------- ### Define Intents for User Messages in .sc Files Source: https://context7.com/baslie/salutebot-docs/llms.txt Define user intents to recognize and categorize user messages using machine learning-based natural language understanding within a scenario file (.sc). Supports pattern matching, intent recognition, entity extraction, and global intents. Configuration limits apply to the number of intents, phrases, and phrase length. ```javascript // In scenario file (.sc) // Define intent with example phrases theme: / // Intent triggered by patterns (highest priority) state: OrderPizza q!: * (заказ|заказать) * пицц * q: * (хочу|желаю) * пицц * a: Какую пиццу вы хотите заказать? go!: /SelectPizza // Intent using Brain ML recognition state: CheckStatus intent!: /checkOrder a: Введите номер вашего заказа // Intent with entity extraction state: BookTable q!: * (забронировать|бронь) * стол * $NUMBER::guests * (человек|персон) * script: var numberOfGuests = $parseTree.guests; $session.guestCount = numberOfGuests; a: Забронировать стол на {{$session.guestCount}} человек. На какое время? // Global intent (works from any state) state: Help intent: /help a: Я могу помочь вам заказать пиццу, проверить статус заказа или забронировать стол. // Configuration limits: // - Max 1000 intents per project // - Max 3000 total example phrases // - Max 400 characters per phrase // - Default threshold: 0.2 (20% confidence) // - Priority: Patterns > STS Classifier > Intents ``` -------------------------------- ### HTTP Request Configuration (JavaScript) Source: https://context7.com/baslie/salutebot-docs/llms.txt Defines the configuration for an HTTP POST request, including URL, headers, request body, timeout, and variables for storing the response and status. This is typically configured in a visual editor for graph blocks. ```javascript // Graph Block: HTTP Request // Configure in visual editor: { "method": "POST", "url": "https://api.example.com/orders", "headers": { "Authorization": "Bearer ${apiToken}", "Content-Type": "application/json" }, "body": { "orderId": "$orderId", "customer": { "name": "$customerName", "phone": "$customerPhone" }, "items": "$cartItems", "total": "$totalAmount" }, "timeout": 5000, "resultVariable": "orderResponse", "statusVariable": "httpStatus" } ```