Table of Contents

What's New?

New Updates for Bitrix24 Bot Platform API.


January 2022

New methods in Chat API (REST revision 30):


August 2020

New methods in IMOPENLINES REST API in revision 2:


July 2020

December 2019

July 2019

April 2019

February 2019

August 2018

February 2018

December 2017


Where to begin?

This chapter provides general overview of what chatbots are, what purpose do they serve, how they operate and how to create your own chatbot application - with an example of completed chatbot for Bitrix24 platform.

What is Chatbot?


Chatbot - is a virtual chat-based bot, a software program that is created to imitate human behavior when conversing with several parties.

What is a chatbot, why it is required, and why develop it at all?

Although chatbots have become a trend only quite recently, today we can find a plethora of them, especially for Slack or Telegram. Chatbots can perform a variety of useful functions ranging from ticket booking to team management. Users don’t have to leave their favorite messenger to communicate with a chatbot.

What a chatbot can do?

  • Perform routine actions - they can do straightforward, tedious work without human intervention; the end result being usually better that, produced by a human, because chatbot cannot get tired;
  • Search and aggregate news and analytical data (Data-Driven Collaboration): data is available anywhere to all interested parties via their messengers;
  • E-commerce - for quick purchases without lengthy search; for communication with customers;
  • Act as a first customer support tier - client relations, assistants, consultants, frequently asked questions, telephony;
  • Just for Fun - just for the fun of it.

Bitrix24 Bot Platform

Bitrix24 chat (both private and group one) is a part of a complex ecosystem, being one of the multiple channels of communication that is fully integrated with other business tools. The use of chatbots in this context leads to a variety of possibilities for business users, since Bitrix24 (in browser, Desktop- and mobile- applications) already serves as the main workplace for many companies.

An example of a simplest chatbot is one that can post the essential information in chats about the parameters of identification system, integrated with Bitrix24. Another useful bot can help delivery couriers to process orders based on deals existing in the Bitrix24 CRM straight in the messenger of their mobile devices - no need to develop a separate mobile application for them.

Development of a chatbot for Bitrix24 - is a lucrative option for workflows automation in a fast and handy fashion. It is handy because getting information via a messenger is the user preference today. It is fast because the development process for a chatbot in Bitrix24 is quite straightforward.

Note: To learn more about Bitrix24 chatbots, view some of the standard, out-of-the-box Bitrix24 chatbots here.



Chatbot Features


Chatbot:

  • is a special kind of user in the system that can talk to anyone, but cannot log in to the system;
  • supports slash-commands processing;
  • can have a dedicated keyboard for responses, creating simple chat for a basic terminal.

Slash-commands

Slash-commands allow to quickly create requests for input or reception of information, or to format messages.

Note: Detailed information about commands can be found here


Keyboards

Keyboards have quite significant amount of capabilities.

  • Giphy
    Use the More button to get more images without entering the specified keyword twice:

  • Note: Get more information about keyboards here


    Chats

    If properly programmed, chatbot can communicate as effectively as a live person. It can post event reminders (about current tasks, meetings) or provide reference information. Chatbots can even go as far as create their own chats and invite human beings to those chats, to discuss a task, for example.

    Note: Get more information about chats here


    Notifications

    Chatbot notifications can used to carry a lot of useful information. The notifications can include various data from multiple external systems.

    Note: Get more information about notifications here



    Chatbot Lifecycle

    Chatbot submits posts to a chat using REST API, and receives replies and user commands via the REST API Events (POST requests).

    The following figure shows a typical chatbot's lifecycle:



    Creating an Application

    The most important thing to remember about chatbots is their logic which is typically a reaction to an action performed by a user or system.

    The chatbot API includes the six events that cover the required range of responses:

    • ONAPPINSTALL - event to install a chatbot application.
    • ONAPPUPDATE - updates the chatbot application.
    • ONIMJOINCHAT - event initiated when a chatbot is invited to conversation, either by a user's call in a private chat, or when the bot is connected to a group chat.
    • ONIMBOTMESSAGEADD - event initiated when a chatbot is invited to conversation, either by a user's call in a private chat, or when the bot is connected to a group chat.
    • ONIMCOMMANDADD - event initiated after a user sends a command to a bot in a private or group chat (chatbot cannot participate in the chat, if the command is global).
    • ONIMBOTDELETE - event initiated after the chatbot application is deleted. The event is initiated in parallel with OnAppUninstall.

    All we have to do to implement the required chatbot logic is to add event handlers:

    1. Register the chatbot when installing it on the portal.
    2. Show a welcome message when the bot is invited to the chat.
    3. Analyze user requests and send something back in return. Where analysis means a simple "command line review", and not the lexical breakdown of natural language.

    To fulfill the requirements, the chatbot REST API contains simple methods a developer can use. Only the two of those are needed to get started:

    In the ONAPPINSTALL event handler, we are going to call the imbot.register method to add the chatbot to the current portal. When out chatbot receives an invitation via the ONIMJOINCHAT event, a call to the imbot.message.add method will show chatbot reference information. Finally, we will use the ONIMBOTMESSAGEADD method in the imbot.message.add event handler to reply to the user. It could not be easier, could it?

    Another treat for a lazy developer: we don't have to implement OAuth 2.0 in our application because all the authentication parameters are passed to event handlers in the $_REQUEST array.

    Note: for a full list of Chatbot API events and methods, please use this link.



    Chatbot Example

    To illustrate a fully functional, yet simple bot, we are going to create application that informs users of their overdue tasks. Our chatbot will recognize only one command: what's hot. The range of recognized commands can be extended anytime to get any kind of reports directly to the Bitrix24 chat.

    Example of a simple chatbot:

    <?php
    /**
     * Simple and handy reporting chatbot for bitrix24
     */
    
    $appsConfig     = array();
    $configFileName = '/config_' . trim(str_replace('.', '_', $_REQUEST['auth']['domain'])) . '.php';
    if (file_exists(__DIR__ . $configFileName)) {
       include_once __DIR__ . $configFileName;
    }
    // receive event "new message for bot"
    if ($_REQUEST['event'] == 'ONIMBOTMESSAGEADD') {
       // check the event - register this application or not
       if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
          return false;
       }
       // response time
       $arReport = getAnswer($_REQUEST['data']['PARAMS']['MESSAGE'], $_REQUEST['data']['PARAMS']['FROM_USER_ID']);
       $arReport['attach'][] = array("MESSAGE" => 'As soon as you're through with these tasks, just ask me [send=what's hot]What's hot?[/send] again – I'll give you more to have on your plate!');
       
       // send answer message
       $result = restCommand('imbot.message.add', 
          array(
             "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
             "MESSAGE"   => $arReport['title'] . "\n" . $arReport['report'] . "\n",
             "ATTACH"    => array_merge(
                $arReport['attach']
             ),
          ), 
          $_REQUEST["auth"]);
    
    } // receive event "open private dialog with bot" or "join bot to group chat"
    else {
       if ($_REQUEST['event'] == 'ONIMBOTJOINCHAT') {
          // check the event - register this application or not
          if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
             return false;
          }
          // send help message how to use chat-bot. For private chat and for group chat need send different instructions.
          $result = restCommand('imbot.message.add', array(
             'DIALOG_ID' => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
             'MESSAGE'   => Hello! I'm Reportoo, I can be a pain in the butt because I'm honest and candid.',
             "ATTACH"    => array(
                array('MESSAGE' => '[send=what's hot]What's hot?[/send]'),
             ),
          ), $_REQUEST["auth"]);
    
       } // receive event "delete chat-bot"
       else {
          if ($_REQUEST['event'] == 'ONIMBOTDELETE') {
             // check the event - register this application or not
             if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
                return false;
             }
             // unset application variables
             unset($appsConfig[$_REQUEST['auth']['application_token']]);
             // save params
             saveParams($appsConfig);
    
          } // receive event "Application install"
          else {
             if ($_REQUEST['event'] == 'ONAPPINSTALL') {
                // handler for events
                $handlerBackUrl = ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . (in_array($_SERVER['SERVER_PORT'],
                   array(80, 443)) ? '' : ':' . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'];
                // If your application supports different localizations
                // use $_REQUEST['data']['LANGUAGE_ID'] to load correct localization
                // register new bot
                $result = restCommand('imbot.register', array(
                   'CODE'                  => 'ReportBot',
                   // app unique string bot ID (required)
                   'TYPE'                  => 'B',
                   // Bot type: B – robot with immediate response; H – human-like bot with a response delay from 2 to 10 seconds
                   'EVENT_MESSAGE_ADD'     => $handlerBackUrl,
                   // new message from user" event handler (required)
                   'EVENT_WELCOME_MESSAGE' => $handlerBackUrl,
                   // "bot invited" event handler (required)
                   'EVENT_BOT_DELETE'      => $handlerBackUrl,
                   // "user deleted bot" event handler (required)
                   'PROPERTIES'            => array( // Chatbot personal data (required)
                      'NAME'              => 'Reportoo',
                      // Bot name (NAME either LAST_NAME is required)
                      'LAST_NAME'         => '',
                      // Bot name (NAME either LAST_NAME is required)
                      'COLOR'             => 'AQUA',
                      // Bot color for mobile app: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
                      'EMAIL'             => 'no@mail.com',
                      // bot e-mail
                      'PERSONAL_BIRTHDAY' => '2016-03-23',
                      // birthday, YYYY-mm-dd
                      'WORK_POSITION'     => 'I'm here to tell you about your tasks',
                      // Position – used as bot description
                      'PERSONAL_WWW'      => '',
                      // site link
                      'PERSONAL_GENDER'   => 'M',
                      // Bot gender, (M)ale or (F)emale or empty, if not required
                      'PERSONAL_PHOTO'    => 'iVBORw0KGgoAAAANSUhEUgAAADoAAAA6CAYAAADhu0ooAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAEdVJREFUeNq8m3uMHVd9xz/nNzP37tvetdfe9dtxnDghIbHJgxClBAnSJKVVGqw0gfJHoU0aiiqBVLWVqoqC1AdSVQlVbXkLSEmQg4oSi4hCWgihhEfiuiHNy3HsrF9rr9f73nvvzPxO/5gzM2fm7iKiBkba3bv3zpxzfuf8Ht/f9/e7JnrkgEUoLgsYQFFEQUWKjxUF3P8K6j4Q/zlVRMQbBwQlm0Td3dkARgUVb8xiDveOUk7gX+p+iXjr0GIUVfdaQBXEeKvWYlQF70Z/DnG3K5p9oIq450w2Q3GvKRbsfisYze4zKEa9MYuptfhfVUHculSzWTV7rd6mKG4N6paOZnNK9l6+3lC9xSHZYpB8Z9wy853JTzo/SSm3Qd0N/kkU96o4wQV/PvG2N9tCKQ/MO//8rKQYuvwEN362W+UB2VxrEMSCUFks3mSKiHrjOcUVyfesEDBffKGAUm5W8aQ4DZF80eJWLsWGFWorUo4n+RLVqWQ5T65hxQa7963bKSOlSkpxoxtQyY/cDamlgognR3ESIsWi84WWwktpBm4n87HQUrXVvS/iaYfnM2wulrvB1nyGpfacZ2+ZpgkhWup0vl/l0ZMdfS5ZvvhcUyTbPeMLL/miPHtQz8q911ROo9Qq3ySMp6o2V1mtPmdy31T7379HEIOK77N876bFenL1U8nt3jkhyed2n/tmoJ6MgIpmzwvO2+YHq8XGSu1EK2N4Xth6KlpssFMUzwKzuRRCVUuX58dzSs59505GRFEFYwxxmkCSQKIQBBCGhKFgCp9bDSfinYYbtFi50XKjxDmtFCDuQJKQBgFIQBBFiDH+rmR+QGquQTMtLaJH5hx8+9NKjKyebLnwxKaA4evX30S8/3189JLLQBMS6+5ys4ovsFKEC/WdhPo2n522BUjafHDHbmbueC8/fsethFFI6uxfvaAoUoY2deu1ArYSV+l2AHn8VF/gPH5pqS+3bxjnzs3bCSXg76/cR3+jCZoUOqb+5PmpOsclWtVJ8eZBQS2QKJ/bdz1rGg2uHRnlQ9t3Z85NSicntfidvzY1K5QK+FAXfrUMtqJepMvdvjuG2J8A+I3RjZCkxenlKlgGQM9fe146DzP58RgRsCl712+ojN/WBLAF+qr6APHCHwVAAW+6Uockv91zQp4DUN/mhB9cmKKdJMVg9+7YDaliSSkduBSqlKAkqSVOU+I086FWtXAguUJatZDEfGD7roqgD04cAwlKr1zGRoqQqeXb2dTqK6kPuaScUijDsJZoRFUxErC0tMD3p6eKhdwwvI6+vj5ULakqSZoS25i00yFZXsJ22libZquxMbbTIWm3SDvLpGmH1FpShdRaCELu2LC5GPvM8hJzi/OVOK1o7TRqYMVzv2EVjZSQzbfHXGCjLmhaCMUQS8CDJ4/xzg1jAPRFEfuGhnny7CnCIOCG4XW8feMmbhsdY1f/IENhSJijIGvpqHK+0+Hw3AUeOnmch08cp5OmYA3r+vrYMtBfrP+BiWMQRgRBUMEE6qJAhrAogIqI52sAEx38mvXjiuZ42LlmrdhvNbjHNmYobDB7+3uK97507BWem5nmDy/ew46+fl7v9eT5c3z4Z4e4Zs1avrDvrcX7+773LQ5dmCaKIi978QNmDlvLEGaLMAkmOnjAFu5X5OcuonACTrnT1IIm/Pfbb+Oq4RGstVhreSMuiyWQ7PSmWsuMPvZvEAqRhAVMzeOxr6nSNY5vzjnAzj/UVYT0oIeoIGIgSfnp7PQbKmQWHkwx5mOTZyDulEDBRQCpO02tYVwvzJTQ08tCjFRhHNRgIJkX1STlg9t28Ztjm99QIYsNd4JeMjAAYtBUUWurAMOzucrJeuHLVJRVpBrkfRPIY2qeQAskccyHd17Mp/Zdx/pGk1/mde3wOl699U6wljRNMKYkRWwlilZBg9SRkSpe8C6T6Aqg98Bckigf3LqDv3vT1fQ4O/plX9v6+nnuHbeBhUTTLA3QkqnwjbNCCLijFi3SDCkQjEiJYEpsnwmvxnLLuvV8/PKrfmVC5teewTU8dM0NEKekmhbJfOGc8tiqHirULHZIgT29ZEKds0GrOZBVZaMIH9l9OWPNntfpXLKMZ6Wf4h732n+vft21eTv3bNsBcYpa6xFhTg7Et8SCWZA6yVbNl0vyS4BElfdvu4hbRsdWF8gTIGcfxOFXYwwG6KRpRfDiHvc6/7uS0NZavrD3OoIwLE5V0Squr6QRjhyzDvEU5utjRqfK1gHzPc0+PrRz96oC+n9PLC3yxPmzfP/8Wf7rwjQT7RaxKolaUiwBhsAYIhE2NRpct3aYG0ZGedeGcXb29UNNWD98NSTgn6/cy73P/AgjAcb6iZCXCZGDHsGEBw9YsxIXWou8sSp/sn0Xf3vF3lVPcTHu8MmXn+fTE8eYnD6XDRQ1IIggClkxf7IWUoWkA50YDKxZu457Nm3mr/ZcyYaevkpszIU2xiAPfwUaTaIw6AI1dRkKQX1YUXJMpUMKrOWHN72Lq9esXVHIP3j6KT736otZmtbby8cvvYIdPX08Pn2WLx09AlFEIB7j5xYUawpxzK3jW7hn01YmO20+8dLzzM/NApb9uy7hi3uvZyBqdAl83+Ef89lXjxBGDXBmsRKSs4AJHzlg8QhfswIMtMCNA4P8x03v6hJyqtXiLU9+h4m5GYgisHD2lt9itLc8iU+88DP+8vnDhI1m12Lidpt7d+7m03uvK95bjmO2Pn6Q861lUGWop5cnbnwHV60ZqcT6lxfm2fP4o0jQRAJTcXzFiZYkmWbMOYLxaEilREqJplw7NLyibb7v0FNMzM1img0QQyMIKkIC3D46Bs52Cyo0Vxur3O6yH5wN9kYRO/oHQAKIIuZaLW5/6omuTb5kcAiJmqhRrwpQZSy0RAGOk3UgQYUKr5uFWcve9aNdQs6223z73CREIaEJQKGTpBxbmK/c9+UTx8HmiXtWC/E51389NZGvHoDFdpuX5ubAGAIMhCGn5mY4MjfbBQhuGFqb2bhQ4f198CBAWOFyKky9R3yoZZ9TG//qi0L6gpClVos4ykGysvNb3+D9O3axrXeAb06e4tDUJPT0uDFNxgflJGcQcOD4UXbNTHP35m1Mtlt8/vjRzGAkyJLwNAEMG3p6KydqreWdoxv5wdlJiKIqP1zDwWGVyKpkoOWdNmWspxsgRBLwnzfezB8dfobD8xeIk05GfaYJX3nxuUw9HU1Ju4UFUisgrtaWp0mp5ejUWf767JlMfcMg89SiRI0GuwdH+OSeKxlqNKqZiTG8aWiNh+LUI6y1Ul4JKQpJWq9/lVeq9AfhijZ63fB6fnLzLVxotTkft5lPYjrW0rIWY8EaaGIIjcECoUBkhFShYxUDpFhaVrPUjOz+ZmDolYCNzR6GPRSmNUJuU08fpGkB3HPCIKdFcuY/NPWktca/iFuIWSWNwlqMCMM9TYZ7fklZjAMLtmaf1lr6o9CBizzjkkqNtYCCWqsbqMfF+OC4penKiKgrvdNV2Yn6/7/wM8ZgvBjs22mc2m46tlaQsj6XXqm85DSlOF0PhOk4/rkUS+4cVhO6vkhZIV779/u0zUr35feeaS9lSbl6z2uVYTCFtopX45Qqs56B35BXFudXZQF8NmC1E1xNkJX+1oWsb5x4p/vszAXH9VLhe+vPS/2oqZWFVDPV+ebk6VUFTa0lWeWnk6YOzGc0iP+TpCkY0/VXbckLJ2maeWufmFMt7PbhUychkMopVx0Nrj5aLUx2gWJFCQLhJ1OTKwoaW+XBkxM8tzCHWktgDOPNXnYPDADwyuIiZ9stMDAcRlw+OMR4Ty+T7RavLC7Q0pTAGAbDkPWNzLtOddrMJXGG1QwExrCnf4gbR9bRDMLMTIBzrRaH5i+AhGVF24N/uSwZYPAbHGr5aPHSwA9nL/D0zAXesrYKBac6Hf7x2BGenc9Qy/pGkw9s28mbhzLw/6OZab504hhTnTaXDgzx+auu5bLBIVILf/bCs7y4MM/aqMHdm7Zy7/YMfX33+DkeOjXBTNzJ7MsY9g6t5aF9b2W8WaZuv3foR6BKIKGXFpV2Kl4FLytBi6DVlNwrBmW/YhNy4OTxrhNd32jwxzt3eyV4VkwKVvpcbcbYR8Yw1uxhtNFktNFkrNlDZExhEh1Vfn/rTtY3ygzm66cm+ObJ4xmwcPyRahUkFPUfgSC4+3c+ZkzZJ1TYgMmKs8Zk6hwEwrm4w6+NrGejF8ADY7hyaA3Pzc/ywuI8aqGVpkzHHZ6ZvcB3p87y2vKys1llPkk43W5xcPI0T89O09KsFhoaQ0OEI4sLfPvcJC8tLhA75HTHxk18/NIrCBwWfmVxgfsOPcWUZiS3YEAMxtm+kBWji0YnYwirRJFU0FEB9p3wLy/M89VTE/zN0NouPmj/+BYeO3eGtqYcnpvl6NIiFlhIEtouBs8lCd84c5LvTE2ykCQspFklbilN+N70OZ6dn8UCF+IOS+6zpgj7x7dUAMujk6d4ud0myG3TqyLnElhVr6FLsj4j311LHTPWYtlXT01w48h63r1hvPL+/vEt/Hhmmk8dO0JLU1qdboCh1jKXxMwlcZdqLyQJC14JMr/u23YR+8e3FP+fbi3z5YnXXMLvcUQqVUYBqbBGknvYrC6pXdXnSuxDmVxe4l+OH+WlFeLq/dt3cefY5qpnN4beIKA/CImMvC7kd+fYZu73aqSxKp+dOMrLy3NubX4LkFeMz1NOj4wPgvfe9THjSk4ZsWWwmul3Fx2JBSMcXVqkpcrbhtfRG5R8zXDU4OL+QabjDs8vzGOA0UaT64dHuHpoGDEwHWd10Fzl+4OQdY0GkQiptUV/yp1jm/nTXXvYMzDoEhzL106f4BMv/S/LasEYrM0Qmao6sGIxRjJOyWHwXIYguPuuj2FMVk/RjHTyvFIhqHqOyRjDMzMztDTl2rUjFWHHmj3sWzNMYAwvLMxzzdph/mL35bxnfAuNIODQ3EyhogNhyM3rRvnt8S3s7OtnKm7T0ZT7t++qCNlR5YGTr/HnL/4Ps50kYxSwWAvWGMQarFiX+dnM3KypEHGhg/WVbrCiabEG2Kn0ASr/dPwIy5rwkZ2XcEn/YPHszr5+PnnZm3nb8DpOtJbZ2tvHUBixo7ePPm9TRqIG+zdt4ddHxzjbbrOlp4eLevu5w1P/M+0Wn5s4yj8cfYnFOKk1YDneWSQj3L2ep7zIlGczYaUTS3xGskxdpTCAiovDonxx4lVOLC9x3/ZdvHvDpoqN5Qs+2W5xsrXMxPISQ0FUaMD23n42NXvpC0K29wZ89KJLC94I4N+nzvCZ40d57NzpQt3V9SUWJW2n7EZKTCsitWxTMNEjB2zJoHgFVtcH6J+quMal8rBLGLCx2cPvbt7OPZu2ccXgml+8VOH5gDwp+Nn8LA+eeo0HTh5nst2qBjI1LrmuteBJN/PnF05NdPCAxW+RkTrHWy2Xq/rUaDcffWn/IO/euIlbR8e4aWT09ZX1p8/x2LkzHJw8xYsreHVrs1Sw0g1alDer+Lzs1c16c03wSNbDIIAVjxPNi77uYetRiap50WZ14NcQ4a1r13HNmhGuHFrDxf0DbO3pY8QR0dNxh4nWEkcWF3h2bpafzk7z1Mx5Oqsk4b4iqmvVKzmDMryI3x7uusLUgIkePWDV1pJcrbXq5eV+8drQnQ0bq/yc4tcbfqmu0FdXS+Yra9XcaRXn6fXaetmMFpRJ1bhzs87i1q9O0KJNqILcpPqdANGydyEHFFlzoBYNgvmDeReX1NBRSWWUr62VFapH3RVSy//36E3RA6jqC1unXaSrSVl8B2S9doaSMpQV+R6plNKLloiaMKb4UbVZRuEVDl4nEZg9lzc8SrUj32rZR78StyQGMK753tQdgXTnkvX/6zHLVJTGnaJaj5Xz6SqXH3obYLs2Iq+7SqlJHjeUN2h2MwZeiw4gajy076dllTPJdN641Cf/6oelntSX7c+Vvviu1vF8tw0YQdUWsxgXK4vyiJpKNVsqX4eRwmYrRSa/6UjU7wvW4kM/XfM9XdEMrNSYCKr98/WviqzEGRep4UpdJLVuGPGRWfVrKWVVTsqG5+KLCNWvtPzfAOI42kZvxsE0AAAAAElFTkSuQmCC',
                      // Bot avatar - base64
                   ),
                ), $_REQUEST["auth"]);
                // save params
                $appsConfig[$_REQUEST['auth']['application_token']] = array(
                   'BOT_ID'      => $result['result'],
                   'LANGUAGE_ID' => $_REQUEST['data']['LANGUAGE_ID'],
                );
                saveParams($appsConfig);
                // write debug log
                // writeToLog($result, 'ReportBot register');
             }
          }
       }
    }
    /**
     * Save application configuration.
     *
     * @param $params
     *
     * @return bool
     */
    function saveParams($params) {
       $config = "<?php\n";
       $config .= "\$appsConfig = " . var_export($params, true) . ";\n";
       $config .= "?>";
       $configFileName = '/config_' . trim(str_replace('.', '_', $_REQUEST['auth']['domain'])) . '.php';
       file_put_contents(__DIR__ . $configFileName, $config);
       return true;
    }
    /**
     * Send rest query to Bitrix24.
     *
     * @param       $method - Rest method, ex: methods
     * @param array $params - Method params, ex: array()
     * @param array $auth   - Authorize data, ex: array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
     *
     * @return mixed
     */
    function restCommand($method, array $params = array(), array $auth = array()) {
       $queryUrl  = 'https://' . $auth['domain'] . '/rest/' . $method;
       $queryData = http_build_query(array_merge($params, array('auth' => $auth['access_token'])));
       // writeToLog(array('URL' => $queryUrl, 'PARAMS' => array_merge($params, array("auth" => $auth["access_token"]))), 'ReportBot send data');
       $curl = curl_init();
       curl_setopt_array($curl, array(
          CURLOPT_POST           => 1,
          CURLOPT_HEADER         => 0,
          CURLOPT_RETURNTRANSFER => 1,
          CURLOPT_URL            => $queryUrl,
          CURLOPT_POSTFIELDS     => $queryData,
       ));
       $result = curl_exec($curl);
       curl_close($curl);
       $result = json_decode($result, 1);
       return $result;
    }
    /**
     * Write data to log file.
     *
     * @param mixed  $data
     * @param string $title
     *
     * @return bool
     */
    function writeToLog($data, $title = '') {
       $log = "\n------------------------\n";
       $log .= date("Y.m.d G:i:s") . "\n";
       $log .= (strlen($title) > 0 ? $title : 'DEBUG') . "\n";
       $log .= print_r($data, 1);
       $log .= "\n------------------------\n";
       file_put_contents(__DIR__ . '/imbot.log', $log, FILE_APPEND);
       return true;
    }
    /**
     * Command received, create report
     *
     * @param      string $text message sent by user
      * @param      int $user user ID
     *
     * @return     array
     */
    function getAnswer($command = '', $user) {
    
       switch (strtolower($command)) {
           case 'what's hot':
               $arResult = b24BadTasks($user);
               break;
           default:
              $arResult = array(
                'title' => 'I'm stuck',
                'report'  => 'Sorry, what is it you wanted? I can't hear you!',
             );
       }
    
       return $arResult;
    }
    
    function b24BadTasks ($user) {
       $tasks = restCommand('task.item.list', 
          array(
             'ORDER' => array('DEADLINE' => 'desc'),
             'FILTER' => array('RESPONSIBLE_ID' => $user, '<DEADLINE' => 'Y-m-d'),
             'PARAMS' => array(),
             'SELECT' => array()
          ), 
          $_REQUEST["auth"]);
       
       if (count($tasks['result']) > 0) {
          $arTasks = array();
          foreach ($tasks['result'] as $id => $arTask) {
             $arTasks[] = array(
                'LINK' => array(
                   'NAME' => $arTask['TITLE'],
                   'LINK' => 'https://'.$_REQUEST['auth']['domain'].'/company/personal/user/'.$arTask['RESPONSIBLE_ID'].'/tasks/task/view/'.$arTask['ID'].'/'
                )
             );
             $arTasks[] = array(
                'DELIMITER' => array(
                   'SIZE' => 400,
                   'COLOR' => '#c6c6c6'
                )
             );
          }
          $arReport = array(
             'title' => 'Oh yeah, we've got trouble. Tackle these ASAP:',
             'report'  => '',
             'attach' => $arTasks
          );
       }
       else {
          $arReport = array(
             'title' => 'You're awesome!',
             'report'  => 'You're no fun, no tasks overdue. Just joking, keep it up!',
          );
       }
       return $arReport;
    }
    

    At a first glance, you may find this code frightening. But do not fret. After you have finished this course, you will see that it's actually quite simple.

    Users can create a chatbot for personal use, or publish it on Bitrix24.Market.

    Note: Chatbot does not require a HTTPS certificate explicitly. However, it is highly recommended due to potential transfer of personal or sensitive information. The application must be saved in UTF-8 encoding.

    To get a feel of what a chatbot application is, without publishing it on Applications24, take the example code, save it to your server and run the bot on your account. Bitrix24 has a local application option and here's how to use it:

    • Select Applications > Market > Add Application1 on the main menu:

      Click the image to expand <

    • Next, select Other 2:

      Click image to expand

    • And then, select Local Application 3:

      Click image to expand

    • Choose the Server application type. Specify the bot name as, for example, "Reportoo". Enable the option Script only (no user interface) and assign access permissions for the app:
      - Chat and Notifications (im): no messages can be sent to a user without this permission,
      - Creating and managing Chat bots (imbot) – chat bot cannot be registered without this permission,
      - Tasks (task) and Tasks (extended permissions) (task_extended) – without this permission, application won't be able to generate task reports to inform the user via chat bot:

      Click image to expand

    • Since we have all the event handlers in one file, specify the same app URL in both fields.
    • In case you create a bot for Bitrix24 On-premise, without the option Script only (no user interface), you need to use the Static application type and the mandatory field Archive containing your application (ZIP) to indicate the path to installation file.

    Actually, we are done: a message saying a new user (Reportoo) has joined the Bitrix24 account should now be visible in the public chat. We can now add it to the chat, then click the "What's hot" link and get a list of overdue tasks.



    Creating an Open Channel Chatbot

    Design of a chatbot intended for use with Open Channels is almost identical to the standard chatbot, discussed earlier, except for the following small details:

    1. An Open Channel chatbot must have O (zero) passed in the TYPE parameter when calling imbot.register to register a bot.
    2. If you want to extend an existing bot to support Open Channels, you have to add a new key OPENLINE => Y to enable hybrid mode.

      Attention! A hybrid mode enabled chatbot has to distinguish between private, group and Open Channel chats. To do so, simply check the CHAT_ENTITY_TYPE parameter when processing the ONIMBOTMESSAGEADD and ONIMBOTJOINCHAT events. It is set to CHAT_ENTITY_TYPE => LINES when the bot is used in an Open Channel chat.

    Otherwise, the chatbot application is the same as the standard chatbot.

    For deeper integration with Open Channels, an imopenlines scope access permission is required.

    This permission enables the use of the commands:


    Attention: The use of HTTPS certificate is not required for chatbots, but is highly recommended due to possible transmission of client's confidential data. The app itself shall have UTF-8 encoding.


    Download chatbot example for Open Channels

    We have prepared ITR Bot as the example used for Open Channels. It can be downloaded:

    • from GitHub (itr.php) service.
    • or found in "Bitrix24 Self-Hosted" here: \Bitrix\ImBot\Bot\OpenlinesMenuExample.

    This chatbot as the first tier of customer support - initially, all messages will be going to it first, and only then to the employees in the queue after a period of time, that is specified in the Open Channel settings. Also, a class will be added to it for constructing a multilevel chat menu.


    It means that even now you can use the code from the chatbot example on your server and launch a chatbot as a local application, without publishing it at Applications24:

    • Go to the left menu Applications > Add Application tab and select the Add button for My Account Only option:

    • Indicate the chatbot name, specifically, «ITR Bot», and enable Available as script only option and grant access permission rights for at least Creating and managing Chat bots (imbot) (the app won't be able to register the chatbot without these rights), as well as enable rights for Open Channels (imopenlines) (the app won't be able to work with Open Channels without these rights).

    • Due to specifics of how our code is written, it handles all events, so we will indicate the same URL in the both link windows of the app settings.
    • Please note, this chatbot does not publish messages about the fact it was invited to the account. After installation is complete, the chatbot will be accessible in the Open Channel settings, where it should be enabled. Also, specify the time period after which a conversation is switched form the chatbot to the queue:

      Note: Client can switch over from an operator earlier, by sending the message with zero digit or by selecting 0. Wait operator answer menu item. In any case, user can click 0 in any chatbot and he/she will be switched to an operator, without additional processing.

    • After the settings are saved, chatbot is ready for use. The example demonstrates the dialogue - first, ITR Bot responds, the client clicks on the menu items, then queue is switched to an operator (client has selected 0. Wait operator answer menu item):

    • Your own ITR Bot menu can be configured via itrRun method.
      /**
       * Run ITR menu
       *
       * @param $portalId
       * @param $dialogId
       * @param $userId
       * @param string $message
       * @return bool
       */
      function itrRun($portalId, $dialogId, $userId, $message = '')
      {
      	if ($userId <= 0)
      		return false;
      
      	$menu0 = new ItrMenu(0);
      	$menu0->setText('Main menu (#0)');
      	$menu0->addItem(1, 'Text', ItrItem::sendText('Text message (for #USER_NAME#)'));
      	$menu0->addItem(2, 'Text without menu', ItrItem::sendText('Text message without menu', true));
      	$menu0->addItem(3, 'Open menu #1', ItrItem::openMenu(1));
      	$menu0->addItem(0, 'Wait operator answer', ItrItem::sendText('Wait operator answer', true));
      
      	$menu1 = new ItrMenu(1);
      	$menu1->setText('Second menu (#1)');
      	$menu1->addItem(2, 'Transfer to queue', ItrItem::transferToQueue('Transfer to queue'));
      	$menu1->addItem(3, 'Transfer to user', ItrItem::transferToUser(1, false, 'Transfer to user #1'));
      	$menu1->addItem(4, 'Transfer to bot', ItrItem::transferToBot('marta', true, 'Transfer to bot Marta', 'Marta not found :('));
      	$menu1->addItem(5, 'Finish session', ItrItem::finishSession('Finish session'));
      	$menu1->addItem(6, 'Exec function', ItrItem::execFunction(function($context){
      		$result = restCommand('imbot.message.add', Array(
      			"DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
      			"MESSAGE" => 'Function executed (action)',
      		), $_REQUEST["auth"]);
      		writeToLog($result, 'Exec function');
      	}, 'Function executed (text)'));
      	$menu1->addItem(9, 'Back to main menu', ItrItem::openMenu(0));
      
      	$itr = new Itr($portalId, $dialogId, 0, $userId);
      	$itr->addMenu($menu0);
      	$itr->addMenu($menu1);
      	$itr->run(prepareText($message));
      
      	return true;
      }
      


    Example: Creating a Support Channel

    With the Open Channels module, you can set up a technical support line for any Bitrix24 application, including chatbots.

    The following procedure is required:

    1. Open Manage Open Channels (account main menu Company > Open Channels item) and create a tech support Open Channel for your product:

    2. Then, connect a new Bitrix24.Network communication channel:

    3. Once connection is done, the Bitrix24.Network connection settings page becomes available:

      • Be sure to fill in the fields: Name, Short description and select an Avatar - to help your clients find you.
      • The Welcome Message will be shown to a user every time they open your Bitrix24.Network Open Channel:

      • Notice the Searchable option: uncheck it to create a private support channel. It is available only if a user specifies a unique ID in the search text.

        Checking the Searchable option makes your open channel searchable just like any Bitrix24.Network user.

    Your open channel can be auto connected to the user's account using the imopenlines.network.join REST command:

    $result = restCommand('imopenlines.network.join', Array(
    
        'CODE' => 'a588e1a88baaf301b9d0b0b33b1eefc2b' // search code as specified on the Connectors page
    
    ), $_REQUEST["auth"]);
    

    After the Open Channel is configured, you can write a welcome message to a client via the imopenlines.network.message.add REST command:

    Thank you for installation, we will be glad to help, if you have any questions - write to this chat. Have a good Day! :)
    

    Note: The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the Javascript-BX24.callMethod, or bitrix24-php-sdk methods. It is also possible to open such support channel via BX24.im.openMessenger JavaScript-method.



    Possible Chatbot Usage Scenarios

    Below you can find a brief description of ready-to-use Bitrix24 chatbots. These chatbot types are provisional: you can create a chatbot that can combine 2 or 3 types.

    • Personal Assistant

      Mia is your personal assistant. She can help you find answers to your questions, remind you of events, play tic-tac-toe or just do little chit-chat.

    • Specialist Purpose Bot

      Support Bot is designed for internal use for faster access to Bitrix24 helpdesk ticket system.

    • Open Channel Bots

      Open Channel Bot can get a user in contact with you and help along the way.

    • Entertainment Bots

      Giphy searches through a large library of animated GIF files so you can pick an image you find appropriate to your query and share it with your colleagues.

    Note: A full list of Bitrix24 chatbots is available in the section with the same name Bitrix24.Market.




    Messages

    In this chapter we will discuss messages and how to design, format and use them in Bitrix24 chats.

    Formatting

    Message text can be formatted by applying bold or strikethrough script or quote style. This lesson will show how to use user commands and REST API to format chat messages.

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example; it is used. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    Formatting Tags

    Consider the following example:

    [B]bold[/B] text
    [U]underline[/U] text
    [I]oblique[/I] text
    [S]strikethrough[/S] text
    

    When posted to the chat, the message will be rendered like this:

    Here's how we can use REST API to format the message:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[B]bold[/B] text
    [U]underline[/U] text
    [I]oblique[/I] text
    [S]strikethrough[/S] text",
    ), $_REQUEST["auth"]);
    

    Line Break

    To add a line break, add one of these sequences to the code:

    [BR]
    # BR # (no spaces)
    \n
    

    Any of these codes create a line break:

    Using line breaks in a REST API call:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "First line[BR]Second line",
    ), $_REQUEST["auth"]);
    

    Quotes

    To format text as a quote, use a double closing angle bracket sequence or enclose text in two lines formed by the minus sign:

    >>first quote line
    >>second quote line
    
    ------------------------------------------------------
    John Doe [08.04.2016 13:06:49]
    Hello everyone!
    ------------------------------------------------------
    

    The second method produces a result that looks a bit different because the first line contains the author name and time stamp:

    Creating a quote using a REST API call:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => ">>first quote line
    >>second quote line
    
    ------------------------------------------------------
    John Doe [08.04.2016 13:06:49]
    Hello everyone!
    ------------------------------------------------------",
    ), $_REQUEST["auth"]);
    

    Hyperlinks

    Any text that conforms to the hyperlink pattern will be converted to a hyperlink. If the hyperlink URL resolves to a page containing rich formatting, it will be recognized by the system and will be added to the message:

    Adding a hyperlink using a REST API call:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "http://bitrix24.com",
    ), $_REQUEST["auth"]);
    

    Note: To disable rich formatting, use 'URL_PREVIEW' => 'N' key when adding a message:
    restCommand('imbot.message.add', Array(
    "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
    "MESSAGE" => "http://bitrix24.com",
    'URL_PREVIEW' => 'N' 
    ), $_REQUEST["auth"]);
    


    If the message contains a link to an image file http://shelenkov.com/bitrix/images/mantis.jpg (with a .png, .jpg or .gif extension), it will be posted as an image:


    A BB code URL is also supported - [URL=http://bitrix24.com]Link to Bitrix24[/URL]:

    This code uses REST API to add a BB URL code to the message:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[URL=http://bitrix24.com]Link to Bitrix24[/URL]",
    ), $_REQUEST["auth"]);
    

    IM supports special codes similar to the URL code.

    • [USER=5]Alexandra[/USER] - adds a link to a user.
    • [CALL=18012334455]call[/CALL] - adds a button to make a call using Bitrix24.
    • [CHAT=12]link[/CHAT] - adds a chat link.

    These codes are also supported by REST API:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[USER=5]Alexandra[/USER]
    [CALL=18012334455]call[/CALL]
    [CHAT=12]link[/CHAT]",
    ), $_REQUEST["auth"]);
    

    Indents

    Use the tab character to indent the text:

    Using indents in a REST API call:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "
    Indent
       Indent
          Indent",
    ), $_REQUEST["auth"]);
    

    Active Links (commands)

    To have a link send some text to the bot, use the SEND tag:

    [send=text]button caption[/send] - sends text to the bot.
    

    You can use this tag to force a user to send a hard-coded text to the bot. However, a preferable method is by using the Keyboards

    Adding a command using REST API:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[send=text]button caption[/send] - sends text to the bot",
    ), $_REQUEST["auth"]);
    

    If additional user input is required by the command, use the PUT tag:

    [put=/search]Enter search text[/put]
    

    Use this tag to automatically add the command text to the input field. Once a user clicks the PUT link, the text that is specified after the equal sign will be added to the text input field. Now the user has to enter additional information and click the Send button. Again, a preferable method is by using the Keyboards)

    Using REST API to prompt the user to enter text:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[put=/search]Enter search text[/put]",
    ), $_REQUEST["auth"]);
    

    Attachments

    Use attachments to make a message more pronounced and comprehensive.

    To embed an attachment to the message text, add a special BB code ATTACH to the message specified in the MESSAGE key. The [ATTACH=1] code will be replaced with the attachment when showing the message. If no ATTACH code is specified in the message text while the actual attachment exists, it will be shown at the end of the message.

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "Message with middle attach [ATTACH=1] from bot",
       "ATTACH" => Array(
          "ID" => 1,
          "COLOR" => "#29619b",
          "BLOCKS" => Array(
             Array("LINK" => Array(
                "NAME" => "Ticket #12345: new IM module for API",
                "DESC" => "Need this done before the release!",
                "LINK" => "https://api.bitrix24.com/"
             )),
             Array("IMAGE" => Array(
                "NAME" => "Example",
                "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
             ))
          )
       )
    ), $_REQUEST["auth"]);
    

    Note For detailed description of extended attachments, please refer to this lesson.



    Attachments

    Attachments can be used with any IM messages, irrespective of their origin (messages from a user or a chatbot).

    Using Attachments

    Before adding an attachment to a message you have to create it along with the message. While the message itself is defined by the MESSAGE key, attachments are created as an array of attachment objects and passed over to the REST command in the ATTACH key. There are two versions of the attachment object: full and short.


    Full ATTACH version:

    JavaScript:

    	ATTACH: {
    	   ID: 1,
    	   COLOR: "#29619b",
    	   BLOCKS: [
    		  {...},
    		  {...},
    	   ]
    	}
    

    PHP:

    "ATTACH" => Array(
       "ID" => 1,
       "COLOR" => "#29619b",
       "BLOCKS" => Array(
          array(...),
          array(...),
       )
    )
    

    Array keys:

    • ID - specifies the attachment ID for use in the ATTACH BB code. The attachment ID is required to place attachment in any part of a message, not only at the end of it.

      To add an attachment to the message text, add the [ATTACH=1] with the attachment ID, for example: [ATTACH=1]. Then, the message is displayed to the user, the code will be replaced with the attachment. Please note, BB-code is optional: if not specified, the attachment will be placed at the end of the message.

    • COLOR specifies the attachment background color. This key is optional; the default color is the color of the recipient's chat (or, if this is a notification - current user color). This key is optional, if not required.
    • BLOCKS specifies the attachment layout (see below).

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "Message with middle attach [ATTACH=1] from bot",
       "ATTACH" => Array(
          "ID" => 1,
          "COLOR" => "#29619b",
          "BLOCKS" => Array(
             Array("LINK" => Array(
                "NAME" => "Ticket #12345: new IM module API",
                "DESC" => "Need this done before the release!",
                "LINK" => "https://api.bitrix24.com/"
             )),
             Array("IMAGE" => Array(
                "NAME" => "Implementation example",
                "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
             ))
          )
       )
    ), $_REQUEST["auth"]);
    


    Short ATTACH version:

    If all you want is an attachment below the message text, you can omit the ID and the COLOR keys:

    JavaScript:

    	ATTACH: [
    	  {...},
    	  {...},
       ]
    

    PHP:

    "ATTACH" => Array(
       array(...),
       array(...),
    )
    

    Unlike the full version, layout goes in the short version without the BLOCKS keys.

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "Message from bot",
       "ATTACH" => Array(
          Array("LINK" => Array(
             "NAME" => "Ticket  #12345: new IM module API",
             "DESC" => "Need this done before the release!",
             "LINK" => "https://api.bitrix24.com/"
          )),
          Array("IMAGE" => Array(
             "NAME" => "Implementation example",
             "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
          ))
       )
    ), $_REQUEST["auth"]);
    

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Attention: Due to structural complexity, attachments are not added to XMPP, e-mail or push notifications.



    Collections of Attachment Blocks


    User Blocks

    The USER block shows user name and optional avatar. The AVATAR and LINK keys are optional.

    Example:

    Array("USER" => Array(
       "NAME" => "John Smith",
       "AVATAR" => "http://shelenkov.com/bitrix/images/avatar.png",
       "LINK" => "http://shelenkov.com/",
    )),
    

    An entity ID can be used instead of the LINK key:

    • CHAT_ID => 1 specifies the chat link;
    • BOT_ID => 66 specifies the chatbot;
    • USER_ID => 1 specifies the user profile link.


    Hyperlink Block

    The LINK key displays a block with a hyperlink, description and image. This block is created automatically when a rich link is detected. The DESC and PREVIEW fields are optional.

    Example:

    
    Array("LINK" => Array(
       "NAME" => "Ticket #12345: new IM module API",
       "DESC" => "Need this done before the release!",
       "LINK" => "https://api.bitrix24.com/",
       "PREVIEW" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png"
    )),
    

    Entity ID can be used instead of the LINK key:

    • CHAT_ID => 1 - specifies chat link;
    • USER_ID => 1 - specifies user profile link.


    Text Block

    The MESSAGE key displays text with basic BB code defined formatting.

    Example:

    Array("MESSAGE" => "API will be accessible in the [B]im 16.0.0[/B] update"),
    

    The following BB codes are possible: USER, CHAT, SEND, PUT, CALL, BR, B, U, I, S.



    Delimiter

    DELIMITER - The DELIMITER key prints a visual separator, a line. The COLOR and SIZE keys are optional.

    Example:

    Array("DELIMITER" => Array(
       'SIZE' => 200,
       'COLOR' => "#c6c6c6"
    )),
    


    Layout Block

    The GRID key is used to format the enclosed arrays in blocks, rows or 2 columns.

    1. "DISPLAY" => "BLOCK" - Specifies that the enclosed arrays are to be shown one below the other.

      A WIDTH key is available to specify the block width in pixels.

      Example:

      Array("GRID" => Array(
          Array(
              "NAME" => "Description",
              "VALUE" => "Structured entity enclosures are required in IM messages and notifications.",
              "DISPLAY" => "BLOCK",
              "WIDTH" => "250"
          ),
          Array(
              "NAME" => "Category",
              "VALUE" => "Suggestions",
              "DISPLAY" => "BLOCK"
          ),
      )),
      
    2. "DISPLAY" => "LINE" This key value specifies that each block is rendered one after the other in sequence until there is no space left, thereafter wrapping to a new line.

      A WIDTH key is available to specify the block width in pixels.

      Example:

      Array("GRID" => Array(
         Array(
            "NAME" => "Priority",
            "VALUE" => "High",
            "COLOR" => "#ff0000",
            "DISPLAY" => "LINE",
             "WIDTH" => "250"
         ),
         Array(
            "NAME" => "Category",
            "VALUE" => "Suggestions",
            "DISPLAY" => "LINE"
         ),
      )), 
      
    3. "DISPLAY" => "COLUMN". This key value formats the blocks in two columns.

      A WIDTH key is available to specify the block width in pixels.

      Example:

      Array("GRID" => Array(
          Array(
              "NAME" => "Priority",
              "VALUE" => "High",
              "DISPLAY" => "COLUMN"
              "WIDTH" => "250"
          ),
          Array(
              "NAME" => "Category",
              "VALUE" => "Suggestions",
              "DISPLAY" => "COLUMN"
          ),
      )),
      

    All layout types can use the additional keys:

    • COLOR - specifies the color to apply to the block (the VALUE key);
    • CHAT_ID - value is treated as the chat ID and will become chat link;
    • USER_ID - value is treated as the user ID and will become user profile link;
    • LINK - value will be shown as a link.
    • The VALUE key can also use these BB codes: USER, CHAT, SEND, PUT, CALL.


    Image Block

    The IMAGE key displays an image. It is recommended to provide a PREVIEW key value specifying a scaled down version of the image. If this key is missing, the LINK value is used instead. The NAME and PREVIEW keys are optional.

    Example:

    Array("IMAGE" => Array(
        Array(
            "NAME" => "Hello, I'm Mantis",
            "LINK" => "http://shelenkov.com/bitrix/images/mantis.jpg",
            "PREVIEW" => "http://shelenkov.com/bitrix/images/mantis.jpg"
        )
    )),
    


    File Block

    The FILE key shows a formatted file download link. The NAME (filename) and SIZE (file size in bytes) keys are optional.

    Example:

    Array("FILE" => Array(
        Array(
            "NAME" => "mantis.jpg",
            "LINK" => "http://shelenkov.com/bitrix/images/mantis.jpg",
            "SIZE" => "1500000"
        )
    )),
    


    Examples and Suggested Usage

    Treat the ATTACH object like it's a LEGO toy. Construct it according to your vision and requirements using available block types. The order in which you specify blocks is relevant.


    Example «A Bug Tracker»

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "You have a new notification",
       "ATTACH" => Array(
          Array("USER" => Array(
             "NAME" => "Mantis Notifications",
             "AVATAR" => "http://shelenkov.com/bitrix/images/mantis2.jpg",
             "LINK" => "http://shelenkov.com/",
          )),
          Array("LINK" => Array(
             "NAME" => "Open Mantis",
             "LINK" => "http://shelenkov.com/",
          )),
          Array("DELIMITER" => Array(
             'SIZE' => 200,
             'COLOR' => "#c6c6c6"
          )),
          Array("GRID" => Array(
             Array(
                "NAME" => "Project",
                "VALUE" => "BUGS",
                "DISPLAY" => "LINE",
                "WIDTH" => 100
             ),
             Array(
                "NAME" => "Category",
                "VALUE" => "im",
                "DISPLAY" => "LINE",
                "WIDTH" => 100
             ),
             Array(
                "NAME" => "Summary",
                "VALUE" => "Structured entity enclosures are required in IM messages and notifications.",
                "DISPLAY" => "BLOCK"
             ),
          )),
          Array("DELIMITER" => Array(
             'SIZE' => 200,
             'COLOR' => "#c6c6c6"
          )),
          Array("GRID" => Array(
             Array(
                "NAME" => "New ticket",
                "VALUE" => "",
                "DISPLAY" => "ROW",
                "WIDTH" => 100
             ),
             Array(
                "NAME" => "Assigned to",
                "VALUE" => "Evgeniy Shelenkov",
                "DISPLAY" => "ROW",
                "WIDTH" => 100
             ),
             Array(
                "NAME" => "Deadline",
                "VALUE" => "04.11.2015 17:50:43",
                "DISPLAY" => "ROW",
                "WIDTH" => 100
             ),
          )),
       )
    ), $_REQUEST["auth"]);
    


    Example: Notification

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "You have new notification",
       "ATTACH" => Array(
          Array("MESSAGE" => "Hey guys, update [b]im 16.0.0[/b] has been tested and is now ready for release.[BR] Add tags as required.[BR] No new commits are accepted."),
          Array("IMAGE" => Array(
             "LINK" => "http://shelenkov.com/bitrix/images/win.jpg",
          )),
       )
    ), $_REQUEST["auth"]);
    


    Using Keyboards

    Custom keyboards are essentially toolbars containing one or more user defined buttons. The keyboards provide alternative means of input, allowing a user to communicate with a chatbot by clicking the buttons.


    Adding a Keyboard to a Chatbot

    A keyboard is actually part of a chatbot message. To create a keyboard, you have to specify a KEYBOARD key with parameters defining the keyboard layout.

    The following methods support the KEYBOARD key:

    Consider the following example:

    restCommand('imbot.command.answer', Array(
       "COMMAND_ID" => $command['COMMAND_ID'],
       "MESSAGE_ID" => $command['MESSAGE_ID'],
       "MESSAGE" => "Hello! My name is EchoBot :)[br] I am designed to answer your questions!",
       "KEYBOARD" => Array(
          Array(
            "TEXT" => "Bitrix24",
            "LINK" => "http://bitrix24.com",
            "BG_COLOR" => "#29619b",
            "TEXT_COLOR" => "#fff",
            "DISPLAY" => "LINE",
          ),
          Array(
            "TEXT" => "BitBucket",
            "LINK" => "https://bitbucket.org/Bitrix24com/rest-bot-echotest",
            "BG_COLOR" => "#2a4c7c",
            "TEXT_COLOR" => "#fff",
            "DISPLAY" => "LINE",
          ),
          Array("TYPE" => "NEWLINE"), // line break
          Array("TEXT" => "Echo", "COMMAND" => "echo", "COMMAND_PARAMS" => "test from keyboard", "DISPLAY" => "LINE"),
          Array("TEXT" => "List", "COMMAND" => "echoList", "DISPLAY" => "LINE"),
          Array("TEXT" => "Help", "COMMAND" => "help", "DISPLAY" => "LINE"),
       )
    ), $_REQUEST["auth"]);
    

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example; it is used. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Each button in the keyboard is defined by the following keys:

    • TEXT - specifies the button text;
    • LINK - specifies a hyperlink;
    • COMMAND - a command to send to the bot;
    • COMMAND_PARAMS - specifies command parameters;
    • BG_COLOR - specifies the button color;
    • BLOCK - if set to Y, the keyboard will be disabled after this button is clicked. Only the buttons that send ajax commands to bot can block the keyboard (be advised, that Links to third-party resources and instant Actions do not block the keyboard). Blocking is needed to limit execution of ajax commands due to their asynchronicity and standby time: the keyboard is blocked after clicking the button and Bitrix24 backend reaction standby is ON, so that user couldn't click on second button, etc. Backend processes commands and decides, whether to unblock the keyboard, hide it or create new one;
    • DISABLED - specify Y to disable the button;
    • TEXT_COLOR - specifies the button text color;
    • DISPLAY - specifies the button layout in the row. If set to BLOCK, only this button can occupy the row. If set to LINE, the buttons will be aligned one after the other;
    • WIDTH - button width in pixels. Try to avoid making buttons wider than 255 pixels, because it's the maximum width on mobile devices.
    • APP_ID - specifies the ID of an installed chat application.
    • APP_PARAMS - parameters that will be passed over to the chat application.
    • ACTION - action can have the following type (REST revision 28):
      • PUT - enter into input field.
      • SEND - send text.
      • COPY - copy text to clipboard.
      • CALL - call.
      • DIALOG - open specified dialog.
    • ACTION_VALUE - each type has its own value (REST revision 28):
      • PUT - text inserted into input field.
      • SEND - text to be sent.
      • COPY - text copied to clipboard.
      • CALL - phone number in the international format.
      • DIALOG - dialog ID. Can be both user ID or chat ID in format chatXXX.
    • The TEXT key is required. To perform sensible action, one of the LINK and COMMAND keys are required as well.

      If the LINK key is not empty, the button is treated as an external link. If COMMAND and COMMAND_PARAMS keys are specified, the button sends command to the bot.

      If the APP_ID and APP_PARAMS keys are specified, the button will open a chat application window.

      To start a new row of buttons, add a button containing only one key: "TYPE" => "NEWLINE".



      Command Processing on the Chatbot Side

      Chatbots use commands to process button clicks.

      1. To make a command recognizable, it has to be registered using the imbot.command.register (method in the ONAPPINSTALL event handler. To make the command available only from the keyboard, add the "HIDDEN" => "Y" key).

        Use these keys in the button description to fire a command:

        "COMMAND" => "page", // command to send to chatbot 
        "COMMAND_PARAMS" => "1", // command parameters
        
      2. Button click will generate ONIMCOMMANDADD event.

      3. 1. In the event handler, create a new message as a response or update an existing message (effectively creating page-by-page navigation feature).

      4. The [data][COMMAND] array passed to the event handler will contain the event information. This array now contains a new key, COMMAND_CONTEXT to describe calling context:
        • TEXTAREA for commands posted by user by typing in from the device keyboard;
        • KEYBOARD for commands originating from the chatbot keyboard or a context menu.
        • MENU for commands originating from context menu.

      You can find an updated EchoBot example here, example (bot.php).


      Application Launch Processing for Chatbot

      Application for chat, launched from context menu, is working based on principles of Context Application.

      Examples

      1. Giphy
        Use the More button to get more images for the specified keyword:


      Using Context Menus

      A context menu allows for chatbot-to-user interaction from the message context menu.


      Adding Custom Items to the Context Menu

      A context menu is part of a chatbot message. To add custom menu items, you have to specify MENU key.

      The following methods support the Menu:

      Consider the following example:

      restCommand('im.message.add', Array(
         "DIALOG_ID" => 12,
         "MESSAGE" => "Hello! Message with context menu!",
         "MENU" => Array(
            Array(
              "TEXT" => "Bitrix24",
              "LINK" => "http://bitrix24.com",
            ),
            Array(
               "TEXT" => "Echo", 
               "COMMAND" => "echo", 
               "COMMAND_PARAMS" => "test from keyboard"
            ),
            Array(
               "TEXT" => "Open app", 
               "APP_ID" => "12", 
               "APP_PARAMS" => "TEST"
            ),
         )
      ), $_REQUEST["auth"]);
      

      Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example; it is used. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Each custom item in the context menu is defined by a set of keys:

      • TEXT - specifies text for a menu item;
      • LINK - specifies a hyperlink;
      • COMMAND - sends command to the bot;
      • COMMAND_PARAMS - specifies command parameters;
      • APP_ID - specifies ID of an installed chat application.
      • APP_PARAMS - parameters that will be passed over to the chat application.
      • DISABLED - specifies Y to disable the menu item.
      • ACTION - action can have the following type (REST revision 28):
        • PUT - enter into input field.
        • SEND - send text.
        • COPY - copy text to clipboard.
        • CALL - call.
        • DIALOG - open specified dialog.
      • ACTION_VALUE - each type has its own value (REST revision 28):
        • PUT - text inserted into input field.
        • SEND - text to be sent.
        • COPY - text copied to clipboard.
        • CALL - phone number in the international format.
        • DIALOG - dialog ID. Can be both user ID or chat ID in format chatXXX.
      • TEXT, LINK or COMMAND are required.

        If the LINK key is not empty, the menu item is treated as an external link. If the COMMAND and COMMAND_PARAMS keys are specified, the menu item sends a command to the bot, without posting it in the chat. Available from API (platform version) revision 26

        If the APP_ID and APP_PARAMS keys are specified, the menu item will open a chat application window.

        If it is necessary to specify two lines with buttons in a row, then to separate them, create a button with the following content: "TYPE" => "NEWLINE".



        Command Processing on the Chatbot side

        Chatbots use commands to process menu items.

        1. To make a command recognizable, it has to be registered using imbot.command.register method in the ONAPPINSTALL event handler. (To make the command available only from the menu, add the "HIDDEN" => "Y" key).

          Use these keys in the menu item description to fire a command:

          "COMMAND" => "page", // command to send to chatbot 
          "COMMAND_PARAMS" => "1", // command parameters
          
        2. Menu item, when selected, generates ONIMCOMMANDADD event.

        3. Create a new message in the event handler as a response or update an existing message (effectively creating the page navigation feature).

        4. The [data][COMMAND] array passed to the event handler will contain the event information. This array now contains a new COMMAND_CONTEXT key to describe the calling context:
          • TEXTAREA for commands posted by user by typing in from the device keyboard;
          • KEYBOARD for commands originating from the chatbot keyboard or a context menu.

        Application Launch Processing for Chat

        Applications for chat, launched from context menu are working based on the Context Application principles.


        Bot API

        To work with Bot API, indicate scope: imbot (chatbot creation and management) when creating an application (or uploading a new version).


        Working with Chatbots

        Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


        Attention! For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

        Attention! CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.


        MethodDescription
        imbot.register Registers chatbot.
        imbot.unregister Deletes chatbot from system.
        imbot.update Updates chatbot data.
        imbot.bot.list Gets available chatbots.

        Note: For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

        CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.


    imbot.register

    Registers chatbot

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

    CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.

    Method call

    $result = restCommand('imbot.register', Array(
    
        'CODE' => 'newbot', // String ID for bot, unique within your application framework (required)
        'TYPE' => 'H', // Bot type, H - chatbot, immediate responses, O - chatbot for Open Channels,  S - chatbot with extended privileges (supervisor)
        'EVENT_HANDLER' => 'http://www.hazz/chatApi/event.php', // Link to the handler of events, incoming from the server; see. Event Handlers section below (req.)  
        'OPENLINE' => 'Y', // Enable Open Channel support mode (optional, if TYPE = 'O').
        'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
        'PROPERTIES' => Array( // Chatbot properties (req.)
            'NAME' => 'NewBot', // Chatbot name (one field NAME or LAST_NAME is required)
            'LAST_NAME' => '', // Chatbot last name (one field NAME or LAST_NAME is required)
            'COLOR' => 'GREEN', // Chatbot color for mobile application: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN,  AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
            'EMAIL' => 'test@test.com', // E-mail for communication
            'PERSONAL_BIRTHDAY' => '2016-03-11', // Birthday, yyyy-mm-dd
            'WORK_POSITION' => 'My First Bot', // Job title, used as description for chatbot
            'PERSONAL_WWW' => 'http://test.com', // Link to site
            'PERSONAL_GENDER' => 'F', // Chatbot gender, valid values M -  male, F - female, empty, if not required to be specified
            'PERSONAL_PHOTO' => '/* base64 image */', // Chatbot icon - base64
        )
    
    ), $_REQUEST["auth"]);
    

    Required fields:

    • CODE - String ID for chatbot, unique within your application framework.
    • PROPERTIES - Array with chatbot properties.
    • EVENT_HANDLER - Link to the event handler for message sending to chatbot.
    • or
    • EVENT_MESSAGE_ADD - Link to event handler: send message to chatbot.
    • EVENT_WELCOME_MESSAGE - Link to event handler: open dialogue with chatbot or invite the chatbot to group chat.
    • EVENT_BOT_DELETE - Link to event handler: delete chat bot on the client side.

    Returns:

    BOT_ID numerical ID for created bot or an error.

    Event handlers:

    If you require to process events via different event handlers, then instead of EVENT_HANDLER you can specify each event handler individually:
     'EVENT_MESSAGE_ADD' => 'http://www.hazz/chatApi/event.php', // Link to event handler: send message to chatbot (required)
     'EVENT_WELCOME_MESSAGE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: open dialogue with chatbot or invite the chatbot to group chat (required)
     'EVENT_BOT_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: delete chat bot on the client side (required)
     'EVENT_MESSAGE_UPDATE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message update events 
     'EVENT_MESSAGE_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message deletion events 
    

    Related links:

    REST API - Installation and Update Events

    Possible error codes

    Code Description
    EVENT_MESSAGE_ADD_ERROR Event handler link is invalid or not specified.
    EVENT_WELCOME_MESSAGE_ERROR Event handler link is invalid or not specified.
    EVENT_BOT_DELETE_ERROR Event handler link is invalid or not specified.
    CODE_ERROR Chatbot string ID is not specified.
    NAME_ERROR One of chatbot required fields NAME or LAST_NAME is not specified.
    WRONG_REQUEST Something went wrong.
    MAX_COUNT_ERROR Maximum number of registered bots for single application is reached.

    Chatbot with extended privileges (supervisor) - it is the bot that has access to all messages in chats, where it is present (to all chats, if the bot was invited with history access rights, and to new chats, if the history access rights are unavailable to it).

    To create chatbot with extended privileges, specify type S in the field TYPE in the method imbot.register.

    Please note, if this action is not required by the logic of your application, it is recommended for the chatbot to respond to user messages only when this chatbot is mentioned. This can be checked via field TO_USER_ID, which will be passed to the event.

    Attention! Bitrix24 REST restricts the work of event handlers, if more than one chatbot is to be installed within single application framework. Only one event handler per one application is permitted. That is why, upon registration of second chatbot, the following links to event handlers EVENT_MESSAGE_ADD, EVENT_WELCOME_MESSAGE and EVENT_BOT_DELETE shall be the same as for the first bot.

    If within single application framework processing of several bots is required, then it shall be specified inside the event handler. So that during event execution, chatbot array is transmitted for proper processing of chatbots.

    Maximum number of bots for a single application is 5.


    imbot.unregister

    Deletes chatbot from the system

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

    CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.

    Method call

    $result = restCommand('imbot.unregister', Array(
    
        'BOT_ID' => 39 // Bot numerical ID 
        'CLIENT_ID' => '', // Chatbot string ID, used only in Webnooks mode
    
    ), $_REQUEST["auth"]);
    

    Attention! Все чаты один-на-один данного чат-бота с пользователями будут утеряны.

    Return:

    true or error.

    Related links:

    REST API - Installation and Update Events

    Possible error codes:

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.

    imbot.update

    Updates chatbot data

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

    CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.

    Method call

    $result = restCommand('imbot.update', Array(
    
        'BOT_ID' => 39, // Chatbot ID, shall be modified (required)
        'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode (required)
        'FIELDS' => Array( // Data for update (required)
            'CODE' => 'newbot', // String ID for bot, unique within your application framework 
            'EVENT_HANDLER' => 'http://www.hazz/chatApi/event.php', // Link to the handler of events, received from the server, see Event Handlers below (req.)  
            'PROPERTIES' => Array( // Required when bot data is updated
                'NAME' => 'UpdatedBot', // Chatbot name 
                'LAST_NAME' => '', // Chatbot last name 
                'COLOR' => 'MINT', // Chatbot color for mobile application: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME,  BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
                'EMAIL' => 'test2@test.com', // E-mail for communication
                'PERSONAL_BIRTHDAY' => '2016-03-12', // Birthday, yyyy-mm-dd
                'WORK_POSITION' => 'My second bot', // Job title, used as description for chatbot
                'PERSONAL_WWW' => 'http://test2.com', // Link to site
                'PERSONAL_GENDER' => 'M', // Chatbot gender, valid values M -  male, F - female, empty, if not required to be specified
                'PERSONAL_PHOTO' => '/* base64 image */', // Chatbot icon - base64
            )
        )
    
    ), $_REQUEST["auth"]);
    

    Required fields:

    • BOT_ID - Chatbot ID, shall be modified.
    • FIELDS - Array with data to be updated.
    • PROPERTIES - Array with chatbot properties.
    • EVENT_HANDLER - link to the event handler for message sending to chatbot.
    • or
    • EVENT_MESSAGE_ADD - Link to event handler: send message to chatbot.
    • EVENT_WELCOME_MESSAGE - Link to event handler: open dialogue with chatbot or invite the chatbot to group chat.
    • EVENT_BOT_DELETE - Link to event handler: delete chat bot on the client side.

    Return:

    true or error.

    Event handlers

    If you require to process events via different event handlrs, then instead of EVENT_HANDLER you can specify each event handler individually:

    :
     'EVENT_MESSAGE_ADD' => 'http://www.hazz/chatApi/event.php', // Link to event handler: send message to chatbot (required)
     'EVENT_WELCOME_MESSAGE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: open dialogue with chatbot or invite the chatbot to group chat (required)
     'EVENT_BOT_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: delete chat bot on the client side (required)
     'EVENT_MESSAGE_UPDATE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message update events 
     'EVENT_MESSAGE_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message deletion events 
    

    Related links:

    REST API - Installation and Update Events

    Possible error codes:

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    EVENT_MESSAGE_ADD_ERROR Event handler link invalid or not specified
    EVENT_WELCOME_MESSAGE_ERROR Event handler link invalid or not specified.
    EVENT_BOT_DELETE_ERROR Event handler link invalid or not specified.
    NAME_ERROR One of chatbot required fields NAME or LAST_NAME is not specified.
    WRONG_REQUEST Something went wrong.

    Method imbot.update no longer supports updates for the fields TYPE and OPENLINE (im 17.5.10).



    imbot.bot.list

    Gets available chatbots

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

    CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.

    Method call

    $result = restCommand('imbot.bot.list', Array(
    ), $_REQUEST["auth"]);
    

    Return:

    Array of arrays, containing chatbots data:

    • ID - chatbot ID.
    • NAME - chatbot name.
    • CODE - internal code.
    • OPENLINE - enable or disable Open Channel support.

    Giphy service

    [ICO_NEW data-adding-timestamp="1702313533"]

    Giphy – service is an online database and serach system that allows for users to search and share animated GIF files.


    МетодMethod description
    imbot.Giphy.list Getting list of GIF images by string.
    imbot.Giphy.listPopular Getting popular GIF images. Returns 15 GIF images.


    [/ICO_NEW]

    imbot.Giphy.list

    [ICO_NEW data-adding-timestamp="1702313607"]

    Getting list of GIF-images in a string


    Parameters

    Parameter Example Required Description Revision
    filter 32
    filter.search 'test' Yes String, to search GIF images. 32
    limit 15 No How many GIF images to get. 32
    offset 15 No Offset. 32

    Associated P&P events

    No

    Calling method and repsonse

    JavaScript

    BX.rest.callMethod('imbot.Giphy.list', {
    	filter: {search: 'test'}
    })
    	.then(result => console.log(result.data()))
    	.catch(result => console.error(result.error()))
    ;
    

    Response example

    [
    	{
    		"preview": "https://media4.giphy.com/media/gw3IWyGkC0rsazTi/200w_d.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200w_d.webp&ct=g",
    		"original": "https://media4.giphy.com/media/gw3IWyGkC0rsazTi/200.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media0.giphy.com/media/yNs2a0jRkYxy6191B2/200w_d.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200w_d.webp&ct=g",
    		"original": "https://media0.giphy.com/media/yNs2a0jRkYxy6191B2/200.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media2.giphy.com/media/3o8dFjB7T9lNldqliM/200w_d.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200w_d.webp&ct=g",
    		"original": "https://media2.giphy.com/media/3o8dFjB7T9lNldqliM/200.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media0.giphy.com/media/xT1XGWGd90BrYwnTl6/200w_d.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200w_d.webp&ct=g",
    		"original": "https://media0.giphy.com/media/xT1XGWGd90BrYwnTl6/200.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media4.giphy.com/media/8FNlmNPDTo2wE/200w_d.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200w_d.webp&ct=g",
    		"original": "https://media4.giphy.com/media/8FNlmNPDTo2wE/200.webp?cid=b7142cb9hgdk6b19hsx8g5powaqrznauiaw5mc0uhjmpc4uu&rid=200.webp&ct=g"
    	},
    		...
    ]
    

    Key description:

    • preview – animation preview with fixed width of 200 px, a version of original image reduced to 6 frames;
    • original – full animation version.

    Possible error codes

    • Possible customer-related errors:

      Code Description
      EMPTY_SEARCH_ERROR String for searching GIF images cannot be empty.

    • Standard controller errors (for example, autowaring issue).
    • Server-related issue. Standard «microservice», module issues that include:
      • LICENSE_NOT_FOUND
      • WRONG_SIGN
      • LICENSE_DEMO
      • LICENSE_NOT_ACTIVE


    [/ICO_NEW]

    imbot.Giphy.listPopular

    [ICO_NEW data-adding-timestamp="1702313675"]

    Getting popular GIF images. Returns 15 GIF images


    Parameters

    No

    Associated P&P events

    No

    Calling method and response

    JavaScript

    BX.rest.callMethod('imbot.Giphy.listPopular', {})
    	.then(result => console.log(result.data()))
    	.catch(result => console.error(result))
    ;
    

    Response example

    [
    	{
    		"preview": "https://media0.giphy.com/media/KT38VKe0p2aM35i7HS/200w_d.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200w_d.webp&ct=g",
    		"original": "https://media0.giphy.com/media/KT38VKe0p2aM35i7HS/200.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media3.giphy.com/media/uUP7F5A1rQR9uKls9P/200w_d.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200w_d.webp&ct=g",
    		"original": "https://media3.giphy.com/media/uUP7F5A1rQR9uKls9P/200.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media3.giphy.com/media/r7I5UK3W25OIyAlsrc/200w_d.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200w_d.webp&ct=g",
    		"original": "https://media3.giphy.com/media/r7I5UK3W25OIyAlsrc/200.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media1.giphy.com/media/3o7TKoWXm3okO1kgHC/200w_d.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200w_d.webp&ct=g",
    		"original": "https://media1.giphy.com/media/3o7TKoWXm3okO1kgHC/200.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200.webp&ct=g"
    	},
    	{
    		"preview": "https://media2.giphy.com/media/9GIFGeuuinRxgEj7Zq/200w_d.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200w_d.webp&ct=g",
    		"original": "https://media2.giphy.com/media/9GIFGeuuinRxgEj7Zq/200.webp?cid=b7142cb9xia5p36zjc2wowjrd10gh7hfpt4eirrcrzhps7z7&rid=200.webp&ct=g"
    	},
    		...
    ]
    

    Key description:

    • preview – animation preview with fixed width of 200 px, a version of original image, reduced to 6 frames;
    • original – full animation version.

    Possible error codes

    Server-related issues. Standard errors «microservice», module errors that include:

    • LICENSE_NOT_FOUND
    • WRONG_SIGN
    • LICENSE_DEMO
    • LICENSE_NOT_ACTIVE


    [/ICO_NEW]

    Working with Chats

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    MethodMethod description
    imbot.chat.user.list Gets list of participants.
    imbot.chat.user.add Invites participants.
    imbot.chat.user.delete Removes participants.
    imbot.chat.leave Chatbot exit from specified chat.
    imbot.chat.updateTitle Chat title update.
    imbot.chat.updateColor Chat color update.
    imbot.chat.updateAvatar Chat icon update.
    imbot.chat.add Chatbot creates a chat.
    imbot.chat.get Gets chat ID.
    imbot.chat.setOwner Chatbot changes a chat owner.
    imbot.dialog.get Gets information about dialog/chat.


    imbot.chat.user.list

    Gets list of participants

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.user.list', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot 
    
    ), $_REQUEST["auth"]);
    

    Return:

    Array with participant IDs or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable


    imbot.chat.user.add

    Invites participants

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.user.add', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'USERS' => Array(3,4) // New users ID
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    WRONG_REQUEST Insufficient rights to add a participant to the chat or the participant is already in the chat.


    imbot.chat.user.delete

    Removes participants

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.user.delete', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'USER_ID' => 4 // Deleted user ID
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    USER_ID_EMPTY User ID is unavailable.
    WRONG_REQUEST Insufficient rights to add a particiant to the chat, or the participant is already in the chat.

    imbot.chat.leave

    Chatbot exit from specified chat

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.leave', Array(
    
       'CHAT_ID' => 13 // Chat ID to exit
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    ACCESS_ERROR Insufficient rights for sending status to this chat.
    BOT_ID_ERROR Chatbot not found.


    imbot.chat.updateTitle

    Chat title update

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.updateTitle', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'TITLE' => 'New name for chat' // New title
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot  
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    TITLE_EMPTY Fail to send new chat title.
    WRONG_REQUEST Title is already set or the specified chat already exists.


    imbot.chat.updateColor

    Chat color update

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.updateColor', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'COLOR' => 'MINT' // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN,  AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot  
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    WRONG_COLOR Color is not included into available colors list.
    WRONG_REQUEST Color is already defined or the existing chat does not exist.


    imbot.chat.updateAvatar

    Updates chat icon

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.updateAvatar', Array(
    
       'CHAT_ID' => 13 // Chat ID
       'AVATAR' => '/* base64 image */' // Image in base64 format
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot    
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID is unavailable.
    AVATAR_ERROR incorrect image format is defined.
    WRONG_REQUEST Chat does not exist.


    imbot.chat.add

    Chatbot creates a chat

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.add', Array(
    
      'TYPE' => 'CHAT' // OPEN - opened to join chat, CHAT - usual chat with invitations, CHAT by default 
       'TITLE' => 'My new private chat', // Chat title
       'DESCRIPTION' => 'Very important chat', // Chat description
       'COLOR' => 'PINK', // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
       'MESSAGE' => 'Welcome to the chat', // First greeting message in the chat
       'USERS' => Array(1,2), // Chat participants (req.)
       'AVATAR' => '/* base64 image */', // Chat icon in base64 format
       'ENTITY_TYPE' => 'CHAT', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
       'ENTITY_ID' => 13, // Entity numerical ID; it can be used for chat search and for easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
       'OWNER_ID' => 39, // Chat owner ID. May not be specified, if your are creating chat under the necessary user.
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot
    
    ), $_REQUEST["auth"]);
    
    Required fields: USERS (chat participants).

    Return:

    CHAT_ID or error.

    Possible error codes

    Code Description
    USERS_EMPTY No chat participants.
    WRONG_REQUEST Something went wrong.

    imbot.chat.get

    Gets chat ID

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.get', Array(
    
       'ENTITY_TYPE' => 'OPEN', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE (req.)
       'ENTITY_ID' => 13, // Numerical entity ID; it can be used for chat search and easy context definition in the following events handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE  (req.)
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot
       
    ), $_REQUEST["auth"]);
    

    Required fields :

    • ENTITY_TYPE - arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc); it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.
    • ENTITY_ID - numeric entity ID; it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.

    Return:

    Returns: returns chat ID CHAT_ID or null.


    imbot.chat.setOwner

    Chatbot changes a chat owner

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Method call

    $result = restCommand('imbot.chat.setOwner', Array(
    
    
       'CHAT_ID' => 13 // Chat ID
       'USER_ID' => '2' // New chat owner ID
       'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot    
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID was not transmitted.
    USER_ID_EMPTY New chat owner ID was not transmitted.
    WRONG_REQUEST Method is called by user without owner's rights or indicated user is not a chat participant.


    imbot.dialog.get

    Gets information about dialog/chat

    Revision: 24

    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Required Description Revision
    DIALOG_ID chat29 Yes Chat ID for image upload 24

    Method call

    JavaScript

    BX24.callMethod('imbot.dialog.get', {
    	DIALOG_ID: 'chat29'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('imbot.dialog.get', Array(
    	'DIALOG_ID': 'chat29'
    ), $_REQUEST["auth"]);
    

    Response example

    {
        "result": 
      {
        "id": "21191",
        "title": "Mint chat No.3",
        "owner": "2",
        "extranet": false,
        "avatar": "",
        "color": "#4ba984",
        "type": "chat",
        "entity_type": "",
        "entity_data_1": "",
        "entity_data_2": "",
        "entity_data_3": "",
        "date_create": "2017-10-14T12:15:32+02:00",
        "message_type": "C"
      }
    }
    

    Key description:

    • id – chat ID
    • title – chat name
    • owner – chat owner ID
    • extranet – extranet user chat participation attribute (true/false)
    • color – chat color in hex format
    • avatar – link to avatar (when empty - avatar is not defined)
    • type – chat type (group chat, chat for call, Open Channel chat, etc)
    • entity_type – chat external code - type
    • entity_id – chat external code – ID
    • entity_data_1 – external data for chat
    • entity_data_2 – external data for chat
    • entity_data_3 – external data for chat
    • date_create – chat created date in АТОМ format
    • message_type – chat message type

    Example of response with error

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Key description:

    • error – returned error code
    • error_description – error brief description

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Chat ID not passed
    ACCESS_ERROR Current user doesn't have access permissions to chat

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Messages

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    МетодMethod description
    imbot.message.add Sends a chatbot message.
    imbot.message.update Updates (changes) the chatbot message.
    imbot.message.delete Deletes chatbot message.
    imbot.message.like Sets message "Like".
    imbot.chat.sendTyping Sends "Chatbot is typing a message...".

    Attention! These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.



    imbot.message.add

    Sends message from chatbot

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.

    Method call

    $result = restCommand('imbot.message.add', Array(
    
         'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
        'DIALOG_ID' => 1, // Dialog ID: it can be either USER_ID, or chatXX - where XX is chat ID, transmitted in events ONIMBOTMESSAGEADD and ONIMJOINCHAT
        'MESSAGE' => 'answer text' // Message text
        'ATTACH' => '' // Attachment, optional field 
        'KEYBOARD' => '' // Keyboard, optional field 
        'MENU' => '' // Context menu, optional field
        'SYSTEM' => 'N' // Display messages as system messages, optional field, by default 'N'
        'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, by default 'Y'
    
    ), $_REQUEST["auth"]);
    

    You can post message on behalf of bot in private dialogues (they will be shown as system message). To do it, specify FROM_USER_ID and TO_USER_ID instead of DIALOG_ID.

    Return

    Message identifier: MESSAGE_ID or an error.

    Related links:

    Possible errors:

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    DIALOG_ID_EMPTY Dialogue ID is not transmitted.
    MESSAGE_EMPTY Message text is not transmitted.
    ATTACH_ERROR Complete transmitted object was not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    MENU_ERROR Complete transmitted menu object was not validated.
    MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).
    WRONG_REQUEST Something went wrong.


    imbot.message.update

    Updates (changes) the chatbot message

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.

    Method call

    $result = restCommand('imbot.message.update', Array(
    
        'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
        'MESSAGE_ID' => 1, // Message ID
        'MESSAGE' => 'answer text' // Message text, optional field, if null value is specified – message will be deleted
        'ATTACH' => '' // Attachment, optional field 
        'KEYBOARD' => '' // Keyboard, optional field 
        'MENU' => '' // Context menu, optional field
        'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, by default 'Y'
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Related links

    Possible error codes

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    MESSAGE_EMPTY Message text is not transmitted.
    CANT_EDIT_MESSAGE You do not have access to this message or time to modify it has expired (more than 3 days passed since publishing).
    ATTACH_ERROR Complete transmitted attachment was not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    MENU_ERROR Complete transmitted menu object was not validated.
    MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).


    imbot.message.delete

    Deletes chatbot message

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.

    Method call

    $result = restCommand('imbot.message.delete', Array(
    
        'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
        'MESSAGE_ID' => 1, // Message ID
        'COMPLETE' => 'N', //  If message is required to be deleted completely, without a trace, then specify 'Y' (optional parameter)
    
    ), $_REQUEST["auth"]);
    

    Return

    true or error.

    Possible error codes

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    MESSAGE_ID_ERROR Message ID was not transmitted.
    CANT_EDIT_MESSAGE You do not have access to this message or time to modify it has expired (more than 3 days passed since publishing).


    imbot.message.like

    Message «Like»

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.

    Method call

    $result = restCommand('imbot.message.like', Array(
    
        'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
        'MESSAGE_ID' => 1, // Message ID (any message, sent in personal dialogues or in group chats, where chatbot is located)
        'ACTION' => 'auto' // Action, connected with method: plus – click «Like»; minus – «Like» is removed; auto – automatic calculation, tick should/shouldn't be specified. If not specified, it will work in auto mode 
    
    ), $_REQUEST["auth"]);
    

    Return

    true or error.

    Possible error codes

    Code Description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    MESSAGE_ID_ERROR Message ID was not transmitted.
    WITHOUT_CHANGES After «Like» status call, it did not change.


    imbot.chat.sendTyping

    Sends "Chatbot is typing a message...»

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.

    Method call

    $result = restCommand('imbot.chat.sendTyping', Array(
    
        'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
        'DIALOG_ID' => 1, // Dialogue ID, it is either USER_ID, or chatXX – where XX is chat ID, transmitted in events ONIMBOTMESSAGEADD and ONIMJOINCHAT
    
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Related links:

    Possible error codes

    Code Description
    BOT_ID_ERROR Chatbot not found.
    DIALOG_ID_EMPTY Dialogue ID not transmitted.


    Commands

    Commands include general and local:
    • General commands work in any dialogue or chat. Example of such chat (COMMON = Y):
      /giphy picture
      

      Such command call in any chat formulates the response from chatbot, even if the chat doesn't have a chatbot.


    • Local commands work only in personal corresponding with the Chatbot and in group chats, where chatbot is a participant. The example of such command (COMMON = N):
      /help
      

      Call of this command in EchoBot example will return the list of accessible commands.


    Working with Commands

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    MethodDescription
    imbot.command.register Registers command for processing by chatbot.
    imbot.command.unregister Deletes a command processing.
    imbot.command.update Updates data in command.
    imbot.command.answer Publishes response to command.

    Note: Command processing requires for application to process a command-adding event ONIMCOMMANDADD.



    imbot.command.register

    Registers command for processing by chatbot

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: Command processing requires for application to process a command-adding event ONIMCOMMANDADD.

    Method call

    $result = restCommand('imbot.command.register', Array(
    
       'BOT_ID' => 62, // Command owner chatbot ID 
       'COMMAND' => 'echo', // Text of command, which user will enter in chats 
       'COMMON' => 'Y', // If 'Y’ is specified, then the command is accessible in all chats, if ‘N’ – then it is accessible only in chats with chatbot
        'HIDDEN' => 'N', // Hidden command or not – ‘N’ by default 
       'EXTRANET_SUPPORT' => 'N', // Extranet users access to command, ‘N’ by default
        'CLIENT_ID' => '', // chatbot string ID, used only in Webhooks mode 
       'LANG' => Array( // Array of translations, preferably to specify, as a minimum for ENG
          Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Get echo message', 'PARAMS' => 'some text'), // Language, command description, which data to be required to be entered after the command.
       ),
       'EVENT_COMMAND_ADD' => 'http://www.hazz/chatApi/bot.php', // Link to command handler
    
    ), $_REQUEST["auth"]);
    

    Return:

    COMMAND_ID or error.

    Related links:

    Possible error codes

    Code Description
    EVENT_COMMAND_ADD Link to event handler is invalid or not specified.
    COMMAND_ERROR Command text is not specified, to which chatbot should respond.
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
    LANG_ERROR Phrases are not transmitted for visible command.
    WRONG_REQUEST Something went wrong.

    Attention! Bitrix24 REST restricts the work of event handlers, if more than one chatbot is to be installed within single application framework. Only one event handler per one application is permitted. That is why, upon registration of second command, the following links to event handlers EVENT_COMMAND_ADD all be the same as for the first command.

    If processing of several commands is required within single application framework, then it shall be specified inside the event handler. So that during event execution, chatbot array is transmitted for proper processing of chatbots.


    imbot.command.unregister

    Deletes a command processing

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: Command processing requires for application to process a command-adding event ONIMCOMMANDADD.

    Method call

    $result = restCommand('imbot.command.unregister', Array(
    
        'COMMAND_ID' => 13, // Deletion command ID 
        'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
    ), $_REQUEST["auth"]);
    

    Return:

    true or error.

    Possible error codes

    Code Description
    COMMAND_ID_ERROR Command not found.
    APP_ID_ERROR Chatbot is not a part of this application: you can only work with chatbots, installed within application framework.
    WRONG_REQUEST Something went wrong.



    imbot.command.update

    Updates data in command

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: Command processing requires for application to process a command-adding event ONIMCOMMANDADD.

    Method call

    $result = restCommand('imbot.command.update', Array(
    
       'COMMAND_ID' => 13, // Chat ID
       'FIELDS' => Array(
          'EVENT_COMMAND_ADD' => 'http://www.hazz/chatApi/bot.php', // Link to command handler
          'HIDDEN' => 'N', // Command is hidden or not 
          'EXTRANET_SUPPORT' => 'N', // Extranet users command access
          'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
          'LANG' => Array( // New translation phrases, all previous will be deleted  
             Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Get echo message', 'PARAMS' => 'some text'),
          ),
       )
    
    ), $_REQUEST["auth"]);
    

    Required fields: command ID and one of required fields for editing.

    Return:

    true or error.

    Possible error codes

    Code Description
    COMMAND_ID_ERROR Command not found.
    APP_ID_ERROR Chatbot is not a part of this application: you can only work with chatbots, installed within application framework.
    EVENT_COMMAND_ADD Link to event handler invalid or not specified.
    WRONG_REQUEST Something went wrong.

    imbot.command.answer

    Publishes response to command

    Attention! restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Note: Command processing requires for application to process a command-adding event ONIMCOMMANDADD.

    Method call

    $result = restCommand('imbot.command.answer', Array(
    
        'COMMAND_ID' => 13, // ID for command that prepared the report, (required to be specified or COMMAND)
        'COMMAND' => 'echo', // Name of command that prepared the answer (required to be specified or COMMAND_ID)
        'MESSAGE_ID' => 1122, // ID for message that requires an answer
        'MESSAGE' => 'answer text' // Answer text
        'ATTACH' => '' // Attachment, optional field
        'KEYBOARD' => '' // Keyboard, optional field
        'MENU' => '' // Context menu, optional field
        'SYSTEM' => 'N' // Display messages as system message, optional field, 'N' by default
        'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, 'Y' by default
        'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
    
    ), $_REQUEST["auth"]);
    

    Return:

    Command MESSAGE_ID or error.

    Related links:

    Possible error codes

    Code Description
    COMMAND_ID_ERROR Command not found.
    APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application frameworkприложения.
    MESSAGE_EMPTY Message text is not transmitted.
    ATTACH_ERROR Complete transmitted attachment object was not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    MENU_ERROR Complete transmitted object menu was not validated.
    MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).
    WRONG_REQUEST Something went wrong.

    Working with Events

    When generating an event (adding a new message, opening of a dialogue with chatbot, chatbot invitation to a chat, deletion of chatbot from the client side) request for event handler is generated, indicated during bot registration. Find more details about this mechanism here.


    ONAPPINSTALL event to install application

    [data] => Array(
      [LANGUAGE_ID] = eng // Account's basic language 
      [VERSION] = 1 // Application version
    )
    [auth] => Array(
        [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key for sending requests to REST-service
        [scope] => imbot // Permitted access levels
        [domain] => b24.hazz // Bitrix24 account domain on which the application was installed
        [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token. It helps you to “beat back” redundant requests to event handler. All events have this field.
    
        [expires_in] => 3600 // Token expiration time, after which the new one shall be requested
        [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authorization 
        [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authorization
    )
    

    Attention! Basic variant of the work with chatbot, fields expires_in, member_id, refresh_token - are not required. If they are required for your application, you can read more about them here. Example of bot has an option for extension.



    ONAPPUPDATE event to update application

    [data] => Array(
      [LANGUAGE_ID] = eng // Basic language of account 
      [VERSION] = 2 // New version of account
      [PREVIOUS_VERSION] => 1 // Old version of application
    )
    [auth] => Array(
        [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key for requests to REST-service 
        [scope] => imbot // Permitted access levels
        [domain] => b24.hazz // Bitrix24 account domain, on which the application is installed  
        [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token. It helps you to “beat back” redundant requests to event handler. All events have this field.
    
        [expires_in] => 3600 // Token expiration time, after which the new one shall be requested
        [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authorization 
        [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authorization
    )
    


    Attention! All, that is described below – is the content of [data] field in the event. Authoriztion data in the [auth] key contain data of user-initiator of event. To receive bot authorization data, use [data][BOT][__BOT_CODE__].

    ONIMBOTMESSAGEADD event initiated when chatbot receives a message

    [BOT] => Array // Codes array for chatbots, to which the message is intended, 
    (
        [39] => Array
        (
       [AUTH] => Array // Parameters for authorization as chatbot, to complete actions 
             (
                [domain] => b24.hazz
                [member_id] => d41d8cd98f00b204e9800998ecf8427e
                [application_token] => 8006ddd764e69deb28af0c768b10ed65
             )
            [BOT_ID] => 39    
            [BOT_CODE] => newbot
        )
    )
    [PARAMS] => Array // Message data array 
    (
        [DIALOG_ID] => 1    // Dialogue ID
        [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
        [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
        [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
        [MESSAGE_ID] => 392 // Message ID
        [MESSAGE] => test3 // Message
        [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
        [FROM_USER_ID] => 1 // User ID who sent a message 
        [TO_USER_ID] => 1 // Chatbot ID or User ID: it will be Chatbot ID in person-to-person chat, and in group chat - User ID, who received a message. If '0' is specified - it is addressed to all chat participants
        [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
        [LANGUAGE] => com    // Account default language ID
    ).  
    [USER] => Array // Message owner data array, can be empty, if ID = 0
    (
        [ID] => 1 // User ID
        [NAME] => John Smith // User name and last name 
        [FIRST_NAME] => John // User name 
        [LAST_NAME] => Smith // User last name 
        [WORK_POSITION] => // Work position 
        [GENDER] => M // Gender, can be either M (make), or F (female)
        [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
        [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
        [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
        [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
    )
    


    Event for chatbot to update a message
    ONIMBOTMESSAGEUPDATE

    [BOT] => Array // Codes array for chatbots, to which the message is intended
    (
        [39] => Array
        (
       [AUTH] => Array // Parameters for authorization as chatbot, to perform actions
             (
                [domain] => b24.hazz
                [member_id] => d41d8cd98f00b204e9800998ecf8427e
                [application_token] => 8006ddd764e69deb28af0c768b10ed65
             )
            [BOT_ID] => 39    
            [BOT_CODE] => newbot
        )
    )
    [PARAMS] => Array // Message data array
    (
        [DIALOG_ID] => 1    // Dialogue ID
        [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
        [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
        [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
        [MESSAGE_ID] => 392 // Message ID
        [MESSAGE] => test3 // Message
        [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
        [FROM_USER_ID] => 1 // User ID who sent a message 
        [TO_USER_ID] => 1 // Chatbot ID or User ID: it will be Chatbot ID in person-to-person chat, and in group chat - User ID, who received a message. If '0' is specified - it is addressed to all chat participants
        [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
        [LANGUAGE] => com    // Account default language ID
    )
    [USER] => Array // Message owner data array, can be empty, if ID = 0
    (
        [ID] => 1 // User ID
        [NAME] => John Smith // User name and last name 
        [FIRST_NAME] => John // User name 
        [LAST_NAME] => Smith // User last name 
        [WORK_POSITION] => // Work position 
        [GENDER] => M // Gender, can be either M (make), or F (female)
        [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
        [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
        [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
        [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
    )
    


    Event for chatbot to delete a message
    ONIMBOTMESSAGEDELETE

    [BOT] => Array // Codes array for chatbots, to which the message is intended
    (
        [39] => Array
        (
       [AUTH] => Array // Parameters for authorization as chatbot, to perform actions
             (
                [domain] => b24.hazz
                [member_id] => d41d8cd98f00b204e9800998ecf8427e
                [application_token] => 8006ddd764e69deb28af0c768b10ed65
             )
            [BOT_ID] => 39    
            [BOT_CODE] => newbot
        )
    )
    [PARAMS] => Array // Message data array
    (
        [DIALOG_ID] => 1    // Dialogue ID
        [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
        [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
        [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
        [MESSAGE_ID] => 392 // Message ID
        [MESSAGE] => test3 // Message
        [FROM_USER_ID] => 1 // User ID who sent a message 
        [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
        [LANGUAGE] => com    // Account default language ID
    )
    [USER] => Array // Message owner data array, can be empty, if ID = 0
    (
        [ID] => 1 // User ID
        [NAME] => John Smith // User name and last name 
        [FIRST_NAME] => John // User name 
        [LAST_NAME] => Smith // User last name 
        [WORK_POSITION] => // Work position 
        [GENDER] => M // Gender, can be either M (make), or F (female)
        [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
        [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
        [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
        [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
    )
    


    ONIMCOMMANDADD event for chatbot to receive command

    [COMMAND] => Array // Commands array, which are called by the user
    (
        [14] => Array 
        (
          [AUTH] => Array // Parameters to authorize as chatbot to perform actions
          (
             [domain] => b24.hazz
             [member_id] => d41d8cd98f00b204e9800998ecf8427e
             [application_token] => 8006ddd764e69deb28af0c768b10ed65
          )
          [BOT_ID] => 62 // Chatbot ID
          [BOT_CODE] => echobot // Chatbot code
          [COMMAND] => echo // Called command
          [COMMAND_ID] => 14 // Command ID
          [COMMAND_PARAMS] => test // Parameters, with which the command was called 
          [COMMAND_CONTEXT] => TEXTAREA // Command execution context. TEXTAREA - if the command is inputted manually, or KEYBOARD, if a keyboard key is pressed
          [MESSAGE_ID] => 1221 // Message ID, which needs a response
        )
    )
    [PARAMS] => Array // Message data array
    (
        [DIALOG_ID] => 1    // Dialogue ID
        [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
        [MESSAGE_ID] => 1221 // Message ID
        [MESSAGE] => /echo test // Message
        [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
        [FROM_USER_ID] => 1 // User ID who sent a message 
        [TO_USER_ID] => 2 // Other user ID (accessible only in person-to-person chats)
        [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
        [LANGUAGE] => com    // Account default language ID
    
    )
    [USER] => Array // Message owner data array, can be empty, if ID = 0
    (
        [ID] => 1 // User ID
        [NAME] => John Smith // User name and last name 
        [FIRST_NAME] => John // User name 
        [LAST_NAME] => Smith // User last name 
        [WORK_POSITION] => // Work position 
        [GENDER] => M // Gender, can be either M (make), or F (female)
    )
    


    ONIMBOTJOINCHAT event initiated then chatbot receives information that it has joined a chat (or private chat)

    [BOT] => Array // Code array for chatbot, for which the event is intended 
    (
        [39] => Array // Parameters for authorization as chatbot to perform actions 
        (
       [AUTH] => Array // Parameters for authorization as chatbot to perform actions
            (
                [domain] => b24.hazz 
                [member_id] => d41d8cd98f00b204e9800998ecf8427e
                [application_token] => 8006ddd764e69deb28af0c768b10ed65
            )
            [BOT_ID] => 39    
            [BOT_CODE] => newbot
        )
    )
    [PARAMS] => Array
    (	
        [DIALOG_ID] => 1    // Dialogue ID
     [MESSAGE_ID] => 392 // Message ID
        [CHAT_TYPE] => P    // Type of message and chat, can be P (one-on-one chat), C (with limited number of participants), O (public chat)
        [CHAT_ENTITY_TYPE] => 'LINES'    // Chat subtype, can have LINES value (Open Channels) or empty 
        [USER_ID] => 1   // User ID (for person-to-person chats – user who opened chatbot, for group chats – user who invited chatbot)
        [LANGUAGE] => com    // Account default language ID
    )
    [USER] => Array // Message owner data array, can be empty, if ID = 0
     (
    
    
    
        [ID] => 1 // User ID
        [NAME] => John Smith // User name and last name 
        [FIRST_NAME] => John // User name 
        [LAST_NAME] => Smith // User last name 
        [WORK_POSITION] => // Work position 
        [GENDER] => M // Gender, can be either M (male), or F (female)
    )
    


    ONIMBOTDELETE event initiated when chatbot is deleted

    [BOT_ID] => 39 // Chatbot ID
    [BOT_CODE] => giphy // Chatbot code
    


    Example of handler code to work with events

    Example is fully functional, saves the configuration into a file: it will help you understand how chatbots generally are functioning.

    File with commentaries and group icon are accessible in the repository at the following address: https://github.com/bitrix24com/bots/

    Full List of Bot API Methods and Events

    Working with chatbots:

    MethodMethod Description
    imbot.register Chatbot registration.
    imbot.unregister Chatbot deletion.
    imbot.update Chatbot data update.
    imbot.bot.list Getting available chat bots.

    Working with chats:

    MethodMethod Description
    imbot.chat.user.list Retrieving list of participants.
    imbot.chat.user.add Participants invitation.
    imbot.chat.user.delete Participants deletion.
    imbot.chat.leave Chatbot exit from specified chat.
    imbot.chat.updateTitle Chat title update.
    imbot.chat.updateColor Chat color update.
    imbot.chat.updateAvatar Chat icon update.
    imbot.chat.add Creating a chat by chatbot.
    imbot.chat.get Getting chat ID.
    imbot.chat.setOwner Chat owner change by chatbot.
    imbot.dialog.get Getting dialog data.

    Working with messages:

    MethodMethod Description
    imbot.message.add Sends message from chatbot.
    imbot.message.update Updates (changes) chatbot message.
    imbot.message.delete Deletes chatbot message.
    imbot.message.like Sets message "Like".
    imbot.chat.sendTyping Sends "Chatbot is typing a message...".

    Working with commands:

    MethodMethod Description
    imbot.command.register Registration of command to be processed by chatbot.
    imbot.command.unregister Command processing deletion.
    imbot.command.update Command data update.
    imbot.command.answer Posting command answer.

    Working with events:

    EventEvent description
    ONAPPINSTALL Application installation event.
    ONAPPUPDATE Application update event.
    ONIMBOTMESSAGEADD Event for chatbot to receive message.
    ONIMBOTMESSAGEUPDATE Event for chatbot to update message.
    ONIMBOTMESSAGEDELETE Event for chatbot to delete message.
    ONIMCOMMANDADD Event for chatbot to receive a command.
    ONIMJOINCHAT Event for chatbot to receive information that it has joined a chat (or private chat).
    ONIMBOTDELETE Event to delete chatbot.

    Chat API

    To work with Chat API when creating an application (or loading of new app version) the im (Chat and notifications) scope must be specified.


    Platform version

    im.revision.get

    The method gets information about API revisions

    Revision: 18

    Parameters

    None.

    Call example

    JavaScript

    BX24.callMethod('im.revision.get', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.revision.get', Array(
    ), $_REQUEST["auth"]);
    

    Example of response

    {    
    	"result": {
    		"rest": 18,
    		"web": 117,
    		"mobile": 9,
    	}
    }
    

    Description of keys:

    • rest – API revision for REST clients
    • web – API revision for web/desktop client
    • mobile – API revision for mobile client

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    Working with Chats

    Note: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    MethodDescription
    im.chat.add Creates a chat.
    im.chat.user.list Gets list of participants.
    im.chat.user.add Invites participants.
    im.chat.user.delete Excludes participants.
    im.chat.leave Updates chat title.
    im.chat.updateTitle Updates chat title.
    im.chat.updateColor Updates chat color.
    im.chat.updateAvatar Updates chat avatar.
    im.chat.setOwner Change chat owner.
    im.chat.get Gets chat ID.
    im.chat.mute Disables notifications in chat.


    im.chat.add

    Creates chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Req. Description Revision
    TYPE CHAT No Chat type OPEN | CHAT
    (OPEN - open for joining, CHAT - standard chat by invitations, default value: CHAT)
    18
    TITLE New private chat No Chat title 18
    DESCRIPTION Very important chat No Chat description 18
    COLOR PINK No Chat color for mobile app: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE 18
    MESSAGE Welcome to chat No First salutation message in chat 18
    USERS Array(1,2) Yes Chat participants 18
    AVATAR base64 image No Chat avatar in base64 format 18
    ENTITY_TYPE CHAT No Entity ID, can be implemented for searching by this field and for simple context definition in event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE 18
    ENTITY_ID 13 No Entity numerical ID, can be used for chat search and for simple context definition in event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE 18
    OWNER_ID 39 No Chat owner ID. May be skipped, query sender is assigned as owner. 18

    Calling method and response

    PHP

    $result = restCommand('im.chat.add', Array(
    
       'TYPE' => 'CHAT',
       'TITLE' => 'My new private chat',
       'DESCRIPTION' => 'Very important chat',
       'COLOR' => 'PINK',
       'MESSAGE' => 'Welcome to chat',
       'USERS' => Array(1,2), 
       'AVATAR' => 'base64 image',
       'ENTITY_TYPE' => 'CHAT',
       'ENTITY_ID' => 13,
       'OWNER_ID' => 39,
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": 123
    }
    

    Response example on error

    {
        "error": "USERS_EMPTY",
        "error_description": "Chat participants not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    USERS_EMPTY Chat participants not passed
    WRONG_REQUEST Something went wrong

    im.chat.user.list

    Gets list of participants

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18

    Called method and response

    PHP

    $result = restCommand('im.chat.user.list', Array(
    
       'CHAT_ID' => 13
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": [1,2]
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed or incorrect ID is passed.

    im.chat.user.add

    Invites participants

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18
    USERS Array(3,4) Yes New user IDs 18
    HIDE_HISTORY N No Shows chat history for the user added using this method. Boolean Y/N - "N" by default. New user won't see the chat history, if passed as "Y". 18

    Called method and response

    PHP

    $result = restCommand('im.chat.user.add', Array(
    
       'CHAT_ID' => 13,
       'USERS' => Array(3,4)
       'HIDE_HISTORY' => N,
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief code

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    WRONG_REQUEST You don't have sufficient access permissions for adding participants to chat or participant already included into chat

    im.chat.user.delete

    Excludes participants

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18
    USER_ID 4 Yes Excluded user ID 18

    Called method and response

    PHP

    $result = restCommand('im.chat.user.delete', Array(
    
       'CHAT_ID' => 13,
       'USER_ID' => 4
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    USER_ID_EMPTY User ID not passed
    WRONG_REQUEST You have insufficient access permissions for adding participants to chat or participant is already included into chat

    im.chat.leave

    Leaves chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18

    Called method and response

    PHP

    $result = restCommand('im.chat.leave', Array(
    
       'CHAT_ID' => 13
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    WRONG_REQUEST You are not a member of this chat

    im.chat.updateTitle

    Updates chat title

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 No Chat ID 18
    TITLE New chat name No New title 18

    Called method and response

    PHP

    $result = restCommand('im.chat.updateTitle', Array(
    
       'CHAT_ID' => 13,
       'TITLE' => 'New chat name'
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID now passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    TITLE_EMPTY New chat title not passed
    WRONG_REQUEST Title not set or specified chat doesn't exist

    im.chat.updateColor

    Chat color updates

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18
    COLOR MINT Yes Chat color for mobile app (RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE) 18

    Called method and response

    PHP

    $result = restCommand('im.chat.updateColor', Array(
    
       'CHAT_ID' => 13,
       'COLOR' => 'MINT'
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    WRONG_COLOR Color is not included into the list of available colors
    WRONG_REQUEST Color is already indicated or indicated color doesn't exist

    im.chat.updateAvatar

    Updates avatar chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18
    AVATAR /* base64 image */ Yes Image in base64 format 18

    Called method and response

    PHP

    $result = restCommand('im.chat.updateAvatar', Array(
    
       'CHAT_ID' => 13,
       'AVATAR' => '/* base64 image */'
    
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    AVATAR_ERROR Incorrect image format is not passed
    WRONG_REQUEST Chat doesn't exist

    im.chat.setOwner

    Changes chat owner

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 13 Yes Chat ID 18
    USER_ID 2 Yes New chat owner ID 18

    Called method and response

    PHP

    $result = restCommand('im.chat.setOwner', Array(
    
       'CHAT_ID' => 13,
       'USER_ID' => '2'
    
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID is not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    USER_ID_EMPTY New chat owner ID is not passed
    WRONG_REQUEST Method is called by a regular non-owner chat participant or specified user is not a chat participant

    im.chat.get

    Gets chat ID

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    ENTITY_TYPE CRM - for CRM,
    [dw]LINES[/dw][di]From agent/operator[/di] or [dw]LIVECHAT[/dw][di]From user[/di] - for open lines
    Yes Entity ID. Can be used for chat search or defining context in event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE 18
    ENTITY_ID LEAD|13 - for CRM,
    facebook|2|1647215182041969|862 - for [dw]open lines[/dw][di]ENTITY_ID matches with USER_CODE from session.[/di]
    Yes Entity numerical ID. Can be used for chat search or defining context in event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE 18

    Called method and response

    PHP

    $result = restCommand('im.chat.get', Array(
    
       'ENTITY_TYPE' => 'CRM',
       'ENTITY_ID' => 'LEAD|13',
       
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": 10
    }
    
    Result: returns CHAT_ID or null.

    im.chat.mute

    Disables notifications in chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    CHAT_ID 17 Yes Chat ID 19
    MUTE Y Yes Disable or enable notifications - Y|N 19
    • Variants for MUTE key: Y или N.

    Called method and response

    JavaScript

    BX24.callMethod('im.chat.mute', {
    	'CHAT_ID': 17,
    	'MUTE': 'Y'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.chat.mute', Array(
    	'CHAT_ID' => 17,
    	'MUTE' => 'Y'
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID can't be empty"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed

    Working with Dialogs


    MethodMethod description
    im.dialog.messages.get Gets list of recent chat messages.
    im.dialog.read Modifies the 'message unread' status: all messages prior the specified message (but including the message itself) are marked as read.
    im.dialog.unread Modifies the 'message read' status: all messages after the specified message (but including the message itself) are marked as unread.

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Methods, indicated using javascript method BX24.callMethod:

    MethodMethod description
    im.dialog.users.list Gets information about chat participants (supports pagination).
    im.dialog.writing Sends status "writing to...".
    im.dialog.read.all Set «read» mark for all dialogs.


    im.dialog.messages.get

    Gets list of recent chat messages

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    USER_ID 1 Yes Dialog ID. Format:
    chatXXX – recipient chat, in case of chat message
    or XXX – recipient ID, in case of private conversation
    19
    LAST_ID 28561624 No ID of the last loaded message 19
    FIRST_ID 454322 No ID of the first loaded message 19
    LIMIT 20 No Limiting of number of selected messages in dialog 19
    • If the LAST_ID and FIRST_ID keys were not passed, the last 20 chat messages will be loaded.
    • To load next 20 messages you must pass LAST_ID with the minimal message ID, received from the last selection.
    • If you need to load next 20 messages, you must pass FIRST_ID with the maximum message ID, received from the last selection.
    • If you need to load first 20 messages, you must pass FIRST_ID with the ID equal to '0'. You will receive the result with the very first message, available to you in this chat.

    Attention! Due to potential significant volume of data, this method does not support standard Bitrix24 REST API page navigation.


    Called method and response

    JavaScript

    BX24.callMethod('im.dialog.messages.get', {
    	DIALOG_ID: 'chat29'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.dialog.messages.get', Array(
    	'DIALOG_ID': 'chat29'
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": {
    		"messages": [
    		  {
    			"id": 28561624,
    			"chat_id": 29,
    			"author_id": 1,
    			"date": "2018-01-29T16:58:47+03:00",
    			"text": "http://squirrel.com",
    			"params": {
    			  "URL_ID": [
    				5
    			  ],
    			  "URL_ONLY": "Y",
    			  "ATTACH": [
    				{
    				  "ID": "5",
    				  "BLOCKS": [
    					{
    					  "RICH_LINK": [
    						{
    						  "NAME": "Squirrel",
    						  "LINK": "http://squirrel.com",
    						  "DESC": "Can find everything",
    						  "PREVIEW": "https://yastatic.net/morda-logo/i/share-logo-ru.png"
    						}
    					  ]
    					}
    				  ],
    				  "COLOR": "transparent"
    				}
    			  ]
    			}
    		  },
    		  {
    			"id": 28561623,
    			"chat_id": 29,
    			"author_id": 28,
    			"date": "2018-01-29T16:43:38+03:00",
    			"text": "",
    			"params": {
    			  "FILE_ID": [
    				540
    			  ]
    			}
    		  },
    		  {
    			"id": 28561622,
    			"chat_id": 29,
    			"author_id": 1,
    			"date": "2018-01-29T16:43:12+03:00",
    			"text": "Its operational :)",
    			"params": {
    			  "IS_EDITED": "Y"
    			}
    		  },
    		  {
    			"id": 28561618,
    			"chat_id": 29,
    			"author_id": 0,
    			"date": "2018-01-25T15:15:22+03:00",
    			"text": "John Harrington changed chat topic to \"The big chat\"",
    			"params": null
    		  },
    		],
    		"users": {
    		  "1": {
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		  },
    		  "28": {
    			"id": 28,
    			"name": "Chris Curtis",
    			"first_name": "Chris",
    			"last_name": "Curtis",
    			"work_position": "manager",
    			"color": "#728f7a",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/8b8/100_100_2/26.jpg",
    			"gender": "M",
    			"birthday": "26-01",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  58
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "8 (97643) 4590-563-2318",
    			  "personal_mobile": "8 (33741) 1578-234-8853",
    			  "personal_phone": ""
    			}
    		  },
    		},
    		"files": {
    			"540": {
    				"id": 540,
    				"chatId": 29,
    				"date": "2018-01-29T16:43:39+03:00",
    				"type": "image",
    				"preview": "",
    				"name": "1176297_698081120237288_696773366_n.jpeg",
    				"size": 55013,
    				"image": {
    					"width": 960,
    					"height": 640
    				},
    				"status": "done",
    				"progress": 100,
    				"authorId": 1,
    				"authorName": "John Harrington",
    				"urlPreview": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/show.file.php?fileId=540&preview=Y&fileName=1176297_698081120237288_696773366_n.jpeg",
    				"urlShow": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/show.file.php?fileId=540&fileName=1176297_698081120237288_696773366_n.jpeg",
    				"urlDownload": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/download.file.php?fileId=540"
    			}
    		},
    		"chat_id": 29
    	}
    }    
    

    Description of keys:

    • messages – array of messages:

      • id – message ID
      • chat_id – chat ID
      • author_id – author of messages (0 - for system message)
      • date – date of the message in ATOM format
      • text – message text
      • params – message parameters, parameter object, if parameters are not passed null (main types are described below)
    • users – user data description objects:

      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – avatar link (if empty, then avatar is not specified)
      • gender – user gender
      • birthday – user birthday in DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channels user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – idle date when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • files – object, describing files in selected messages:

      • id – file ID
      • chatId – chat ID
      • date – date when file is modified
      • type – file type: image – image, file – file
      • name – name of loaded file
      • size – actual size of image in bytes
      • image – actual image size in px
      • width – width in px
      • height – height in px
      • status – current status: done – loaded, upload – loading in progress
      • progress – loading progress percentage: 100 – loaded, -1 – current status unavailable
      • authorId – ID of the user who loaded an object
      • authorName – first and last name of user who loaded an object
      • urlPreview – link to image preview (available fro images)
      • urlShow – link to switch to object in "show" mode
      • urlDownload – link to start the download
    • chat_id – chat ID

    Description of additional parameters:

    • ATTACH – object containing rich formatting
    • KEYBOARD – object containing keyboard description
    • IS_DELETED – flag that specifies message deleting
    • IS_EDITED – flag that specifies that message is edited
    • FILE_ID – array of file IDs
    • LIKE – array of user IDs. Those user 'liked' the message

    Examples of response when error occurs

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Dialog ID not passed
    ACCESS_ERROR Current user does not have appropriate permissions to access the dialog

    im.dialog.read

    Modifies the 'message unread' status: all messages prior the specified message (but including the message itself) are marked as read

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Req. Description Revision
    DIALOG_ID chat29 Yes Dialog ID (chatXXX for chat and user ID for private dialog) 21
    MESSAGE_ID 12 Yes The ID for the recent read chat message 21

    Called method and response

    JavaScript

    BX24.callMethod('im.dialog.read', {
      'DIALOG_ID': chat29,
      'MESSAGE_ID': 12,
    }, function(result){
      if(result.error())
      {
        console.error(result.error().ex);
      }
      else
      {
        console.log(result.data());
      }
    });
    

    PHP

    $result = restCommand('im.dialog.read', Array(
      'DIALOG_ID' => chat29,
      'MESSAGE_ID' => 12,  
    ), $_REQUEST["auth"]);
    

    Response example

    {
      "result": true
    } 
    
    {
        "result": 
        {
            dialogId: "chat76", 
            chatId: 76, 
            counter: 1, 
            lastId: 6930
        }
    } 
    
    • dialogId – read chat ID
    • chatId – chat ID
    • counter – number of unread messages after method execution
    • lastId – recent read message

    When method is unable to set new read tag:

    {
     "result": false
    }
    

    Examples of response with error

    {
        "error": "MESSAGE_ID_ERROR",
        "error_description": "Message ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief error description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Incorrect message ID
    DIALOG_ID_EMPTY Incorrect dialog ID

    im.dialog.unread

    Modifies the 'message read' status: all messages after the specified message (but including the message itself) are marked as unread

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Req. Description Revision
    DIALOG_ID chat29 Yes Dialog ID (chatXXX for chat and user ID for private dialog) 21
    MESSAGE_ID 12 Yes Dialog ID. Format:
    chatXXX – recipient chat in case of chat message
    or XXX – recipient ID, in case of private conversation message
    21

    Method call

    JavaScript

    BX24.callMethod('im.dialog.unread', {
      'DIALOG_ID': chat29,
      'MESSAGE_ID': 12,
    }, function(result){
      if(result.error())
      {
        console.error(result.error().ex);
      }
      else
      {
        console.log(result.data());
      }
    });
    

    PHP

    $result = restCommand('im.dialog.unread', Array(
      'DIALOG_ID' => chat29,
      'MESSAGE_ID' => 12,  
    ), $_REQUEST["auth"]);
    

    Response example

    {
      "result": true
    } 
    

    Examples of response with error

    {
        "error": "MESSAGE_ID_ERROR",
        "error_description": "Message ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Incorrect message ID
    DIALOG_ID_EMPTY Incorrect dialog ID

    im.dialog.get

    Gets information about dialog/chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    DIALOG_ID chat29 Yes Dialog ID. Format:
    chatXXX – recipient chat, in case of chat message
    or XXX – recipient ID in case of private conversation message
    24


    Method call and response

    JavaScript

    BX24.callMethod('im.dialog.get', {
    	DIALOG_ID: 'chat29'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.dialog.get', Array(
    	'DIALOG_ID': 'chat29'
    ), $_REQUEST["auth"]);
    

    Response example

    {
        "result": 
      {
        "id": "21191",
        "title": "Mint chat No.3",
        "owner": "2",
        "extranet": false,
        "avatar": "",
        "color": "#4ba984",
        "type": "chat",
        "entity_type": "",
        "entity_data_1": "",
        "entity_data_2": "",
        "entity_data_3": "",
        "date_create": "2017-10-14T12:15:32+02:00",
        "message_type": "C"
      }
    }
    

    Key description:

    • id – chat ID
    • title – chat name
    • owner – chat owner ID
    • extranet – extranet user chat participation attribute (true/false)
    • color – chat color in hex format
    • avatar – link to avatar (when empty - avatar is not defined)
    • type – chat type (group chat, chat for call, Open Channel chat, etc)
    • entity_type – chat external code - type
    • entity_id – chat external code – ID
    • entity_data_1 – external data for chat
    • entity_data_2 – external data for chat
    • entity_data_3 – external data for chat
    • date_create – chat created date in АТОМ format
    • message_type – chat message type

    Example of response with error

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Key description:

    • error – returned error code
    • error_description – error brief description

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Chat ID not passed
    ACCESS_ERROR Current user doesn't have access permissions for chat

    im.dialog.users.list

    Gets information about chat participants (supports pagination)

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

    Parameters

    Parameter Example Required Description Revision
    DIALOG_ID chat74 Yes Dialog ID. Format:
    • chatXXX – recipient chat in case of chat message
    • or
    • XXX – recipient ID, in case of private conversation message
    30
    SKIP_EXTERNAL N No Skip all system users - 'Y'|'N' (default 'N') 30
    SKIP_EXTERNAL_EXCEPT_TYPES 'bot, email' No String with system user types to be shown in selection 30

    Called method and response

    JavaScript

    B24.callMethod(
      'im.dialog.users.list',
      {
        DIALOG_ID: 'chat74',
        SKIP_EXTERNAL: 'Y'
      },
      res => {
        if (res.error())
        {
          console.error(result.error().ex);
        }
        else
        {
          console.log(res.data())
        }
      }
    )
    

    Response example

    [
      {
        "id": 1019,
        "active": true,
        "name": "alexa shasha",
        "first_name": "alexa",
        "last_name": "shasha",
        "work_position": "",
        "color": "#df532d",
        "avatar": "",
        "gender": "M",
        "birthday": "",
        "extranet": false,
        "network": false,
        "bot": false,
        "connector": false,
        "external_auth_id": "default",
        "status": "online",
        "idle": false,
        "last_activity_date": "2021-10-30T11:24:12+02:00",
        "mobile_last_date": "2021-10-20T13:02:33+02:00",
        "absent": false,
        "departments": [
          1
        ],
        "phones": false
      },
      {
        "id": 1,
        "active": true,
        "name": "John Smith",
        "first_name": "John",
        "last_name": "Smith",
        "work_position": "",
        "color": "#df532d",
        "avatar": "",
        "gender": "M",
        "birthday": "",
        "extranet": false,
        "network": false,
        "bot": false,
        "connector": false,
        "external_auth_id": "default",
        "status": "online",
        "idle": false,
        "last_activity_date": "2021-10-30T13:36:34+02:00",
        "mobile_last_date": "2021-10-27T16:39:26+02:00",
        "absent": false,
        "departments": [
          1
        ],
        "phones": false
      }
    ]
    

    Key description:

    • id – user ID
    • active – active user status (not dismissed)
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in hex format
    • avatar – avatar link (empty indicates that avatar is not specified)
    • gender – user gender
    • birthday – user birthday in DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channels user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – idle date when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • departments – department IDs
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array with phone numbers:
      • work_phone – work phone
      • personal_mobile – mobile phone
      • personal_phone – personal phone

    Examples of response on errors

    {
      "error":"DIALOG_ID_EMPTY",
      "error_description":"Dialog ID can\u0027t be empty"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Parameter DIALOG_ID is not specified or doesn't match the format
    ACCESS_ERROR Current user doesn't have access to data


    im.dialog.writing

    Sends status "writing to..."

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

    Parameters

    Parameter Example Required Description Revision
    DIALOG_ID 13 Yes Dialog ID. Format:
    • chatXXX – recipient chat, in case of chat
    • or
    • XXX – recipient ID, in case of private conversation
    30

    Called method and response

    JavaScript

    B24.callMethod(
      'im.dialog.writing',
      {},
      function(result){
        if(result.error())
        {
            console.error(result.error().ex);
        }
        else
        {
            console.log(result.data());
        }
    });
    

    Response example

    true
    

    Example of response on error

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Parameter DIALOG_ID not passed on doesn't match to format XXX
    CHAT_ID_EMPTY Parameter DIALOG_ID not passed or doesn't match the format chatXXX
    ACCESS_ERROR User doesn't have access permission to this chat


    im.dialog.read.all

    Set «read» mark for all dialogs

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

    Parameters

    Parameters are not passed.

    Called method and response

    JavaScript

    B24.callMethod(
      'im.dialog.read.all',
      {
      },
      res => console.log(res.data())
    )
    

    Response example

    true
    


    Working with Messages


    MethodMethod description
    im.message.add Sends message to chat.
    im.message.update Sends chatbot message edits.
    im.message.delete Deletes chatbot messages.
    im.message.like Sets a message "Like".

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Methods, indicated using javascript method BX24.callMethod:

    MethodMethod description
    im.message.command Use bot commands.
    im.message.share Create new entities by chat message: new chat, task, Feed post, calendar event.


    im.message.update

    Sends chatbot message updates

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    MESSAGE_ID 1 Yes Message ID 18
    MESSAGE Message text No Message text. Passing empty value deletes the message 18
    ATTACH No Attachment 18
    URL_PREVIEW Y No Convert links to rich links 18
    KEYBOARD No Keyboard 18
    MENU No Context menu 18

    Related links:

    Using keboards
    Using attachments
    Formatting


    Calling methods and response

    PHP

    $result = restCommand('im.message.update', Array(
    
        'MESSAGE_ID' => 1,
        'MESSAGE' => 'Message text',
        'ATTACH' => '',
        'URL_PREVIEW' => 'Y',
        'KEYBOARD' => '',
        'MENU' => '',
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    
    Result выпонения: true or error.


    Response example on error

    {
        "error": "MESSAGE_ID_ERROR",
        "error_description": "Message ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Message ID not passed
    CANT_EDIT_MESSAGE You don't have access to this message or time for its edit has expired (more than 3 days has passed since publication)
    ATTACH_ERROR Complete passed attachment object not validated
    ATTACH_OVERSIZE Maximum permissible attachment size exceeded (30 Kb)
    KEYBOARD_ERROR Complete sent keyboard object was not validated
    KEYBOARD_OVERSIZE Maximum permissible keyboard size exceeded (30 Kb)
    MENU_ERROR Complete passed menu object not validated
    MENU_OVERSIZE Maximum permissible menu size exceeded (30 Kb)

    im.message.delete

    Deletes chatbot message

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    MESSAGE_ID 1 Yes Message ID 18

    Called method and response

    PHP

    $result = restCommand('im.message.delete', Array(
    
        'MESSAGE_ID' => 1,
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": true
    }
    
    Result: true or error.


    Example of response on error

    {
        "error": "MESSAGE_ID_ERROR",
        "error_description": "Message ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Message ID not passed
    CANT_EDIT_MESSAGE You don't have access to this message

    im.message.like

    Sets "like"

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    MESSAGE_ID 1 Yes Message ID (any message sent in private conversations or group chats with chatbot available) 18
    ACTION auto No Action, associated with the method: plus - set the "Like"; minus - removes the "Like"; auto - automatically calculates if the Like is to be set. When parameter is not specified, operates in auto mode 18

    Called method and response

    PHP

    $result = restCommand('im.message.like', Array(
    
        'MESSAGE_ID' => 1,
        'ACTION' => 'auto',
    
    ), $_REQUEST["auth"]);
    

    Example response

    {
    	"result": true
    }
    
    Result: true or error.


    Example of response on error

    {
        "error": "MESSAGE_ID_ERROR",
        "error_description": "Message ID not passed"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Message ID not passed
    WITHOUT_CHANGES "Like" status didn't change after the call

    im.message.add

    Sends message to chat

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

    Parameters

    Parameter Example Required Description Revision
    DIALOG_ID chat13
    or
    256
    Yes Dialog ID. Format:
    chatXXX – recipient chat, in case of message for chat
    or XXX – recipient ID, in case of private conversation message
    18
    MESSAGE Message text Yes Message text 18
    SYSTEM N No Show message as a system message. Optional fields, 'N' by default. 18
    ATTACH No Attachment 18
    URL_PREVIEW Y No Convert links to rich links. Optional field, 'Y' by default 18
    KEYBOARD No Keyboard 18
    MENU No Context menu 18

    Called method and response

    PHP

    $result = restCommand('im.message.add', Array(
    
        'DIALOG_ID' => 'chat13',
        'MESSAGE' => 'Message text',
        'SYSTEM' => 'N',
        'ATTACH' => '',
        'URL_PREVIEW' => 'Y',
        'KEYBOARD' => '',
        'MENU' => '',
    
    ), $_REQUEST["auth"]);
    

    Response example

    {
    	"result": 11
    }
    
    Executed result: MESSAGE_ID or an error.


    Response example on error

    {
        "error": "USER_ID_EMPTY",
        "error_description": "Recipient ID not specified for person-to-person chat message"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    USER_ID_EMPTY Recipient code not specified for person-to-person chat message
    CHAT_ID_EMPTY Message recipient chat not specified for a chat message
    ACCESS_ERROR Insufficient access permissions to send the message
    MESSAGE_EMPTY Message text not passed
    ATTACH_ERROR Весь переданный объект вложения не прошел валидацию
    ATTACH_OVERSIZE Maximum allowed attachment size exceeded (30 Kb)
    KEYBOARD_ERROR Complete passed keyboard object was not validated
    KEYBOARD_OVERSIZE Maximum permissible keyboard size exceeded (30 Kb)
    MENU_ERROR Complete passed menu object not validated
    MENU_OVERSIZE Maximum permissible menu size exceeded (30 Kb)
    PARAMS_ERROR Something went wrong

    im.message.command

    Uses bot command

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

    Parameters

    Parameter Example Required Description Revision
    MESSAGE_ID 278 Yes Message ID with option to send a bot command 30
    BOT_ID 1 Yes Bot ID in chat 30
    COMMAND 'KEYBOARD' Yes Command to be executed by bot 30
    COMMAND_PARAMS 'stop' Yes Command parameters 30

    Pass the message with selection of bot commands.


    Called method and response

    JavaScript

    B24.callMethod(
      'im.message.command',
      {
        MESSAGE_ID: 278,
        BOT_ID: 1,
        COMMAND: 'KEYBOARD',
        COMMAND_PARAMS: 'stop'
      },
      res => {
        if (res.error())
        {
          console.error(result.error().ex);
        }
        else
        {
          console.log(res.data())
        }
      }
    )
    

    Response example

    true
    

    Example of response on error

    {
      "error":"PARAMS_ERROR",
      "error_description":"Incorrect params"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Parameter MESSAGE_ID not specified or isn't an integer
    BOT_ID_ERROR Parameter BOT_ID not specified or isn't an integer
    COMMAND_ERROR Parameter COMMAND not specified
    PARAMS_ERROR Parameter COMMAND_PARAMS not specified or doesn't match the bot parameter command


    im.message.share

    Creates new entities from chat message: new chat, task, Feed post, calendar event

    [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

    Parameters

    Parameter Example Required Description Revision
    MESSAGE_ID 289 Yes Message ID use to create new entity 30
    DIALOG_ID 'chat74' Yes Dialog ID. Format:
    • chatXXX – recipient chat in case of chat message
    • or
    • XXX – recipient ID, in case of private conversation message
    30
    TYPE 'TASK' Yes Created entity type:
    • 'CHAT' – creates new chat based on message
    • 'TASK' – creates new task based on message
    • 'POST' – creates Feed post based on message
    • 'CALEND' – creates calendar event based on message
    30

    Pass the message having the selection of bot commands.


    Called method and response

    JavaScript

    B24.callMethod(
      'im.message.share',
      {
        MESSAGE_ID: 289,
        DIALOG_ID: 'chat74',
        TYPE: 'CHAT',
      },
      res => {
        if (res.error())
        {
          console.error(result.error().ex);
        }
        else
        {
          console.log(res.data())
        }
      }
    )
    

    Response example

    true
    

    Example of response on error

    {
      "error":"PARAMS_ERROR",
      "error_description":"Incorrect params"
    }
    

    Key description:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Code Description
    MESSAGE_ID_ERROR Parameter MESSAGE_ID not specified or isn't an integer
    DIALOG_ID_EMPTY Parameter DIALOG_ID not specified or doesn't match the format
    ACCESS_ERROR Current user doesn't have access permission to chat or conversation
    PARAMS_ERROR Parameter TYPE not specified or doesn't match to the available parameters


    Working with Files

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    MethodMethod description
    im.disk.folder.get Get information on the folder storing files for chat.
    im.disk.file.commit Publish uploaded file into chat.
    im.disk.file.delete Delete files inside chat folder.
    im.disk.file.save Save files to your Bitrix24.Drive.


    im.disk.folder.get

    The method gets information on folder storing files for chat

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    CHAT_ID 17 Yes Chat ID 18

    Method call

    JavaScript

    BX24.callMethod('im.disk.folder.get', {
    	'CHAT_ID': 17,
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.disk.folder.get', Array(
    	'CHAT_ID' => 17,
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": {
    		ID: 127
    	}
    }   
    

    Example of response when error occurs

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    ACCESS_ERROR Current user does not have appropriate permissions to access the dialog
    INTERNAL_ERROR Server error, please contact technical support

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    im.disk.file.commit

    The method publishes loaded file in the chat

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    CHAT_ID 17 Yes Chat ID 18
    UPLOAD_ID 213 Yes* ID of the file, downloaded via DISK module methods 18
    DISK_ID 112 Yes* ID of the file, available from the local drive 18
    MESSAGE Important document No File description will be published in chat 18
    SILENT_MODE N No Open Channel chat parameter that specifies if the file data was sent to a client or to another designation 18
    • To call the API successfully, specify CHAT_ID and one за two fields – UPLOAD_ID or DISK_ID.

    Attention! File must be preliminarily downloaded via the disk.folder.uploadfile method.


    Method call

    JavaScript

    BX24.callMethod('im.disk.file.commit', {
    	'CHAT_ID': 17,
    	'UPLOAD_ID': 112,
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.disk.file.commit', Array(
    	'CHAT_ID' => 17,
    	'UPLOAD_ID' => 112,
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": true
    } 
    

    Example of response with errors

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    ACCESS_ERROR Current user does not have permissions to access the dialog
    FILES_ERROR File ID not passed

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    im.disk.file.delete

    The method deletes files inside chat folder

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    CHAT_ID 17 Yes Chat ID 18
    DISK_ID 112 Yes File ID 18

    Method call

    JavaScript

    BX24.callMethod('im.disk.file.delete', {
    	'CHAT_ID': 17,
    	'DISK_ID': 112,
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.disk.file.delete', Array(
    	'CHAT_ID' => 17,
    	'DISK_ID' => 112,
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": true
    } 
    

    Example of response when error occurs

    {
        "error": "CHAT_ID_EMPTY",
        "error_description": "Chat ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    CHAT_ID_EMPTY Chat ID not passed
    FILES_ERROR File ID not passed

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    im.disk.file.save

    Saves file to your Bitrix24.Drive

    Revision: 21
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    DISK_ID 112 Yes File ID 21

    Method call

    JavaScript

    BX24.callMethod('im.disk.file.save', {
      'DISK_ID': 112,
    }, function(result){
      if(result.error())
      {
        console.error(result.error().ex);
      }
      else
      {
        console.log(result.data());
      }
    });
    

    PHP

    $result = restCommand('im.disk.file.save', Array(
      'DISK_ID' => 112,
    ), $_REQUEST["auth"]);
    

    Response example

    {
      "result": {
        "folder": {"id": 130, "name": "Saved file"},
        "file": {"id": 578, "name": "image.png"}
      }
    }
    

    Example of response with error

    {
      "error": "FILE_ID_EMPTY",
      "error_description": "File ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – error brief description

    Possible error codes

    Код Description
    FILE_SAVE_ERROR Unable to delete file
    FILE_ID_EMPTY Unable to pass file ID

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    Working with Users

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


    MethodMethod description
    im.user.get Get user data.
    im.user.list.get Get multiple users data.
    im.user.status.get Get information on specified user status.
    im.user.status.set Specify user status.
    im.user.status.idle.start Specify the automatic status «Away».
    im.user.status.idle.end Disable the automatuc status «Away».


    im.user.get

    The method gets user data

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID 5 No User ID 18
    AVATAR_HR N No Generate avatar in high resolution 18
    • If the ID key is not passed, current user data will be selected.

    Method call

    JavaScript

    BX24.callMethod('im.user.get', {ID: 5}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.get', Array(
    	'ID' => 5,
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": {
    		"id": 5,
    		"name": "John Harrington",
    		"first_name": "John",
    		"last_name": "Harrington",
    		"work_position": "",
    		"color": "#df532d",
    		"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    		"gender": "M",
    		"birthday": "",
    		"extranet": false,
    		"network": false,
    		"bot": false,
    		"connector": false,
    		"external_auth_id": "default",
    		"status": "online",
    		"idle": false,
    		"last_activity_date": "2018-01-29T17:35:31+03:00",
    		"desktop_last_date": false,
    		"mobile_last_date": false,
    		"departments": [
    		  50
    		],
    		"absent": false,
    		"phones": {
    		  "work_phone": "",
    		  "personal_mobile": "",
    		  "personal_phone": ""
    		}
    	}
    }   
    

    Description of keys:

    • id – user ID
    • name – first and last user name
    • first_name – user first name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, the avatar is not specified)
    • avatar_hr – link to avatar in high resolution (available only when a query with parameter AVATAR_HR = 'Y')
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute Bitrix24.Network (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – user selected status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • departments – department IDs
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    Example of response when an error occurs

    {
        "error": "ID_EMPTY",
        "error_description": "User ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    ID_EMPTY User ID not passed
    USER_NOT_EXISTS User with indicated ID not found
    ACCESS_DENIED Current user does not have permissions to access the data

    Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



    im.user.list.get

    The method gets multiple users data

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID [4,5] Yes User IDs 19
    AVATAR_HR N No Generate avatar in high resolution 19
    • If the ID key is not passed, current user data will be selected.

    Method call

    JavaScript

    BX24.callMethod('im.user.list.get', {ID: [4,5]}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.list.get', Array(
    	'ID' => [4,5],
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": {
    		4: null,
    		5: {
    			"id": 5,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		}
    	}
    } 
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • avatar_hr – link to avatar in high resolution (available only when a query with parameter AVATAR_HR = 'Y')
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • departments – department IDs
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    • Example of response when an error occurs

      {
          "error": "INVALID_FORMAT",
          "error_description": "A wrong format for the ID field is passed"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      INVALID_FORMAT User ID not passed

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.user.status.get

      The method gets information on the specified user status

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      None

      Method call

      JavaScript

      BX24.callMethod('im.user.status.get', {}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.status.get', Array(
      ), $_REQUEST["auth"]);
      

      Example of response

      {
      	"result": "dnd"
      }
      

      Description of result:

      • online – Online
      • dnd – Do not disturb
      • away – Away

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.user.status.set

      The method specifies user status

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      STATUS online Yes New user status 18

      The following statuses are available:

      • online – Online
      • dnd – Do not disturb
      • away – Away

      Method call

      JavaScript

      BX24.callMethod('im.user.status.set', {}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.status.set', Array(
      ), $_REQUEST["auth"]);
      

      Example of response

      {
        "result": true
      }
      

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.user.status.idle.start

      The method specifies automatic status "Away"

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      AGO 10 No Number of minutes away 18

      Method call

      JavaScript

      BX24.callMethod('im.user.status.idle.start', {
      	'AGO': 10
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.status.idle.start', Array(
      	'AGO' => 10
      ), $_REQUEST["auth"]);
      

      Example of response

      {
        "result": true
      }
      

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.user.status.idle.end

      The method disables automatic status "Away"

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      None

      Method call

      JavaScript

      BX24.callMethod('im.user.status.idle.end', {}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.status.idle.start', Array(
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
        "result": true
      }
      

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      Working with Departments

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


      Methodmethod description
      im.department.get Get data department data.
      im.department.colleagues.list Get list of users included into your department.
      im.department.managers.get Get list of department managers.
      im.department.employees.get Get list of department employees.


      im.department.get

      The method gets department data

      Revision: 18
      To get information about the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      ID [51] Yes Department IDs 18
      USER_DATA N No Download user data 18
      • If the USER_DATA = Y parameter is passed, manager data will downloaded additionally with the result.

      Method call

      JavaScript

      BX24.callMethod('im.department.get', {ID: [51]}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.department.get', Array(
      	'ID' => [51],
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
      	"result": [
      		{
      			"id": 51,
      			"name": "New York branch",
      			"full_name": "New York branch / Bitrix24"
      			"manager_user_id": 11,
      		}
      	]
      }    
      

      Description of keys:

      • id – department ID
      • name – department abbreviated name
      • full_name – department full name
      • manager_user_data – manager data description object (unavailable, if USER_DATA != 'Y'):
        • id – user ID
        • name – user first and last name
        • first_name – user name
        • last_name – user last name
        • work_position – position
        • color – user color in 'hex' format
        • avatar – link to avatar (if empty, avatar is not specified)
        • gender – user gender
        • birthday – user birthday in the DD-MM format, if empty – not specified
        • extranet – extranet user attribute (true/false)
        • network – Bitrix24.Network user attribute (true/false)
        • bot – bot attribute (true/false)
        • connector – Open Channel user attribute (true/false)
        • external_auth_id – external authorization code
        • status – selected user status
        • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
        • last_activity_date – date of the last user action, in ATOM format
        • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
        • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

      Example of response when error occurs

      {
          "error": "INVALID_FORMAT",
          "error_description": "A wrong format for the ID field is passed"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      INVALID_FORMAT Invalid ID format is passed

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.department.colleagues.list

      The method gets list of users in your department

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      USER_DATA N No Download user data 19
      OFFSET 0 No Offset selection of users 19
      LIMIT 10 No User selection limit 19
      • If the USER_DATA = Y parameter is passed, the array of objects with the specific user data is passed instead of IDs array.
      • The method supports standard Bitrix24 REST API pagewise navigation. Additionally it can build navigation via OFFSET and LIMIT parameters.

      Method call

      JavaScript

      BX24.callMethod('im.department.colleagues.list', {USER_DATA: 'Y'}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      		console.log('total', result.total());
      	}
      });
      

      PHP

      $result = restCommand('im.department.colleagues.list', Array(
      	'USER_DATA' => 'Y'
      ), $_REQUEST["auth"]);	
      

      Example of response

      With the option USER_DATA = N:

      {
      	"result": [1],
      	"total": 1
      }    
      

      With the option USER_DATA = Y:

      {    
      	"result": [
      		{
      			"id": 1,
      			"name": "John Harrington",
      			"first_name": "John",
      			"last_name": "Harrington",
      			"work_position": "",
      			"color": "#df532d",
      			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      			"gender": "M",
      			"birthday": "",
      			"extranet": false,
      			"network": false,
      			"bot": false,
      			"connector": false,
      			"external_auth_id": "default",
      			"status": "online",
      			"idle": false,
      			"last_activity_date": "2018-01-29T17:35:31+03:00",
      			"desktop_last_date": false,
      			"mobile_last_date": false,
      			"departments": [
      			  50
      			],
      			"absent": false,
      			"phones": {
      			  "work_phone": "",
      			  "personal_mobile": "",
      			  "personal_phone": ""
      			}
      		}
      	],
      	"total": 1
      }     
      

      Description of keys:

      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
      • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.department.managers.get

      The method gets list of department managers

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      ID [105] Yes Department IDs 19
      USER_DATA N No Download user data 19
      • If the USER_DATA = Y parameter is passed, the array of objects with user data will be passed in the response instead of IDs array.

      Method call

      JavaScript

      BX24.callMethod('im.department.managers.get', {USER_DATA: 'Y'}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.department.managers.get', Array(
      	'USER_DATA' => 'Y'
      ), $_REQUEST["auth"]);
      

      Example of response

      With the option USER_DATA = N:

      {
      	"result": {
      		105: [1]
      	},
      }    
      

      With the option USER_DATA = Y:

      {    
      	"result": {
      		105: {
      			"id": 1,
      			"name": "John Harrington",
      			"first_name": "John",
      			"last_name": "Harrington",
      			"work_position": "",
      			"color": "#df532d",
      			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      			"gender": "M",
      			"birthday": "",
      			"extranet": false,
      			"network": false,
      			"bot": false,
      			"connector": false,
      			"external_auth_id": "default",
      			"status": "online",
      			"idle": false,
      			"last_activity_date": "2018-01-29T17:35:31+03:00",
      			"desktop_last_date": false,
      			"mobile_last_date": false,
      			"departments": [
      			  50
      			],
      			"absent": false,
      			"phones": {
      			  "work_phone": "",
      			  "personal_mobile": "",
      			  "personal_phone": ""
      			}
      		}
      	}
      }       
      

      Description of keys:

      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
      • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

      Example of response when error occurs

      {
          "error": "ID_EMPTY",
          "error_description": "Department ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      ID_EMPTY

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.department.employees.get

      The method gets list of employees in a department

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      ID [105] Yes Department IDs 19
      USER_DATA N No Download user data 19
      • If the parameterUSER_DATA = Y, the array of objects with user data is passed in the response instead of IDs array.

      Method call

      JavaScript

      BX24.callMethod('im.department.employees.get', {USER_DATA: 'Y'}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.department.employees.get', Array(
      	'USER_DATA' => 'Y'
      ), $_REQUEST["auth"]);	
      

      Example of response

      With the option USER_DATA = N:

      {
      	"result": {
      		105: [1]
      	}
      }    
      

      With the option USER_DATA = Y:

      {    
      	"result": {
      		105: {
      			"id": 1,
      			"name": "John Harrington",
      			"first_name": "John",
      			"last_name": "Harrington",
      			"work_position": "",
      			"color": "#df532d",
      			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      			"gender": "M",
      			"birthday": "",
      			"extranet": false,
      			"network": false,
      			"bot": false,
      			"connector": false,
      			"external_auth_id": "default",
      			"status": "online",
      			"idle": false,
      			"last_activity_date": "2018-01-29T17:35:31+03:00",
      			"desktop_last_date": false,
      			"mobile_last_date": false,
      			"departments": [
      			  50
      			],
      			"absent": false,
      			"phones": {
      			  "work_phone": "",
      			  "personal_mobile": "",
      			  "personal_phone": ""
      			}
      		}
      	}
      }       
      

      Description of keys:

      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
      • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

      Example of response when error occurs

      {
          "error": "ID_EMPTY",
          "error_description": "Department ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      ID_EMPTY ID list not passed

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      Working with Search

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


      MethodMethod description
      im.search.user.list User search.
      im.search.chat.list Chat search.
      im.search.department.list Department search.
      im.search.last.get Get an element list of the last search.
      im.search.last.add And a history element of the last search.
      im.search.last.delete Delete a history element of the last search.


      im.search.user.list

      The method searches for users

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      FIND John Yes Search phrase 19
      BUSINESS N No Search among users with business tool access 19
      AVATAR_HR N No Generate avatar in high resolution 19
      OFFSET 0 No Offset of user selection 19
      LIMIT 10 No User selection limit 19
      • Search is performed by the following fields: Name, Last name, Position, Department.
      • The method supports standard Bitrix24 REST API pagewise naviagation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

      Method call

      JavaScript

      BX24.callMethod('im.search.user.list', {
      	FIND: 'John'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      		console.log('total', result.total());
      	}
      });
      

      PHP

      $result = restCommand('im.search.user.list', Array(
      	'FIND' => 'Евгений'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {    
      	"result": {
      		1: {
      			"id": 1,
      			"name": "John Harrington",
      			"first_name": "John",
      			"last_name": "Harrington",
      			"work_position": "",
      			"color": "#df532d",
      			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      			"gender": "M",
      			"birthday": "",
      			"extranet": false,
      			"network": false,
      			"bot": false,
      			"connector": false,
      			"external_auth_id": "default",
      			"status": "online",
      			"idle": false,
      			"last_activity_date": "2018-01-29T17:35:31+03:00",
      			"desktop_last_date": false,
      			"mobile_last_date": false,
      			"departments": [
      			  50
      			],
      			"absent": false
      		}
      	},
      	"total": 1
      }      
      

      Description of keys:

      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

      Example of response when error occurs

      {
          "error": "FIND_SHORT",
          "error_description": "Too short a search phrase."
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      FIND_SHORT Search phrase is top short, search is possible with three symbols minimum.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.search.chat.list

      The method performs chat search

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      FIND Mint Yes Search phrase 19
      OFFSET 0 No Offset of user selection 19
      LIMIT 10 No User selection limit 19
      • Search is performed by the following fields: chat participants Title, First name and Last name.
      • The method supports standard Bitrix24 REST API pagewise navigation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

      Method call

      JavaScript

      BX24.callMethod('im.search.chat.list', {
      	FIND: 'Mint'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      		console.log('total', result.total());
      	}
      });
      

      PHP

      $result = restCommand('im.search.chat.list', Array(
      	'FIND' => 'Mint'
      ), $_REQUEST["auth"]);
      

      Example of response

      {    
      	"result": {
      		21191:  {
      			"id": 21191,
      			"title": "Mint chat No.3",
      			"owner": 2,
      			"extranet": false,
      			"avatar": "",
      			"color": "#4ba984",
      			"type": "chat",
      			"entity_type": "",
      			"entity_data_1": "",
      			"entity_data_2": "",
      			"entity_data_3": "",
      			"date_create": "2017-10-14T12:15:32+02:00",
      			"message_type": "C"
      		}
      	},
      	"total": 1
      }    
      

      Description of keys:

      • id – chat ID
      • title – chat name
      • owner – chat owner user ID
      • color – chat color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • type – chat type (group chat, call chat, open channel chat and etc.)
      • entity_type – chat external code – type
      • entity_id – chat external code – ID
      • entity_data_1 – external data for chat
      • entity_data_2 – external data for chat
      • entity_data_3 – external data for chat
      • date_create – date when chat is created in ATOM format
      • message_type – type of chat messages

      Example of response when error occurs

      {
          "error": "FIND_SHORT",
          "error_description": "Too short a search phrase."
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      FIND_SHORT Search phrase is top short, search is performed with three symbols minimum.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.search.department.list

      The method searches for departments

      Revision: 19
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      FIND York Yes Search phase 19
      USER_DATA N No Download user data 19
      OFFSET 0 No Offset of user selection 19
      LIMIT 10 No User selection limit 19
      • If the parameter USER_DATA = Y, the manager data will be uploaded with the result.
      • Search is performed by the following fields: Department full name.
      • The method supports standard Bitrix24 REST API pagewise navigation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

      Method call

      JavaScript

      BX24.callMethod('im.search.department.list', {
      	FIND: 'York'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log('users', result.data());
      		console.log('total', result.total());
      	}
      });
      

      PHP

      $result = restCommand('im.search.department.list', Array(
      	'FIND' => 'York'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {    
      	"result": [
      		{
      			id: 51,
      			name: "New York branch",
      			full_name: "New York branch / Bitrix24",
      			manager_user_id: 11
      		}
      	],
      	"total": 1
      }             
      

      Description of keys:

      • id – department ID
      • name – department abbreviated name
      • full_name – department full name
      • manager_user_data – manager data description object (unavailable, if USER_DATA != 'Y')
        • id – user ID
        • name – user first and last name
        • first_name – user name
        • last_name – user last name
        • work_position – position
        • color – user color in 'hex' format
        • avatar – link to avatar (if empty, avatar is not specified)
        • gender – user gender
        • birthday – user birthday in the DD-MM format, if empty – not specified
        • extranet – extranet user attribute (true/false)
        • network – Bitrix24.Network user attribute (true/false)
        • bot – bot attribute (true/false)
        • connector – Open Channel user attribute (true/false)
        • external_auth_id – external authorization code
        • status – selected user status
        • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
        • last_activity_date – date of the last user action, in ATOM format
        • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
        • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

      Example of response when error occurs

      {
          "error": "FIND_SHORT",
          "error_description": "Too short a search phrase."
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      FIND_SHORT Search phrase is top short, search is performed with three symbols minimum.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.search.last.get

      The method gets list of elements of the last search

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      SKIP_OPENLINES N No Skip open channel chats 18
      SKIP_CHAT N No Skip chats 18
      SKIP_DIALOG N No Skip one-on-one dialogs 18

      Method call

      JavaScript

      BX24.callMethod('im.search.last.get', {}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.business.list', Array(
      ), $_REQUEST["auth"]);	
      

      Example of response

      {    
      	"result": [
      		{
      			"id": 1,
      			"type": "user",
      			"title": "John Harrington",
      			"avatar": {
      				"url": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      				"color": "#df532d"
      			}
      			"user": {
      				"id": 1,
      				"name": "John Harrington",
      				"first_name": "John",
      				"last_name": "Harrington",
      				"work_position": "",
      				"color": "#df532d",
      				"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
      				"gender": "M",
      				"birthday": "",
      				"extranet": false,
      				"network": false,
      				"bot": false,
      				"connector": false,
      				"external_auth_id": "default",
      				"status": "online",
      				"idle": false,
      				"last_activity_date": "2018-01-29T17:35:31+03:00",
      				"desktop_last_date": false,
      				"mobile_last_date": false,
      				"departments": [
      				  50
      				],
      				"absent": false,
      				"phones": {
      				  "work_phone": "",
      				  "personal_mobile": "",
      				  "personal_phone": ""
      				}
      			}
      		}
      	]
      }              
      

      Description of keys:

      • id – dialog ID (number if user, chatXXX if chat)
      • name – record type (user – if user, chat – if chat)
      • avatar – record avatar description object:
        • url – link to avatar (if empty, the avatar not specified)
        • color – dialog color in 'hex' format
      • title – record title
      • user – user data description object (unavailable, if record type – chat):
        • id – user ID
        • name – user first and last name
        • first_name – user name
        • last_name – user last name
        • work_position – position
        • color – user color in 'hex' format
        • avatar – link to avatar (if empty, avatar is not specified)
        • gender – user gender
        • birthday – user birthday in the DD-MM format, if empty – not specified
        • extranet – extranet user attribute (true/false)
        • network – Bitrix24.Network user attribute (true/false)
        • bot – bot attribute (true/false)
        • connector – Open Channel user attribute (true/false)
        • external_auth_id – external authorization code
        • status – selected user status
        • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
        • last_activity_date – date of the last user action, in ATOM format
        • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
        • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
      • chat – chat data description object (unavailable in this record type - user):
        • id – chat ID
        • title – chat name
        • owner – chat owner user name
        • extranet – attribute of extranet user chat participation (true/false)
        • color – chat color in 'hex' format
        • avatar – link to avatar (if empty, the avatar is not specified)
        • type – chat type (group chat, call chat, open line chat and etc.)
        • entity_type – external code for chat – type
        • entity_id – external code for chat – ID
        • entity_data_1 – external data for chat
        • entity_data_2 – external data for chat
        • entity_data_3 – external data for chat
        • date_create – date of chat creation in АТОМ format
        • message_type – type chat messages

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.search.last.add

      The method adds a history element of the last search

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      DIALOG_ID chat17 Yes Dialog ID 18
      • DIALOG_ID – dialog ID (number – if user, chatXXX – if chat).

      Method call

      JavaScript

      BX24.callMethod('im.search.last.add', {
      	'DIALOG_ID': 'chat17'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.search.last.add', Array(
      	'DIALOG_ID' => 'chat17'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
      	"result": true
      }          
      

      Example of response when error occurs

      {
          "error": "DIALOG_ID_EMPTY",
          "error_description": "Dialog ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error code

      Code Description
      DIALOG_ID_EMPTY Dialog ID not passed.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      im.search.last.delete

      The method deletes a history element of the last search

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      Parameter Example Req. Description Revision
      DIALOG_ID chat17 Yes Dialog ID 18
      • DIALOG_ID – dialog ID (number – if user, chatXXX – if chat).

      Method call

      JavaScript

      BX24.callMethod('im.search.last.delete', {
      	'DIALOG_ID': 'chat17'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.search.last.delete', Array(
      	'DIALOG_ID' => 'chat17'
      ), $_REQUEST["auth"]);
      

      Example of response

      {
      	"result": true
      }        
      

      Example of response when error occurs

      {
          "error": "DIALOG_ID_EMPTY",
          "error_description": "Dialog ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      DIALOG_ID_EMPTY Dialog ID not passed.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      Working with Recent Chat List


      MethodMethod description
      im.recent.get List of recent user conversations.
      im.recent.pin Pins conversation in favorites.
      im.recent.hide Deletes conversation in the list of recent chats.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Methods, indicated using javascript method BX24.callMethod:

      МетодMethod description
      im.recent.unread Marks conversation or chat as "unread".
      im.recent.list Gets list of recent user conversations (with pagination support).

      im.recent.get

      Sending system notification

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      Parameter Example Req. Description Revision
      SKIP_OPENLINES N None Skip Open Channel chats 18
      SKIP_CHAT N None Skip chats 18
      SKIP_DIALOG N None Skip one-on-one dialogs 18
      LAST_UPDATE 2019-07-11T10:45:31+02:00 None Limit for passed data, date in ATOM format 23
      ONLY_OPENLINES N None Selecting only Open Channel chats 29
      LAST_SYNC_DATE 2019-07-11T10:45:31+02:00 None Previous fetch date to upload changes performed in the list from this date. Fetching returns data not older that 7 days. Date in ATOM format 29

      Called method and response

      JavaScript

      BX24.callMethod('im.recent.get', {
      	'SKIP_OPENLINES': 'Y'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.user.status.idle.start', Array(
      	'SKIP_OPENLINES' => 'Y'
      ), $_REQUEST["auth"]);
      

      Example of response

      {
      	"result": [
      		{
      			"id": "1",
      		 	"type": "user",
      		 	"avatar": {
      				"url": "http://www.hazz/upload/resize_cache/main/1af/100_100_2/1464255149.png",
      				"color": "#df532d"
      		  	},
      			"title": "John Harrington",
      			"message": {
      				"id": "30468",
      				"text": "1",
      				"file": false,
      				"attach": false,
      				"author_id": "1"
      			},
      			"counter": "3",
      			"date": "2017-10-17T11:12:56+02:00",
      			"user": {
      				"id": "1",
      				"name": "John Harrington",
      				"first_name": "John",
      				"last_name": "Harrington",
      				"work_position": "IT specialist",
      				"color": "#df532d",
      				"avatar": "http://www.hazz/upload/resize_cache/main/1af/100_100_2/1464255149.png",
      				"gender": "M",
      				"birthday": false,
      				"extranet": false,
      				"network": false,
      				"bot": false,
      				"connector": false,
      				"external_auth_id": "default",
      				"status": "online",
      				"idle": false,
      				"last_activity_date": "2017-10-17T11:16:01+02:00",
      				"mobile_last_date": "2017-05-26T12:04:58+02:00",
      				"absent": "2017-11-01T00:00:00+02:00"
      			}
      		},
      		{
      			"id": "chat21191",
      			"type": "chat",
      			"avatar": {
      				"url": "",
      				"color": "#4ba984"
      			},
      			"title": "Mint Chat No.3",
      			"message": {
      				"id": "30467",
      				"text": "Permission for Bitrix24 update received from [Attachment]",
      				"file": false,
      				"attach": true,
      				"author_id": "2"
      			},
      			"counter": "0",
      			"date": "2017-10-17T10:38:20+02:00",
      			"chat": {
      				"id": "21191",
      				"title": "Mint chat No.3",
      				"owner": "2",
      				"extranet": false,
      				"avatar": "",
      				"color": "#4ba984",
      				"type": "chat",
      				"entity_type": "",
      				"entity_data_1": "",
      				"entity_data_2": "",
      				"entity_data_3": "",
      				"date_create": "2017-10-14T12:15:32+02:00",
      				"message_type": "C"
      			}
      		}
      	]
      }       
      

      Description of keys:

      • id – dialog ID (number if user, chatXXX if chat)
      • name – record type (user – if user, chat – if chat)
      • avatar – record avatar description object:
        • url – link to avatar (if empty, the avatar is not specified)
        • color – dialog color in 'hex' format
      • title – record title (First name, last name – for user, chat name - for chat)
      • messages – message description object:
        • id – message ID
        • text – message text (without BB-codes and string breaks)
        • file – file availability (true/false)
        • attach – attachment availability (true/false)
        • author_id – message author
        • date – message date in ATOM format
      • counter – counter for unread messages
      • user – user data description object (unavailable in this record type - chat):
        • id – user ID
        • name – user first and last name
        • first_name – user name
        • last_name – user last name
        • work_position – position
        • color – user color in 'hex' format
        • avatar – link to avatar (if empty, avatar is not specified)
        • gender – user gender
        • birthday – user birthday in the DD-MM format, if empty – not specified
        • extranet – extranet user attribute (true/false)
        • network – Bitrix24.Network user attribute (true/false)
        • bot – bot attribute (true/false)
        • connector – Open Channel user attribute (true/false)
        • external_auth_id – external authorization code
        • status – selected user status
        • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
        • last_activity_date – date of the last user action, in ATOM format
        • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
        • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
      • chat – chat data description object (unavailable if record type - user):
        • id – chat ID
        • title – chat name
        • owner – user-chat owner ID
        • extranet – attribute of extranet user participation in chat (true/false)
        • color – chat color in 'hex' format
        • avatar – link to avatar (if empty, avatar is not specified)
        • type – chat type (group chat, call chat, open channel chat and etc.)
        • entity_type – external code for chat – type
        • entity_id – external code for chat – identifier
        • entity_data_1 – external data for chat
        • entity_data_2 – external data for chat
        • entity_data_3 – external data for chat
        • date_create – date when chat is created in ATOM format
        • message_type – type of chat messages

      im.recent.pin

      Pins dialog in favorites

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      Parameter Example Req. Description Revision
      DIALOG_ID chat17 Yes Dialog ID. Format:
      chatXXX – recipient chat, when sending message to chat
      19
      PIN Y No Pin or unpin a dialog 19
      • If the PIN = N parameter is specified, the pinned dialog will be unpinned.

      Called method and response

      JavaScript

      BX24.callMethod('im.recent.pin', {
      	'DIALOG_ID': 'chat17'
      	'PIN': 'Y'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.recent.pin', Array(
      	'DIALOG_ID' => 'chat17',
      	'PIN' => 'Y'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
      	"result": true
      }      
      

      Example of response when error occurs

      {
          "error": "DIALOG_ID_EMPTY",
          "error_description": "Dialog ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      DIALOG_ID_EMPTY Dialog ID not passed.

      im.recent.hide

      Deletes dialog from list of recent chats

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Examples

      Parameter Example Req. Description Revision
      DIALOG_ID chat17 Yes Dialog ID. Format:
      chatXXX – recipient chat, when message is sent to chat
      or XXX – recipient ID, when message is for private conversation
      18

      Called method and response

      JavaScript

      BX24.callMethod('im.recent.hide', {
      	'DIALOG_ID': 'chat17'
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.recent.hide', Array(
      	'DIALOG_ID' => 'chat17'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
      	"result": true
      }  
      

      Example of response when error occurs

      {
          "error": "DIALOG_ID_EMPTY",
          "error_description": "Dialog ID can't be empty"
      }
      

      Description of keys:

      • error – error code
      • error_description – brief description of error

      Possible error codes

      Code Description
      DIALOG_ID_EMPTY Dialog ID not passed.

      im.recent.unread

      Set chat or conversation as "unread"

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

      Parameters

      Parameter Example Required Description Revision
      DIALOG_ID 'chat74' Yes Dialog ID. Format:
      • chatXXX – recipient chat, when message is sent to chat
      • or
      • XXX – recipient ID, when message is sent to private conversation
      30
      ACTION 'Y' No Mark|unmark the dialog as «unread» - 'Y'|'N' 30

      Called method and response

      JavaScript

      B24.callMethod(
        'im.recent.unread',
        {
          DIALOG_ID: 'chat74',
          ACTION: 'Y'
        },
        res => {
          if (res.error())
          {
            console.error(result.error().ex);
          }
          else
          {
            console.log(res.data())
          }
        }
      )
      

      Response example

      true //when mark|unmark is successful
      

      Example of response on error

      {
        "error":"DIALOG_ID_EMPTY",
        "error_description":"Dialog ID can\u0027t be empty"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      DIALOG_ID_EMPTY DIALOG_ID parameter not passed or doesn't correspond to format


      im.recent.list

      Sending system notification

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 30

      Parameters

      Parameter Example Required Description Revision
      SKIP_OPENLINES 'Y' No Skip Open lines chats 30
      SKIP_DIALOG 'N' No Skip "person-to-person" conversations 30
      SKIP_CHAT 'Y' No Skip chats 30
      LAST_MESSAGE_DATE '2021-10-30' No Date of the last chat message 30


      Called method and response

      JavaScript

      B24.callMethod(
        'im.recent.list',
        {
          LAST_MESSAGE_DATE: '2021-10-30'
        },
        res => {
          if (res.error())
          {
            console.error(result.error().ex);
          }
          else
          {
            console.log(res.data())
          }
        }
      )
      

      Response example

      {
        "items": [
          {
            "id": "chat71",
            "chat_id": 71,
            "type": "chat",
            "avatar": {
              "url": "",
              "color": "#8474c8"
            },
            "title": "Violet guest No.3 - Open line 2",
            "message": {
              "id": 267,
              "text": "Form sent \"Contact details for open lines\" [Attachment]",
              "file": false,
              "author_id": 0,
              "attach": true,
              "date": "2021-10-27T18:20:45+02:00",
              "status": "received"
            },
            "counter": 3,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-27T18:20:45+02:00",
            "chat": {
              "id": 71,
              "name": "Violet guest No.3 - Open line 2",
              "owner": 0,
              "extranet": false,
              "avatar": "",
              "color": "#8474c8",
              "type": "lines",
              "entity_type": "LINES",
              "entity_id": "livechat|2|70|2016",
              "entity_data_1": "N|NONE|0|N|N|7|1635351612|0|0|0",
              "entity_data_2": "",
              "entity_data_3": "",
              "mute_list": [],
              "manager_list": [],
              "date_create": "2021-10-27T18:20:12+02:00",
              "message_type": "L"
            },
            "lines": {
              "id": 7,
              "status": 5,
              "date_create": "2021-10-27T18:20:12+02:00"
            },
            "user": {
              "id": 0
            },
            "options": []
          },
          {
            "id": "chat69",
            "chat_id": 69,
            "type": "chat",
            "avatar": {
              "url": "",
              "color": "#3e99ce"
            },
            "title": "Blue guest No.3 - Open line 2",
            "message": {
              "id": 258,
              "text": "Form sent \"Contact details for open lines\" [Attachment]",
              "file": false,
              "author_id": 0,
              "attach": true,
              "date": "2021-10-27T18:16:22+02:00",
              "status": "received"
            },
            "counter": 3,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-27T18:16:22+02:00",
            "chat": {
              "id": 69,
              "name": "Blue guest No.3 - Open line 2",
              "owner": 0,
              "extranet": false,
              "avatar": "",
              "color": "#3e99ce",
              "type": "lines",
              "entity_type": "LINES",
              "entity_id": "livechat|2|68|2015",
              "entity_data_1": "N|NONE|0|N|N|6|1635351343|0|0|0",
              "entity_data_2": "",
              "entity_data_3": "",
              "mute_list": [],
              "manager_list": [],
              "date_create": "2021-10-27T18:15:43+02:00",
              "message_type": "L"
            },
            "lines": {
              "id": 6,
              "status": 5,
              "date_create": "2021-10-27T18:15:43+02:00"
            },
            "user": {
              "id": 0
            },
            "options": []
          },
          {
            "id": "chat67",
            "chat_id": 67,
            "type": "chat",
            "avatar": {
              "url": "",
              "color": "#29619b"
            },
            "title": "Sky blue guest No.2 - Open line 2",
            "message": {
              "id": 250,
              "text": "hi",
              "file": false,
              "author_id": 2014,
              "attach": false,
              "date": "2021-10-27T17:11:36+02:00",
              "status": "received"
            },
            "counter": 5,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-27T17:11:36+02:00",
            "chat": {
              "id": 67,
              "name": "Sky blue guest No.2 - Open line 2",
              "owner": 0,
              "extranet": false,
              "avatar": "",
              "color": "#29619b",
              "type": "lines",
              "entity_type": "LINES",
              "entity_id": "livechat|2|66|2014",
              "entity_data_1": "N|NONE|0|N|N|5|1635346774|0|0|0",
              "entity_data_2": "",
              "entity_data_3": "",
              "mute_list": [],
              "manager_list": [],
              "date_create": "2021-10-27T16:59:34+02:00",
              "message_type": "L"
            },
            "lines": {
              "id": 5,
              "status": 5,
              "date_create": "2021-10-27T16:59:34+02:00"
            },
            "user": {
              "id": 2014,
              "active": true,
              "name": "Guest",
              "first_name": "Guest",
              "last_name": "",
              "work_position": "",
              "color": "#4ba5c3",
              "avatar": "",
              "gender": "M",
              "birthday": "",
              "extranet": true,
              "network": false,
              "bot": false,
              "connector": true,
              "external_auth_id": "imconnector",
              "status": "online",
              "idle": false,
              "last_activity_date": "2021-10-27T17:11:36+02:00",
              "mobile_last_date": false,
              "absent": false,
              "departments": [],
              "phones": false,
              "desktop_last_date": false
            },
            "options": []
          },
          {
            "id": "chat65",
            "chat_id": 65,
            "type": "chat",
            "avatar": {
              "url": "",
              "color": "#df532d"
            },
            "title": "John Tester - Open line 2",
            "message": {
              "id": 225,
              "text": "New deal created [Attachment]",
              "file": false,
              "author_id": 0,
              "attach": true,
              "date": "2021-10-25T14:48:28+02:00",
              "status": "received"
            },
            "counter": 6,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-25T14:48:28+02:00",
            "chat": {
              "id": 65,
              "name": "John Tester - Open line 2",
              "owner": 0,
              "extranet": false,
              "avatar": "",
              "color": "#df532d",
              "type": "lines",
              "entity_type": "LINES",
              "entity_id": "livechat|2|64|2011",
              "entity_data_1": "Y|DEAL|12|N|N|4|1635166080|0|0|0",
              "entity_data_2": "LEAD|0|COMPANY|0|CONTACT|9|DEAL|12",
              "entity_data_3": "",
              "mute_list": [],
              "manager_list": [],
              "date_create": "2021-10-25T14:48:00+02:00",
              "message_type": "L"
            },
            "lines": {
              "id": 4,
              "status": 5,
              "date_create": "2021-10-25T14:48:00+02:00"
            },
            "user": {
              "id": 0
            },
            "options": []
          },
          {
            "id": "chat39",
            "chat_id": 39,
            "type": "chat",
            "avatar": {
              "url": "",
              "color": "#4ba984"
            },
            "title": "No robot chat",
            "message": {
              "id": 161,
              "text": "here's the question",
              "file": false,
              "author_id": 1,
              "attach": false,
              "date": "2021-10-08T13:19:33+02:00",
              "status": "delivered"
            },
            "counter": 0,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-08T13:19:33+02:00",
            "chat": {
              "id": 39,
              "name": "No robot chat",
              "owner": 1018,
              "extranet": false,
              "avatar": "",
              "color": "#4ba984",
              "type": "chat",
              "entity_type": "",
              "entity_id": "",
              "entity_data_1": "",
              "entity_data_2": "",
              "entity_data_3": "",
              "mute_list": [],
              "manager_list": [],
              "date_create": "2021-09-27T15:57:53+02:00",
              "message_type": "C"
            },
            "user": {
              "id": 1,
              "active": true,
              "name": "John Smith",
              "first_name": "John",
              "last_name": "Smith",
              "work_position": "",
              "color": "#df532d",
              "avatar": "",
              "gender": "M",
              "birthday": "",
              "extranet": false,
              "network": false,
              "bot": false,
              "connector": false,
              "external_auth_id": "default",
              "status": "online",
              "idle": false,
              "last_activity_date": "2021-10-30T15:52:40+02:00",
              "mobile_last_date": "2021-10-27T16:39:26+02:00",
              "absent": false,
              "departments": [
                1
              ],
              "phones": false,
              "desktop_last_date": "2021-10-21T11:07:54+02:00"
            },
            "options": []
          },
          {
            "id": 1018,
            "chat_id": 28,
            "type": "user",
            "avatar": {
              "url": "",
              "color": "#df532d"
            },
            "title": "Chris Maxwell",
            "message": {
              "id": 160,
              "text": "Pushes incoming",
              "file": false,
              "author_id": 1018,
              "attach": false,
              "date": "2021-10-08T13:19:32+02:00",
              "status": "delivered"
            },
            "counter": 0,
            "pinned": false,
            "unread": false,
            "date_update": "2021-10-08T13:20:59+02:00",
            "user": {
              "id": 1018,
              "active": true,
              "name": "Chris Maxwell",
              "first_name": "Chris",
              "last_name": "Maxwell",
              "work_position": "",
              "color": "#df532d",
              "avatar": "",
              "gender": "M",
              "birthday": "",
              "extranet": false,
              "network": false,
              "bot": false,
              "connector": false,
              "external_auth_id": "default",
              "status": "online",
              "idle": false,
              "last_activity_date": "2021-10-29T16:29:17+02:00",
              "mobile_last_date": "2021-10-08T13:24:22+02:00",
              "absent": false,
              "departments": [
                1
              ],
              "phones": false,
              "desktop_last_date": "2021-10-18T16:51:09+02:00"
            },
            "options": []
          }
        ],
        "hasMore": false
      }
      

      Key description:

      • id – dialog ID (numeral indicates a user; when chatXXX – indicates chat)
      • type – record type (user indicates a user, when chat – indicates chat)
      • avatar – record avatar description object:
        • url – avatar link (when empty, avatar is specified)
        • color – dialog color in hex format
      • title – record title (first and last name – for user, dialog name – for chat)
      • messages – message description object:
        • id – message ID
        • text – message text (without BB-codes and line breaks)
        • file – files are available (true/false)
        • attach – attachments are available (true/false)
        • author_id – message author
        • date – message date
      • counter – unread messages counter
      • user – user data description object (unavailable, when this record type - chat):
        • id – user ID
        • name – user first and last name
        • first_name – user first name
        • last_name – user last name
        • work_position – position
        • color – user color in hex format
        • avatar – avatar link (when empty, avatar is not specified)
        • gender – user gender
        • birthday – user birthday in DD-MM format, when empty – not specified
        • extranet – extranet user attribute (true/false)
        • networkBitrix24.Network network user attribute (true/false)
        • bot – bot attribute (true/false)
        • connector – open lines user attribute (true/false)
        • external_auth_id – external auth code
        • status – selected user status
        • idle – date, when user is away from computer, in АТОМ format (when not specified, then false)
        • last_activity_date – date of the user last activity in АТОМ format
        • mobile_last_date – date of the last activity in mobile app in АТОМ format (when not specified, then false)
        • absent – date when user vacation ends, in АТОМ format (when not specified, then false)
      • chat – chat data object description (unavailable, when record type is user):
        • id – chat ID
        • title – chat name
        • owner – chat owner-user ID
        • extranet – extranet user chat participation attribute (true/false)
        • color – chat color in hex format
        • avatar – avatar link (when empty, then avatar is not specified)
        • type – chat type (group chat, call chat, open lines chat and etc.)
        • entity_type – external code for chat – type
        • entity_id – chat external code – ID
        • entity_data_1 – external data for chat
        • entity_data_2 – external data for chat
        • entity_data_3 – external data for chat
        • date_create – chat created date in АТОМ format
        • message_type – chat message type
      • pinned – attached chat or not
      • unread – manual mark for chat as unread
      • date_update – date of the last update in associated entities

      Working with Counters

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


      im.counters.get

      The method gets counter data

      Revision: 18
      Get information on the current API revision (platform version) – im.revision.get.

      Parameters

      None

      Method call

      JavaScript

      BX24.callMethod('im.counters.get', {}, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.counters.get', Array(
      ), $_REQUEST["auth"]);	
      

      Example of response

      {    
      	"result": {
      		"CHAT": {18: 1},
      		"DIALOG": {1: 3, 5: 1},
      		"LINES": {},
      		"TYPE" {
      			"ALL": 5,
      			"CHAT": 1,
      			"DIALOG": 4,
      			"LINES": 0,
      			"NOTIFY": 0
      		}
      	}
      }   
      

      Description of keys:

      • CHAT – object, containing list of chats that have unread messages
      • DIALOG – object, containing list of dialogs that have unread messages
      • LINES – object, containing list of Open Channel chats that have unread messages
      • TYPE – object, containing cumulative counters
        • ALL – cumulative counter for all entities
        • CHAT – cumulative counter for chats
        • DIALOG – cumulative counter for dialogs
        • LINES – cumulative counter for Open Channels
        • NOTIFY – cumulative counter for notifications

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      Working with Notifications

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.


      MethodMethod description
      im.notify.personal.add Sending personal notification.
      im.notify.system.add Sending personal notification.
      im.notify.delete Deleting notification.
      im.notify.read Limiting read notifications.

      Methods, indicated using javascript method BX24.callMethod:

      МетодMethod description
      im.notify.read.list "Reading" the list of notifications, excluding the CONFIRM notification type.
      im.notify.answer Response to a notification, supporting a quick response.
      im.notify.confirm Interaction with notification buttons.

      im.notify.personal.add

      Sending personal notification

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      Parameter Example Required Description Revision
      USER_ID 1 Yes User ID, notification recipient 18
      MESSAGE Personal notification Yes Notification text 18
      MESSAGE_OUT Personal notification text for email No Notification text for email. When not specified, uses the field MESSAGE 18
      TAG TEST No Notification tag, unique within the system. Other notifications will be deleted upon adding notification with existing tag. 18
      SUB_TAG SUB|TEST No Additional tag, without duplication check. 18
      ATTACH No Attachment 18

      Related links

      How to handle attachments


      Called method and response

      PHP

      $result = restCommand('im.notify.personal.add', Array(
      
         'USER_ID' => 1,
         'MESSAGE' => 'Personal notification',
         'MESSAGE_OUT' => 'Personal notification text for email',
         'TAG' => 'TEST',
         'SUB_TAG' => 'SUB|TEST',
         'ATTACH' => ''
        
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": 123
      }
      
      Execution result: notification ID or error.


      Response example on error

      {
          "error": "USER_ID_EMPTY",
          "error_description": "Recipient ID not specified"
      }
      

      Key description:

      • error – error code
      • error_description – brief error description

      Possible error codes

      Код Description
      USER_ID_EMPTY Recipient ID not specified
      MESSAGE_EMPTY Message text is empty
      ATTACH_ERROR Attachment object validation error
      ATTACH_OVERSIZE Maximum allowed attachment size exceeded (30 Kb)

      im.notify.system.add

      Sending system notification

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      Parameter Example Required Description Revision
      USER_ID 1 Yes User ID, notification recipient 18
      MESSAGE System notification Yes Notification text 18
      MESSAGE_OUT System notification text for email No Notification text for email. When not specified is not set, uses the field MESSAGE 18
      TAG TEST No Notification tag, unique within the system. Deletes other notifications when adding the notification with existing tag. 18
      SUB_TAG SUB|TEST No Additional tag, without duplicate check 18
      ATTACH Array() No Attachment 18

      Related links

      How to handle attachments


      Called method and response

      PHP

      $result = restCommand('im.notify.system.add', Array(
      
         'USER_ID' => 1,
         'MESSAGE' => 'System notification',
         'MESSAGE_OUT' => 'System notification text for email',
         'TAG' => 'TEST',
         'SUB_TAG' => 'SUB|TEST',
         'ATTACH' => Array()
        
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": 123
      }
      
      Result: notification ID or error.


      >

      Response example on error

      {
          "error": "USER_ID_EMPTY",
          "error_description": "Recipient is not specified"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      USER_ID_EMPTY Recipient ID is not specified
      MESSAGE_EMPTY Message text is empty
      ATTACH_ERROR Attachment object validation error
      ATTACH_OVERSIZE Maximum allowed attachment size exceeded (30 Kb)

      im.notify.delete

      Deleting notification

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      Parameter Example Required Description Revision
      USER_ID 123 Yes Notification ID 18
      TAG TEST Yes* Notification tag, unique within the system. 18
      SUB_TAG SUB|TEST Yes* Additional tag, without duplicate check 18

      * You need to indicate one of three required parameters for selection: ID (notification ID), TAG (notification tag) or SUB_TAG (additional tag).


      Related links

      How to handle attachments


      Called method and response

      PHP

      $result = restCommand('im.notify.delete', Array(
      
          'ID' => 13,
          'TAG' => 'TEST',
          'SUB_TAG' => 'SUB|TEST'
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Response: true or error.


      Example of response on error

      {
          "error": "PARAMS_ERROR",
          "error_description": "Error deleting notification"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      PARAMS_ERROR Error deleting notification

      im.notify.read

      The method cancels notification for read messages.

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

      Parameters

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18
      Parameter Example Req. Description Revision
      ID 17 Yes Notification ID 18
      ONLY_CURRENT N No Read only the specified notification 18
      • If the ONLY_CURRENT parameter is passed with Y, a read notification check is set only for the specified ID. Otherwise, the check is set for notification with equal or higher ID.

      Method call

      JavaScript

      BX24.callMethod('im.notify.read', {
      	'ID': 17,
      }, function(result){
      	if(result.error())
      	{
      		console.error(result.error().ex);
      	}
      	else
      	{
      		console.log(result.data());
      	}
      });
      

      PHP

      $result = restCommand('im.notify.read', Array(
      	'DIALOG_ID' => '17'
      ), $_REQUEST["auth"]);	
      

      Example of response

      {
      	"result": true
      }        
      

      im.notify.read.list

      "Reading" the list of notifications, excluding CONFIRM notification type

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Parameters

      Parameter Example Required Description Revision
      IDS [1,2,3] Yes Array with notification IDs 30
      ACTION 'Y' No Mark as read|unread (Y|N) 30


      Called method and response

      JavaScript

      B24.callMethod(
        'im.notify.read.list',
        {
          IDS: [1,2,3],
          ACTION: 'Y'
        },
        res => {
          if (res.error())
          {
            console.error(result.error().ex);
          }
          else
          {
            console.log(res.data())
          }
        }
      

      Response example

      true
      

      Response example on error

      {
        "error": "PARAMS_ERROR",
        "error_description": "No IDS param or it is not an array"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      PARAMS_ERROR Parameter IDS not passed or is not an array


      im.notify.answer

      Response to notification, supporting quick reply

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Parameters

      Parameter Example Required Description Revision
      ID 270 Yes Notification ID, supporting quick reply 30
      ANSWER_TEXT 'Hello' Yes Quick reply text 30


      Called method and response

      JavaScript

      B24.callMethod(
        'im.notify.answer',
        {
          ID: 270,
          ANSWER_TEXT: 'Hello'
        },
        res => {
          if (res.error())
          {
            console.error(result.error().ex);
          }
          else
          {
            console.log(res.data())
          }
        }
      )
      

      Response example

      {
        "result_message": [
          "You response is sent successfully."
        ]
      }
      

      Returns array with messages to your response.


      Example of response when passing notification ID not supporting quick reply

      {
        "result_message": false
      }
      

      Example of response on error

      {
        "error":"NOTIFY_ID_ERROR",
        "error_description":"Notification ID can\u0027t be empty"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      ID_ERROR Parameter ID not passed or isn't an integer
      ANSWER_TEXT_ERROR Parameter ANSWER_TEXT not passed or isn't an empty string

      im.notify.confirm

      Interaction with notification buttons

      [dw]Revision[/dw][di]Get current information about current API revision (platform version) – im.revision.get[/di]: 18

      Parameters

      Parameter Example Required Description Revision
      ID 288 Yes Notification ID, supporting reply via button click 30
      NOTIFY_VALUE 'Y' Yes Selected reply value (button value) 30

      For example, the notification is as follows:

      • Accept button has 'Y' value
      • Deny button has 'N' value

      Called method and response

      JavaScript

      B24.callMethod(
        'im.notify.confirm',
        {
          ID: 288,
          NOTIFY_VALUE: 'Y'
        },
        res => {
          if (res.error())
          {
            console.error(result.error().ex);
          }
          else
          {
            console.log(res.data())
          }
        }
      )
      

      Response example

      {
        "result_message": [
          "Invitation accepted"
        ]
      }
      

      Example of response on error

      {
        "error":"NOTIFY_VALUE_ERROR",
        "error_description":"Notification Value  can\u0027t be empty"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      ID_ERROR Parameter ID is not passed or isn't an integer
      NOTIFY_VALUE_ERROR Parameter NOTIFY_VALUE is not specified or empty

      Full List of Chat API Methods

      Platform version:

      MethodMethod description
      im.revision.get Gets information about API revisions.

      Working dialogs:

      MethodMethod description
      im.dialog.messages.get Gets the list of last messages in chat.

      Working with messages:

      MethodMethod description
      im.message.add Sends message to chat.
      im.message.update Updates chatbot message.
      im.message.delete Deletes chatbot message.
      im.message.like "Like" a message.

      Working with files:

      MethodMethod description
      im.disk.folder.get Gets information on folder storing files for chat
      im.disk.file.commit Publishes loaded file in the chat.
      im.disk.file.delete Deletes files inside chat folder.

      Working with users:

      MethodMethod description
      im.user.get Gets user data.
      im.user.list.get Gets multiple users data.
      im.user.business.list Gets list of users with access to business tools.
      im.user.status.get Gets information on the specified user status.
      im.user.status.set Specifies user status.
      im.user.status.idle.start Specifies automatic status "Away"
      im.user.status.idle.end Disables automatic status "Away"

      Working with departments:

      MethodMethod description
      im.department.get Gets department data.
      im.department.colleagues.list Gets list of users in your department.
      im.department.managers.get Gets list of department managers.
      im.department.employees.get Gets list of employees in a department.

      Working with search:

      MethodMethod description
      im.search.user.list Searches for users.
      im.search.chat.list Searches for chats.
      im.search.department.list Searches for departments.
      im.search.last.get Gets list of elements of the last search.
      im.search.last.add Adds a history element of the last search.
      im.search.last.delete Deletes a history element of the last search.

      Working with the list of recent chats:

      MethodMethod description
      im.recent.get Gets the last user dialogs.
      im.recent.pin Pins dialog in favorites.
      im.recent.hide Deletes dialog from the list of recent chats.

      Working with counters:

      MethodMethod description
      im.counters.get Gets counter data.

      Working with notifications:

      MethodMethod description
      im.notify.personal.add Sends personal notification.
      im.notify.system.add Sends sysytem notification.
      im.notify.delete Deletes notification.
      im.notify.read Cancels notification for read messages.


      Application for Chat

      What is it about?

      Applications for chat

      Developers now can integrate into Bitrix24 Messenger, by adding an icon to text input panel:

      If the app is not loading the image, service Application for chat icon will appear. After clicking on it, a text variant of the icon will appear.


      There are two types of chat application:

      1. JS command - when clicking on the icon, a chatbot command will be inserted into input field, a command will be sent to chat, telephone call will be initiated, or a support open channel will be opened.

        With the help of this format, developers can integrate a button in their chatbots to contact them.

        Example of such command for Martha chatbot - an icon for tick-tack-toe game:

      2. IFRAME application - it is an improved format. When clicking the button, IFRAME application will open, where the developer can do anything he/she desires.

        Application can cooperate with chat via JS-commands:

        • to insert message into input field
        • to send message on behalf of user
        • to close dialogue
        • to open technical support chat (OC consultant)
        • to make call

        Example of such implementation can be found in the example of Giphy chatbot:

        Tell the difference - previously you we're typing command in the form of a message and GIPHY returned you a random picture on the topic. Now you can see, what you are sending out.


        Attention: icons can understand context, and it means that the app can be displayed only in those chats that you require.

        For example, to communicate with technical support, it is better to deploy the app in your chatbot context. In other chats it will be excessive. Or you can develop a special application for Open Channels - it should be displayed only in the context of Open Channels.

        Accessible contexts: all, chat, bot, lines, user, call.

        Postfix can be added to each context -admin - then the icon will be displayed in the required context only to administrators.


      Context applications

      Context Applications are created to help user to interface with chatbot within the specific dialogue (message).

      For example, client writes in an open channel, open channel chatbot analyzes the message and prepares the variants of responses. To not disturb the work of operators and not to show the full flow of data to it, we are neatly creating a button, upon clicking on which, the IFRAME application will be initialized.


      Creating an Application

      There are two types of applications: JS-command and IFRAME-application.

      Please read how to work with applications via API-methods.



      Register application for chat

      REST method: imbot.app.register

      Method call for JS-command:
      $result = restCommand('imbot.app.register', Array(
      
         'BOT_ID' => 62, // Bot ID of chat application owner
         'CODE' => 'echo', // Application code for chat
         'JS_METHOD' => 'SEND', 
         'JS_PARAM' => '/help', 
         'ICON_FILE' => '/* base64 image */', // Your application icon - base64
         'CONTEXT' => 'BOT', // Application context
         'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
         'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
         'LANG' => Array( // translations array; it is preferably to indicate minimum for EN       Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot BUTTON', 'DESCRIPTION' => 'Send help command'),
      
         )
      
      ), $_REQUEST["auth"]);
      

      Variants for JS_METHOD:

      • PUT - insert command for chatbot in text area, JS_PARAM can contain only command text and parameters for it (permitted symbols: a-z 0-9 - + _ / ).
      • SEND - send command to chatbot, JS_PARAM can contain only command text and parameters for it (permitted symbols a-z 0-9 - + _ / ).
      • CALL - call to a phone number.
      • SUPPORT - open technical support chatbot, operating via Open Channels. Open Channel JS_PARAM code must be indicated (32 symbols).

      ICON_FILE application icon format:

      • Base64 of your icon should returned to this field. Icon format is detailed in this documentation.
      • Please note, if this field is not specified, the application will be accessible in the system dialogue "Applications for chat".

      Application context CONTEXT:

      • ALL - application will be accessible in all chats.
      • USER - application will be accessible only in Person-to-person chats.
      • CHAT - application will be accessible only in Group chats.
      • BOT - application will be accessible only to chatbot that have installed the app.
      • LINES - application will be accessible only in Open Channels chats.
      • CALL - application will be accessible only in chats, created within Telephony framework.

      Postfix -admin can be added to each context, then the application will be accessible in the required context only to Bitrix24 administrators.


      Method call for IFRAME-application:
      $result = restCommand('imbot.app.register', Array(
      
         'BOT_ID' => 62, // Bot ID of chat application owner
         'CODE' => 'echo', // Application code for chat
         'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php', 
         'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
         'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
         'HASH' => 'd1ab17949a572b0979d8db0d5b349cd2', // token for access to your frame to check the signature, 32 symbols. 
         'ICON_FILE' => '/* base64 image */', // Your application icon - base64
         'CONTEXT' => 'BOT', // Application context
         'HIDDEN' => 'N', // application is hidden or not 
         'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
         'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
         'LANG' => Array( // translations array; it is preferably to indicate minimum for EN Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Echobot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
         )
      
      ), $_REQUEST["auth"]);
      

      Attention:
      1. Although, when registering IFRAME-application you are specifying the window size, it can be reduced by the app to the actually available dimensions. Ideal variant - to create an app in such manner that it would fit into minimal dimensions and could freely adapt to an increase or a reduction of size; it will be very important for mobile devices.
      2. Link to IFRAME must lead to site with active HTTPS-certificate. You can find IFRAME-processor development rules and limitations in the following documentation.
      3. It is imperative to check HASH prior to completion of any operations.
      4. Applications are accessible only after page reloading or after service hit on server (refresh time differs for various installations, from 15 to 26 minutes). Application will immediately appear only when interfacing with context button.
      5. You shall specify the desired values of width and height of the app window in the IFRAME_WIDTH and IFRAME_HEIGHT values. If the messenger window will end up being smaller, than the app window - the app window will be reduced to the messenger window. Otherwise, if the message window ends up being larger than the app window - the desired dimensions for the app will be used.
      6. If the app is called from the context (keyboard or menu), the app will be called in the context mode, in this mode the IFRAME_POPUP values will be ignored.

      Return: APP_ID numerical ID of created application or an error.

      Possible errors:

      Error codeError description
      BOT_ID_ERROR Chatbot not found.
      APP_ID_ERROR Application for chat is not part to this REST-application, you can only work with applications for chat, installed within the framework of current REST-application.
      IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
      HASH_ERROR You have not specified HASH for application. We recommend using unique HASH for each IFRAME and each installation.
      PARAMS_ERROR Error when specifying JS-command or IFRAME-parameters.
      LANG_ERROR Language phrases are not returned for visible command.
      WRONG_REQUEST Something went wrong.


      Delete application for chat

      REST-method: imbot.app.unregister

      Method call:
      $result = restCommand('imbot.app.unregister', Array(
      
          'APP_ID' => 13, // delete command ID
      
      ), $_REQUEST["auth"]);
      
      Return: true or an error.

      Possible errors:

      Error codeError description
      CHAT_APP_ID_ERROR Application not found.
      APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
      WRONG_REQUEST Something went wrong.


      Update application data in chat

      Attention: required fields are application ID field and one of the fields, needed for editing. If JS and IFRAME methods are called in one command, only JS method will be used.

      REST-method: imbot.app.update

      Method call:
      $result = restCommand('imbot.app.update', Array(
      
         'APP_ID' => 13, // chat ID
         'FIELDS' => Array(
            'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php',
             'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
             'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
             'JS_METHOD' => 'SEND', 
             'JS_PARAM' => '/help', 
            'HASH' => 'register', // token for access to your frame, 32 symbols. 
             'ICON_FILE' => '/* base64 image */', // Your application icon - base64
             'CONTEXT' => 'BOT', // Application context
            'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’      
             'LIVECHAT_SUPPORT' => 'N', // Online chat support
            'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window
            'LANG' => Array( // translations array; it is preferably to indicate minimum for EN          Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
            )
         )
      ), $_REQUEST["auth"]);
      
      Return: true or an error.

      Possible errors:

      Error codeError description
      CHAT_APP_ID_ERROR Application not found.
      APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
      IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
      WRONG_REQUEST Something went wrong.


      imbot.app.register

      Register application for chat


      There are two types of applications: JS-command and IFRAME-application.

      REST method: imbot.app.register

      Method call for JS-command:
      $result = restCommand('imbot.app.register', Array(
      
         'BOT_ID' => 62, // Bot ID of chat application owner
         'CODE' => 'echo', // Application code for chat
         'JS_METHOD' => 'SEND', 
         'JS_PARAM' => '/help', 
         'ICON_FILE' => '/* base64 image */', // Your application icon - base64
         'CONTEXT' => 'BOT', // Application context
         'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
         'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
         'LANG' => Array( // translations array; it is preferably to indicate minimum for EN       Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot BUTTON', 'DESCRIPTION' => 'Send help command'),
      
         )
      
      ), $_REQUEST["auth"]);
      

      Variants for JS_METHOD:

      • PUT - insert command for chatbot in text area, JS_PARAM can contain only command text and parameters for it (permitted symbols: a-z 0-9 - + _ / ).
      • SEND - send command to chatbot, JS_PARAM can contain only command text and parameters for it (permitted symbols a-z 0-9 - + _ / ).
      • CALL - call to a phone number.
      • SUPPORT - open technical support chatbot, operating via Open Channels. Open Channel JS_PARAM code must be indicated (32 symbols).

      ICON_FILE application icon format:

      • Base64 of your icon should returned to this field. Icon format is detailed in this documentation.
      • Please note, if this field is not specified, the application will be accessible in the system dialogue "Applications for chat".

      Application context CONTEXT:

      • ALL - application will be accessible in all chats.
      • USER - application will be accessible only in Person-to-person chats.
      • CHAT - application will be accessible only in Group chats.
      • BOT - application will be accessible only to chatbot that have installed the app.
      • LINES - application will be accessible only in Open Channels chats.
      • CALL - application will be accessible only in chats, created within Telephony framework.

      Postfix -admin can be added to each context, then the application will be accessible in the required context only to Bitrix24 administrators.


      Method call for IFRAME-application:
      $result = restCommand('imbot.app.register', Array(
      
         'BOT_ID' => 62, // Bot ID of chat application owner
         'CODE' => 'echo', // Application code for chat
         'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php', 
         'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
         'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
         'HASH' => 'd1ab17949a572b0979d8db0d5b349cd2', // token for access to your frame to check the signature, 32 symbols. 
         'ICON_FILE' => '/* base64 image */', // Your application icon - base64
         'CONTEXT' => 'BOT', // Application context
         'HIDDEN' => 'N', // application is hidden or not 
         'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
         'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
         'LANG' => Array( // translations array; it is preferably to indicate minimum for EN Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Echobot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
         )
      
      ), $_REQUEST["auth"]);
      

      Attention:
      1. Although, when registering IFRAME-application you are specifying the window size, it can be reduced by the app to the actually available dimensions. Ideal variant - to create an app in such manner that it would fit into minimal dimensions and could freely adapt to an increase or a reduction of size; it will be very important for mobile devices.
      2. Link to IFRAME must lead to site with active HTTPS-certificate. You can find IFRAME-processor development rules and limitations in the following documentation.
      3. It is imperative to check HASH prior to completion of any operations.
      4. Applications are accessible only after page reloading or after service hit on server (refresh time differs for various installations, from 15 to 26 minutes). Application will immediately appear only when interfacing with context button.
      5. You shall specify the desired values of width and height of the app window in the IFRAME_WIDTH and IFRAME_HEIGHT values. If the messenger window will end up being smaller, than the app window - the app window will be reduced to the messenger window. Otherwise, if the message window ends up being larger than the app window - the desired dimensions for the app will be used.
      6. If the app is called from the context (keyboard or menu), the app will be called in the context mode, in this mode the IFRAME_POPUP values will be ignored.

      Return: APP_ID numerical ID of created application or an error.

      Possible errors:

      Error codeError description
      BOT_ID_ERROR Chatbot not found.
      APP_ID_ERROR Application for chat is not part to this REST-application, you can only work with applications for chat, installed within the framework of current REST-application.
      IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
      HASH_ERROR You have not specified HASH for application. We recommend using unique HASH for each IFRAME and each installation.
      PARAMS_ERROR Error when specifying JS-command or IFRAME-parameters.
      LANG_ERROR Language phrases are not returned for visible command.
      WRONG_REQUEST Something went wrong.

      imbot.app.unregister

      Delete application for chat

      Method call

      $result = restCommand('imbot.app.unregister', Array(
      
          'APP_ID' => 13, // Идентификатор команды для удаления
      
      ), $_REQUEST["auth"]);
      
      Return: true or an error.

      Possible errors:

      Error codeError description
      CHAT_APP_ID_ERROR Application not found.
      APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
      WRONG_REQUEST Something went wrong.

      imbot.app.update

      Update application data in chat

      Attention: required fields are application ID field and one of the fields, needed for editing. If JS and IFRAME methods are called in one command, only JS method will be used.

      REST-method: imbot.app.update

      Method call:
      $result = restCommand('imbot.app.update', Array(
      
         'APP_ID' => 13, // chat ID
         'FIELDS' => Array(
            'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php',
             'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
             'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
             'JS_METHOD' => 'SEND', 
             'JS_PARAM' => '/help', 
            'HASH' => 'register', // token for access to your frame, 32 symbols. 
             'ICON_FILE' => '/* base64 image */', // Your application icon - base64
             'CONTEXT' => 'BOT', // Application context
            'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’      
             'LIVECHAT_SUPPORT' => 'N', // Online chat support
            'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window
            'LANG' => Array( // translations array; it is preferably to indicate minimum for EN          Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
            )
         )
      ), $_REQUEST["auth"]);
      
      Return: true or an error.

      Possible errors:

      Error codeError description
      CHAT_APP_ID_ERROR Application not found.
      APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
      IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
      WRONG_REQUEST Something went wrong.

      Context Applications

      You find details about what is context application here.


      To work with context, you need to complete several actions:

      1. Creating an Application. You can register a hidden application, then it will not be displayed on the text input panel.
      2. Send (or update) any message with attached keyboard or from menu.
      3. You must input application identifier in the parameters of keyboard button or menu item.

      Method call:
      restCommand('imbot.message.add', Array(
         "DIALOG_ID" => 2,
         "BOT_ID" => 17,
         "MESSAGE" => "Hello! My name is ChatBot :)",
         "KEYBOARD" => [{"TEXT":"Open App","APP_ID":11}],
         "MENU" => [{"TEXT":"Open App","APP_ID":11}]
      
      ), $_REQUEST["auth"]);
      

      aside from APP_ID, you can input ant line into parameter APP_PARAMS; when your IFRAME will open, the data will be transferred to parameter BUTTON_PARAMS.

      You can find IFRAME-processor development rules and limitations in this documentation. When creating a message, you can use one of two options – KEYBOARD or MENU.



      Create Application Icon for Chat

      Then creating Application for chat icon, you need to follow several simple rules:

      1. Icon could be created with a transparent background, in .PNG format.

      2. Canvas size: 108x66 px, left part is used for inactive icon, second part - to show an active icon:

      3. Main part of the icon could not be larger than 45x32 px and shall be specifically aligned in the middle of each part:

      4. Main color of inactive icon - #b3b7bc, active - #2fc7f7:


        Below you can find several templates, for your convenience:

        textarea_icon.psd marta_icon.psd textarea_icon_f.psd
      5. To load an image, when registering or updating an application, you need to specify IMAGE_FILE key. The value of this key shall be your image base64:

        'ICON_FILE' => base64_encode(file_get_contents(__DIR__.'/icon_button.png')), 
        

        Attention: you may choose not to create an icon for the application. Then it will be folded into the service button:



      Create IFRAME-processor

      After application for chat is registered, you need to use IFRAME-processor.

      Attention: please note, that when registering an application, you are specifying window size, but it can be minimized by the app to its actual permitted dimensions. Ideal option - is to adapt the app to fit freely within sizing changes. It is essential for mobile devices.


      Your page will be open with the following data

      Array
      (
          [BOT_ID] => 17
          [BOT_CODE] => echoBot
          [APP_ID] => 11
          [APP_CODE] => echoFrame
          [DOMAIN] => https://test.bitrix24.com
          [DOMAIN_HASH] => 0e9c40cee01d6f182e9261b38b30b5c3
          [USER_ID] => 2
          [USER_HASH] => 7e23ac8b6f6c7044076301c7f81cd745
          [DIALOG_ID] => 950
          [CONTEXT] => textarea 
          [LANG] => com 
          [IS_CHROME] => Y 
          [MESSAGE_ID] => 12333 
          [BUTTON_PARAMS] => test
          [DIALOG_ENTITY_ID] => telegrambot|8|173633217|569
          [DIALOG_ENTITY_DATA_1] => Y|LEAD|56|N|N|1765
          [DIALOG_CONTEXT] => lines 
      
      )
      

      Parameter details:

      • BOT_ID and BOT_CODE - chatbot data, with which the application is launched.
      • APP_ID and APP_CODE - application data for launched application chat.
      • DOMAIN - account address, from which the app was launched.
      • DOMAIN_HASH - this HASH field, returned when icon is registered. It is used to cut off unauthorized requests.
      • USER_ID - user ID.
      • USER_HASH - HASH string to validate request at client's account.
      • DIALOG_ID - launched dialogue ID at user's account at the moment when the frame is opened.
      • CONTEXT - dialogue request, can be text area or button.
      • LANG - current client interface language.
      • IS_CHROME - the frame launch check in Google Chrome browser: was it launched or not.
      • DIALOG_CONTEXT - this parameter is not yet available. The request can be all, chat, bot, lines, user, request .
      • DIALOG_ENTITY_ID - additional chat data (this parameter is not yet available). Data is split for Open Channels|. Field values for Open Channels: 1 - channel, through which user writes, 2 – OC ID, 3 and 4 – service data (parameter is not yet available).
      • DIALOG_ENTITY_DATA_1 - chat additional data (this parameter is not yet available). Data is split for Open Channels|. Field values for Open Channels: 1 – saved in CRM, 2 – CRM entity type, 3 - CRM entity ID, 4 and 5 – service data, 6 – Open Channel session ID.

      If the frame is launched in the context mode:

      • MESSAGE_ID - message ID.
      • BUTTON_PARAMS - button parameter, set during sending.


      Interfacing with parent window (with messenger)

      You need to configure interfacing function with the main window, data initialization and forwarding.

      Initialization example:

      <script type="text/javascript">
         // initialize communication with main window function 
         function frameCommunicationInit()
         {
            if (!window.frameCommunication)
            {
               window.frameCommunication = {timeout: {}};
            }
            if(typeof window.postMessage === 'function')
            {
               window.addEventListener('message', function(event){
                  var data = {};
                  try { data = JSON.parse(event.data); } catch (err){}
         
                  if (data.action == 'init')
                  {
                     frameCommunication.uniqueLoadId = data.uniqueLoadId;
                     frameCommunication.postMessageSource = event.source;
                     frameCommunication.postMessageOrigin = event.origin;
                  }
               });
            }
         }
      
         // send data to main window function
         function frameCommunicationSend(data)
         {
            data['uniqueLoadId'] = frameCommunication.uniqueLoadId;
            var encodedData = JSON.stringify(data);
            if (!frameCommunication.postMessageOrigin)
            {
               clearTimeout(frameCommunication.timeout[encodedData]);
               frameCommunication.timeout[encodedData] = setTimeout(function(){
                  frameCommunicationSend(data);
               }, 10);
               return true;
            }
            
            if(typeof window.postMessage === 'function')
            {
               if(frameCommunication.postMessageSource)
               {
                  frameCommunication.postMessageSource.postMessage(
                     encodedData,
                     frameCommunication.postMessageOrigin
                  );
               }
            }
         }
         frameCommunicationInit();
      </script>
      

      The following function will be accessible to you:

      • Command to send text from user:
        frameCommunicationSend({'action': 'send', 'message': 'Send message'})

      • Command to send text to input field:
        frameCommunicationSend({'action': 'put', 'message': 'Put message'})

      • Command to start call:
        frameCommunicationSend({'action': 'call', 'number': '123456'})

      • Command to open dialogue with your open channel:
        frameCommunicationSend({'action': 'support', 'code': '6a4cdbcf753addac1a573ea64be826ca'})

      • Close frame command:
        frameCommunicationSend({'action': 'close'})



      Registration and security

      You can forgo checking the incoming requests, but we strongly recommend doing it.

      Based on the incoming data you can perform the required checks:

      1. We recommend checking REFERER for matching with specified domain.
      2. We recommend checking domain and its HASH.
      3. We recommend checking user and its HASH.
      4. Use unique HASH for each new registration.

      You can develop a sufficiently secure application if you combine all those factors.


      When registering a command, you must specify HASH-string. User and domain will use it to undersign:

      $hash = '0e9c40cee01d6f182e9261b38b30b5c3'; // HASH, specified during registration of the application.
      
      $check = parse_url($_GET['DOMAIN']);
      
      // check for validity of specified domain
      if ($_GET['DOMAIN_HASH'] == md5($check['host'].$hash))
      {
         echo 'OK';
      }
      
      // check for validity of specified user 
      if ($_GET['USER_HASH'] == md5($_GET['USER_ID'].$hash))
      {
         echo 'OK';
      }
      
      // check for REFERER
      if (strpos($_SERVER['HTTP_REFERER'], $_GET['DOMAIN'])!== 0)
      {
         echo 'OK';
      }
      

      The work in such mode is reviewed in detail in the preview example, which you can download here.

      New Desktop Clients

      To work with applications for chat, you will need a modern web browser and new desktop applications:

      • Windows: download
      • Mac OS: download
      • Unix: client is in development, alpha version with enabled frames will be published later. Brick does not yet support this function.


      REST API

      REST API Capabilities

      REST API is designed to create applications for Bitrix24 Cloud Service.

      REST API allows to receive access and to manage such Bitrix24 Cloud Service tool as:

      • CRM,
      • Workflows,
      • Drive,
      • Social Network,
      • Telephony,
      • Lists,
      • Notifications,
      • Tasks,
      • Working with users and multiple Company Divisions,
      • Feed,
      • Calendars.

      To use REST API methods by third-party applications, the specific app should be registered in Bitrix24 Marketplace. In this case, the application has all the necessary data to receive the OAuth 2.0 key.

      The overview of how REST method is called is the following:

      https://domain_B24.bitrix24.{en|de}/rest/name_method.transport?parameters_method&auth=key_authorization
      
      where transport - optional parameter, which can have values json or xml. By default - json.

      Request can be sent via both GET and POST methods.

      Parameter values are accepted in UTF-8 encoding.

      Attention! There is a limit for the number of requests: two requests per second. If the limit is exceeded, then the restriction is triggered after 50 requests.
      Bitrix24 Enterprise edition has the limit of 5 queries per second. Number of queries limit - 250.

      Note: An excessive load, generated by your application/webhook can trigger an overload blocking:
      [
      'error' => 'OVERLOAD_LIMIT',
      'error_description' => 'REST API is blocked due to overload.'
      ]
      
      You can submit a ticket to unblock REST API to Helpdesk.

      Bitrix Bot Platform API is an integral part of general REST system. Documentation for all the rest of methods is available in REST API documentation.

      Open Channels

      Attention! You need to have access to the imopenlines (Open Channels) scope to use the methods IMOPENLINES REST in addition to the imbot (Creating and managing chatbots) access permissions.


      MethodMethod description
      imopenlines.dialog.get Get information on the dialog (chat) for Open Channel operator.


      Platform version

      imopenlines.revision.get – getting information about Open Channels API revisions

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 2

      Parameters

      No.

      Call example

      JavaScript

      BX24.callMethod('imopenlines.revision.get', {}, function(result){
          if(result.error())
          {
              console.error(result.error().ex);
          }
          else
          {
              console.log(result.data());
          }
      });
      

      PHP

      $result = restCommand('imopenlines.revision.get', Array(
      ), $_REQUEST["auth"]);
      

      Response example

      {    
          "result": {
              "rest": 2,
              "web": 1,
              "mobile": 1,
          }
      }
      

      Key description:

      • rest – API revision for REST clients
      • web – API revision for Web/Desktop client
      • mobile – API revision for mobile client

      Attention: restCommand function is used here for illustration purposes only. It is taken from the EchoBot example. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.



      Handling Open Channels

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.


      MethodMethod description
      imopenlines.network.join Connect Open Channel by code.
      imopenlines.network.message.add Send Open Channel message to selected user.


      imopenlines.network.join

      Connecting an open channel by code

      [dw]Revision[/dw][di] Get information about current API version (platform version) – im.revision.get[/di]: 1

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Req. Description Revision
      CODE ab515f5d85a8b844d484f6ea75a2e494 Yes Code for searching from connector page 1


      Method call and response

      PHP

      $result = restCommand('imopenlines.network.join', Array(
      
          'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494'
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": 42
      }
      

      Result: chatbot ID or error.

      Example of response on error

      {
          "error": "NOT_FOUND",
          "error_description": "Openline is not found"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      IMBOT_ERROR Imbot module is not installed
      NOT_FOUND Open Channel not found
      INACTIVE Open Channel presently is unavailable


      imopenlines.network.message.add

      Sending Open Channel message to selected user

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 2

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Req. Description Revision
      CODE ab515f5d85a8b844d484f6ea75a2e494 Yes Registered Open Channel code 1
      USER_ID 2 Yes Message recipient ID 1
      MESSAGE message text Yes Message text 1
      ATTACH No Attachment 1
      KEYBOARD No Keyboard 1
      URL_PREVIEW Y No Convert links to rich links, by default set as 'Y' 1


      Method call and response

      PHP

      $result = restCommand('imopenlines.network.message.add', Array(
      
      	'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494',
      	'USER_ID' => 2,
      	'MESSAGE' => 'message text',
      	'ATTACH' => '',
      	'KEYBOARD' => '',
      	'URL_PREVIEW' => 'Y'
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Result: true or error.

      Restrictions

      • You can send message not more than once for each user during a one week period.

        Note: There are no restrictions for the account with Partner (NFR) license.

      • You can use keyboard only for formatting link button at third-party site.

      Response example on error

      {
          "error": "CODE_ERROR",
          "error_description": "Open Channel code is incorrect"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      CODE_ERROR Open Channel code is incorrect.
      USER_ID_EMPTY User ID is empty.
      MESSAGE_EMPTY Message text is empty.
      ATTACH_ERROR Attachment object is not validated.
      ATTACH_OVERSIZE Maximum permissible attachment size exceeded (30 Kb).
      KEYBOARD_ERROR Passed keyboard object is not validated.
      KEYBOARD_OVERSIZE Maximum permissible keyboard size exceeded (30 Kb).
      USER_MESSAGE_LIMIT Message limit exceeded for specific user.
      WRONG_REQUEST Something went wrong.


      Related links:



      Handling Dialogs

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.


      MethodMethod description
      imopenlines.dialog.get Gets agent information in Open Channel dialog (chat).


      imopenlines.dialog.get

      Gets information on dialog (chat) of Open Channel operator

      Revision: 2
      Get information on current API revision (Open channel platform version) – imopenlines.revision.get.

      Parameters
      Parameter Example Required Description Revision
      CHAT_ID 13 No Chat numerical ID 2
      DIALOG_ID chat29 No Dialog identifier. Format:
      chatXXX – recipient chat in case of chat message
      or XXX – recipient ID, if message for private dialog/chat
      2
      SESSION_ID 1743 No Session ID in Open Channel 2
      USER_CODE livechat|1|1373|211 No Open Channel User string ID sourced from CRM, for example livechat|1|1373|211 or imol|livechat|1|1373|211 2


      Can be used to call any of parameters.

      Method call and response

      JavaScript

      BX24.callMethod('imopenlines.dialog.get', {USER_CODE: 'livechat|1|1373|211'}, function(result){
          if(result.error())
          {
              console.error(result.error().ex);
          }
          else
          {
              console.log(result.data());
          }
      });
      

      PHP

      $result = restCommand('imopenlines.dialog.get', Array(
      	'DIALOG_ID': 'chat29'
      ), $_REQUEST["auth"]);
      

      Response example

      {
          "result": 
        {
      	avatar: ""
      	color: "#4ba984"
      	date_create: "2020-05-12T17:40:55+02:00"
      	dialog_id: null
      	entity_data_1: "N|NONE|0|N|N|0|1591872180|1|0|"
      	entity_data_2: ""
      	entity_data_3: ""
      	entity_id: "livechat|1|1363|203"
      	entity_type: "LINES"
      	extranet: false
      	id: 1364
      	manager_list: []
      	message_type: "L"
      	name: "John Smith - Priority support"
      	owner: 0
      	type: "lines"
        }
      }
      

      Key description:

      • avatar – link to avatar (when empty, avatar is not specified)
      • color – chat color in hex format
      • date_create – chat created date in АТОМ format
      • dialog_id – dialog ID
      • entity_data_1 – ex chat external data t
      • entity_data_2 – chat external data
      • entity_data_3 – chat external data
      • entity_id – chat external code – identifier
      • entity_type – chat external code – type
      • extranet – extranet user chat participation attribute (true/false)
      • id – chat ID
      • manager_list – list of operators
      • message_type – chat message type
      • name – Open Channel name
      • owner – chat creator ID
      • type – chat type (group[ chat, call chat, Open Channel chat and etc.)


      Response example in case of error

      {
          "error": "DIALOG_ID_EMPTY",
          "error_description": "Dialog ID can't be empty"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error ID codes

      ID Description
      DIALOG_ID_EMPTY Dialog ID not passed
      ACCESS_ERROR Current user doesn't have access permissions for dialog


      Handling chat bots

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.


      MethodMethod description
      imopenlines.bot.session.operator Switch conversation to free operator.
      imopenlines.bot.session.transfer Switch conversation to specific operator.
      imopenlines.bot.session.finish Finish current session.
      imopenlines.bot.session.message.send Send automatic chatbot message.


      imopenlines.bot.session.operator

      Switch conversation to free operator

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 1

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Required Description Revision
      CHAT_ID 12 Yes Chat ID 1


      Method call and response

      PHP

      
      $result = restCommand('imopenlines.bot.session.operator', Array(
      
          'CHAT_ID' => 12
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Result: true or error.

      Example of response on error

      {
          "error": "CHAT_ID_EMPTY",
          "error_description": "No chat ID"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      CHAT_ID_EMPTY No chat ID.
      WRONG_CHAT Specified chat is not under bot control.
      BOT_ID_ERROR Incorrect chatbot ID.


      imopenlines.bot.session.transfer

      Switch conversation to specific operator

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 1

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Required Description Revision
      CHAT_ID 112 Yes Chat ID 1
      USER_ID 12 Yes User ID, to which forwarding is performed. 1
      LEAVE N Yes Y/N. If 'N’ is specified – chatbot will not leave this chat after forwarding and will be available until user is confirmed 1


      Note: Instead of USER_ID you can indicate QUEUE_ID for witching to another open channel.

      Method call and response

      PHP

      $result = restCommand('imopenlines.bot.session.transfer', Array(
      
          'CHAT_ID' => 112,
          'USER_ID' => 12,
          'LEAVE' => 'N'
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Result: true or error.

      Example of response on error

      {
          "error": "CHAT_ID_EMPTY",
          "error_description": "No chat ID"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      CHAT_ID_EMPTY No chat ID.
      USER_ID_EMPTY No user ID, to which conversation must be forwarded.
      WRONG_CHAT Incorrect user ID is specified, or this user is chatbot or extranet user.
      BOT_ID_ERROR Incorrect chatbot ID.


      imopenlines.bot.session.finish

      Finish current session

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 1

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Required Description Revision
      CHAT_ID 112 Yes Chat ID 1


      Method call and response

      PHP

      $result = restCommand('imopenlines.bot.session.finish', Array(
      
          'CHAT_ID' => 112
      
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Result: true or error.

      Example of response on error

      {
          "error": "CHAT_ID_EMPTY",
          "error_description": "No chat ID"
      }
      

      Key description:

      • error – error code
      • error_description – error brief description

      Possible error codes

      Code Description
      CHAT_ID_EMPTY No chat ID.
      BOT_ID_ERROR Incorrect chat bot ID.


      imopenlines.bot.session.message.send

      Send automatic chat bot message

      [dw]Revision[/dw][di]You can get information about the current API version (platform version) as follows: im.revision.get[/di]: 1

      Attention! To use the IMOPENLINES REST methods you need to have access permissions for imbot (Creating and managing chat bots) as well as access to the imopenlines (Open channels) scope.

      Parameters

      Parameter Example Required Description Revision
      CHAT_ID 2 Yes Chat ID, taken by current agent 1
      MESSAGE message text Yes Sent message 1
      NAME WELCOME Yes Message type: WELCOME - greetings message, DEFAULT - standard message. Empty be default 1


      Method call and response

      PHP

      $result = restCommand('imopenlines.bot.session.message.send', Array(
      
      	'CHAT_ID' => 2,
      	'MESSAGE' => 'message text',
      	'NAME' => 'WELCOME'
      ), $_REQUEST["auth"]);
      

      Response example

      {
      	"result": true
      }
      
      Result: true or error.


      Send Commands and Extend Authorization

      Within our course, we interface with Bitrix24 via PHP.

      All examples are provided with the use of restCommand functions:

      restCommand('imbot.message.add', Array(
         "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
         "MESSAGE" => "[put=/search]Input search string[/put]",
      ), $_REQUEST["auth"]);
      
      where:
      First parameter - API name (imbot.message.add);
      Second parameter - API data return (Array(...))
      Third parameter - Data for request authorization ($_REQUEST["auth"]).

      Note: This function is used as an example. You can use your own function, based on interfacing protocol, or BX24.callMethod javascript-method, or a partner development bitrix24-php-sdk.

      RestCommand function

      /**
       * Send rest query to Bitrix24.
       *
       * @param $method - Rest method, ex: methods
       * @param array $params - Method params, ex: Array()
       * @param array $auth - Authorize data, ex: Array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
       * @param boolean $authRefresh - If authorize is expired, refresh token
       * @return mixed
       */
      function restCommand($method, array $params = Array(), array $auth = Array(), $authRefresh = true)
      {
         $queryUrl = "https://".$auth["domain"]."/rest/".$method;
         $queryData = http_build_query(array_merge($params, array("auth" => $auth["access_token"])));
         
         $curl = curl_init();
      
         curl_setopt_array($curl, array(
            CURLOPT_POST => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => 1,
            CURLOPT_URL => $queryUrl,
            CURLOPT_POSTFIELDS => $queryData,
         ));
      
         $result = curl_exec($curl);
         curl_close($curl);
      
         $result = json_decode($result, 1);
      
         if ($authRefresh && isset($result['error']) && in_array($result['error'], array('expired_token', 'invalid_token')))
         {
            $auth = restAuth($auth);
            if ($auth)
            {
               $result = restCommand($method, $params, $auth, false);
            }
         }
      
         return $result;
      }
      

      RestAuth function

      /**
       * Get new authorize data if you authorize is expire.
       *
       * @param array $auth - Authorize data, ex: Array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
       * @return bool|mixed
       */
      function restAuth($auth)
      {
         if (!CLIENT_ID || !CLIENT_SECRET)
            return false;
      
         if(!isset($auth['refresh_token']) || !isset($auth['scope']) || !isset($auth['domain']))
            return false;
      
         $queryUrl = 'https://'.$auth['domain'].'/oauth/token/';
         $queryData = http_build_query($queryParams = array(
            'grant_type' => 'refresh_token',
            'client_id' => CLIENT_ID,
            'client_secret' => CLIENT_SECRET,
            'refresh_token' => $auth['refresh_token'],
            'scope' => $auth['scope'],
         ));
         
         $curl = curl_init();
      
         curl_setopt_array($curl, array(
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $queryUrl.'?'.$queryData,
         ));
      
         $result = curl_exec($curl);
         curl_close($curl);
      
         $result = json_decode($result, 1);
         
         return $result;
      }
      


      Event Subscription

      REST API interface allows to install your own server event handlers.

      An events handler is an URL to which the system sends a request after a user performs an action on the Bitrix24 account, hosting the application.

      The handler receives the following data on input:

      • event - specifies the event name.
      • data - an array containing the event data.
      • auth - contains the authentication information.

      The handler can be:

      • using received authentication information to send requests to REST API.
      • be installed only by a user with account administrative rights.

      Attention! If the event handler requires access to REST API to work with data, then it is strongly recommended to use the retrieved authentication data specifically, and not the data, saved on application side.

      When installing a handler, the application can specify a user whose credentials will be used by the event handler for authentication. By default, the event handler will be authenticated as a user whose actions triggered the event.

      An event handler is not called immediately after an event occurred. It will be activated after some time which depends on a current server load

      List of available event can be found via the REST method events.

      Event handler is installed as follows:

      • via REST method event.bind on the basis of restCommand:
        $handlerBackUrl  = 'http://www.my-domain.com/handler/';
        $result = restCommand('event.bind', Array(
           'EVENT' => 'OnAppUpdate',
           'HANDLER' => $handlerBackUrl
        ), $_REQUEST["auth"]);
        
      • or via BX24.callBind JS-library function:
        BX24.callBind('OnAppUpdate', 'http://www.my-domain.com/handler/');
        

        To get the list of registered event handlers, use REST method events.get.

        Removal of registered handler is done via REST method event.unbind or via JS-library function BX24.callUnbind.

        To grant application the access a specific event, a corresponding access permission has to be requested when registering an application version.

        Application can install any number of handlers of the same event, but all handlers shall be installed with authentication of different users. Furthermore, ability to call a handler depends on the access permission of a user, whose authorization is used to activate a handler.

        event names are case-independent.

        Attention! When uninstalling or installing a new version of an application, all event handlers, installed by this application, will be deleted.


        Installation and Update Events

        When installing and updating the application, 2 events are used: ONAPPINSTALL and ONAPPUPDATE. Both events has the same set of data, with only one different parameter - [PREVIOUS_VERSION] => 1, where old version of the app is specified.


        ONAPPINSTALL event for installation of the application

        [data] => Array(
          [LANGUAGE_ID] = com // Account basic language
          [VERSION] = 1 // Application version
        )
        [auth] => Array(
            [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key to send request to REST service
            [scope] => imbot // Permitted access levels 
            [domain] => b24.hazz // Bitrix24 domain account, on which the application is installed
            [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token will help you to "fend off" redundant requests to event handler; this field is available in all events
        
            [expires_in] => 3600 // Token expiration period, after which new token will have to be requested
            [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authentication
            [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authentication
        )
        

        ONAPPUPDATE event to update application

        [data] => Array(
          [LANGUAGE_ID] = com // Account basic language
          [VERSION] = 2 // Application new version
          [PREVIOUS_VERSION] => 1 // Application old version
        )
        [auth] => Array(
            [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key to send request to REST service
            [scope] => imbot // Permitted access levels 
            [domain] => b24.hazz // Bitrix24 domain account, on which the application is installed
            [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token will help you to "end off" redundant requests to event handler; this field is available in all events
        
            [expires_in] => 3600 // Token expiration period, after which new token will have to be requested
            [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authentication
            [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authentication
        )
        

        Attention! Fields expires_in, member_id, refresh_token - are not required in the basic chatbot operation. But, if it's required for your application, then you can read how to work with them here. Extension option is included into the bot example.



        Open Channels and Chatbot Sessions

        Attention! You need to have access to the imopenlines (Open Channels) scope to use the methods IMOPENLINES REST in addition to the imbot (Creating and managing chatbots) access permissions.


        Connect Open Channel via code

        REST method: imopenlines.network.join

        Method call:
        $result = restCommand('imopenlines.network.join', Array(
        
            'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494' // code for search from connector page
        
        ), $_REQUEST["auth"]);
        
        Return: true or error code.

        Possible errors:

        Error codeError description
        IMBOT_ERROR Bot management module is not installed.
        NOT_FOUND Open Channel not found.
        INACTIVE Open Channel is unavailable at the moment.

        Sent message from Open Channel to selected user

        REST method: imopenlines.network.message.send

        Method call:
        $result = restCommand('imopenlines.network.message.send', Array(
        
        	'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494', // code of registered open channel
        	'USER_ID' => 2, // message recipient user code
        	'MESSAGE' => 'message text' // Message text
        	'ATTACH' => '' // Attachment, optional field
        	'KEYBOARD' => '' // Keyboard, optional field
        	'URL_PREVIEW' => 'Y' // Concert link to rich-link, optional field, by default 'Y'
        
        ), $_REQUEST["auth"]);
        
        Return: true or error code.

        Limitations:
        • You can send a message not more than once for each user during a week.
        • You can use keyboard only to configure the button-link to external site.

        Related links:

        Using Keyboards
        Attachments
        Formatting

        Possible errors:

        Error codeError description
        CODE_ERROR Incorrect code for Open Channel.
        USER_ID_EMPTY No ID for recipient user.
        MESSAGE_EMPTY No message text.
        ATTACH_ERROR Attachment object was not validated.
        ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
        KEYBOARD_ERROR Keyboard object was not validated.
        KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
        USER_MESSAGE_LIMIT Message limit for specific user was exceeded.
        WRONG_REQUEST Something went wrong.


        Switch conversation to a free operator

        REST method: imopenlines.bot.session.operator

        Method call:
        $result = restCommand('imopenlines.bot.session.operator', Array(
        
            'CHAT_ID' => 12 // Chat ID
        
        ), $_REQUEST["auth"]);
        
        Return: true or Error code.

        Possible errors:

        Error codeError description
        CHAT_ID_EMPTY No chat ID.
        WRONG_CHAT Specified chat is not under bot control.
        BOT_ID_ERROR Incorrect chatbot ID.


        Switch conversation to a specific operator

        REST method: imopenlines.bot.session.transfer

        Method call:
        $result = restCommand('imopenlines.bot.session.transfer', Array(
        
            'CHAT_ID' => 12 // Chat ID
            'USER_ID' => 12 // User ID, to which forwarding is performed
            'LEAVE' => 'N' // Y/N. If 'N’ is specified – chatbot will not leave this chat after forwarding and will be available until user is confirmed	
        
        ), $_REQUEST["auth"]);
        

        Note: Instead of USER_ID, QUEUE_ID can be specified to switch to another open channel.

        Return: true or Error code.

        Possible errors:

        Error codeError description
        CHAT_ID_EMPTY No chat ID.
        USER_ID_EMPTY No user ID, to which conversation must be forwarded.
        WRONG_CHAT Incorrect user ID is specified, or this user is chatbot or extranet user.
        BOT_ID_ERROR Incorrect chatbot ID.


        Current session finish

        REST method: imopenlines.bot.session.finish

        Method call:
        $result = restCommand('imopenlines.bot.session.finish', Array(
        
            'CHAT_ID' => 12 // Chat ID	
        
        ), $_REQUEST["auth"]);
        
        Return: true or Error code.

        Possible errors:

        Error codeError description
        CHAT_ID_EMPTY No chat ID.
        BOT_ID_ERROR Incorrect chatbot ID.

        Sending chatbot automatic message

        REST method: imopenlines.bot.session.message.send

        Revision: 1

        Get information on current API revision (Open channel platform version) – imopenlines.revision.get.

        Parameters

        Parameter Example Required Description Revision
        CHAT_ID 2 Yes Chat ID received by current operator 1
        MESSAGE message text Yes Message text 1
        NAME WELCOME Yes Message type: WELCOME - greetings message, DEFAULT - standard message. Empty be default 1


        Method call and response

        PHP

        $result = restCommand('imopenlines.bot.session.message.send', Array(
        
        	'CHAT_ID' => 2,
        	'MESSAGE' => 'message text',
        	'NAME' => 'WELCOME'
        ), $_REQUEST["auth"]);
        

        Response example

        {
        	"result": true
        }
        
        Returns: true or error.

        Note: Based on Open Channel REST API you can create technical support channel for your clients.



        JS methods for IFRAME applications

        Within IFRAME applications, you can use methods to open user dialogues or to manage window sizes. The following functions are provided to work with web-messenger:

        The following functions are available for handling web messengers:

        MethodDescription
        BX24.im.openMessenger Opens messenger window.
        BX24.im.openHistory Opens history window.
        BX24.im.callTo Internal video/audio calls.
        BX24.im.phoneTo Call to phone number.


        BX24.im.openMessenger

        This method opens messenger window

        Method call

        <script>
            BX24.im.openMessenger('dialogId');
        </script>
        
        Parameters:
        • dialogId - conversation/dialog ID:
          • userId or chatXXX - chat, where XXX - chat ID (can be just a number).
          • sgXXX - group chat, where XXX - social network group number (chat must be permitted in this group).
          • imol|XXXX - open channel, where XXX - code, retrieved via REST method imopenlines.network.join.

        In case of passing nothing, opens chat interface with the recent opened conversation.



        BX24.im.openHistory

        This method opens history window

        Method call

        <script>
            BX24.im.openHistory('dialogId');
        </script>
        
        Parameters:
        • dialogId - conversation/dialog ID:
          • userId or chatXXX - chat, where XXX - chat ID (it can just a number).
          • imol|XXXX - open channel, where XXX - is an open channel session number.


        BX24.im.callTo

        Internal communication call

        Method call

        <script>
            BX24.im.callTo('userId[, video=true]');
        </script>
        
        Parameters:
        • dialogId - Bitrix24 account user ID.
        • video - designates a call as video call (true - video call, false - audio call). Optional parameter.


        BX24.im.phoneTo

        Call to a phone number

        Method call

        <script>
            BX24.im.phoneTo('number');
        </script>
        
        Parameters:
        • number - phone number (string). Phone number can have the following format: 84012112233 or 8 (495) 711-22-33.


        Additional Materials



        These Materials can be helpful during development of chatbots for Bitrix24:

        Application for New Chat Design

        New Chat design

        Previous format for applications embedded to chat was introduced before unified Rest Placement format (location for [ds]embedding[/ds][di] You application can add features in a specially designated standard UI areas: CRM object details, various lists of elements or items, etc.

        Use the 'placement.bind' to assign the embedding location. Single application can set an arbitrary number of handlers, even for the same embedding location (for example, if you need to add several operations in a CRM lead's context menu).

        Learn more...[/di] Rest applications).

        After the release of Rest Placement format for developers to solve product embedding objectives, had to learn two different implementation formats - ([ds]legacy format[/ds][di] Developers can embed into Messenger, by adding its icon into text input panel.

        There are two types of applications for chat - JS command or IFRAME app.

        Learn more...[/di] for chats and the new type - for the rest of entities) and support of several formats is too resource-consuming.

        That's why the new Chat design that will be released soon to customers in 2023 introduces the unified format for the Rest Placement.

        New Chat has several embedding locations:

        • IM_NAVIGATION – application for the left navigation menu (by its design, its an application inside the chat environment without embedding directly into chat);
        • IM_TEXTAREA – application for panel above input field (this format existed before – for generating content when typing the message);
        • IM_SIDEBAR – application for sidebar (you can create applications that add extra scenarios for chat – for example, separate drive for chat or knowledge base);
        • IM_CONTEXT_MENU – application for opening message context menu inside chat, by embedding an option to "Create using" (similar to "Create task” or "Create meeting" based on the message);
        • IM_SMILES_SELECTOR – application for extending smileys and giphy options (custom image or smileys sources can be used).

        Embedding locations general info

        Applications for the new Chat design

        All embeddings have standard format and are registered via the method placement.bind. For example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_SIDEBAR',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/sidebar.php',
                'LANG_ALL' => [
                    'en' => [
                        'TITLE' => 'Application in sidebar',
                    ],
                ],
                'OPTIONS' => [
                    'iconName' => 'fa-bug',
                    'context' => 'USER;LINES',
                    'role' => 'ADMIN',
                    'extranet' => 'N',
                ]
            ]
        );
        

        Let's overview the section OPTIONS in detail:

        • iconName – application icon (this is a code from library Font Awesome 6.0). Icon is displayed everywhere, except for context menu and smiley selector;
        • context – app rendering context. If you can display the application only for specific types of chats (active for all chat types by default);

          Note: The option ALL has a highest priority above all the rest of options, that's why there is no sense to list other types of chats together with it. If such has occurred, the values for specific chat types will be ignored. Due to this, an incorrect value of one of passed options will still get an error upon registering the app.

        • role – user role to display this application, to show this application для которой будет показываться это приложение (by default USER – available to all);
        • extranet – application available for [ds]extranet users[/ds][di] "Extranet" allows for company to implement conference calls with suppliers, distributors and other external users without access to internal corporate information.

          External users (extranet users) do not have access to your internal Bitrix24, do not see the structure and any other company information, they can work only inside special extranet groups or projects.

          Learn more...[/di] (disabled by default).


        IM_NAVIGATION

        Application for the left navigation menu

        Embedding code: IM_NAVIGATION

        By design this is an application inside chat environment without embedding the app directly into the chat.

        Parameters

        Parameter Required Description
        iconName Yes Icon class name in the format Font Awesome (for example, fa-cloud).
        role No User role that has access to this application (by default, USER). Supports the following values:
        • USER – application is available for all users;
        • ADMIN – application is available only to Bitrix24 administrator.
        extranet No Application is available for extranet users (N by default). Supports the following values:
        • N – application is unavailable for extranet users;
        • Y – application is available for extranet users.

        The IFRAME opens, but current chat context isn't passed to it (because navigation – is an entity outside chat context).

        Application frame is opened inside the chat environment, simulating the general UI grid.

        Call example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_NAVIGATION',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/navigation.php',
                'LANG_ALL' => [
                    'en' => [
                        'TITLE' => 'Application for the left navigation menu',
                    ],
                ],
                'OPTIONS' => [
                    'iconName' => 'fa-check',
                    'role' => 'USER',
                    'extranet' => 'N',
                ]
            ]
        );
        



        IM_TEXTAREA

        Application for panel above the input field

        Embedding code: IM_TEXTAREA

        This format was available previously and isn't new. It generates content at the moment of message writing.

        Parameters

        Parameter Required Description
        iconName Yes Icon class name in the format Font Awesome (for example, fa-cloud).
        context No Chat type to embed the app (ALL by default). Supports the multiple selection via ; of the following values:
        • USER – all user chats, excluding bots;
        • CHAT – all group chats, except lines and crm;
        • LINES – chat type lines (open channels);
        • CRM – only chats created within CRM;
        • ALL – all chats.
        role No Application is available for this user role (USER by default). Supports the following values:
        • USER – application is available for all users;
        • ADMIN – application is available only for Bitrix24 administrators.
        color No Color. Available values: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, ORANGE, MARENGO, GRAY, GRAPHITE.
        width No Recommended frame width in the legacy chat design (100 by default).
        height No Recommended frame height as in the legacy chat design (100 by default).
        extranet No Application is available for extranet users (N by default). Supports the following values:
        • N – application is unavailable for extranet users;
        • Y – application is available for extranet users.

        This embedding has a current opening context, passed via current chat's dialogId.

        const context = BX24.placement.info().options;
        

        Opens application's IFRAME with specified dimensions. The system automatically reduces the size, if it exceeds the permissible value (your application must consider this).

        Call example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_TEXTAREA',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/textarea.php',
                'LANG_ALL' => [
                    'en' => [
                        'TITLE' => 'Application for panel above the input field',
                    ],
                ],
                'OPTIONS' => [
                    'iconName' => 'fa-bars',
                    'context' => 'USER;CHAT',
                    'role' => 'USER',
                    'color' => 'GRAPHITE',
                    'width' => '200',
                    'height' => '100',
                    'extranet' => 'N',
                ]
            ]
        );
        



        IM_SIDEBAR

        Application for sidebar

        Embedding code: IM_SIDEBAR

        You can create applications that add additional scenarios for chat. For example, for separate drive for chat or a knowledge base.

        Parameters

        Parameter Required Description
        iconName Yes Icon class name in the format Font Awesome (for example, fa-cloud).
        context No Chat type to embed the app (ALL by default). Supports the multiple selection via ; of the following values:
        • USER – all user chats, excluding bots;
        • CHAT – all group chats, except lines and crm;
        • LINES – chat type lines (open channels);
        • CRM – only chats created within CRM;
        • ALL – all chats.
        role No Application is available for this user role (USER by default). Supports the following values:
        • USER – application is available for all users;
        • ADMIN – application is available only for Bitrix24 administrators.
        color No Color. Available values: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, ORANGE, MARENGO, GRAY, GRAPHITE.
        extranet No Application is available for extranet users (N by default). Supports the following values:
        • N – application is unavailable for extranet users;
        • Y – application is available for extranet users.

        This embedding has a current opening context, passed via current chat's dialogId.

        const context = BX24.placement.info().options;
        

        Application will simulate the sidebar operational scenario (opens slider, repeating the sidebar details layer).

        Call example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_SIDEBAR',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/sidebar.php',
                'LANG_ALL' => [
                    'ru' => [
                        'TITLE' => 'Application for sidebar',
                    ],
                ],
                'OPTIONS' => [
                    'iconName' => 'fa-bug',
                    'context' => 'USER;LINES',
                    'role' => 'ADMIN',
                    'color' => 'AQUA',
                    'extranet' => 'N',
                ]
            ]
        );
        



        IM_CONTEXT_MENU

        Application for opening message context menu inside chat

        Embedding code: IM_CONTEXT_MENU

        Embedding into the item "Create using" (similar to "Create task” or "Create meeting" based on a message).

        Parameters

        Parameter Required Description
        context No Chat type to embed the app (ALL by default). Supports the multiple selection via ; of the following values:
        • USER – all user chats, excluding bots;
        • CHAT – all group chats, except lines and crm;
        • LINES – chat type lines (open channels);
        • CRM – only chats created within CRM;
        • ALL – all chats.
        role No Application is available for this user role (USER by default). Supports the following values:
        • USER – application is available for all users;
        • ADMIN – application is available only for Bitrix24 administrators.
        extranet No Application is available for extranet users (N by default). Supports the following values:
        • N – application is unavailable for extranet users;
        • Y – application is available for extranet users.

        This embedding has a current opening context, passed via current chat's dialogId.

        const context = BX24.placement.info().options;
        

        Opens application's IFRAME with specified dimensions. The system automatically reduces the size, if it exceeds the permissible value (your application must consider this).

        Call example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_CONTEXT_MENU',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/context_menu.php',
                'LANG_ALL' => [
                    'en' => [
                        'TITLE' => 'Application for opening message context menu inside chat',
                    ],
                ],
                'OPTIONS' => [
                    'context' => 'USER;CHAT',
                    'role' => 'USER',
                    'extranet' => 'N',
                ]
            ]
        );
        



        IM_SMILES_SELECTOR

        Application for extending smiley and giphy options

        Embedding code: IM_SMILES_SELECTOR

        Can contain custom sources for images or smileys.

        Parameters

        Parameter Required Description
        context No Chat type to embed the app (ALL by default). Supports the multiple selection via ; of the following values:
        • USER – all user chats, excluding bots;
        • CHAT – all group chats, except lines and crm;
        • LINES – chat type lines (open channels);
        • CRM – only chats created within CRM;
        • ALL – all chats.
        role Нет Роль пользователя, для которой доступно это приложение (по умолчанию USER). Поддерживает следующие значения:
        • USER – приложение доступно для всех пользователей;
        • ADMIN – приложение доступно только для администраторов портала.
        extranet No Application is available for extranet users (N by default). Supports the following values:
        • N – application is unavailable for extranet users;
        • Y – application is available for extranet users.

        This embedding has a current opening context, passed via current chat's dialogId.

        const context = BX24.placement.info().options;
        

        Application is rendered within a pop up window with selector of smileys and giphy (without option to alter size).

        Call example:

        CRest::call(
            'placement.bind',
            [
                'PLACEMENT' => 'IM_TEXTAREA',
                'HANDLER' => 'https://example.com/apps/immarket/handlers/smiles_selector.php',
                'LANG_ALL' => [
                    'en' => [
                        'TITLE' => 'Application for extending smiley and giphy options',
                    ],
                ],
                'OPTIONS' => [
                    'context' => 'USER;LINES',
                    'role' => 'USER',
                    'extranet' => 'Y',
                ]
            ]
        );